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/>.
10 * This file contains functions for building file lists for the save/load dialogs.
14 #include "3rdparty/md5/md5.h"
15 #include "fileio_func.h"
17 #include "network/network_content.h"
18 #include "screenshot.h"
19 #include "string_func.h"
20 #include "strings_func.h"
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
);
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
51 if ((_savegame_sort_order
& SORT_BY_NAME
) == 0 && (*this).mtime
!= other
.mtime
) {
52 r
= ClampTo
<int32_t>(this->mtime
- other
.mtime
);
54 r
= StrNaturalCompare((*this).title
, other
.title
);
56 if (r
== 0) return false;
57 return (_savegame_sort_order
& SORT_DESCENDING
) ? r
> 0 : r
< 0;
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
)
70 assert(fop
== SLO_LOAD
|| fop
== SLO_SAVE
);
71 switch (abstract_filetype
) {
76 FiosGetSavegameList(fop
, show_dirs
, *this);
80 FiosGetScenarioList(fop
, show_dirs
, *this);
84 FiosGetHeightmapList(fop
, show_dirs
, *this);
93 * Find file information of a file by its name from the file list.
94 * @param file The filename to return information about. Can be the actual name
95 * or a numbered entry into the filename list.
96 * @return The information on the file, or \c nullptr if the file is not available.
98 const FiosItem
*FileList::FindItem(const std::string_view file
)
100 for (const auto &it
: *this) {
101 const FiosItem
*item
= &it
;
102 if (file
== item
->name
) return item
;
103 if (file
== item
->title
) return item
;
106 /* If no name matches, try to parse it as number */
108 int i
= std::strtol(file
.data(), &endptr
, 10);
109 if (file
.data() == endptr
|| *endptr
!= '\0') i
= -1;
111 if (IsInsideMM(i
, 0, this->size())) return &this->at(i
);
113 /* As a last effort assume it is an OpenTTD savegame and
114 * that the ".sav" part was not given. */
115 std::string
long_file(file
);
117 for (const auto &it
: *this) {
118 const FiosItem
*item
= &it
;
119 if (long_file
== item
->name
) return item
;
120 if (long_file
== item
->title
) return item
;
127 * Get the current path/working directory.
129 std::string
FiosGetCurrentPath()
135 * Browse to a new path based on the passed \a item, starting at #_fios_path.
136 * @param *item Item telling us what to do.
137 * @return \c true when the path got changed.
139 bool FiosBrowseTo(const FiosItem
*item
)
141 switch (item
->type
) {
142 case FIOS_TYPE_DRIVE
:
144 assert(_fios_path
!= nullptr);
145 *_fios_path
= std::string
{ item
->title
, 0, 1 } + ":" PATHSEP
;
149 case FIOS_TYPE_INVALID
:
152 case FIOS_TYPE_PARENT
: {
153 assert(_fios_path
!= nullptr);
154 auto s
= _fios_path
->find_last_of(PATHSEPCHAR
);
155 if (s
!= std::string::npos
&& s
!= 0) {
156 _fios_path
->erase(s
); // Remove last path separator character, so we can go up one level.
159 s
= _fios_path
->find_last_of(PATHSEPCHAR
);
160 if (s
!= std::string::npos
) {
161 _fios_path
->erase(s
+ 1); // go up a directory
167 assert(_fios_path
!= nullptr);
168 *_fios_path
+= item
->name
;
169 *_fios_path
+= PATHSEP
;
172 case FIOS_TYPE_DIRECT
:
173 assert(_fios_path
!= nullptr);
174 *_fios_path
= item
->name
;
178 case FIOS_TYPE_OLDFILE
:
179 case FIOS_TYPE_SCENARIO
:
180 case FIOS_TYPE_OLD_SCENARIO
:
190 * Construct a filename from its components in destination buffer \a buf.
191 * @param path Directory path, may be \c nullptr.
192 * @param name Filename.
193 * @param ext Filename extension (use \c "" for no extension).
194 * @return The completed filename.
196 static std::string
FiosMakeFilename(const std::string
*path
, const char *name
, const char *ext
)
200 if (path
!= nullptr) {
202 /* Remove trailing path separator, if present */
203 if (!buf
.empty() && buf
.back() == PATHSEPCHAR
) buf
.pop_back();
206 /* Don't append the extension if it is already there */
207 const char *period
= strrchr(name
, '.');
208 if (period
!= nullptr && StrEqualsIgnoreCase(period
, ext
)) ext
= "";
210 return buf
+ PATHSEP
+ name
+ ext
;
214 * Make a save game or scenario filename from a name.
215 * @param name Name of the file.
216 * @return The completed filename.
218 std::string
FiosMakeSavegameName(const char *name
)
220 const char *extension
= (_game_mode
== GM_EDITOR
) ? ".scn" : ".sav";
222 return FiosMakeFilename(_fios_path
, name
, extension
);
226 * Construct a filename for a height map.
227 * @param name Filename.
228 * @return The completed filename.
230 std::string
FiosMakeHeightmapName(const char *name
)
232 std::string
ext(".");
233 ext
+= GetCurrentScreenshotExtension();
235 return FiosMakeFilename(_fios_path
, name
, ext
.c_str());
240 * @param name Filename to delete.
241 * @return Whether the file deletion was successful.
243 bool FiosDelete(const char *name
)
245 return FioRemove(FiosMakeSavegameName(name
));
248 typedef std::tuple
<FiosType
, std::string
> FiosGetTypeAndNameProc(SaveLoadOperation fop
, const std::string
&filename
, const std::string_view ext
);
251 * Scanner to scan for a particular type of FIOS file.
253 class FiosFileScanner
: public FileScanner
{
254 SaveLoadOperation fop
; ///< The kind of file we are looking for.
255 FiosGetTypeAndNameProc
*callback_proc
; ///< Callback to check whether the file may be added
256 FileList
&file_list
; ///< Destination of the found files.
260 * @param fop Purpose of collecting the list.
261 * @param callback_proc The function that is called where you need to do the filtering.
262 * @param file_list Destination of the found files.
264 FiosFileScanner(SaveLoadOperation fop
, FiosGetTypeAndNameProc
*callback_proc
, FileList
&file_list
) :
265 fop(fop
), callback_proc(callback_proc
), file_list(file_list
)
268 bool AddFile(const std::string
&filename
, size_t basepath_length
, const std::string
&tar_filename
) override
;
272 * Try to add a fios item set with the given filename.
273 * @param filename the full path to the file to read
274 * @return true if the file is added.
276 bool FiosFileScanner::AddFile(const std::string
&filename
, size_t, const std::string
&)
278 auto sep
= filename
.rfind('.');
279 if (sep
== std::string::npos
) return false;
280 std::string ext
= filename
.substr(sep
);
282 auto [type
, title
] = this->callback_proc(this->fop
, filename
, ext
);
283 if (type
== FIOS_TYPE_INVALID
) return false;
285 for (const auto &fios
: file_list
) {
286 if (filename
== fios
.name
) return false;
289 FiosItem
*fios
= &file_list
.emplace_back();
291 std::error_code error_code
;
292 auto write_time
= std::filesystem::last_write_time(OTTD2FS(filename
), error_code
);
296 fios
->mtime
= std::chrono::duration_cast
<std::chrono::milliseconds
>(write_time
.time_since_epoch()).count();
300 fios
->name
= filename
;
302 /* If the file doesn't have a title, use its filename */
304 auto ps
= filename
.rfind(PATHSEPCHAR
);
305 fios
->title
= StrMakeValid(filename
.substr((ps
== std::string::npos
? 0 : ps
+ 1)));
307 fios
->title
= StrMakeValid(title
);
315 * Fill the list of the files in a directory, according to some arbitrary rule.
316 * @param fop Purpose of collecting the list.
317 * @param show_dirs Whether to list directories.
318 * @param callback_proc The function that is called where you need to do the filtering.
319 * @param subdir The directory from where to start (global) searching.
320 * @param file_list Destination of the found files.
322 static void FiosGetFileList(SaveLoadOperation fop
, bool show_dirs
, FiosGetTypeAndNameProc
*callback_proc
, Subdirectory subdir
, FileList
&file_list
)
328 assert(_fios_path
!= nullptr);
331 /* A parent directory link exists if we are not in the root directory */
332 if (!FiosIsRoot(*_fios_path
)) {
333 FiosItem
&fios
= file_list
.emplace_back();
334 fios
.type
= FIOS_TYPE_PARENT
;
337 SetDParamStr(0, "..");
338 fios
.title
= GetString(STR_SAVELOAD_PARENT_DIRECTORY
);
341 /* Show subdirectories */
342 std::error_code error_code
;
343 for (const auto &dir_entry
: std::filesystem::directory_iterator(OTTD2FS(*_fios_path
), error_code
)) {
344 if (!dir_entry
.is_directory()) continue;
345 if (FiosIsHiddenFile(dir_entry
) && dir_entry
.path().filename() != PERSONAL_DIR
) continue;
347 FiosItem
&fios
= file_list
.emplace_back();
348 fios
.type
= FIOS_TYPE_DIR
;
350 fios
.name
= FS2OTTD(dir_entry
.path().filename());
351 SetDParamStr(0, fios
.name
+ PATHSEP
);
352 fios
.title
= GetString(STR_SAVELOAD_DIRECTORY
);
355 /* Sort the subdirs always by name, ascending, remember user-sorting order */
356 SortingBits order
= _savegame_sort_order
;
357 _savegame_sort_order
= SORT_BY_NAME
| SORT_ASCENDING
;
358 std::sort(file_list
.begin(), file_list
.end());
359 _savegame_sort_order
= order
;
362 /* This is where to start sorting for the filenames */
363 sort_start
= file_list
.size();
366 FiosFileScanner
scanner(fop
, callback_proc
, file_list
);
367 if (subdir
== NO_DIRECTORY
) {
368 scanner
.Scan({}, *_fios_path
, false);
370 scanner
.Scan({}, subdir
, true, true);
373 std::sort(file_list
.begin() + sort_start
, file_list
.end());
376 FiosGetDrives(file_list
);
380 * Get the title of a file, which (if exists) is stored in a file named
381 * the same as the data file but with '.title' added to it.
382 * @param file filename to get the title for
383 * @param subdir the sub directory to search in
384 * @return The file title.
386 static std::string
GetFileTitle(const std::string
&file
, Subdirectory subdir
)
388 FILE *f
= FioFOpenFile(file
+ ".title", "r", subdir
);
389 if (f
== nullptr) return {};
392 size_t read
= fread(title
, 1, lengthof(title
), f
);
395 assert(read
<= lengthof(title
));
396 return StrMakeValid({title
, read
});
400 * Callback for FiosGetFileList. It tells if a file is a savegame or not.
401 * @param fop Purpose of collecting the list.
402 * @param file Name of the file to check.
403 * @param ext A pointer to the extension identifier inside file
404 * @return a FIOS_TYPE_* type of the found file, FIOS_TYPE_INVALID if not a savegame, and the title of the file (if any).
405 * @see FiosGetFileList
406 * @see FiosGetSavegameList
408 std::tuple
<FiosType
, std::string
> FiosGetSavegameListCallback(SaveLoadOperation fop
, const std::string
&file
, const std::string_view ext
)
410 /* Show savegame files
411 * .SAV OpenTTD saved game
412 * .SS1 Transport Tycoon Deluxe preset game
413 * .SV1 Transport Tycoon Deluxe (Patch) saved game
414 * .SV2 Transport Tycoon Deluxe (Patch) saved 2-player game */
416 if (StrEqualsIgnoreCase(ext
, ".sav")) {
417 return { FIOS_TYPE_FILE
, GetFileTitle(file
, SAVE_DIR
) };
420 if (fop
== SLO_LOAD
) {
421 if (StrEqualsIgnoreCase(ext
, ".ss1") || StrEqualsIgnoreCase(ext
, ".sv1") ||
422 StrEqualsIgnoreCase(ext
, ".sv2")) {
423 return { FIOS_TYPE_OLDFILE
, GetOldSaveGameName(file
) };
427 return { FIOS_TYPE_INVALID
, {} };
431 * Get a list of savegames.
432 * @param fop Purpose of collecting the list.
433 * @param show_dirs Whether to show directories.
434 * @param file_list Destination of the found files.
435 * @see FiosGetFileList
437 void FiosGetSavegameList(SaveLoadOperation fop
, bool show_dirs
, FileList
&file_list
)
439 static std::optional
<std::string
> fios_save_path
;
441 if (!fios_save_path
) fios_save_path
= FioFindDirectory(SAVE_DIR
);
443 _fios_path
= &(*fios_save_path
);
445 FiosGetFileList(fop
, show_dirs
, &FiosGetSavegameListCallback
, NO_DIRECTORY
, file_list
);
449 * Callback for FiosGetFileList. It tells if a file is a scenario or not.
450 * @param fop Purpose of collecting the list.
451 * @param file Name of the file to check.
452 * @param ext A pointer to the extension identifier inside file
453 * @return a FIOS_TYPE_* type of the found file, FIOS_TYPE_INVALID if not a scenario and the title of the file (if any).
454 * @see FiosGetFileList
455 * @see FiosGetScenarioList
457 std::tuple
<FiosType
, std::string
> FiosGetScenarioListCallback(SaveLoadOperation fop
, const std::string
&file
, const std::string_view ext
)
459 /* Show scenario files
460 * .SCN OpenTTD style scenario file
461 * .SV0 Transport Tycoon Deluxe (Patch) scenario
462 * .SS0 Transport Tycoon Deluxe preset scenario */
463 if (StrEqualsIgnoreCase(ext
, ".scn")) {
464 return { FIOS_TYPE_SCENARIO
, GetFileTitle(file
, SCENARIO_DIR
) };
468 if (fop
== SLO_LOAD
) {
469 if (StrEqualsIgnoreCase(ext
, ".sv0") || StrEqualsIgnoreCase(ext
, ".ss0")) {
470 return { FIOS_TYPE_OLD_SCENARIO
, GetOldSaveGameName(file
) };
474 return { FIOS_TYPE_INVALID
, {} };
478 * Get a list of scenarios.
479 * @param fop Purpose of collecting the list.
480 * @param show_dirs Whether to show directories.
481 * @param file_list Destination of the found files.
482 * @see FiosGetFileList
484 void FiosGetScenarioList(SaveLoadOperation fop
, bool show_dirs
, FileList
&file_list
)
486 static std::optional
<std::string
> fios_scn_path
;
488 /* Copy the default path on first run or on 'New Game' */
489 if (!fios_scn_path
) fios_scn_path
= FioFindDirectory(SCENARIO_DIR
);
491 _fios_path
= &(*fios_scn_path
);
493 std::string base_path
= FioFindDirectory(SCENARIO_DIR
);
494 Subdirectory subdir
= (fop
== SLO_LOAD
&& base_path
== *_fios_path
) ? SCENARIO_DIR
: NO_DIRECTORY
;
495 FiosGetFileList(fop
, show_dirs
, &FiosGetScenarioListCallback
, subdir
, file_list
);
498 std::tuple
<FiosType
, std::string
> FiosGetHeightmapListCallback(SaveLoadOperation
, const std::string
&file
, const std::string_view ext
)
500 /* Show heightmap files
501 * .PNG PNG Based heightmap files
502 * .BMP BMP Based heightmap files
505 FiosType type
= FIOS_TYPE_INVALID
;
508 if (StrEqualsIgnoreCase(ext
, ".png")) type
= FIOS_TYPE_PNG
;
509 #endif /* WITH_PNG */
511 if (StrEqualsIgnoreCase(ext
, ".bmp")) type
= FIOS_TYPE_BMP
;
513 if (type
== FIOS_TYPE_INVALID
) return { FIOS_TYPE_INVALID
, {} };
515 TarFileList::iterator it
= _tar_filelist
[SCENARIO_DIR
].find(file
);
516 if (it
!= _tar_filelist
[SCENARIO_DIR
].end()) {
517 /* If the file is in a tar and that tar is not in a heightmap
518 * directory we are for sure not supposed to see it.
519 * Examples of this are pngs part of documentation within
520 * collections of NewGRFs or 32 bpp graphics replacement PNGs.
523 for (Searchpath sp
: _valid_searchpaths
) {
524 std::string buf
= FioGetDirectory(sp
, HEIGHTMAP_DIR
);
526 if (buf
.compare(0, buf
.size(), it
->second
.tar_filename
, 0, buf
.size()) == 0) {
532 if (!match
) return { FIOS_TYPE_INVALID
, {} };
535 return { type
, GetFileTitle(file
, HEIGHTMAP_DIR
) };
539 * Get a list of heightmaps.
540 * @param fop Purpose of collecting the list.
541 * @param show_dirs Whether to show directories.
542 * @param file_list Destination of the found files.
544 void FiosGetHeightmapList(SaveLoadOperation fop
, bool show_dirs
, FileList
&file_list
)
546 static std::optional
<std::string
> fios_hmap_path
;
548 if (!fios_hmap_path
) fios_hmap_path
= FioFindDirectory(HEIGHTMAP_DIR
);
550 _fios_path
= &(*fios_hmap_path
);
552 std::string base_path
= FioFindDirectory(HEIGHTMAP_DIR
);
553 Subdirectory subdir
= base_path
== *_fios_path
? HEIGHTMAP_DIR
: NO_DIRECTORY
;
554 FiosGetFileList(fop
, show_dirs
, &FiosGetHeightmapListCallback
, subdir
, file_list
);
558 * Get the directory for screenshots.
559 * @return path to screenshots
561 const char *FiosGetScreenshotDir()
563 static std::optional
<std::string
> fios_screenshot_path
;
565 if (!fios_screenshot_path
) fios_screenshot_path
= FioFindDirectory(SCREENSHOT_DIR
);
567 return fios_screenshot_path
->c_str();
570 /** Basic data to distinguish a scenario. Used in the server list window */
571 struct ScenarioIdentifier
{
572 uint32_t scenid
; ///< ID for the scenario (generated by content).
573 MD5Hash md5sum
; ///< MD5 checksum of file.
574 std::string filename
; ///< filename of the file.
576 bool operator == (const ScenarioIdentifier
&other
) const
578 return this->scenid
== other
.scenid
&& this->md5sum
== other
.md5sum
;
581 bool operator != (const ScenarioIdentifier
&other
) const
583 return !(*this == other
);
588 * Scanner to find the unique IDs of scenarios
590 class ScenarioScanner
: protected FileScanner
, public std::vector
<ScenarioIdentifier
> {
591 bool scanned
; ///< Whether we've already scanned
594 ScenarioScanner() : scanned(false) {}
597 * Scan, but only if it's needed.
598 * @param rescan whether to force scanning even when it's not necessary
600 void Scan(bool rescan
)
602 if (this->scanned
&& !rescan
) return;
604 this->FileScanner::Scan(".id", SCENARIO_DIR
, true, true);
605 this->scanned
= true;
608 bool AddFile(const std::string
&filename
, size_t, const std::string
&) override
610 FILE *f
= FioFOpenFile(filename
, "r", SCENARIO_DIR
);
611 if (f
== nullptr) return false;
613 ScenarioIdentifier id
;
614 int fret
= fscanf(f
, "%u", &id
.scenid
);
616 if (fret
!= 1) return false;
617 id
.filename
= filename
;
620 uint8_t buffer
[1024];
623 /* open the scenario file, but first get the name.
624 * This is safe as we check on extension which
625 * must always exist. */
626 f
= FioFOpenFile(filename
.substr(0, filename
.rfind('.')), "rb", SCENARIO_DIR
, &size
);
627 if (f
== nullptr) return false;
629 /* calculate md5sum */
630 while ((len
= fread(buffer
, 1, (size
> sizeof(buffer
)) ? sizeof(buffer
) : size
, f
)) != 0 && size
!= 0) {
632 checksum
.Append(buffer
, len
);
634 checksum
.Finish(id
.md5sum
);
643 /** Scanner for scenarios */
644 static ScenarioScanner _scanner
;
647 * Find a given scenario based on its unique ID.
648 * @param ci The content info to compare it to.
649 * @param md5sum Whether to look at the md5sum or the id.
650 * @return The filename of the file, else \c nullptr.
652 const char *FindScenario(const ContentInfo
*ci
, bool md5sum
)
654 _scanner
.Scan(false);
656 for (ScenarioIdentifier
&id
: _scanner
) {
657 if (md5sum
? (id
.md5sum
== ci
->md5sum
)
658 : (id
.scenid
== ci
->unique_id
)) {
659 return id
.filename
.c_str();
667 * Check whether we've got a given scenario based on its unique ID.
668 * @param ci The content info to compare it to.
669 * @param md5sum Whether to look at the md5sum or the id.
670 * @return True iff we've got the scenario.
672 bool HasScenario(const ContentInfo
*ci
, bool md5sum
)
674 return (FindScenario(ci
, md5sum
) != nullptr);
678 * Force a (re)scan of the scenarios.
686 * Constructs FiosNumberedSaveName. Initial number is the most recent save, or -1 if not found.
687 * @param prefix The prefix to use to generate a filename.
689 FiosNumberedSaveName::FiosNumberedSaveName(const std::string
&prefix
) : prefix(prefix
), number(-1)
691 static std::optional
<std::string
> _autosave_path
;
692 if (!_autosave_path
) _autosave_path
= FioFindDirectory(AUTOSAVE_DIR
);
694 static std::string _prefix
; ///< Static as the lambda needs access to it.
696 /* Callback for FiosFileScanner. */
697 static FiosGetTypeAndNameProc
*proc
= [](SaveLoadOperation
, const std::string
&file
, const std::string_view ext
) {
698 if (StrEqualsIgnoreCase(ext
, ".sav") && file
.starts_with(_prefix
)) return std::tuple(FIOS_TYPE_FILE
, std::string
{});
699 return std::tuple(FIOS_TYPE_INVALID
, std::string
{});
702 /* Prefix to check in the callback. */
703 _prefix
= *_autosave_path
+ this->prefix
;
705 /* Get the save list. */
707 FiosFileScanner
scanner(SLO_SAVE
, proc
, list
);
708 scanner
.Scan(".sav", *_autosave_path
, false);
710 /* Find the number for the most recent save, if any. */
711 if (list
.begin() != list
.end()) {
712 SortingBits order
= _savegame_sort_order
;
713 _savegame_sort_order
= SORT_BY_DATE
| SORT_DESCENDING
;
714 std::sort(list
.begin(), list
.end());
715 _savegame_sort_order
= order
;
717 std::string_view name
= list
.begin()->title
;
718 std::from_chars(name
.data() + this->prefix
.size(), name
.data() + name
.size(), this->number
);
723 * Generate a savegame name and number according to _settings_client.gui.max_num_autosaves.
724 * @return A filename in format "<prefix><number>.sav".
726 std::string
FiosNumberedSaveName::Filename()
728 if (++this->number
>= _settings_client
.gui
.max_num_autosaves
) this->number
= 0;
729 return fmt::format("{}{}.sav", this->prefix
, this->number
);
733 * Generate an extension for a savegame name.
734 * @return An extension in format "-<prefix>.sav".
736 std::string
FiosNumberedSaveName::Extension()
738 return fmt::format("-{}.sav", this->prefix
);