Skip to content

APath#

An add-on to AString with functions for working with the path.

Header:#include <AUI/IO/APath.h>
CMake:aui_link(my_target PUBLIC aui::core)

Detailed Description#

Note

In most file systems, both a regular file and a folder with the same name can exist on the same path.

Example usage:

APath someDir = "someDir";
APath filePath = someDir / "myfile.txt"; // "/" replaced with a system file separator

Note

Sometimes the word "file" refers to both a regular file (txt, png, jpeg, etc.) and a folder (directory, a file that contains other regular files and folders), i.e. a unit of the file system, which is often a confusion in terminology. Here and further:

  • file - a unit of the file system.
  • regular file - a file that can be read or written to. You can think of as a sequence of bytes or a stream of bytes.
  • folder (directory) - a file that may have child files (both regular files and folders)

Public Types#

DefaultPath#


enum APath::DefaultPath

Constant Description
DefaultPath::APPDATA Folder for application data. {windows} Maps to C:/Users/ %user% /.appdata/Roaming/. {linux} Maps to $HOME/.local/share/. {android} Maps to \<internal_storage_path\>/__aui_appdata. {ios} Maps to \<internal_storage_path\>/__aui_appdata.
DefaultPath::TEMP Folder for temporary data. {windows} Maps to user's temp folder %temp%. {linux} Maps to system temp directory /tmp. {macos} Maps to system temp directory /tmp. {android} Maps to AUI-managed temporary directory: \<internal_storage_path\>/__aui_tmp. {ios} Maps to AUI-managed temporary directory: \<internal_storage_path\>/__aui_tmp.
DefaultPath::HOME User home directory. {windows} Maps to user's home folder C:\\Users\\ %user%. {linux} Maps to user's home folder /home/$USER.

Public Methods#

absolute#


APath APath::absolute()

Get the absolute (full) path to the file.

Returns
the absolute (full) path to the file

chmod#


const APath& APath::chmod(int newMode)

Changes mode (permissions) on file

Arguments
newMode
new mode.

It's convenient to use octet literal on newMode:

APath p("file.txt");
p.chmod(0755); // -rwxr-xr-x

copy#


static void APath::copy(const APath& source, const APath& destination)

Copy regular file.

Arguments
source
source file
destination
destination file

exists#


bool APath::exists()
Returns
true if whether regular file or a folder exists on this path

A file can exist as a regular file or(and) as a folder. This function will return false only if neither the folder nor the file does not exists on this path.

Checkout the isRegularFileExists or isDirectoryExists function to check which type of the file exists on this path.

extension#


AString APath::extension()

File extension.

Returns
file extension

`/home/user/file.cpp -> cpp

extensionChanged#


APath APath::extensionChanged(const AString& newExtension)

Returns same path but with extension changed.

file#


APath APath::file(const AString& fileName)

Path of the child element. Relevant only for folders.

Arguments
fileName
name of child file
Returns
path to child file relatively to this folder

with fileName = work: /home/user -> /home/user/work

It's convient to use / syntax instead:

APath("/home/user") / "work"

Examples#

examples/app/notes/CMakeLists.txt

Notes App - Note taking app that demonstrates usage of AListModel, AProperty, user data saving and loading.

cmake_minimum_required(VERSION 3.16)

# Uncomment this code to pull AUI:
#
# file(
#         DOWNLOAD
#         https://raw.githubusercontent.com/aui-framework/aui/master/aui.boot.cmake
#         ${CMAKE_CURRENT_BINARY_DIR}/aui.boot.cmake)
# include(${CMAKE_CURRENT_BINARY_DIR}/aui.boot.cmake)
#
examples/app/game_of_life/CMakeLists.txt

Game of Life - Game of Life implementation that uses advanced large dynamic data rendering techniques such as [ITexture], [AImage] to be GPU friendly. The computation is performed in [AThreadPool].

endif ()

# Uncomment this code to pull AUI:
#
# file(
#         DOWNLOAD
#         https://raw.githubusercontent.com/aui-framework/aui/master/aui.boot.cmake
#         ${CMAKE_CURRENT_BINARY_DIR}/aui.boot.cmake)
# include(${CMAKE_CURRENT_BINARY_DIR}/aui.boot.cmake)
#
examples/ui/views/CMakeLists.txt

Views Example - All-in-one views building example.

cmake_minimum_required(VERSION 3.16)

# Uncomment this code to pull AUI:
#
# file(
#         DOWNLOAD
#         https://raw.githubusercontent.com/aui-framework/aui/master/aui.boot.cmake
#         ${CMAKE_CURRENT_BINARY_DIR}/aui.boot.cmake)
# include(${CMAKE_CURRENT_BINARY_DIR}/aui.boot.cmake)
#
examples/basic/hello_world/CMakeLists.txt

Console Hello World Example - Basic CLI Hello World application.

cmake_minimum_required(VERSION 3.16)
project(project_template)

# Use AUI.Boot
file(
    DOWNLOAD 
    https://raw.githubusercontent.com/aui-framework/aui/master/aui.boot.cmake 
    ${CMAKE_CURRENT_BINARY_DIR}/aui.boot.cmake)
include(${CMAKE_CURRENT_BINARY_DIR}/aui.boot.cmake)

filename#


APath APath::filename()

File name.

Returns
file name

/home/user/file.cpp -> file.cpp

filenameWithoutExtension#


APath APath::filenameWithoutExtension()

File name without extension.

Returns
file name without extension

`/home/user/file.cpp -> file

