Codechange: Return pair from instead of optional out parameter. (#13166)
[openttd-github.git] / src / fios.cpp
blob0cdae26f718efa8f13e210a1eb2f0200ccde51b9
1 /*
2 * This file is part of OpenTTD.
3 * OpenTTD is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, version 2.
4 * OpenTTD is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
5 * See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with OpenTTD. If not, see <http://www.gnu.org/licenses/>.
6 */
8 /**
9 * @file fios.cpp
10 * This file contains functions for building file lists for the save/load dialogs.
13 #include "stdafx.h"
14 #include "3rdparty/md5/md5.h"
15 #include "fileio_func.h"
16 #include "fios.h"
17 #include "network/network_content.h"
18 #include "screenshot.h"
19 #include "string_func.h"
20 #include "strings_func.h"
21 #include "tar_type.h"
22 #include <sys/stat.h>
23 #include <charconv>
24 #include <filesystem>
26 #include "table/strings.h"
28 #include "safeguards.h"
30 /* Variables to display file lists */
31 static std::string *_fios_path = nullptr;
32 SortingBits _savegame_sort_order = SORT_BY_DATE | SORT_DESCENDING;
34 /* OS-specific functions are taken from their respective files (win32/unix .c) */
35 extern bool FiosIsRoot(const std::string &path);
36 extern bool FiosIsHiddenFile(const std::filesystem::path &path);
37 extern void FiosGetDrives(FileList &file_list);
39 /* get the name of an oldstyle savegame */
40 extern std::string GetOldSaveGameName(const std::string &file);
42 /**
43 * Compare two FiosItem's. Used with sort when sorting the file list.
44 * @param other The FiosItem to compare to.
45 * @return for ascending order: returns true if da < db. Vice versa for descending order.
47 bool FiosItem::operator< (const FiosItem &other) const
49 int r = false;
51 if ((_savegame_sort_order & SORT_BY_NAME) == 0 && (*this).mtime != other.mtime) {
52 r = ClampTo<int32_t>(this->mtime - other.mtime);
53 } else {
54 r = StrNaturalCompare((*this).title, other.title);
56 if (r == 0) return false;
57 return (_savegame_sort_order & SORT_DESCENDING) ? r > 0 : r < 0;
60 /**
61 * Construct a file list with the given kind of files, for the stated purpose.
62 * @param abstract_filetype Kind of files to collect.
63 * @param fop Purpose of the collection, either #SLO_LOAD or #SLO_SAVE.
64 * @param show_dirs Whether to show directories.
66 void FileList::BuildFileList(AbstractFileType abstract_filetype, SaveLoadOperation fop, bool show_dirs)
68 this->clear();
70 assert(fop == SLO_LOAD || fop == SLO_SAVE);
71 switch (abstract_filetype) {
72 case FT_NONE:
73 break;
75 case FT_SAVEGAME:
76 FiosGetSavegameList(fop, show_dirs, *this);
77 break;
79 case FT_SCENARIO:
80 FiosGetScenarioList(fop, show_dirs, *this);
81 break;
83 case FT_HEIGHTMAP:
84 FiosGetHeightmapList(fop, show_dirs, *this);
85 break;
87 case FT_TOWN_DATA:
88 FiosGetTownDataList(fop, show_dirs, *this);
89 break;
91 default:
92 NOT_REACHED();
96 /**
97 * Find file information of a file by its name from the file list.
98 * @param file The filename to return information about. Can be the actual name
99 * or a numbered entry into the filename list.
100 * @return The information on the file, or \c nullptr if the file is not available.
102 const FiosItem *FileList::FindItem(const std::string_view file)
104 for (const auto &it : *this) {
105 const FiosItem *item = &it;
106 if (file == item->name) return item;
107 if (file == item->title) return item;
110 /* If no name matches, try to parse it as number */
111 char *endptr;
112 int i = std::strtol(file.data(), &endptr, 10);
113 if (file.data() == endptr || *endptr != '\0') i = -1;
115 if (IsInsideMM(i, 0, this->size())) return &this->at(i);
117 /* As a last effort assume it is an OpenTTD savegame and
118 * that the ".sav" part was not given. */
119 std::string long_file(file);
120 long_file += ".sav";
121 for (const auto &it : *this) {
122 const FiosItem *item = &it;
123 if (long_file == item->name) return item;
124 if (long_file == item->title) return item;
127 return nullptr;
131 * Get the current path/working directory.
133 std::string FiosGetCurrentPath()
135 return *_fios_path;
139 * Browse to a new path based on the passed \a item, starting at #_fios_path.
140 * @param *item Item telling us what to do.
141 * @return \c true when the path got changed.
143 bool FiosBrowseTo(const FiosItem *item)
145 switch (item->type) {
146 case FIOS_TYPE_DRIVE:
147 #if defined(_WIN32)
148 assert(_fios_path != nullptr);
149 *_fios_path = std::string{ item->title, 0, 1 } + ":" PATHSEP;
150 #endif
151 break;
153 case FIOS_TYPE_INVALID:
154 break;
156 case FIOS_TYPE_PARENT: {
157 assert(_fios_path != nullptr);
158 auto s = _fios_path->find_last_of(PATHSEPCHAR);
159 if (s != std::string::npos && s != 0) {
160 _fios_path->erase(s); // Remove last path separator character, so we can go up one level.
163 s = _fios_path->find_last_of(PATHSEPCHAR);
164 if (s != std::string::npos) {
165 _fios_path->erase(s + 1); // go up a directory
167 break;
170 case FIOS_TYPE_DIR:
171 assert(_fios_path != nullptr);
172 *_fios_path += item->name;
173 *_fios_path += PATHSEP;
174 break;
176 case FIOS_TYPE_DIRECT:
177 assert(_fios_path != nullptr);
178 *_fios_path = item->name;
179 break;
181 case FIOS_TYPE_FILE:
182 case FIOS_TYPE_OLDFILE:
183 case FIOS_TYPE_SCENARIO:
184 case FIOS_TYPE_OLD_SCENARIO:
185 case FIOS_TYPE_PNG:
186 case FIOS_TYPE_BMP:
187 case FIOS_TYPE_JSON:
188 return false;
191 return true;
195 * Construct a filename from its components in destination buffer \a buf.
196 * @param path Directory path, may be \c nullptr.
197 * @param name Filename.
198 * @param ext Filename extension (use \c "" for no extension).
199 * @return The completed filename.
201 static std::string FiosMakeFilename(const std::string *path, const char *name, const char *ext)
203 std::string buf;
205 if (path != nullptr) {
206 buf = *path;
207 /* Remove trailing path separator, if present */
208 if (!buf.empty() && buf.back() == PATHSEPCHAR) buf.pop_back();
211 /* Don't append the extension if it is already there */
212 const char *period = strrchr(name, '.');
213 if (period != nullptr && StrEqualsIgnoreCase(period, ext)) ext = "";
215 return buf + PATHSEP + name + ext;
219 * Make a save game or scenario filename from a name.
220 * @param name Name of the file.
221 * @return The completed filename.
223 std::string FiosMakeSavegameName(const char *name)
225 const char *extension = (_game_mode == GM_EDITOR) ? ".scn" : ".sav";
227 return FiosMakeFilename(_fios_path, name, extension);
231 * Construct a filename for a height map.
232 * @param name Filename.
233 * @return The completed filename.
235 std::string FiosMakeHeightmapName(const char *name)
237 std::string ext(".");
238 ext += GetCurrentScreenshotExtension();
240 return FiosMakeFilename(_fios_path, name, ext.c_str());
244 * Delete a file.
245 * @param name Filename to delete.
246 * @return Whether the file deletion was successful.
248 bool FiosDelete(const char *name)
250 return FioRemove(FiosMakeSavegameName(name));
253 typedef std::tuple<FiosType, std::string> FiosGetTypeAndNameProc(SaveLoadOperation fop, const std::string &filename, const std::string_view ext);
256 * Scanner to scan for a particular type of FIOS file.
258 class FiosFileScanner : public FileScanner {
259 SaveLoadOperation fop; ///< The kind of file we are looking for.
260 FiosGetTypeAndNameProc *callback_proc; ///< Callback to check whether the file may be added
261 FileList &file_list; ///< Destination of the found files.
262 public:
264 * Create the scanner
265 * @param fop Purpose of collecting the list.
266 * @param callback_proc The function that is called where you need to do the filtering.
267 * @param file_list Destination of the found files.
269 FiosFileScanner(SaveLoadOperation fop, FiosGetTypeAndNameProc *callback_proc, FileList &file_list) :
270 fop(fop), callback_proc(callback_proc), file_list(file_list)
273 bool AddFile(const std::string &filename, size_t basepath_length, const std::string &tar_filename) override;
277 * Try to add a fios item set with the given filename.
278 * @param filename the full path to the file to read
279 * @return true if the file is added.
281 bool FiosFileScanner::AddFile(const std::string &filename, size_t, const std::string &)
283 auto sep = filename.rfind('.');
284 if (sep == std::string::npos) return false;
285 std::string ext = filename.substr(sep);
287 auto [type, title] = this->callback_proc(this->fop, filename, ext);
288 if (type == FIOS_TYPE_INVALID) return false;
290 for (const auto &fios : file_list) {
291 if (filename == fios.name) return false;
294 FiosItem *fios = &file_list.emplace_back();
296 std::error_code error_code;
297 auto write_time = std::filesystem::last_write_time(OTTD2FS(filename), error_code);
298 if (error_code) {
299 fios->mtime = 0;
300 } else {
301 fios->mtime = std::chrono::duration_cast<std::chrono::milliseconds>(write_time.time_since_epoch()).count();
304 fios->type = type;
305 fios->name = filename;
307 /* If the file doesn't have a title, use its filename */
308 if (title.empty()) {
309 auto ps = filename.rfind(PATHSEPCHAR);
310 fios->title = StrMakeValid(filename.substr((ps == std::string::npos ? 0 : ps + 1)));
311 } else {
312 fios->title = StrMakeValid(title);
315 return true;
320 * Fill the list of the files in a directory, according to some arbitrary rule.
321 * @param fop Purpose of collecting the list.
322 * @param show_dirs Whether to list directories.
323 * @param callback_proc The function that is called where you need to do the filtering.
324 * @param subdir The directory from where to start (global) searching.
325 * @param file_list Destination of the found files.
327 static void FiosGetFileList(SaveLoadOperation fop, bool show_dirs, FiosGetTypeAndNameProc *callback_proc, Subdirectory subdir, FileList &file_list)
329 size_t sort_start = 0;
331 file_list.clear();
333 assert(_fios_path != nullptr);
335 if (show_dirs) {
336 /* A parent directory link exists if we are not in the root directory */
337 if (!FiosIsRoot(*_fios_path)) {
338 FiosItem &fios = file_list.emplace_back();
339 fios.type = FIOS_TYPE_PARENT;
340 fios.mtime = 0;
341 fios.name = "..";
342 SetDParamStr(0, "..");
343 fios.title = GetString(STR_SAVELOAD_PARENT_DIRECTORY);
344 sort_start = file_list.size();
347 /* Show subdirectories */
348 std::error_code error_code;
349 for (const auto &dir_entry : std::filesystem::directory_iterator(OTTD2FS(*_fios_path), error_code)) {
350 if (!dir_entry.is_directory()) continue;
351 if (FiosIsHiddenFile(dir_entry) && dir_entry.path().filename() != PERSONAL_DIR) continue;
353 FiosItem &fios = file_list.emplace_back();
354 fios.type = FIOS_TYPE_DIR;
355 fios.mtime = 0;
356 fios.name = FS2OTTD(dir_entry.path().filename());
357 SetDParamStr(0, fios.name + PATHSEP);
358 fios.title = GetString(STR_SAVELOAD_DIRECTORY);
361 /* Sort the subdirs always by name, ascending, remember user-sorting order */
362 SortingBits order = _savegame_sort_order;
363 _savegame_sort_order = SORT_BY_NAME | SORT_ASCENDING;
364 std::sort(file_list.begin() + sort_start, file_list.end());
365 _savegame_sort_order = order;
368 /* This is where to start sorting for the filenames */
369 sort_start = file_list.size();
371 /* Show files */
372 FiosFileScanner scanner(fop, callback_proc, file_list);
373 if (subdir == NO_DIRECTORY) {
374 scanner.Scan({}, *_fios_path, false);
375 } else {
376 scanner.Scan({}, subdir, true, true);
379 std::sort(file_list.begin() + sort_start, file_list.end());
381 /* Show drives */
382 FiosGetDrives(file_list);
386 * Get the title of a file, which (if exists) is stored in a file named
387 * the same as the data file but with '.title' added to it.
388 * @param file filename to get the title for
389 * @param subdir the sub directory to search in
390 * @return The file title.
392 static std::string GetFileTitle(const std::string &file, Subdirectory subdir)
394 auto f = FioFOpenFile(file + ".title", "r", subdir);
395 if (!f.has_value()) return {};
397 char title[80];
398 size_t read = fread(title, 1, lengthof(title), *f);
400 assert(read <= lengthof(title));
401 return StrMakeValid({title, read});
405 * Callback for FiosGetFileList. It tells if a file is a savegame or not.
406 * @param fop Purpose of collecting the list.
407 * @param file Name of the file to check.
408 * @param ext A pointer to the extension identifier inside file
409 * @return a FIOS_TYPE_* type of the found file, FIOS_TYPE_INVALID if not a savegame, and the title of the file (if any).
410 * @see FiosGetFileList
411 * @see FiosGetSavegameList
413 std::tuple<FiosType, std::string> FiosGetSavegameListCallback(SaveLoadOperation fop, const std::string &file, const std::string_view ext)
415 /* Show savegame files
416 * .SAV OpenTTD saved game
417 * .SS1 Transport Tycoon Deluxe preset game
418 * .SV1 Transport Tycoon Deluxe (Patch) saved game
419 * .SV2 Transport Tycoon Deluxe (Patch) saved 2-player game */
421 if (StrEqualsIgnoreCase(ext, ".sav")) {
422 return { FIOS_TYPE_FILE, GetFileTitle(file, SAVE_DIR) };
425 if (fop == SLO_LOAD) {
426 if (StrEqualsIgnoreCase(ext, ".ss1") || StrEqualsIgnoreCase(ext, ".sv1") ||
427 StrEqualsIgnoreCase(ext, ".sv2")) {
428 return { FIOS_TYPE_OLDFILE, GetOldSaveGameName(file) };
432 return { FIOS_TYPE_INVALID, {} };
436 * Get a list of savegames.
437 * @param fop Purpose of collecting the list.
438 * @param show_dirs Whether to show directories.
439 * @param file_list Destination of the found files.
440 * @see FiosGetFileList
442 void FiosGetSavegameList(SaveLoadOperation fop, bool show_dirs, FileList &file_list)
444 static std::optional<std::string> fios_save_path;
446 if (!fios_save_path) fios_save_path = FioFindDirectory(SAVE_DIR);
448 _fios_path = &(*fios_save_path);
450 FiosGetFileList(fop, show_dirs, &FiosGetSavegameListCallback, NO_DIRECTORY, file_list);
454 * Callback for FiosGetFileList. It tells if a file is a scenario or not.
455 * @param fop Purpose of collecting the list.
456 * @param file Name of the file to check.
457 * @param ext A pointer to the extension identifier inside file
458 * @return a FIOS_TYPE_* type of the found file, FIOS_TYPE_INVALID if not a scenario and the title of the file (if any).
459 * @see FiosGetFileList
460 * @see FiosGetScenarioList
462 std::tuple<FiosType, std::string> FiosGetScenarioListCallback(SaveLoadOperation fop, const std::string &file, const std::string_view ext)
464 /* Show scenario files
465 * .SCN OpenTTD style scenario file
466 * .SV0 Transport Tycoon Deluxe (Patch) scenario
467 * .SS0 Transport Tycoon Deluxe preset scenario */
468 if (StrEqualsIgnoreCase(ext, ".scn")) {
469 return { FIOS_TYPE_SCENARIO, GetFileTitle(file, SCENARIO_DIR) };
473 if (fop == SLO_LOAD) {
474 if (StrEqualsIgnoreCase(ext, ".sv0") || StrEqualsIgnoreCase(ext, ".ss0")) {
475 return { FIOS_TYPE_OLD_SCENARIO, GetOldSaveGameName(file) };
479 return { FIOS_TYPE_INVALID, {} };
483 * Get a list of scenarios.
484 * @param fop Purpose of collecting the list.
485 * @param show_dirs Whether to show directories.
486 * @param file_list Destination of the found files.
487 * @see FiosGetFileList
489 void FiosGetScenarioList(SaveLoadOperation fop, bool show_dirs, FileList &file_list)
491 static std::optional<std::string> fios_scn_path;
493 /* Copy the default path on first run or on 'New Game' */
494 if (!fios_scn_path) fios_scn_path = FioFindDirectory(SCENARIO_DIR);
496 _fios_path = &(*fios_scn_path);
498 std::string base_path = FioFindDirectory(SCENARIO_DIR);
499 Subdirectory subdir = (fop == SLO_LOAD && base_path == *_fios_path) ? SCENARIO_DIR : NO_DIRECTORY;
500 FiosGetFileList(fop, show_dirs, &FiosGetScenarioListCallback, subdir, file_list);
503 std::tuple<FiosType, std::string> FiosGetHeightmapListCallback(SaveLoadOperation, const std::string &file, const std::string_view ext)
505 /* Show heightmap files
506 * .PNG PNG Based heightmap files
507 * .BMP BMP Based heightmap files
510 FiosType type = FIOS_TYPE_INVALID;
512 #ifdef WITH_PNG
513 if (StrEqualsIgnoreCase(ext, ".png")) type = FIOS_TYPE_PNG;
514 #endif /* WITH_PNG */
516 if (StrEqualsIgnoreCase(ext, ".bmp")) type = FIOS_TYPE_BMP;
518 if (type == FIOS_TYPE_INVALID) return { FIOS_TYPE_INVALID, {} };
520 TarFileList::iterator it = _tar_filelist[SCENARIO_DIR].find(file);
521 if (it != _tar_filelist[SCENARIO_DIR].end()) {
522 /* If the file is in a tar and that tar is not in a heightmap
523 * directory we are for sure not supposed to see it.
524 * Examples of this are pngs part of documentation within
525 * collections of NewGRFs or 32 bpp graphics replacement PNGs.
527 bool match = false;
528 for (Searchpath sp : _valid_searchpaths) {
529 std::string buf = FioGetDirectory(sp, HEIGHTMAP_DIR);
531 if (buf.compare(0, buf.size(), it->second.tar_filename, 0, buf.size()) == 0) {
532 match = true;
533 break;
537 if (!match) return { FIOS_TYPE_INVALID, {} };
540 return { type, GetFileTitle(file, HEIGHTMAP_DIR) };
544 * Get a list of heightmaps.
545 * @param fop Purpose of collecting the list.
546 * @param show_dirs Whether to show directories.
547 * @param file_list Destination of the found files.
549 void FiosGetHeightmapList(SaveLoadOperation fop, bool show_dirs, FileList &file_list)
551 static std::optional<std::string> fios_hmap_path;
553 if (!fios_hmap_path) fios_hmap_path = FioFindDirectory(HEIGHTMAP_DIR);
555 _fios_path = &(*fios_hmap_path);
557 std::string base_path = FioFindDirectory(HEIGHTMAP_DIR);
558 Subdirectory subdir = base_path == *_fios_path ? HEIGHTMAP_DIR : NO_DIRECTORY;
559 FiosGetFileList(fop, show_dirs, &FiosGetHeightmapListCallback, subdir, file_list);
563 * Callback for FiosGetTownDataList.
564 * @param fop Purpose of collecting the list.
565 * @param file Name of the file to check.
566 * @return a FIOS_TYPE_JSON type of the found file, FIOS_TYPE_INVALID if not a valid JSON file, and the title of the file (if any).
568 static std::tuple<FiosType, std::string> FiosGetTownDataListCallback(SaveLoadOperation fop, const std::string &file, const std::string_view ext)
570 if (fop == SLO_LOAD) {
571 if (StrEqualsIgnoreCase(ext, ".json")) {
572 return { FIOS_TYPE_JSON, GetFileTitle(file, SAVE_DIR) };
576 return { FIOS_TYPE_INVALID, {} };
580 * Get a list of town data files.
581 * @param fop Purpose of collecting the list.
582 * @param show_dirs Whether to show directories.
583 * @param file_list Destination of the found files.
585 void FiosGetTownDataList(SaveLoadOperation fop, bool show_dirs, FileList &file_list)
587 static std::optional<std::string> fios_town_data_path;
589 if (!fios_town_data_path) fios_town_data_path = FioFindDirectory(HEIGHTMAP_DIR);
591 _fios_path = &(*fios_town_data_path);
593 std::string base_path = FioFindDirectory(HEIGHTMAP_DIR);
594 Subdirectory subdir = base_path == *_fios_path ? HEIGHTMAP_DIR : NO_DIRECTORY;
595 FiosGetFileList(fop, show_dirs, &FiosGetTownDataListCallback, subdir, file_list);
599 * Get the directory for screenshots.
600 * @return path to screenshots
602 const char *FiosGetScreenshotDir()
604 static std::optional<std::string> fios_screenshot_path;
606 if (!fios_screenshot_path) fios_screenshot_path = FioFindDirectory(SCREENSHOT_DIR);
608 return fios_screenshot_path->c_str();
611 /** Basic data to distinguish a scenario. Used in the server list window */
612 struct ScenarioIdentifier {
613 uint32_t scenid; ///< ID for the scenario (generated by content).
614 MD5Hash md5sum; ///< MD5 checksum of file.
615 std::string filename; ///< filename of the file.
617 bool operator == (const ScenarioIdentifier &other) const
619 return this->scenid == other.scenid && this->md5sum == other.md5sum;
622 bool operator != (const ScenarioIdentifier &other) const
624 return !(*this == other);
629 * Scanner to find the unique IDs of scenarios
631 class ScenarioScanner : protected FileScanner, public std::vector<ScenarioIdentifier> {
632 bool scanned; ///< Whether we've already scanned
633 public:
634 /** Initialise */
635 ScenarioScanner() : scanned(false) {}
638 * Scan, but only if it's needed.
639 * @param rescan whether to force scanning even when it's not necessary
641 void Scan(bool rescan)
643 if (this->scanned && !rescan) return;
645 this->FileScanner::Scan(".id", SCENARIO_DIR, true, true);
646 this->scanned = true;
649 bool AddFile(const std::string &filename, size_t, const std::string &) override
651 auto f = FioFOpenFile(filename, "r", SCENARIO_DIR);
652 if (!f.has_value()) return false;
654 ScenarioIdentifier id;
655 int fret = fscanf(*f, "%u", &id.scenid);
656 if (fret != 1) return false;
657 id.filename = filename;
659 Md5 checksum;
660 uint8_t buffer[1024];
661 size_t len, size;
663 /* open the scenario file, but first get the name.
664 * This is safe as we check on extension which
665 * must always exist. */
666 f = FioFOpenFile(filename.substr(0, filename.rfind('.')), "rb", SCENARIO_DIR, &size);
667 if (!f.has_value()) return false;
669 /* calculate md5sum */
670 while ((len = fread(buffer, 1, (size > sizeof(buffer)) ? sizeof(buffer) : size, *f)) != 0 && size != 0) {
671 size -= len;
672 checksum.Append(buffer, len);
674 checksum.Finish(id.md5sum);
676 include(*this, id);
677 return true;
681 /** Scanner for scenarios */
682 static ScenarioScanner _scanner;
685 * Find a given scenario based on its unique ID.
686 * @param ci The content info to compare it to.
687 * @param md5sum Whether to look at the md5sum or the id.
688 * @return The filename of the file, else \c nullptr.
690 const char *FindScenario(const ContentInfo *ci, bool md5sum)
692 _scanner.Scan(false);
694 for (ScenarioIdentifier &id : _scanner) {
695 if (md5sum ? (id.md5sum == ci->md5sum)
696 : (id.scenid == ci->unique_id)) {
697 return id.filename.c_str();
701 return nullptr;
705 * Check whether we've got a given scenario based on its unique ID.
706 * @param ci The content info to compare it to.
707 * @param md5sum Whether to look at the md5sum or the id.
708 * @return True iff we've got the scenario.
710 bool HasScenario(const ContentInfo *ci, bool md5sum)
712 return (FindScenario(ci, md5sum) != nullptr);
716 * Force a (re)scan of the scenarios.
718 void ScanScenarios()
720 _scanner.Scan(true);
724 * Constructs FiosNumberedSaveName. Initial number is the most recent save, or -1 if not found.
725 * @param prefix The prefix to use to generate a filename.
727 FiosNumberedSaveName::FiosNumberedSaveName(const std::string &prefix) : prefix(prefix), number(-1)
729 static std::optional<std::string> _autosave_path;
730 if (!_autosave_path) _autosave_path = FioFindDirectory(AUTOSAVE_DIR);
732 static std::string _prefix; ///< Static as the lambda needs access to it.
734 /* Callback for FiosFileScanner. */
735 static FiosGetTypeAndNameProc *proc = [](SaveLoadOperation, const std::string &file, const std::string_view ext) {
736 if (StrEqualsIgnoreCase(ext, ".sav") && file.starts_with(_prefix)) return std::tuple(FIOS_TYPE_FILE, std::string{});
737 return std::tuple(FIOS_TYPE_INVALID, std::string{});
740 /* Prefix to check in the callback. */
741 _prefix = *_autosave_path + this->prefix;
743 /* Get the save list. */
744 FileList list;
745 FiosFileScanner scanner(SLO_SAVE, proc, list);
746 scanner.Scan(".sav", *_autosave_path, false);
748 /* Find the number for the most recent save, if any. */
749 if (list.begin() != list.end()) {
750 SortingBits order = _savegame_sort_order;
751 _savegame_sort_order = SORT_BY_DATE | SORT_DESCENDING;
752 std::sort(list.begin(), list.end());
753 _savegame_sort_order = order;
755 std::string_view name = list.begin()->title;
756 std::from_chars(name.data() + this->prefix.size(), name.data() + name.size(), this->number);
761 * Generate a savegame name and number according to _settings_client.gui.max_num_autosaves.
762 * @return A filename in format "<prefix><number>.sav".
764 std::string FiosNumberedSaveName::Filename()
766 if (++this->number >= _settings_client.gui.max_num_autosaves) this->number = 0;
767 return fmt::format("{}{}.sav", this->prefix, this->number);
771 * Generate an extension for a savegame name.
772 * @return An extension in format "-<prefix>.sav".
774 std::string FiosNumberedSaveName::Extension()
776 return fmt::format("-{}.sav", this->prefix);