19#include "physfs/physfs.h"
21#ifdef EVENGINE_WINDOWS
34#include "webgpu/webplatform.h"
40#ifdef EVENGINE_ANDROID
43#include "android/android.h"
49size_t getDriveDelim(
const std::string &
input) {
50 for (
size_t i = 0; i <
input.size(); ++i)
51 if (
input[i] ==
'/' ||
input[i] ==
'\\')
return i;
56std::string getDriveRoot(
const std::string &
input) {
return input.substr(0, getDriveDelim(
input) + 1); }
58std::string skipDriveRoot(
const std::string &
input) {
return input.substr(getDriveDelim(
input) + 1); }
61 std::stringstream
out;
63 bool seenSep =
false, isSep =
false;
64 for (
size_t i = 0; i <
input.size(); ++i) {
66 if (!isSep || !seenSep)
out <<
input[i];
80 requirePath = {
"?.lua",
"?/init.lua"};
81 cRequirePath = {
"??"};
84 const std::string a0 =
c->getArgv(0);
85 if (a0.empty())
init(NULL);
86 else init(a0.c_str());
97 memoryArchive_ =
nullptr;
100#ifdef EVENGINE_ANDROID
101 android::deinitializeVirtualArchive();
104 if (PHYSFS_isInit()) PHYSFS_deinit();
108 if (!PHYSFS_init(arg0))
109 throw Exception(
"Failed to initialize filesystem: %s", PHYSFS_getErrorByCode(PHYSFS_getLastErrorCode()));
116 if (fusedSet)
return;
122 if (!fusedSet)
return false;
127 if (!PHYSFS_isInit())
return false;
129 std::string old_save_path = save_path_full;
132 save_identity = std::string(ident);
142 save_path_full += save_path_relative;
144 save_path_full = normalize(save_path_full);
146#ifdef EVENGINE_ANDROID
147 if (save_identity ==
"") save_identity =
"unnamed";
149 std::string storage_path;
151 storage_path = SDL_AndroidGetExternalStoragePath();
153 storage_path = SDL_AndroidGetInternalStoragePath();
155 std::string save_directory = storage_path +
"/save";
157 save_path_full = storage_path + std::string(
"/save/") + save_identity;
159 if (!android::directoryExists(save_path_full.c_str()) && !android::mkdir(save_path_full.c_str()))
160 SDL_Log(
"Error: Could not create save directory %s!", save_path_full.c_str());
170 if (!old_save_path.empty()) PHYSFS_unmount(old_save_path.c_str());
174 PHYSFS_mount(save_path_full.c_str(),
nullptr, appendToPath);
179 PHYSFS_setWriteDir(
nullptr);
187 if (!PHYSFS_isInit())
return false;
190 if (!game_source.empty())
return false;
192 std::string new_search_path = std::move(
source);
194#ifdef EVENGINE_ANDROID
195 if (!android::createStorageDirectories()) SDL_Log(
"Error creating storage directories!");
197 new_search_path =
"";
199 PHYSFS_Io *gameLoveIO;
200 bool hasFusedGame = android::checkFusedGame((
void **)&gameLoveIO);
205 gameLoveIO->destroy(gameLoveIO);
208 if (!android::initializeVirtualArchive()) {
209 SDL_Log(
"Unable to mount AAsset: %s", PHYSFS_getErrorByCode(PHYSFS_getLastErrorCode()));
215 new_search_path = android::getSelectedGameFile();
218 if (!PHYSFS_mount(new_search_path.c_str(),
nullptr, 1)) {
220 SDL_Log(
"Mounting %s did not work. Loading to memory.", new_search_path.c_str());
221 char * game_archive_ptr = NULL;
222 size_t game_archive_size = 0;
223 if (!android::loadGameArchiveToMemory(new_search_path.c_str(), &game_archive_ptr,
224 &game_archive_size)) {
225 SDL_Log(
"Failure memory loading archive %s", new_search_path.c_str());
228 if (!PHYSFS_mountMemory(game_archive_ptr, game_archive_size, android::freeGameArchiveMemory,
229 "archive.zip",
"/", 0)) {
230 SDL_Log(
"Failure mounting in-memory archive.");
231 android::freeGameArchiveMemory(game_archive_ptr);
238 if (!PHYSFS_mount(new_search_path.c_str(),
nullptr, 1))
return false;
242 game_source = std::move(new_search_path);
250 if (!PHYSFS_isInit() || !data ||
size == 0)
return false;
252 if (!game_source.empty())
return false;
257 if (!
owned)
return false;
261 if (!PHYSFS_mountMemory(
owned,
size,
nullptr,
"game.eve",
"/", 1)) {
262 const auto err = PHYSFS_getErrorByCode(PHYSFS_getLastErrorCode());
263 std::cerr <<
"PhysFS mountMemory failed: " << (err ? err :
"unknown error") << std::endl;
268 memoryArchive_ =
owned;
269 game_source =
"game.eve";
274 if (!PHYSFS_isInit())
return false;
277 if (save_identity.empty() || save_path_full.empty() || save_path_relative.empty())
return false;
281 std::string temp_writedir = getDriveRoot(save_path_full);
282 std::string temp_createdir = skipDriveRoot(save_path_full);
293 size_t startpos = temp_createdir.find_first_not_of(
'/');
294 if (startpos != std::string::npos) temp_createdir = temp_createdir.substr(startpos);
299 if (!PHYSFS_setWriteDir(temp_writedir.c_str()))
return false;
304 PHYSFS_setWriteDir(
nullptr);
309 if (!PHYSFS_setWriteDir(save_path_full.c_str()))
return false;
312 if (!PHYSFS_mount(save_path_full.c_str(),
nullptr, 0)) {
313 PHYSFS_setWriteDir(
nullptr);
321 if (!PHYSFS_isInit() || archive.empty())
return false;
323 std::string realPath;
327 auto it = std::find(allowedMountPaths.begin(), allowedMountPaths.end(), archive);
329 if (it != allowedMountPaths.end())
331 else if (
isFused() && sourceBase.compare(archive) == 0) {
334 realPath = sourceBase;
337 if (archive.size() == 0 || archive.find(
"..") != string::npos || archive ==
"/")
return false;
339 const char* realDir = PHYSFS_getRealDir(archive.c_str());
340 if (!realDir)
return false;
346 if (realPath.find(game_source) == 0)
return false;
352 if (realPath.length() == 0)
return false;
354 return PHYSFS_mount(realPath.c_str(), mountpoint.c_str(), appendToPath) != 0;
358 if (!PHYSFS_isInit())
return false;
360 if (PHYSFS_mountMemory(data->getData(), data->getSize(),
nullptr, archivename.c_str(), mountpoint.c_str(), appendToPath) != 0) {
361 mountedData[archivename] = data;
369 if (!PHYSFS_isInit() || realDir.empty())
return false;
371 if (mountpoint.empty()) mountpoint =
"/";
375 std::lock_guard<std::mutex> lock(mountMu_);
376 if (std::find(mountedRealDirs_.begin(), mountedRealDirs_.end(), realDir) == mountedRealDirs_.end()) {
377 if (!PHYSFS_mount(realDir.c_str(), mountpoint.c_str(), appendToPath ? 1 : 0))
return false;
378 mountedRealDirs_.push_back(realDir);
384 std::lock_guard<std::mutex> lock(mountMu_);
385 auto it = std::find(mountedRealDirs_.begin(), mountedRealDirs_.end(), realDir);
386 if (it == mountedRealDirs_.end())
return false;
387 const bool ok = PHYSFS_unmount(realDir.c_str()) != 0;
388 mountedRealDirs_.erase(it);
393 if (!PHYSFS_isInit() || archive.empty())
return false;
395 auto datait = mountedData.find(archive);
397 if (datait != mountedData.end() && PHYSFS_unmount(archive.c_str()) != 0) {
398 mountedData.erase(datait);
402 std::string realPath;
406 auto it = std::find(allowedMountPaths.begin(), allowedMountPaths.end(), archive);
408 if (it != allowedMountPaths.end())
410 else if (
isFused() && sourceBase.compare(archive) == 0) {
413 realPath = sourceBase;
416 if (archive.size() == 0 || archive.find(
"..") != string::npos || archive ==
"/")
return false;
418 const char* realDir = PHYSFS_getRealDir(archive.c_str());
419 if (!realDir)
return false;
426 const char* mountPoint = PHYSFS_getMountPoint(realPath.c_str());
427 if (!mountPoint)
return false;
429 return PHYSFS_unmount(realPath.c_str()) != 0;
433 for (
const auto &datapair : mountedData) {
434 if (datapair.second == data) {
435 std::string archive = datapair.first;
436 return unmount(archive.c_str());
447#ifdef EVENGINE_WINDOWS
451 cwd = to_utf8(w_cwd);
452 replace_char(cwd,
'\\',
'/');
469 static std::string userDir = normalize(ios::getHomeDirectory());
470#elif defined(EVENGINE_WEBGPU)
471 static std::string userDir = normalize(eve::webgpu_platform::getHomeDirectory());
477#pragma GCC diagnostic push
478#pragma GCC diagnostic ignored "-Wdeprecated-declarations"
480 const char*
dir = PHYSFS_getUserDir();
482#pragma GCC diagnostic pop
484 static std::string userDir;
485 if (
dir) userDir = normalize(
dir);
491 if (appdata.empty()) {
492#ifdef EVENGINE_WINDOWS_UWP
494#elif defined(EVENGINE_WEBGPU)
495 appdata = normalize(eve::webgpu_platform::getAppdataDirectory());
496#elif defined(EVENGINE_WINDOWS)
497 wchar_t *w_appdata = _wgetenv(L
"APPDATA");
498 appdata = to_utf8(w_appdata);
499 replace_char(appdata,
'\\',
'/');
500#elif defined(EVENGINE_MACOSX)
502 udir.append(
"/Library/Application Support");
503 appdata = normalize(udir);
504#elif defined(EVENGINE_IOS)
505 appdata = normalize(ios::getAppdataDirectory());
506#elif defined(EVENGINE_LINUX)
507 char *xdgdatahome = getenv(
"XDG_DATA_HOME");
511 appdata = xdgdatahome;
522 size_t source_len = game_source.length();
524 if (source_len == 0)
return "";
528#ifdef EVENGINE_WINDOWS
530 size_t base_end_pos = game_source.find_last_of(
"/\\", source_len - 2);
532 size_t base_end_pos = game_source.find_last_of(
'/', source_len - 2);
535 if (base_end_pos == std::string::npos)
return "";
538 if (base_end_pos == 0) base_end_pos = 1;
540 return game_source.substr(0, base_end_pos);
544 if (!PHYSFS_isInit())
throw Exception(
"PhysFS is not initialized.");
546 const char*
dir = PHYSFS_getRealDir(filename.c_str());
548 if (
dir ==
nullptr)
throw Exception(
"File does not exist on disk.");
550 return std::string(
dir);
554 if (!PHYSFS_isInit())
return false;
556 PHYSFS_Stat stat = {};
557 if (!PHYSFS_stat(filepath.c_str(), &stat))
return false;
559 info.size = (int64_t)stat.filesize;
560 info.modtime = (int64_t)stat.modtime;
562 if (stat.filetype == PHYSFS_FILETYPE_REGULAR)
564 else if (stat.filetype == PHYSFS_FILETYPE_DIRECTORY)
565 info.type =
"directory";
566 else if (stat.filetype == PHYSFS_FILETYPE_SYMLINK)
567 info.type =
"symlink";
575 if (!PHYSFS_isInit())
return false;
579 if (!PHYSFS_mkdir(
dir.c_str()))
return false;
585 if (!PHYSFS_isInit())
return false;
589 if (!PHYSFS_delete(
file.c_str()))
return false;
622 std::vector<std::string> items;
623 if (!PHYSFS_isInit())
return items;
625 char **rc = PHYSFS_enumerateFiles(
dir.c_str());
627 if (rc ==
nullptr)
return items;
629 for (
char **i = rc; *i != 0; i++) items.push_back(*i);
636 if (!PHYSFS_isInit())
return;
638 PHYSFS_permitSymbolicLinks(enable ? 1 : 0);
642 if (!PHYSFS_isInit())
return false;
644 return PHYSFS_symbolicLinksPermitted() != 0;
652 if (std::find(allowedMountPaths.begin(), allowedMountPaths.end(),
path) == allowedMountPaths.end())
653 allowedMountPaths.push_back(
path);
658bool looksAbsolute(
const std::string &
path) {
659 if (
path.empty())
return false;
660 if (
path[0] ==
'/' ||
path[0] ==
'\\')
return true;
661#ifdef EVENGINE_WINDOWS
662 if (
path.size() >= 2 &&
path[1] ==
':')
return true;
667std::string joinPath(
const std::string &
a,
const std::string &
b) {
668 if (
a.empty())
return b;
669 if (
b.empty())
return a;
670 char last =
a.back();
671 if (last ==
'/' || last ==
'\\')
return a +
b;
675std::string parentDir(
const std::string &
path) {
676 auto pos =
path.find_last_of(
"/\\");
677 if (
pos == std::string::npos)
return ".";
678 if (
pos == 0)
return "/";
682std::string baseName(
const std::string &
path) {
683 auto pos =
path.find_last_of(
"/\\");
684 if (
pos == std::string::npos)
return path;
688bool hasParentSegment(
const std::string &
path) {
689 if (
path ==
"..")
return true;
690 if (
path.size() >= 3 && (
path.compare(0, 3,
"../") == 0 ||
path.compare(0, 3,
"..\\") == 0))
692 return path.find(
"/..") != std::string::npos ||
path.find(
"\\..") != std::string::npos;
695std::filesystem::path pathFromUtf8(
const std::string &
text) {
696 const auto *data =
reinterpret_cast<const char8_t *
>(
text.data());
697 return std::filesystem::path(std::u8string_view(data,
text.size()));
700std::string pathToUtf8(
const std::filesystem::path &
p) {
701 auto u8 =
p.u8string();
702 return std::string(
reinterpret_cast<const char *
>(u8.data()), u8.size());
707FileWatch &Filesystem::watchers() {
708 if (!fileWatch_) fileWatch_ = std::make_unique<FileWatch>();
712bool Filesystem::resolveWatchTarget(
const std::string &
path, std::string &realDir,
713 std::string &filterName, std::string &reportPath) {
717 if (
path.empty())
return false;
727 if (looksAbsolute(
path)) {
732 realDir = parentDir(
path);
733 filterName = baseName(
path);
739 if (hasParentSegment(
path)) {
741 auto candidate = std::filesystem::weakly_canonical(
744 const std::string full = pathToUtf8(candidate);
750 realDir = parentDir(full);
751 filterName = baseName(full);
764 std::string full = joinPath(
root,
path);
765 if (
info.type ==
"directory") {
770 realDir = parentDir(full);
771 filterName = baseName(full);
787 filterName = baseName(
path);
797 realDir = workingDir;
798 filterName = baseName(
path);
807 filterName = baseName(
path);
814 std::string realDir,
filter, report;
815 if (!resolveWatchTarget(
path, realDir,
filter, report))
return false;
816 return watchers().
add(realDir,
filter, report, 1);
820 if (realDir.empty() || reportPath.empty()) {
823 "watchRealDirectory requires a real directory and a report path"));
829 if (!watchers().add(std::move(realDir),
"", std::move(reportPath), 1)) {
839 if (fileWatch_) fileWatch_->clear();
843 if (!fileWatch_)
return 0;
844 return fileWatch_->count();
848 if (!fileWatch_)
return "";
850 if (!fileWatch_->poll(ev)) {
851 lastWatchPath_.clear();
852 lastWatchRealPath_.clear();
855 lastWatchPath_ = ev.
path;
Stable, structured diagnostics shared by engine modules.
#define EVENGINE_MAX_PATH
#define EVENGINE_PATH_SEPARATOR
#define EVENGINE_APPDATA_PREFIX
#define EVENGINE_APPDATA_FOLDER
const ColourScope * parent
static Diagnostic error(DiagnosticCode code, std::string message, std::string path={})
Construct an error diagnostic with the standard error severity.
EVENGINE_API_FOUNDATION public API.
Move-only operation result carrying either a value or Status.
static Result success(T value)
Construct a successful result owning value.
static Result failure(Status status)
Construct a failed result from a structured status.
Data buffer paired with a filename (used for type identification).
bool add(const std::string &realDir, const std::string &filterName, const std::string &reportPath, int scanInterval=1)
bool remove(const std::string &reportPath)
Remove by reportPath previously passed to add().
A File interface, providing generic means of reading from and writing to files.
virtual bool isAndroidSaveExternal() const
Gets whether the Android save is external. Returns a bool.
virtual bool isRealDirectory(const std::string &path) const
Gets whether the given full (OS-dependent) path is a directory.
std::string getSaveDirectory() override
Returns the save directory.
void append(std::string filename, const void *data, int64_t size) const override
Append.
bool setSource(std::string source) override
Sets the source.
int getWatchCount() const override
Returns the watch count.
bool setIdentity(std::string ident, bool appendToPath=false) override
Sets the identity.
void unwatchAll() override
Stops watching all.
std::string getRealDirectory(std::string filename) const override
Returns the real directory.
void setFused(bool value) override
Sets the fused.
bool setSourceFromMemory(const void *data, size_t size) override
Sets the source from memory.
~Filesystem() override
Filesystem.
eve::Result< void > watchRealDirectory(std::string realDir, std::string reportPath) override
Watches real directory.
bool watch(std::string path) override
Watches watch.
std::string getSource() const override
Returns the source.
filesystem::File * newFile(std::string filename) const override
Creates a file. @ownership Caller deletes unless documented otherwise.
std::string getUserDirectory() override
Returns the user directory.
bool createDirectory(std::string dir) override
Creates directory.
bool remove(std::string file) override
Removes remove.
std::vector< std::string > getDirectoryItems(std::string dir) override
Returns the directory items.
bool isFused() const override
True when fused.
bool unmount(std::string archive) override
Unmounts unmount.
std::string pollWatch() override
Polls watch.
std::string getLastWatchRealPath() const override
Returns the last watch real path.
bool mountRealDirectory(std::string realDir, std::string mountpoint, bool appendToPath=false) override
Mounts real directory.
bool unwatch(std::string path) override
Stops watching unwatch.
bool mount(std::string archive, std::string mountpoint, bool appendToPath=false) override
Mounts mount.
std::string getIdentity() const override
Returns the identity.
void init(const char *arg0) override
Initializes init.
bool setupWriteDirectory() override
Setup write directory.
std::vector< std::string > & getCRequirePath() override
Returns the c require path.
std::string getWorkingDirectory() override
Returns the working directory.
FileData * read(std::string filename, int64_t size=File::ALL) const override
Reads read.
bool unmountRealDirectory(std::string realDir) override
Unmounts real directory.
void allowMountingForPath(const std::string &path) override
Allow mounting for path.
void write(std::string filename, const void *data, int64_t size) const override
Writes write.
void setSymlinksEnabled(bool enable) override
Sets the symlinks enabled.
bool getInfo(std::string filepath, Info &info) const override
Returns the info.
bool areSymlinksEnabled() const override
Are symlinks enabled.
std::vector< std::string > & getRequirePath() override
Returns the require path.
std::string getSourceBaseDirectory() const override
Returns the source base directory.
std::string getAppdataDirectory() override
Returns the appdata directory.
std::string getLastWatchPath() const override
Returns the last watch path.
V3 normalize(V3 a)
Module-private road bake implementation helper.
Build metadata (engine git commit, build time, third-party version).