find#


static AVector<APath> APath::find(const AString& filename, const AVector<APath>& locations, APathFinder flags = APathFinder::NONE)
Arguments
filename
Name of the file searching for
locations
paths to directories to search for the file in
flags
lookup flags (see APathFinder)
Returns
full path to the found file; if file not found, an empty string is returned.

Searches for file in specified dirs.

getDefaultPath#


static APath APath::getDefaultPath(DefaultPath path)

Get system's default folder.

Returns
absolute path to default folder.

See APath::DefaultPath definition.

isAbsolute#


bool APath::isAbsolute()

Checks whether path absolute or not.

Returns
true if path is absolute

isDirectoryExists#


bool APath::isDirectoryExists()
Returns
true if folder exists on this path

A file can exist as a regular file or(and) as a folder. This function will return false only if folder does not exists on this path.

isEffectivelyAccessible#


bool APath::isEffectivelyAccessible(AFileAccess flags)

Return true if the current process has specified access flags to path.

Checks permissions and existence of the file identified by this APath using the real user and group identifiers of the process, like if the file were opened by open().

Using this function to check a process's permissions on a file before performing some operation based on that information leads to race conditions: the file permissions may change between the two steps. Generally, it is safer just to attempt the desired operation and handle any permission error that occurs.

isRegularFileExists#


bool APath::isRegularFileExists()
Returns
true if regular file exists on this path

A file can exist as a regular file or(and) as a folder. This function will return false only if regular file does not exists on this path.

isRelative#


bool APath::isRelative()

Checks whether path absolute or not.

Returns
true if path is relative

listDir#


ADeque<APath> APath::listDir(AFileListFlags f = AFileListFlags::DEFAULT_FLAGS)

Get list of (by default) direct children of this folder. This function outputs paths including the path listDir was called on.

Returns
list of children of this folder.

Use AFileListFlags enum flags to customize behaviour of this function.

makeDir#


const APath& APath::makeDir()

Create folder.

Returns
this

makeDirs#


const APath& APath::makeDirs()

Create all nonexistent folders on the path.

Returns
this

move#


static void APath::move(const APath& source, const APath& destination)

Move regular file.

Arguments
source
source file
destination
destination file

Examples#

examples/app/game_of_life/src/main.cpp

Game of Life - Game of Life implementation that uses advanced large dynamic data rendering techniques such as ITexture, AImage to be GPU friendly. The computation is performed in AThreadPool.

class CellsView : public AView {
public:
    static constexpr auto SCALE = 8_dp;

    CellsView(_<Cells> cells) : mCells(std::move(cells)) { connect(mCells->frameComplete, me::updateTexture); }

