载入中...
搜索中...
未找到
Filesystem.cpp
浏览该文件的文档.
2
3#include <algorithm>
4#include <iostream>
5#include <memory>
6#include <mutex>
7#include <sstream>
8#include <string>
9#include <utility>
10
12#include "common/b64.h"
13#include "common/utf8.h"
14#include "common/Exception.h"
15#include "common/Diagnostic.h"
16#include "cmdline/cmdline.h"
17
18// PhysFS
19#include "physfs/physfs.h"
20
21#ifdef EVENGINE_WINDOWS
22#include <direct.h>
23#include <windows.h>
24#else
25#include <sys/param.h>
26#include <unistd.h>
27#endif
28
29#ifdef EVENGINE_IOS
30#include "ios/ios.h"
31#endif
32
33#ifdef EVENGINE_WEBGPU
34#include "webgpu/webplatform.h"
35#endif
36
37#include <filesystem>
38#include <string>
39
40#ifdef EVENGINE_ANDROID
41#include <SDL2/SDL.h>
42
43#include "android/android.h"
44#endif
45
46using namespace std;
47
48namespace {
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;
52 // Something's horribly wrong
53 return 0;
54}
55
56std::string getDriveRoot(const std::string &input) { return input.substr(0, getDriveDelim(input) + 1); }
57
58std::string skipDriveRoot(const std::string &input) { return input.substr(getDriveDelim(input) + 1); }
59
60std::string normalize(const std::string &input) {
61 std::stringstream out;
62
63 bool seenSep = false, isSep = false;
64 for (size_t i = 0; i < input.size(); ++i) {
65 isSep = (input[i] == EVENGINE_PATH_SEPARATOR[0]);
66 if (!isSep || !seenSep) out << input[i];
67 seenSep = isSep;
68 }
69
70 return out.str();
71}
72
73} // namespace
74
75namespace eve {
76namespace filesystem {
77namespace physfs {
78
79Filesystem::Filesystem() : fused(false), fusedSet(false) {
80 requirePath = {"?.lua", "?/init.lua"};
81 cRequirePath = {"??"};
82 if (auto* c = getModInst(eve::cmd,Cmdline)) {
83 // unit_test / embedders never call Cmdline::runArgs: argv stays empty.
84 const std::string a0 = c->getArgv(0);
85 if (a0.empty()) init(NULL);
86 else init(a0.c_str());
87 } else {
88 init(NULL);
89 }
90}
91
93 unwatchAll();
94
95 if (memoryArchive_) {
96 free(memoryArchive_);
97 memoryArchive_ = nullptr;
98 }
99
100#ifdef EVENGINE_ANDROID
101 android::deinitializeVirtualArchive();
102#endif
103
104 if (PHYSFS_isInit()) PHYSFS_deinit();
105}
106
107void Filesystem::init(const char* arg0) {
108 if (!PHYSFS_init(arg0))
109 throw Exception("Failed to initialize filesystem: %s", PHYSFS_getErrorByCode(PHYSFS_getLastErrorCode()));
110
111 // Enable symlinks by default.
112 setSymlinksEnabled(true);
113}
114
116 if (fusedSet) return;
117 this->fused = value;
118 fusedSet = true;
119}
120
122 if (!fusedSet) return false;
123 return fused;
124}
125
126bool Filesystem::setIdentity(std::string ident, bool appendToPath) {
127 if (!PHYSFS_isInit()) return false;
128
129 std::string old_save_path = save_path_full;
130
131 // Store the save directory.
132 save_identity = std::string(ident);
133
134 // Generate the relative path to the game save folder.
135 save_path_relative = std::string(EVENGINE_APPDATA_PREFIX EVENGINE_APPDATA_FOLDER EVENGINE_PATH_SEPARATOR) + save_identity;
136
137 // Generate the full path to the game save folder.
138 save_path_full = std::string(getAppdataDirectory()) + std::string(EVENGINE_PATH_SEPARATOR);
139 if (fused)
140 save_path_full += std::string(EVENGINE_APPDATA_PREFIX) + save_identity;
141 else
142 save_path_full += save_path_relative;
143
144 save_path_full = normalize(save_path_full);
145
146#ifdef EVENGINE_ANDROID
147 if (save_identity == "") save_identity = "unnamed";
148
149 std::string storage_path;
151 storage_path = SDL_AndroidGetExternalStoragePath();
152 else
153 storage_path = SDL_AndroidGetInternalStoragePath();
154
155 std::string save_directory = storage_path + "/save";
156
157 save_path_full = storage_path + std::string("/save/") + save_identity;
158
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());
161#endif
162
163 // We now have something like:
164 // save_identity: game
165 // save_path_relative: ./LOVE/game
166 // save_path_full: C:\Documents and Settings\user\Application Data/LOVE/game
167
168 // We don't want old read-only save paths to accumulate when we set a new
169 // identity.
170 if (!old_save_path.empty()) PHYSFS_unmount(old_save_path.c_str());
171
172 // Try to add the save directory to the search path.
173 // (No error on fail, it means that the path doesn't exist).
174 PHYSFS_mount(save_path_full.c_str(), nullptr, appendToPath);
175
176 // HACK: This forces setupWriteDirectory to be called the next time a file
177 // is opened for writing - otherwise it won't be called at all if it was
178 // already called at least once before.
179 PHYSFS_setWriteDir(nullptr);
180
181 return true;
182}
183
184std::string Filesystem::getIdentity() const { return save_identity.c_str(); }
185
186bool Filesystem::setSource(std::string source) {
187 if (!PHYSFS_isInit()) return false;
188
189 // Check whether directory is already set.
190 if (!game_source.empty()) return false;
191
192 std::string new_search_path = std::move(source);
193
194#ifdef EVENGINE_ANDROID
195 if (!android::createStorageDirectories()) SDL_Log("Error creating storage directories!");
196
197 new_search_path = "";
198
199 PHYSFS_Io *gameLoveIO;
200 bool hasFusedGame = android::checkFusedGame((void **)&gameLoveIO);
201
202 if (hasFusedGame) {
203 if (gameLoveIO) {
204 // Actually we should just be able to mount gameLoveIO, but that's experimental.
205 gameLoveIO->destroy(gameLoveIO);
206 goto oldschool;
207 } else {
208 if (!android::initializeVirtualArchive()) {
209 SDL_Log("Unable to mount AAsset: %s", PHYSFS_getErrorByCode(PHYSFS_getLastErrorCode()));
210 return false;
211 }
212 }
213 } else {
214 oldschool:
215 new_search_path = android::getSelectedGameFile();
216
217 // try mounting first, if that fails, load to memory and mount
218 if (!PHYSFS_mount(new_search_path.c_str(), nullptr, 1)) {
219 // PHYSFS cannot yet mount a zip file inside an .apk
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());
226 return false;
227 }
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);
232 return false;
233 }
234 }
235 }
236#else
237 // Add the directory.
238 if (!PHYSFS_mount(new_search_path.c_str(), nullptr, 1)) return false;
239#endif
240
241 // Save the game source.
242 game_source = std::move(new_search_path);
243
244 return true;
245}
246
247std::string Filesystem::getSource() const { return game_source.c_str(); }
248
249bool Filesystem::setSourceFromMemory(const void* data, size_t size) {
250 if (!PHYSFS_isInit() || !data || size == 0) return false;
251 // Only one source per process.
252 if (!game_source.empty()) return false;
253
254 // PhysFS keeps a pointer to the buffer for the lifetime of the mount, so we
255 // must own a copy that outlives it. Freed in the destructor.
256 void* owned = malloc(size);
257 if (!owned) return false;
258 memcpy(owned, data, size);
259
260 // Mount at "/" so dofile("config.nut") / "main.nut" resolve via PhysFS.
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;
264 free(owned);
265 return false;
266 }
267
268 memoryArchive_ = owned;
269 game_source = "game.eve";
270 return true;
271}
272
274 if (!PHYSFS_isInit()) return false;
275
276 // These must have one be set.
277 if (save_identity.empty() || save_path_full.empty() || save_path_relative.empty()) return false;
278
279 // We need to make sure the write directory is created. To do that, we also
280 // need to make sure all its parent directories are also created.
281 std::string temp_writedir = getDriveRoot(save_path_full);
282 std::string temp_createdir = skipDriveRoot(save_path_full);
283
284 // On some sandboxed platforms, physfs will break when its write directory
285 // is the root of the drive and it tries to create a folder (even if the
286 // folder's path is in a writable location.) If the user's home folder is
287 // in the save path, we'll try starting from there instead.
288 if (save_path_full.find(getUserDirectory()) == 0) {
289 temp_writedir = getUserDirectory();
290 temp_createdir = save_path_full.substr(getUserDirectory().length());
291
292 // Strip leading '/' characters from the path we want to create.
293 size_t startpos = temp_createdir.find_first_not_of('/');
294 if (startpos != std::string::npos) temp_createdir = temp_createdir.substr(startpos);
295 }
296
297 // Set either '/' or the user's home as a writable directory.
298 // (We must create the save folder before mounting it).
299 if (!PHYSFS_setWriteDir(temp_writedir.c_str())) return false;
300
301 // Create the save folder. (We're now "at" either '/' or the user's home).
302 if (!createDirectory(temp_createdir.c_str())) {
303 // Clear the write directory in case of error.
304 PHYSFS_setWriteDir(nullptr);
305 return false;
306 }
307
308 // Set the final write directory.
309 if (!PHYSFS_setWriteDir(save_path_full.c_str())) return false;
310
311 // Add the directory. (Will not be readded if already present).
312 if (!PHYSFS_mount(save_path_full.c_str(), nullptr, 0)) {
313 PHYSFS_setWriteDir(nullptr); // Clear the write directory in case of error.
314 return false;
315 }
316
317 return true;
318}
319
320bool Filesystem::mount(std::string archive, std::string mountpoint, bool appendToPath) {
321 if (!PHYSFS_isInit() || archive.empty()) return false;
322
323 std::string realPath;
324 std::string sourceBase = getSourceBaseDirectory();
325
326 // Check whether the given archive path is in the list of allowed full paths.
327 auto it = std::find(allowedMountPaths.begin(), allowedMountPaths.end(), archive);
328
329 if (it != allowedMountPaths.end())
330 realPath = *it;
331 else if (isFused() && sourceBase.compare(archive) == 0) {
332 // Special case: if the game is fused and the archive is the source's
333 // base directory, mount it even though it's outside of the save dir.
334 realPath = sourceBase;
335 } else {
336 // Not allowed for safety reasons.
337 if (archive.size() == 0 || archive.find("..") != string::npos || archive == "/") return false;
338
339 const char* realDir = PHYSFS_getRealDir(archive.c_str());
340 if (!realDir) return false;
341
342 realPath = realDir;
343
344 // Always disallow mounting of files inside the game source, since it
345 // won't work anyway if the game source is a zipped .love file.
346 if (realPath.find(game_source) == 0) return false;
347
348 realPath += EVENGINE_PATH_SEPARATOR;
349 realPath += archive;
350 }
351
352 if (realPath.length() == 0) return false;
353
354 return PHYSFS_mount(realPath.c_str(), mountpoint.c_str(), appendToPath) != 0;
355}
356
357bool Filesystem::mount(Data *data, std::string archivename, std::string mountpoint, bool appendToPath) {
358 if (!PHYSFS_isInit()) return false;
359
360 if (PHYSFS_mountMemory(data->getData(), data->getSize(), nullptr, archivename.c_str(), mountpoint.c_str(), appendToPath) != 0) {
361 mountedData[archivename] = data;
362 return true;
363 }
364
365 return false;
366}
367
368bool Filesystem::mountRealDirectory(std::string realDir, std::string mountpoint, bool appendToPath) {
369 if (!PHYSFS_isInit() || realDir.empty()) return false;
370 if (!isRealDirectory(realDir)) return false;
371 if (mountpoint.empty()) mountpoint = "/";
372
373 // Track the dir so unmountRealDirectory() / the destructor can clean it up,
374 // even though PhysFS itself needs the OS path string to unmount.
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);
379 }
380 return true;
381}
382
383bool Filesystem::unmountRealDirectory(std::string 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);
389 return ok;
390}
391
392bool Filesystem::unmount(std::string archive) {
393 if (!PHYSFS_isInit() || archive.empty()) return false;
394
395 auto datait = mountedData.find(archive);
396
397 if (datait != mountedData.end() && PHYSFS_unmount(archive.c_str()) != 0) {
398 mountedData.erase(datait);
399 return true;
400 }
401
402 std::string realPath;
403 std::string sourceBase = getSourceBaseDirectory();
404
405 // Check whether the given archive path is in the list of allowed full paths.
406 auto it = std::find(allowedMountPaths.begin(), allowedMountPaths.end(), archive);
407
408 if (it != allowedMountPaths.end())
409 realPath = *it;
410 else if (isFused() && sourceBase.compare(archive) == 0) {
411 // Special case: if the game is fused and the archive is the source's
412 // base directory, unmount it even though it's outside of the save dir.
413 realPath = sourceBase;
414 } else {
415 // Not allowed for safety reasons.
416 if (archive.size() == 0 || archive.find("..") != string::npos || archive == "/") return false;
417
418 const char* realDir = PHYSFS_getRealDir(archive.c_str());
419 if (!realDir) return false;
420
421 realPath = realDir;
422 realPath += EVENGINE_PATH_SEPARATOR;
423 realPath += archive;
424 }
425
426 const char* mountPoint = PHYSFS_getMountPoint(realPath.c_str());
427 if (!mountPoint) return false;
428
429 return PHYSFS_unmount(realPath.c_str()) != 0;
430}
431
433 for (const auto &datapair : mountedData) {
434 if (datapair.second == data) {
435 std::string archive = datapair.first;
436 return unmount(archive.c_str());
437 }
438 }
439
440 return false;
441}
442
443filesystem::File *Filesystem::newFile(std::string filename) const { return new File(filename); }
444
446 if (cwd.empty()) {
447#ifdef EVENGINE_WINDOWS
448
449 WCHAR w_cwd[EVENGINE_MAX_PATH];
450 _wgetcwd(w_cwd, EVENGINE_MAX_PATH);
451 cwd = to_utf8(w_cwd);
452 replace_char(cwd, '\\', '/');
453#else
454 char *cwd_char = new char[EVENGINE_MAX_PATH];
455
456 if (getcwd(cwd_char, EVENGINE_MAX_PATH))
457 cwd = cwd_char; // if getcwd fails, cwd_char (and thus cwd) will still be empty
458
459 delete[] cwd_char;
460#endif
461 }
462
463 return cwd.c_str();
464}
465
467#ifdef EVENGINE_IOS
468 // PHYSFS_getUserDir doesn't give exactly the path we want on iOS.
469 static std::string userDir = normalize(ios::getHomeDirectory());
470#elif defined(EVENGINE_WEBGPU)
471 static std::string userDir = normalize(eve::webgpu_platform::getHomeDirectory());
472#else
473 // PhysFS deprecated PHYSFS_getUserDir() in 2.1 without a non-deprecated
474 // home-directory replacement (PHYSFS_getPrefDir() is app-specific), so the
475 // public API is kept for the home-directory semantics.
476#if defined(__GNUC__)
477#pragma GCC diagnostic push
478#pragma GCC diagnostic ignored "-Wdeprecated-declarations"
479#endif
480 const char* dir = PHYSFS_getUserDir();
481#if defined(__GNUC__)
482#pragma GCC diagnostic pop
483#endif
484 static std::string userDir;
485 if (dir) userDir = normalize(dir);
486#endif
487 return userDir;
488}
489
491 if (appdata.empty()) {
492#ifdef EVENGINE_WINDOWS_UWP
493 appdata = getUserDirectory();
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)
501 std::string udir = getUserDirectory();
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");
508 if (!xdgdatahome)
509 appdata = normalize(std::string(getUserDirectory()) + "/.local/share/");
510 else
511 appdata = xdgdatahome;
512#else
513 appdata = getUserDirectory();
514#endif
515 }
516 return appdata;
517}
518
519std::string Filesystem::getSaveDirectory() { return save_path_full.c_str(); }
520
522 size_t source_len = game_source.length();
523
524 if (source_len == 0) return "";
525
526 // FIXME: This doesn't take into account parent and current directory
527 // symbols (i.e. '..' and '.')
528#ifdef EVENGINE_WINDOWS
529 // In windows, delimiters can be either '/' or '\'.
530 size_t base_end_pos = game_source.find_last_of("/\\", source_len - 2);
531#else
532 size_t base_end_pos = game_source.find_last_of('/', source_len - 2);
533#endif
534
535 if (base_end_pos == std::string::npos) return "";
536
537 // If the source is in the unix root (aka '/'), we want to keep the '/'.
538 if (base_end_pos == 0) base_end_pos = 1;
539
540 return game_source.substr(0, base_end_pos);
541}
542
543std::string Filesystem::getRealDirectory(std::string filename) const {
544 if (!PHYSFS_isInit()) throw Exception("PhysFS is not initialized.");
545
546 const char* dir = PHYSFS_getRealDir(filename.c_str());
547
548 if (dir == nullptr) throw Exception("File does not exist on disk.");
549
550 return std::string(dir);
551}
552
553bool Filesystem::getInfo(std::string filepath, Info &info) const {
554 if (!PHYSFS_isInit()) return false;
555
556 PHYSFS_Stat stat = {};
557 if (!PHYSFS_stat(filepath.c_str(), &stat)) return false;
558
559 info.size = (int64_t)stat.filesize;
560 info.modtime = (int64_t)stat.modtime;
561
562 if (stat.filetype == PHYSFS_FILETYPE_REGULAR)
563 info.type = "file";
564 else if (stat.filetype == PHYSFS_FILETYPE_DIRECTORY)
565 info.type = "directory";
566 else if (stat.filetype == PHYSFS_FILETYPE_SYMLINK)
567 info.type = "symlink";
568 else
569 info.type = "other";
570
571 return true;
572}
573
575 if (!PHYSFS_isInit()) return false;
576
577 if (PHYSFS_getWriteDir() == 0 && !setupWriteDirectory()) return false;
578
579 if (!PHYSFS_mkdir(dir.c_str())) return false;
580
581 return true;
582}
583
584bool Filesystem::remove(std::string file) {
585 if (!PHYSFS_isInit()) return false;
586
587 if (PHYSFS_getWriteDir() == 0 && !setupWriteDirectory()) return false;
588
589 if (!PHYSFS_delete(file.c_str())) return false;
590
591 return true;
592}
593
594FileData *Filesystem::read(std::string filename, int64_t size) const {
595 physfs::File file(filename);
596
597 file.open("rb");
598
599 // close() is called in the File destructor.
600 return file.read(size);
601}
602
603void Filesystem::write(std::string filename, const void *data, int64_t size) const {
604 physfs::File file(filename);
605
606 file.open("wb");
607
608 // close() is called in the File destructor.
609 if (!file.write(data, size)) throw eve::Exception("Data could not be written.");
610}
611
612void Filesystem::append(std::string filename, const void *data, int64_t size) const {
613 physfs::File file(filename);
614
615 file.open("ab");
616
617 // close() is called in the File destructor.
618 if (!file.write(data, size)) throw eve::Exception("Data could not be written.");
619}
620
621std::vector<std::string> Filesystem::getDirectoryItems(std::string dir) {
622 std::vector<std::string> items;
623 if (!PHYSFS_isInit()) return items;
624
625 char **rc = PHYSFS_enumerateFiles(dir.c_str());
626
627 if (rc == nullptr) return items;
628
629 for (char **i = rc; *i != 0; i++) items.push_back(*i);
630
631 PHYSFS_freeList(rc);
632 return items;
633}
634
636 if (!PHYSFS_isInit()) return;
637
638 PHYSFS_permitSymbolicLinks(enable ? 1 : 0);
639}
640
642 if (!PHYSFS_isInit()) return false;
643
644 return PHYSFS_symbolicLinksPermitted() != 0;
645}
646
647std::vector<std::string> &Filesystem::getRequirePath() { return requirePath; }
648
649std::vector<std::string> &Filesystem::getCRequirePath() { return cRequirePath; }
650
651void Filesystem::allowMountingForPath(const std::string &path) {
652 if (std::find(allowedMountPaths.begin(), allowedMountPaths.end(), path) == allowedMountPaths.end())
653 allowedMountPaths.push_back(path);
654}
655
656namespace {
657
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;
663#endif
664 return false;
665}
666
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;
672 return a + "/" + b;
673}
674
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 "/";
679 return path.substr(0, pos);
680}
681
682std::string baseName(const std::string &path) {
683 auto pos = path.find_last_of("/\\");
684 if (pos == std::string::npos) return path;
685 return path.substr(pos + 1);
686}
687
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))
691 return true;
692 return path.find("/..") != std::string::npos || path.find("\\..") != std::string::npos;
693}
694
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()));
698}
699
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());
703}
704
705} // namespace
706
707FileWatch &Filesystem::watchers() {
708 if (!fileWatch_) fileWatch_ = std::make_unique<FileWatch>();
709 return *fileWatch_;
710}
711
712bool Filesystem::resolveWatchTarget(const std::string &path, std::string &realDir,
713 std::string &filterName, std::string &reportPath) {
714 reportPath = path;
715 filterName.clear();
716 realDir.clear();
717 if (path.empty()) return false;
718
719 // "." / "" are not reliable PhysFS paths — watch the real working directory.
720 if (path == "." || path == "./") {
721 reportPath = ".";
722 realDir = getWorkingDirectory();
723 filterName.clear();
724 return isRealDirectory(realDir);
725 }
726
727 if (looksAbsolute(path)) {
728 if (isRealDirectory(path)) {
729 realDir = path;
730 return true;
731 }
732 realDir = parentDir(path);
733 filterName = baseName(path);
734 return isRealDirectory(realDir);
735 }
736
737 // PhysFS rejects `..`. Resolve parent-relative paths against the real cwd
738 // so `fs.watch("..")` / `hot.watchTree("..")` can see a parent workflow.
739 if (hasParentSegment(path)) {
740 std::error_code ec;
741 auto candidate = std::filesystem::weakly_canonical(
742 pathFromUtf8(getWorkingDirectory()) / pathFromUtf8(path), ec);
743 if (!ec) {
744 const std::string full = pathToUtf8(candidate);
745 if (isRealDirectory(full)) {
746 realDir = full;
747 filterName.clear();
748 return true;
749 }
750 realDir = parentDir(full);
751 filterName = baseName(full);
752 return isRealDirectory(realDir);
753 }
754 }
755
756 Info info{};
757 if (getInfo(path, info)) {
758 std::string root;
759 try {
761 } catch (...) {
762 return false;
763 }
764 std::string full = joinPath(root, path);
765 if (info.type == "directory") {
766 realDir = full;
767 filterName.clear();
768 return isRealDirectory(realDir);
769 }
770 realDir = parentDir(full);
771 filterName = baseName(full);
772 return isRealDirectory(realDir);
773 }
774
775 std::string parent = parentDir(path);
776 if (parent == ".") parent.clear();
777 if (!parent.empty()) {
778 Info pinfo{};
779 if (getInfo(parent, pinfo) && pinfo.type == "directory") {
780 std::string root;
781 try {
783 } catch (...) {
784 return false;
785 }
786 realDir = joinPath(root, parent);
787 filterName = baseName(path);
788 return isRealDirectory(realDir);
789 }
790 }
791
792 // Virtual path not in VFS yet (e.g. new file): watch under cwd, not save dir.
793 {
794 std::string workingDir = getWorkingDirectory();
795 if (!workingDir.empty() && isRealDirectory(workingDir)) {
796 if (parent.empty()) {
797 realDir = workingDir;
798 filterName = baseName(path);
799 return true;
800 }
801 }
802 }
803
804 std::string save = getSaveDirectory();
805 if (!save.empty() && isRealDirectory(save)) {
806 realDir = save;
807 filterName = baseName(path);
808 return true;
809 }
810 return false;
811}
812
813bool Filesystem::watch(std::string path) {
814 std::string realDir, filter, report;
815 if (!resolveWatchTarget(path, realDir, filter, report)) return false;
816 return watchers().add(realDir, filter, report, 1);
817}
818
819eve::Result<void> Filesystem::watchRealDirectory(std::string realDir, std::string reportPath) {
820 if (realDir.empty() || reportPath.empty()) {
823 "watchRealDirectory requires a real directory and a report path"));
824 }
825 if (!isRealDirectory(realDir)) {
827 eve::DiagnosticCode::NotFound, "watchRealDirectory path is not a directory", realDir));
828 }
829 if (!watchers().add(std::move(realDir), "", std::move(reportPath), 1)) {
831 eve::DiagnosticCode::Failed, "watchRealDirectory could not add an OS watcher"));
832 }
834}
835
836bool Filesystem::unwatch(std::string path) { return watchers().remove(path); }
837
839 if (fileWatch_) fileWatch_->clear();
840}
841
843 if (!fileWatch_) return 0;
844 return fileWatch_->count();
845}
846
848 if (!fileWatch_) return "";
850 if (!fileWatch_->poll(ev)) {
851 lastWatchPath_.clear();
852 lastWatchRealPath_.clear();
853 return "";
854 }
855 lastWatchPath_ = ev.path;
856 lastWatchRealPath_ = ev.realPath;
857 return ev.kind;
858}
859
860std::string Filesystem::getLastWatchPath() const { return lastWatchPath_; }
861std::string Filesystem::getLastWatchRealPath() const { return lastWatchRealPath_; }
862
863} // namespace physfs
864} // namespace filesystem
865} // namespace eve
int root
Definition AnimSmr.cpp:119
ActiveSource owned
glm::vec4 p[6]
Stable, structured diagnostics shared by engine modules.
EvpackChunkInput input
Definition Evpack.cpp:170
#define EVENGINE_MAX_PATH
Definition Filesystem.h:37
#define EVENGINE_PATH_SEPARATOR
Definition Filesystem.h:36
#define EVENGINE_APPDATA_PREFIX
Definition Filesystem.h:33
#define EVENGINE_APPDATA_FOLDER
Definition Filesystem.h:34
std::int32_t c
float length
const ColourScope * parent
MeleePoint3 b
Definition MeleeHit.cpp:41
MeleePoint3 a
Definition MeleeHit.cpp:40
#define getModInst(N, T)
Definition Module.h:40
std::string path
Definition PlayHost.cpp:111
std::string file
Object::Ptr value
std::string filter
std::string text
ScriptStructure out
std::string_view source
float size
Definition TreeMesh.cpp:158
V3 dir
Definition TreeMesh.cpp:151
Data public API.
Definition Data.h:8
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.
Definition Exception.h:13
Move-only operation result carrying either a value or Status.
Definition Result.h:176
static Result success(T value)
Construct a successful result owning value.
Definition Result.h:185
static Result failure(Status status)
Construct a failed result from a structured status.
Definition Result.h:196
Data buffer paired with a filename (used for type identification).
Definition FileData.h:14
bool add(const std::string &realDir, const std::string &filterName, const std::string &reportPath, int scanInterval=1)
Definition FileWatch.cpp:74
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.
Definition File.h:14
virtual bool isAndroidSaveExternal() const
Gets whether the Android save is external. Returns a bool.
Definition Filesystem.h:109
virtual bool isRealDirectory(const std::string &path) const
Gets whether the given full (OS-dependent) path is a directory.
File public API.
Definition File.h:17
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.
Definition RoadBake.cpp:31
Build metadata (engine git commit, build time, third-party version).
Definition Build.cpp:16
glm::uvec4 info