23#include "utility/system_io/android_system_io.hpp"
35 std::string NormalizePath(
const std::string &path)
37 return std::filesystem::path(path).lexically_normal().string();
41utility::AndroidSystemIO::AndroidSystemIO(AAssetManager *systemInterface)
42 : _assetManager(systemInterface)
58bool utility::AndroidSystemIO::loadDirectory(
const std::string &directory)
61 AAssetManager_openDir(_assetManager, directory.c_str());
62 if (assetDir ==
nullptr) {
64 <<
"Failed to open asset directory: " << directory;
68 const char *fileName =
nullptr;
69 while ((fileName = AAssetDir_getNextFileName(assetDir)) !=
nullptr) {
70 std::string assetPath = directory +
"/" + fileName;
71 if (!this->add(assetPath)) {
72 getLogger().warning() <<
"Failed to load asset: " << assetPath;
75 AAssetDir_close(assetDir);
79std::shared_ptr<utility::File>
80 utility::AndroidSystemIO::add(
const std::string &path)
82 const std::string key = NormalizePath(path);
83 if (this->exists(key)) {
84 return this->open(key);
88 AAssetManager_open(_assetManager, key.c_str(), AASSET_MODE_UNKNOWN);
89 if (file ==
nullptr) {
93 off_t fileLength = AAsset_getLength(file);
99 std::string content(
static_cast<size_t>(fileLength),
'\0');
100 if (!content.empty()) {
101 const int bytesRead =
102 AAsset_read(file, content.data(),
static_cast<size_t>(fileLength));
103 if (bytesRead < 0 ||
static_cast<off_t
>(bytesRead) != fileLength) {
110 auto asset = std::make_shared<utility::File>(path, content);
111 _assets[key] = asset;
115void utility::AndroidSystemIO::remove(
const std::string &path,
bool save)
117 const std::string key = NormalizePath(path);
118 auto it = _assets.find(key);
119 if (it != _assets.end()) {
125 getLogger().warning() <<
"Asset not found: " << key;
129bool utility::AndroidSystemIO::save(
const std::string &path,
130 const std::string &newPath)
132 const std::string key = NormalizePath(path);
133 auto it = _assets.find(key);
134 if (it == _assets.end()) {
135 getLogger().warning() <<
"Asset not found: " << key;
140 if (newPath.empty()) {
141 getLogger().warning()
142 <<
"Cannot save Android asset to original path. Provide a newPath.";
145 const auto &content = it->second->data();
146 std::ofstream file(newPath, std::ios::binary);
147 if (!file.is_open()) {
148 getLogger().warning() <<
"Failed to open file for writing: " << newPath;
151 file.write(
reinterpret_cast<const char *
>(content.data()), content.size());
Abstract logger interface defining stream-style logging operations.
Platform-specific default logger alias.
StandardLogger DefaultLogger
Alias for the platform-specific default logger.
The utility namespace contains classes and functions for the utility project.