    void render(ARenderContext ctx) override {
        AView::render(ctx);
        if (mTexture) {
            ctx.render.rectangle(ATexturedBrush { mTexture }, { 0, 0 }, float(SCALE) * glm::vec2(mCells->size()));
examples/ui/contacts/src/view/ContactDetailsView.cpp

AUI Contacts - Usage of AUI_DECLARATIVE_FOR to make a contacts-like application.

    }
    return viewer(property) << ".row-value";
}

ContactDetailsView::ContactDetailsView(_<Contact> contact) : mContact(std::move(contact)) {
    mOriginalContact = mContact;
    setExtraStylesheet(AStylesheet {
      {
        c(".row-value"),
        Expanding(1, 0),
examples/7guis/cells/src/Formula.cpp

7GUIs Cells - Spreadsheet processor (Excel).

    try {
        auto tokens = token::parse(ATokenizer(expression));
        auto p = ast::parseExpression(tokens);

        return [p = std::shared_ptr(std::move(p))](const Spreadsheet& ctx) -> formula::Value {
            try {
                return p->evaluate(ctx);
            } catch (const AEvaluationLoopException& e) {
                return "#LOOP!";
            } catch (const AException& e) {
examples/7guis/cells/src/AST.cpp

7GUIs Cells - Spreadsheet processor (Excel).

};

struct StringLiteralNode : INode {
    AString value;
    explicit StringLiteralNode(AString value) : value(std::move(value)) {}
    ~StringLiteralNode() override = default;

    formula::Value evaluate(const Spreadsheet& ctx) override { return value; }
};
examples/7guis/cells/src/main.cpp

7GUIs Cells - Spreadsheet processor (Excel).

    AProperty<AString> currentExpression;
};

static _<AView> labelTitle(AString s) {
    return _new<ALabel>(std::move(s)) AUI_WITH_STYLE {
        Opacity { 0.5f },
        ATextAlign::CENTER,
    };
}
examples/7guis/circle_drawer/src/main.cpp

7GUIs Circle Drawer - Undo, redo, dialog control.

    }

    void add(_unique<IAction> action) {
        action->redo();
        nextAction = std::next(mStack.insert(mStack.erase(*nextAction, mStack.end()), std::move(action)));
        nextAction.notify();
    }

    Iterator begin() const {
        return mStack.begin();

nextRandomTemporary#


static APath APath::nextRandomTemporary()

Creates a path to non-existent random file in system temp directory.

The file is guaranteed to be non-existent, however, its parent directory does. The such path can be used for general purposes. The application might create any kind of file on this location (including dirs) or don't create any file either.

operator#


APath APath::operator(const AString& filename)

Path of the child element. Relevant only for folders.

Arguments
filename
child to produce path to
AString filename = "file.txt";
APath path = "path" / "to" / "your" / filename;
Which would supplyValue into "path/to/your/file.txt"
Returns
path to child file relatively to this folder

Examples#

examples/7guis/cells/src/AST.cpp

7GUIs Cells - Spreadsheet processor (Excel).

                    break;
                }

                case got<token::Plus>: {
                    handleBinaryOperator.operator()<BinaryOperatorNodeImpl<std::plus<>>>(Priority::PLUS_MINUS);
                    break;
                }

                case got<token::Minus>: {
                    handleBinaryOperator.operator()<BinaryOperatorNodeImpl<std::minus<>>>(Priority::PLUS_MINUS);

parent#


APath APath::parent()
Returns
path to parent folder

/home/user -> /home

Examples#

examples/ui/views/tests/LayoutManagerTest.cpp

Views Example - All-in-one views building example.

 */
TEST_F(UILayoutManager, ButtonsAlignment) {
    // buttons column should be perfectly aligned
    By::name("Common button")
        .parent()
        .allChildren()
        .check(leftRightAligned(), "elements should be perfectly aligned");
}

processTemporaryDir#


static const APath& APath::processTemporaryDir()

Generates a unique, process-agnostic temporary directory in the system's temp directory.

Returns
Path to a process-agnostic empty pre-created directory in system temp directory.

Creates a safe and islocated workspace for each application instance. By generating a new directory for each process, it prevents, potential conflicts between concurrent processes.

When the application closes, a directory cleanup attempt will be performed.

relativelyTo#


AString APath::relativelyTo(const APath& dir)

Returns same path but without dir

Arguments
dir
some parent, grandparent, grandgrandparent... dir
Returns
same path but without dir

APath("C:/work/mon/test.txt").relativelyTo("C:/work") -> mon/test.txt

removeDirContentsRecursive#


const APath& APath::removeDirContentsRecursive()

Delete directory contents (recursively).

Returns
this

If this APath points to a regular file, the function has no effect. If this APath points to a directory, it removes all contained files (recursively) within that directory but does not remove the directory itself.

If the target does not exist, this function has no effect.

removeFile#


const APath& APath::removeFile()

Delete file. Relevant for empty folders and regular files.

Returns
this

Unlike remove*Recursive functions, this function has no checks before proceeding, thus, it might throw AIOException (including if the target does not exist).

removeFileRecursive#


const APath& APath::removeFileRecursive()

Delete files recursively, including itself.

Returns
this

If this APath points to a regular file, it deletes the file directly. If this APath points to a directory, it first removes all its contents (recursively) before potentially deleting the directory itself.

If the target does not exist, this function has no effect.

systemSlashDirection#


AString APath::systemSlashDirection()

Transforms this path to string with platform's native slashes.

touch#


const APath& APath::touch()
Returns
this.

Creates a file.

withoutUppermostFolder#


APath APath::withoutUppermostFolder()

Remove the uppermost folder from this path

Returns
The same path except uppermost folder

v1.0.0/client/azaza.zip -> client/azaza.zip

workingDir#


static APath APath::workingDir()
Returns
working dir of application