19#elif defined(__HAIKU__)
21#include <storage/FindDirectory.h>
39static const char *
const _subdirs[] = {
42 "save" PATHSEP
"autosave" PATHSEP,
44 "scenario" PATHSEP
"heightmap" PATHSEP,
51 "ai" PATHSEP
"library" PATHSEP,
53 "game" PATHSEP
"library" PATHSEP,
55 "social_integration" PATHSEP,
67std::vector<Searchpath> _valid_searchpaths;
68std::array<TarList, NUM_SUBDIRS> _tar_list;
81static void FillValidSearchPaths(
bool only_local_path)
83 _valid_searchpaths.clear();
85 std::set<std::string> seen{};
86 for (
Searchpath sp = SP_FIRST_DIR; sp < NUM_SEARCHPATHS; sp++) {
89 if (only_local_path) {
104 _valid_searchpaths.emplace_back(sp);
112 _valid_searchpaths.insert(_valid_searchpaths.begin(),
SP_WORKING_DIR);
125 return f.has_value();
136 return std::filesystem::exists(
OTTD2FS(filename), ec);
150 std::string buf = FioGetDirectory(sp, subdir);
167 assert(sp < NUM_SEARCHPATHS);
176 std::string ret = FioGetDirectory(sp, subdir);
184static std::optional<FileHandle> FioFOpenFileSp(
const std::string &filename,
const char *mode,
Searchpath sp,
Subdirectory subdir,
size_t *filesize)
192 MultiByteToWideChar(CP_ACP, 0, mode, -1, Lmode,
static_cast<int>(std::size(Lmode)));
208 if (f.has_value() && filesize !=
nullptr) {
210 fseek(*f, 0, SEEK_END);
211 *filesize = ftell(*f);
212 fseek(*f, 0, SEEK_SET);
227 if (!f.has_value())
return std::nullopt;
229 if (fseek(*f, entry.position, SEEK_SET) < 0) {
233 if (filesize !=
nullptr) *filesize = entry.size;
245 std::optional<FileHandle> f = std::nullopt;
249 f = FioFOpenFileSp(filename, mode, sp, subdir, filesize);
254 if (!f.has_value() && mode[0] ==
'r' && subdir !=
NO_DIRECTORY) {
256 std::string resolved_name = filename;
257 strtolower(resolved_name);
260 std::istringstream ss(resolved_name);
261 std::vector<std::string> tokens;
263 while (std::getline(ss, token, PATHSEPCHAR)) {
265 if (tokens.size() < 2)
return std::nullopt;
267 }
else if (token ==
".") {
271 tokens.push_back(token);
275 resolved_name.clear();
277 for (
const std::string &token : tokens) {
279 resolved_name += PATHSEP;
281 resolved_name += token;
285 TarFileList::iterator it = _tar_filelist[subdir].find(resolved_name);
286 if (it != _tar_filelist[subdir].end()) {
297 if (f.has_value())
break;
320 std::error_code error_code;
321 std::filesystem::create_directories(
OTTD2FS(name), error_code);
331 std::filesystem::path path =
OTTD2FS(filename);
332 std::error_code error_code;
333 std::filesystem::remove(path, error_code);
335 Debug(misc, 0,
"Removing {} failed: {}", filename, error_code.message());
349 if (buf.empty())
return;
351 if (buf.back() != PATHSEPCHAR) buf.push_back(PATHSEPCHAR);
361 for (
char &c : name) {
364#if (PATHSEPCHAR != '/')
366 if (c ==
'/') c = PATHSEPCHAR;
378 _tar_filelist[sd].clear();
379 _tar_list[sd].clear();
380 uint num = this->
Scan(
".tar", sd,
false);
387 Debug(misc, 2,
"Scanning for tars");
408 Debug(misc, 2,
"Scan complete, found {} files", num);
421 return this->
AddFile(filename, 0);
436 return StrMakeValid(std::string_view(buffer.begin(), buffer.end()));
439bool TarScanner::AddFile(
const std::string &filename,
size_t, [[maybe_unused]]
const std::string &tar_filename)
442 assert(tar_filename.empty());
467 TarList::iterator it = _tar_list[this->
subdir].find(filename);
468 if (it != _tar_list[this->subdir].end())
return false;
475 if (!of.has_value())
return false;
478 _tar_list[this->
subdir][filename] = std::string{};
480 std::string filename_base =
FS2OTTD(std::filesystem::path(
OTTD2FS(filename)).filename());
484 size_t num = 0, pos = 0;
488 memset(&empty[0], 0,
sizeof(empty));
491 size_t num_bytes_read = fread(&th, 1, 512, f);
492 if (num_bytes_read != 512)
break;
493 pos += num_bytes_read;
496 if (strncmp(th.magic,
"ustar", 5) != 0 && memcmp(&th.magic, &empty[0], 512 - offsetof(TarHeader, magic)) != 0) {
498 if (memcmp(&th, &empty[0], 512) == 0)
continue;
500 Debug(misc, 0,
"The file '{}' isn't a valid tar-file", filename);
507 if (th.prefix[0] !=
'\0') {
520 auto [_, err] = std::from_chars(size.data(), size.data() + size.size(), skip, 8);
521 if (err != std::errc()) {
522 Debug(misc, 0,
"The file '{}' has an invalid size for '{}'", filename, name);
528 switch (th.typeflag) {
531 if (name.empty())
break;
535 entry.tar_filename = filename;
537 entry.position = pos;
542 Debug(misc, 6,
"Found file in tar: {} ({} bytes, {} offset)", name, skip, pos);
543 if (_tar_filelist[this->subdir].insert(TarFileList::value_type(filename_base + PATHSEPCHAR + name, entry)).second) num++;
552 Debug(misc, 5,
"Ignoring link in tar: {} -> {}", name, link);
561 Debug(misc, 6,
"Found dir in tar: {}", name);
562 if (_tar_list[this->subdir][filename].empty()) _tar_list[this->
subdir][filename] = name;
571 skip =
Align(skip, 512);
572 if (fseek(f, skip, SEEK_CUR) < 0) {
573 Debug(misc, 0,
"The file '{}' can't be read as a valid tar-file", filename);
579 Debug(misc, 4,
"Found tar '{}' with {} new files", filename, num);
593 TarList::iterator it = _tar_list[subdir].find(tar_filename);
595 if (it == _tar_list[subdir].end())
return false;
597 const auto &dirname = (*it).second;
600 if (dirname.empty()) {
601 Debug(misc, 3,
"Extracting {} failed; archive rejected, the contents must be in a sub directory", tar_filename);
605 std::string filename = tar_filename;
606 auto p = filename.find_last_of(PATHSEPCHAR);
608 if (p == std::string::npos)
return false;
610 filename.replace(p + 1, std::string::npos, dirname);
611 Debug(misc, 8,
"Extracting {} to directory {}", tar_filename, filename);
614 for (
auto &it2 : _tar_filelist[subdir]) {
615 if (tar_filename != it2.second.tar_filename)
continue;
618 std::string_view name = it2.first;
619 name.remove_prefix(name.find_first_of(PATHSEPCHAR) + 1);
620 filename.replace(p + 1, std::string::npos, name);
622 Debug(misc, 9,
" extracting {}", filename);
627 if (!in.has_value()) {
628 Debug(misc, 6,
"Extracting {} failed; could not open {}", filename, tar_filename);
634 if (!out.has_value()) {
635 Debug(misc, 6,
"Extracting {} failed; could not open {}", filename, filename);
642 for (; to_copy != 0; to_copy -= read) {
643 read = fread(buffer, 1, std::min(to_copy,
lengthof(buffer)), *in);
644 if (read <= 0 || fwrite(buffer, 1, read, *out) != read)
break;
648 Debug(misc, 6,
"Extracting {} failed; still {} bytes to copy", filename, to_copy);
653 Debug(misc, 9,
" extraction successful");
675 std::string path = exe;
678 for (
size_t pos = path.find_first_of(
'.'); pos != std::string::npos; pos = path.find_first_of(
'.', pos + 1)) {
686 size_t pos = path.find_last_of(PATHSEPCHAR);
687 if (pos == std::string::npos)
return false;
691 if (chdir(path.c_str()) != 0) {
692 Debug(misc, 0,
"Directory with the binary does not exist?");
735 find_directory(B_USER_SETTINGS_DIRECTORY, &path);
736 return std::string(path.Path());
738 const char *home_env = std::getenv(
"HOME");
739 if (home_env !=
nullptr)
return std::string(home_env);
741 const struct passwd *pw = getpwuid(getuid());
742 if (pw !=
nullptr)
return std::string(pw->pw_dir);
756 const char *xdg_data_home = std::getenv(
"XDG_DATA_HOME");
757 if (xdg_data_home !=
nullptr) {
760 tmp += PERSONAL_DIR[0] ==
'.' ? &PERSONAL_DIR[1] : PERSONAL_DIR;
764 tmp +=
"content_download";
767 }
else if (!homedir.empty()) {
769 tmp += PATHSEP
".local" PATHSEP
"share" PATHSEP;
770 tmp += PERSONAL_DIR[0] ==
'.' ? &PERSONAL_DIR[1] : PERSONAL_DIR;
774 tmp +=
"content_download";
783#if !defined(WITH_PERSONAL_DIR)
786 if (!homedir.empty()) {
793 tmp +=
"content_download";
802#if defined(WITH_SHARED_DIR)
811 if (getcwd(cwd, MAX_PATH) ==
nullptr) *cwd =
'\0';
823 if (end == std::string::npos) {
836 if (getcwd(buf,
lengthof(buf)) ==
nullptr) {
847 if (cwd[0] !=
'\0') {
849 if (chdir(cwd) != 0) {
850 Debug(misc, 0,
"Failed to return to working directory!");
854#if !defined(GLOBAL_DATA_DIR)
857 tmp = GLOBAL_DATA_DIR;
862extern void CocoaSetApplicationBundleDir();
863 CocoaSetApplicationBundleDir();
882 FillValidSearchPaths(only_local_path);
885 std::string config_home;
887 const char *xdg_config_home = std::getenv(
"XDG_CONFIG_HOME");
888 if (xdg_config_home !=
nullptr) {
889 config_home = xdg_config_home;
890 config_home += PATHSEP;
891 config_home += PERSONAL_DIR[0] ==
'.' ? &PERSONAL_DIR[1] : PERSONAL_DIR;
892 }
else if (!homedir.empty()) {
894 config_home = homedir;
895 config_home += PATHSEP
".config" PATHSEP;
896 config_home += PERSONAL_DIR[0] ==
'.' ? &PERSONAL_DIR[1] : PERSONAL_DIR;
906 std::string config_dir;
911 if (!personal_dir.empty()) {
912 auto end = personal_dir.find_last_of(PATHSEPCHAR);
913 if (end != std::string::npos) personal_dir.erase(end + 1);
914 config_dir = personal_dir;
918 config_dir = config_home;
920 static const Searchpath new_openttd_cfg_order[] = {
925 for (
const auto &searchpath : new_openttd_cfg_order) {
936 Debug(misc, 1,
"{} found as config directory", config_dir);
939 extern std::string _hotkeys_file;
940 _hotkeys_file = config_dir +
"hotkeys.cfg";
951 if (config_dir == config_home) {
955 if (only_local_path) {
970#if defined(WITH_PERSONAL_DIR)
977 SAVE_DIR,
AUTOSAVE_DIR,
SCENARIO_DIR,
HEIGHTMAP_DIR,
BASESET_DIR,
NEWGRF_DIR,
AI_DIR,
AI_LIBRARY_DIR,
GAME_DIR,
GAME_LIBRARY_DIR,
SCREENSHOT_DIR,
SOCIAL_INTEGRATION_DIR
980 for (
const auto &default_subdir : default_subdirs) {
988 FillValidSearchPaths(only_local_path);
992 for (
const auto &subdir : subdirs) {
1006 for (
auto &c : filename) {
1010 case ':':
case '\\':
case '*':
case '?':
case '/':
1011 case '<':
case '>':
case '|':
case '"':
1026std::unique_ptr<char[]>
ReadFileToMem(
const std::string &filename,
size_t &lenp,
size_t maxsize)
1029 if (!in.has_value())
return nullptr;
1031 fseek(*in, 0, SEEK_END);
1032 size_t len = ftell(*in);
1033 fseek(*in, 0, SEEK_SET);
1034 if (len > maxsize)
return nullptr;
1036 std::unique_ptr<char[]> mem = std::make_unique<char[]>(len + 1);
1039 if (fread(mem.get(), len, 1, *in) != 1)
return nullptr;
1053 if (extension.empty())
return true;
1054 if (filename.length() < extension.length())
return false;
1056 std::string_view filename_sv = filename;
1057 return StrCompareIgnoreCase(extension, filename_sv.substr(filename_sv.length() - extension.length())) == 0;
1069static uint
ScanPath(
FileScanner *fs, std::string_view extension,
const std::filesystem::path &path,
size_t basepath_length,
bool recursive)
1073 std::error_code error_code;
1074 for (
const auto &dir_entry : std::filesystem::directory_iterator(path, error_code)) {
1075 if (dir_entry.is_directory()) {
1076 if (!recursive)
continue;
1077 num +=
ScanPath(fs, extension, dir_entry.path(), basepath_length, recursive);
1078 }
else if (dir_entry.is_regular_file()) {
1079 std::string file =
FS2OTTD(dir_entry.path());
1081 if (fs->
AddFile(file, basepath_length, {})) num++;
1085 Debug(misc, 9,
"Unable to read directory {}: {}", path.string(), error_code.message());
1125 std::string path = FioGetDirectory(sp, sd);
1126 num +=
ScanPath(
this, extension,
OTTD2FS(path), path.size(), recursive);
1130 for (
const auto &tar : _tar_filelist[sd]) {
1131 num +=
ScanTar(
this, extension, tar);
1157uint
FileScanner::Scan(
const std::string_view extension,
const std::string &directory,
bool recursive)
1159 std::string path(directory);
1161 return ScanPath(
this, extension,
OTTD2FS(path), path.size(), recursive);
1171std::optional<FileHandle>
FileHandle::Open(
const std::string &filename,
const std::string &mode)
1175 auto f = _wfopen(
OTTD2FS(filename).c_str(),
OTTD2FS(mode).c_str());
1177 auto f = fopen(filename.c_str(), mode.c_str());
1180 if (f ==
nullptr)
return std::nullopt;
static std::optional< FileHandle > Open(const std::string &filename, const std::string &mode)
Open an RAII file handle if possible.
Helper for scanning for files with a given name.
uint Scan(std::string_view extension, Subdirectory sd, bool tars=true, bool recursive=true)
Scan for files with the given extension in the given search path.
virtual bool AddFile(const std::string &filename, size_t basepath_length, const std::string &tar_filename)=0
Add a file with the given filename.
Subdirectory subdir
The current sub directory we are searching through.
Helper for scanning for files with tar as extension.
Mode
The mode of tar scanning.
@ NEWGRF
Scan for non-base sets.
@ BASESET
Scan for base sets.
@ GAME
Scan for game scripts.
@ SCENARIO
Scan for scenarios and heightmaps.
@ AI
Scan for AIs and its libraries.
uint DoScan(Subdirectory sd)
Perform the scanning of a particular subdirectory.
bool AddFile(const std::string &filename, size_t basepath_length, const std::string &tar_filename={}) override
Add a file with the given filename.
Functions related to debugging.
#define Debug(category, level, format_string,...)
Ouptut a line of debugging information.
std::string _log_file
Filename to reroute output of a forked OpenTTD to.
std::string FioFindFullPath(Subdirectory subdir, const std::string &filename)
Find a path to the filename in one of the search directories.
bool ExtractTar(const std::string &tar_filename, Subdirectory subdir)
Extract the tar with the given filename in the directory where the tar resides.
void DeterminePaths(const char *exe, bool only_local_path)
Acquire the base paths (personal dir and game data dir), fill all other paths (save dir,...
static bool IsValidSearchPath(Searchpath sp)
Checks whether the given search path is a valid search path.
bool FioRemove(const std::string &filename)
Remove a file.
void SanitizeFilename(std::string &filename)
Sanitizes a filename, i.e.
static uint ScanPath(FileScanner *fs, std::string_view extension, const std::filesystem::path &path, size_t basepath_length, bool recursive)
Scan a single directory (and recursively its children) and add any graphics sets that are found.
void AppendPathSeparator(std::string &buf)
Appends, if necessary, the path separator character to the end of the string.
std::string _personal_dir
custom directory for personal settings, saves, newgrf, etc.
static bool _do_scan_working_directory
Whether the working directory should be scanned.
static std::string GetHomeDir()
Gets the home directory of the user.
bool FioCheckFileExists(const std::string &filename, Subdirectory subdir)
Check whether the given file exists.
static void SimplifyFileName(std::string &name)
Simplify filenames from tars.
static bool MatchesExtension(std::string_view extension, const std::string &filename)
Helper to see whether a given filename matches the extension.
void FioCreateDirectory(const std::string &name)
Create a directory with the given name If the parent directory does not exist, it will try to create ...
static uint ScanTar(FileScanner *fs, std::string_view extension, const TarFileList::value_type &tar)
Scan the given tar and add graphics sets when it finds one.
static bool ChangeWorkingDirectoryToExecutable(const char *exe)
Changes the working directory to the path of the give executable.
bool FileExists(const std::string &filename)
Test whether the given filename exists.
std::array< std::string, NUM_SEARCHPATHS > _searchpaths
The search paths OpenTTD could search through.
static std::optional< FileHandle > FioFOpenFileTar(const TarFileListEntry &entry, size_t *filesize)
Opens a file from inside a tar archive.
static std::string ExtractString(std::span< char > buffer)
Helper to extract a string for the tar header.
std::string _highscore_file
The file to store the highscore data in.
bool DoScanWorkingDirectory()
Whether we should scan the working directory.
std::string _config_file
Configuration file of OpenTTD.
void DetermineBasePaths(const char *exe)
Determine the base (personal dir and game data dir) paths.
std::optional< FileHandle > FioFOpenFile(const std::string &filename, const char *mode, Subdirectory subdir, size_t *filesize)
Opens a OpenTTD file somewhere in a personal or global directory.
std::unique_ptr< char[]> ReadFileToMem(const std::string &filename, size_t &lenp, size_t maxsize)
Load a file into memory.
Functions for Standard In/Out file operations.
void AppendPathSeparator(std::string &buf)
Appends, if necessary, the path separator character to the end of the string.
Searchpath
Types of searchpaths OpenTTD might use.
@ SP_SHARED_DIR
Search in the shared directory, like 'Shared Files' under Windows.
@ SP_INSTALLATION_DIR
Search in the installation directory.
@ SP_AUTODOWNLOAD_PERSONAL_DIR_XDG
Search within the autodownload directory located in the personal directory (XDG variant)
@ SP_BINARY_DIR
Search in the directory where the binary resides.
@ SP_AUTODOWNLOAD_PERSONAL_DIR
Search within the autodownload directory located in the personal directory.
@ SP_PERSONAL_DIR
Search in the personal directory.
@ SP_WORKING_DIR
Search in the working directory.
@ SP_APPLICATION_BUNDLE_DIR
Search within the application bundle.
@ SP_AUTODOWNLOAD_DIR
Search within the autodownload directory.
Subdirectory
The different kinds of subdirectories OpenTTD uses.
@ OLD_DATA_DIR
Old subdirectory for the data.
@ NO_DIRECTORY
A path without any base directory.
@ AI_LIBRARY_DIR
Subdirectory for all AI libraries.
@ SCREENSHOT_DIR
Subdirectory for all screenshots.
@ SOCIAL_INTEGRATION_DIR
Subdirectory for all social integration plugins.
@ GAME_LIBRARY_DIR
Subdirectory for all GS libraries.
@ AI_DIR
Subdirectory for all AI files.
@ OLD_GM_DIR
Old subdirectory for the music.
@ SCENARIO_DIR
Base directory for all scenarios.
@ BASE_DIR
Base directory for all subdirectories.
@ SAVE_DIR
Base directory for all savegames.
@ NUM_SUBDIRS
Number of subdirectories.
@ HEIGHTMAP_DIR
Subdirectory of scenario for heightmaps.
@ NEWGRF_DIR
Subdirectory for all NewGRFs.
@ AUTOSAVE_DIR
Subdirectory of save for autosaves.
@ BASESET_DIR
Subdirectory for all base data (base sets, intro game)
@ GAME_DIR
Subdirectory for all game scripts.
Declarations for savegames operations.
constexpr T Align(const T x, uint n)
Return the smallest multiple of n equal or greater than x.
A number of safeguards to prevent using unsafe methods.
std::string _secrets_file
Secrets configuration file of OpenTTD.
std::string _favs_file
Picker favourites configuration file of OpenTTD.
std::string _private_file
Private configuration file of OpenTTD.
Base for loading sprites.
Definition of base types and functions in a cross-platform compatible way.
#define lengthof(array)
Return the length of an fixed size array.
static void StrMakeValid(T &dst, const char *str, const char *last, StringValidationSettings settings)
Copies the valid (UTF-8) characters from str up to last to the dst.
bool StrEqualsIgnoreCase(const std::string_view str1, const std::string_view str2)
Compares two string( view)s for equality, while ignoring the case of the characters.
int StrCompareIgnoreCase(const std::string_view str1, const std::string_view str2)
Compares two string( view)s, while ignoring the case of the characters.
void StrTrimInPlace(std::string &str)
Trim the spaces from given string in place, i.e.
Functions related to low-level strings.
Structs, typedefs and macros used for TAR file handling.
std::wstring OTTD2FS(const std::string &name)
Convert from OpenTTD's encoding to a wide string.
std::string FS2OTTD(const std::wstring &name)
Convert to OpenTTD's encoding from a wide string.
std::string _windows_file
Config file to store WindowDesc.