4 * This file is part of OpenTTD.
5 * 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.
6 * 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.
7 * 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/>.
12 * This file contains functions for building file lists for the save/load dialogs.
17 #include "fileio_func.h"
19 #include "screenshot.h"
20 #include "string_func.h"
27 #include "table/strings.h"
29 /* Variables to display file lists */
30 SmallVector
<FiosItem
, 32> _fios_items
;
31 static char *_fios_path
;
32 SmallFiosItem _file_to_saveload
;
33 SortingBits _savegame_sort_order
= SORT_BY_DATE
| SORT_DESCENDING
;
35 /* OS-specific functions are taken from their respective files (win32/unix/os2 .c) */
36 extern bool FiosIsRoot(const char *path
);
37 extern bool FiosIsValidFile(const char *path
, const struct dirent
*ent
, struct stat
*sb
);
38 extern bool FiosIsHiddenFile(const struct dirent
*ent
);
39 extern void FiosGetDrives();
40 extern bool FiosGetDiskFreeSpace(const char *path
, uint64
*tot
);
42 /* get the name of an oldstyle savegame */
43 extern void GetOldSaveGameName(const char *file
, char *title
, const char *last
);
46 * Compare two FiosItem's. Used with sort when sorting the file list.
47 * @param da A pointer to the first FiosItem to compare.
48 * @param db A pointer to the second FiosItem to compare.
49 * @return -1, 0 or 1, depending on how the two items should be sorted.
51 int CDECL
CompareFiosItems(const FiosItem
*da
, const FiosItem
*db
)
55 if ((_savegame_sort_order
& SORT_BY_NAME
) == 0 && da
->mtime
!= db
->mtime
) {
56 r
= da
->mtime
< db
->mtime
? -1 : 1;
58 r
= strcasecmp(da
->title
, db
->title
);
61 if (_savegame_sort_order
& SORT_DESCENDING
) r
= -r
;
65 /** Free the list of savegames. */
66 void FiosFreeSavegameList()
69 _fios_items
.Compact();
73 * Get descriptive texts. Returns the path and free space
75 * @param path string describing the path
76 * @param total_free total free space in megabytes, optional (can be NULL)
77 * @return StringID describing the path (free space or failure)
79 StringID
FiosGetDescText(const char **path
, uint64
*total_free
)
82 return FiosGetDiskFreeSpace(*path
, total_free
) ? STR_SAVELOAD_BYTES_FREE
: STR_ERROR_UNABLE_TO_READ_DRIVE
;
86 * Browse to a new path based on the passed \a item, starting at #_fios_path.
87 * @param *item Item telling us what to do.
88 * @return A filename w/path if we reached a file, otherwise \c NULL.
90 const char *FiosBrowseTo(const FiosItem
*item
)
92 char *path
= _fios_path
;
97 snprintf(path
, MAX_PATH
, PATHSEP
"");
98 #elif defined(WIN32) || defined(__OS2__)
99 snprintf(path
, MAX_PATH
, "%c:" PATHSEP
, item
->title
[0]);
102 case FIOS_TYPE_INVALID
:
105 case FIOS_TYPE_PARENT
: {
106 /* Check for possible NULL ptr (not required for UNIXes, but AmigaOS-alikes) */
107 char *s
= strrchr(path
, PATHSEPCHAR
);
108 if (s
!= NULL
&& s
!= path
) {
109 s
[0] = '\0'; // Remove last path separator character, so we can go up one level.
111 s
= strrchr(path
, PATHSEPCHAR
);
113 s
[1] = '\0'; // go up a directory
114 #if defined(__MORPHOS__) || defined(__AMIGAOS__)
115 /* On MorphOS or AmigaOS paths look like: "Volume:directory/subdirectory" */
116 } else if ((s
= strrchr(path
, ':')) != NULL
) {
124 strcat(path
, item
->name
);
125 strcat(path
, PATHSEP
);
128 case FIOS_TYPE_DIRECT
:
129 snprintf(path
, MAX_PATH
, "%s", item
->name
);
133 case FIOS_TYPE_OLDFILE
:
134 case FIOS_TYPE_SCENARIO
:
135 case FIOS_TYPE_OLD_SCENARIO
:
145 * Construct a filename from its components in destination buffer \a buf.
146 * @param buf Destination buffer.
147 * @param path Directory path, may be \c NULL.
148 * @param name Filename.
149 * @param ext Filename extension (use \c "" for no extension).
150 * @param size Size of \a buf.
152 static void FiosMakeFilename(char *buf
, const char *path
, const char *name
, const char *ext
, size_t size
)
156 /* Don't append the extension if it is already there */
157 period
= strrchr(name
, '.');
158 if (period
!= NULL
&& strcasecmp(period
, ext
) == 0) ext
= "";
159 #if defined(__MORPHOS__) || defined(__AMIGAOS__)
161 unsigned char sepchar
= path
[(strlen(path
) - 1)];
163 if (sepchar
!= ':' && sepchar
!= '/') {
164 snprintf(buf
, size
, "%s" PATHSEP
"%s%s", path
, name
, ext
);
166 snprintf(buf
, size
, "%s%s%s", path
, name
, ext
);
169 snprintf(buf
, size
, "%s%s", name
, ext
);
172 snprintf(buf
, size
, "%s" PATHSEP
"%s%s", path
, name
, ext
);
177 * Make a save game or scenario filename from a name.
178 * @param buf Destination buffer for saving the filename.
179 * @param name Name of the file.
180 * @param size Length of buffer \a buf.
182 void FiosMakeSavegameName(char *buf
, const char *name
, size_t size
)
184 const char *extension
= (_game_mode
== GM_EDITOR
) ? ".scn" : ".sav";
186 FiosMakeFilename(buf
, _fios_path
, name
, extension
, size
);
190 * Construct a filename for a height map.
191 * @param buf Destination buffer.
192 * @param name Filename.
193 * @param size Size of \a buf.
195 void FiosMakeHeightmapName(char *buf
, const char *name
, size_t size
)
199 strecpy(ext
+ 1, GetCurrentScreenshotExtension(), lastof(ext
));
201 FiosMakeFilename(buf
, _fios_path
, name
, ext
, size
);
206 * @param name Filename to delete.
208 bool FiosDelete(const char *name
)
212 FiosMakeSavegameName(filename
, name
, lengthof(filename
));
213 return unlink(filename
) == 0;
216 typedef FiosType
fios_getlist_callback_proc(SaveLoadDialogMode mode
, const char *filename
, const char *ext
, char *title
, const char *last
);
219 * Scanner to scan for a particular type of FIOS file.
221 class FiosFileScanner
: public FileScanner
{
222 SaveLoadDialogMode mode
; ///< The mode we want to search for
223 fios_getlist_callback_proc
*callback_proc
; ///< Callback to check whether the file may be added
227 * @param mode The mode we are in. Some modes don't allow 'parent'.
228 * @param callback_proc The function that is called where you need to do the filtering.
230 FiosFileScanner(SaveLoadDialogMode mode
, fios_getlist_callback_proc
*callback_proc
) :
232 callback_proc(callback_proc
)
235 /* virtual */ bool AddFile(const char *filename
, size_t basepath_length
, const char *tar_filename
);
239 * Try to add a fios item set with the given filename.
240 * @param filename the full path to the file to read
241 * @param basepath_length amount of characters to chop of before to get a relative filename
242 * @return true if the file is added.
244 bool FiosFileScanner::AddFile(const char *filename
, size_t basepath_length
, const char *tar_filename
)
246 const char *ext
= strrchr(filename
, '.');
247 if (ext
== NULL
) return false;
250 fios_title
[0] = '\0'; // reset the title;
252 FiosType type
= this->callback_proc(this->mode
, filename
, ext
, fios_title
, lastof(fios_title
));
253 if (type
== FIOS_TYPE_INVALID
) return false;
255 for (const FiosItem
*fios
= _fios_items
.Begin(); fios
!= _fios_items
.End(); fios
++) {
256 if (strcmp(fios
->name
, filename
) == 0) return false;
259 FiosItem
*fios
= _fios_items
.Append();
262 if (_tstat(OTTD2FS(filename
), &sb
) == 0) {
265 if (stat(filename
, &sb
) == 0) {
267 fios
->mtime
= sb
.st_mtime
;
273 strecpy(fios
->name
, filename
, lastof(fios
->name
));
275 /* If the file doesn't have a title, use its filename */
276 const char *t
= fios_title
;
277 if (StrEmpty(fios_title
)) {
278 t
= strrchr(filename
, PATHSEPCHAR
);
279 t
= (t
== NULL
) ? filename
: (t
+ 1);
281 strecpy(fios
->title
, t
, lastof(fios
->title
));
282 str_validate(fios
->title
, lastof(fios
->title
));
289 * Fill the list of the files in a directory, according to some arbitrary rule.
290 * @param mode The mode we are in. Some modes don't allow 'parent'.
291 * @param callback_proc The function that is called where you need to do the filtering.
292 * @param subdir The directory from where to start (global) searching.
294 static void FiosGetFileList(SaveLoadDialogMode mode
, fios_getlist_callback_proc
*callback_proc
, Subdirectory subdir
)
297 struct dirent
*dirent
;
301 char d_name
[sizeof(fios
->name
)];
305 /* A parent directory link exists if we are not in the root directory */
306 if (!FiosIsRoot(_fios_path
)) {
307 fios
= _fios_items
.Append();
308 fios
->type
= FIOS_TYPE_PARENT
;
310 strecpy(fios
->name
, "..", lastof(fios
->name
));
311 strecpy(fios
->title
, ".. (Parent directory)", lastof(fios
->title
));
314 /* Show subdirectories */
315 if ((dir
= ttd_opendir(_fios_path
)) != NULL
) {
316 while ((dirent
= readdir(dir
)) != NULL
) {
317 strecpy(d_name
, FS2OTTD(dirent
->d_name
), lastof(d_name
));
319 /* found file must be directory, but not '.' or '..' */
320 if (FiosIsValidFile(_fios_path
, dirent
, &sb
) && S_ISDIR(sb
.st_mode
) &&
321 (!FiosIsHiddenFile(dirent
) || strncasecmp(d_name
, PERSONAL_DIR
, strlen(d_name
)) == 0) &&
322 strcmp(d_name
, ".") != 0 && strcmp(d_name
, "..") != 0) {
323 fios
= _fios_items
.Append();
324 fios
->type
= FIOS_TYPE_DIR
;
326 strecpy(fios
->name
, d_name
, lastof(fios
->name
));
327 snprintf(fios
->title
, lengthof(fios
->title
), "%s" PATHSEP
" (Directory)", d_name
);
328 str_validate(fios
->title
, lastof(fios
->title
));
334 /* Sort the subdirs always by name, ascending, remember user-sorting order */
336 SortingBits order
= _savegame_sort_order
;
337 _savegame_sort_order
= SORT_BY_NAME
| SORT_ASCENDING
;
338 QSortT(_fios_items
.Begin(), _fios_items
.Length(), CompareFiosItems
);
339 _savegame_sort_order
= order
;
342 /* This is where to start sorting for the filenames */
343 sort_start
= _fios_items
.Length();
346 FiosFileScanner
scanner(mode
, callback_proc
);
347 if (subdir
== NO_DIRECTORY
) {
348 scanner
.Scan(NULL
, _fios_path
, false);
350 scanner
.Scan(NULL
, subdir
, true, true);
353 QSortT(_fios_items
.Get(sort_start
), _fios_items
.Length() - sort_start
, CompareFiosItems
);
358 _fios_items
.Compact();
362 * Get the title of a file, which (if exists) is stored in a file named
363 * the same as the data file but with '.title' added to it.
364 * @param file filename to get the title for
365 * @param title the title buffer to fill
366 * @param last the last element in the title buffer
367 * @param subdir the sub directory to search in
369 static void GetFileTitle(const char *file
, char *title
, const char *last
, Subdirectory subdir
)
372 strecpy(buf
, file
, lastof(buf
));
373 strecat(buf
, ".title", lastof(buf
));
375 FILE *f
= FioFOpenFile(buf
, "r", subdir
);
376 if (f
== NULL
) return;
378 size_t read
= fread(title
, 1, last
- title
, f
);
379 assert(title
+ read
<= last
);
381 str_validate(title
, last
);
386 * Callback for FiosGetFileList. It tells if a file is a savegame or not.
387 * @param mode Save/load mode.
388 * @param file Name of the file to check.
389 * @param ext A pointer to the extension identifier inside file
390 * @param title Buffer if a callback wants to lookup the title of the file; NULL to skip the lookup
391 * @param last Last available byte in buffer (to prevent buffer overflows); not used when title == NULL
392 * @return a FIOS_TYPE_* type of the found file, FIOS_TYPE_INVALID if not a savegame
393 * @see FiosGetFileList
394 * @see FiosGetSavegameList
396 FiosType
FiosGetSavegameListCallback(SaveLoadDialogMode mode
, const char *file
, const char *ext
, char *title
, const char *last
)
398 /* Show savegame files
399 * .SAV OpenTTD saved game
400 * .SS1 Transport Tycoon Deluxe preset game
401 * .SV1 Transport Tycoon Deluxe (Patch) saved game
402 * .SV2 Transport Tycoon Deluxe (Patch) saved 2-player game */
403 if (strcasecmp(ext
, ".sav") == 0) {
404 GetFileTitle(file
, title
, last
, SAVE_DIR
);
405 return FIOS_TYPE_FILE
;
408 if (mode
== SLD_LOAD_GAME
|| mode
== SLD_LOAD_SCENARIO
) {
409 if (strcasecmp(ext
, ".ss1") == 0 || strcasecmp(ext
, ".sv1") == 0 ||
410 strcasecmp(ext
, ".sv2") == 0) {
411 if (title
!= NULL
) GetOldSaveGameName(file
, title
, last
);
412 return FIOS_TYPE_OLDFILE
;
416 return FIOS_TYPE_INVALID
;
420 * Get a list of savegames.
421 * @param mode Save/load mode.
422 * @see FiosGetFileList
424 void FiosGetSavegameList(SaveLoadDialogMode mode
)
426 static char *fios_save_path
= NULL
;
428 if (fios_save_path
== NULL
) {
429 fios_save_path
= MallocT
<char>(MAX_PATH
);
430 FioGetDirectory(fios_save_path
, MAX_PATH
, SAVE_DIR
);
433 _fios_path
= fios_save_path
;
435 FiosGetFileList(mode
, &FiosGetSavegameListCallback
, NO_DIRECTORY
);
439 * Callback for FiosGetFileList. It tells if a file is a scenario or not.
440 * @param mode Save/load mode.
441 * @param file Name of the file to check.
442 * @param ext A pointer to the extension identifier inside file
443 * @param title Buffer if a callback wants to lookup the title of the file
444 * @param last Last available byte in buffer (to prevent buffer overflows)
445 * @return a FIOS_TYPE_* type of the found file, FIOS_TYPE_INVALID if not a scenario
446 * @see FiosGetFileList
447 * @see FiosGetScenarioList
449 static FiosType
FiosGetScenarioListCallback(SaveLoadDialogMode mode
, const char *file
, const char *ext
, char *title
, const char *last
)
451 /* Show scenario files
452 * .SCN OpenTTD style scenario file
453 * .SV0 Transport Tycoon Deluxe (Patch) scenario
454 * .SS0 Transport Tycoon Deluxe preset scenario */
455 if (strcasecmp(ext
, ".scn") == 0) {
456 GetFileTitle(file
, title
, last
, SCENARIO_DIR
);
457 return FIOS_TYPE_SCENARIO
;
460 if (mode
== SLD_LOAD_GAME
|| mode
== SLD_LOAD_SCENARIO
) {
461 if (strcasecmp(ext
, ".sv0") == 0 || strcasecmp(ext
, ".ss0") == 0 ) {
462 GetOldSaveGameName(file
, title
, last
);
463 return FIOS_TYPE_OLD_SCENARIO
;
467 return FIOS_TYPE_INVALID
;
471 * Get a list of scenarios.
472 * @param mode Save/load mode.
473 * @see FiosGetFileList
475 void FiosGetScenarioList(SaveLoadDialogMode mode
)
477 static char *fios_scn_path
= NULL
;
479 /* Copy the default path on first run or on 'New Game' */
480 if (fios_scn_path
== NULL
) {
481 fios_scn_path
= MallocT
<char>(MAX_PATH
);
482 FioGetDirectory(fios_scn_path
, MAX_PATH
, SCENARIO_DIR
);
485 _fios_path
= fios_scn_path
;
487 char base_path
[MAX_PATH
];
488 FioGetDirectory(base_path
, sizeof(base_path
), SCENARIO_DIR
);
490 FiosGetFileList(mode
, &FiosGetScenarioListCallback
, (mode
== SLD_LOAD_SCENARIO
&& strcmp(base_path
, _fios_path
) == 0) ? SCENARIO_DIR
: NO_DIRECTORY
);
493 static FiosType
FiosGetHeightmapListCallback(SaveLoadDialogMode mode
, const char *file
, const char *ext
, char *title
, const char *last
)
495 /* Show heightmap files
496 * .PNG PNG Based heightmap files
497 * .BMP BMP Based heightmap files
500 FiosType type
= FIOS_TYPE_INVALID
;
503 if (strcasecmp(ext
, ".png") == 0) type
= FIOS_TYPE_PNG
;
504 #endif /* WITH_PNG */
506 if (strcasecmp(ext
, ".bmp") == 0) type
= FIOS_TYPE_BMP
;
508 if (type
== FIOS_TYPE_INVALID
) return FIOS_TYPE_INVALID
;
510 TarFileList::iterator it
= _tar_filelist
[SCENARIO_DIR
].find(file
);
511 if (it
!= _tar_filelist
[SCENARIO_DIR
].end()) {
512 /* If the file is in a tar and that tar is not in a heightmap
513 * directory we are for sure not supposed to see it.
514 * Examples of this are pngs part of documentation within
515 * collections of NewGRFs or 32 bpp graphics replacement PNGs.
519 FOR_ALL_SEARCHPATHS(sp
) {
521 FioAppendDirectory(buf
, sizeof(buf
), sp
, HEIGHTMAP_DIR
);
523 if (strncmp(buf
, it
->second
.tar_filename
, strlen(buf
)) == 0) {
529 if (!match
) return FIOS_TYPE_INVALID
;
532 GetFileTitle(file
, title
, last
, HEIGHTMAP_DIR
);
538 * Get a list of heightmaps.
539 * @param mode Save/load mode.
541 void FiosGetHeightmapList(SaveLoadDialogMode mode
)
543 static char *fios_hmap_path
= NULL
;
545 if (fios_hmap_path
== NULL
) {
546 fios_hmap_path
= MallocT
<char>(MAX_PATH
);
547 FioGetDirectory(fios_hmap_path
, MAX_PATH
, HEIGHTMAP_DIR
);
550 _fios_path
= fios_hmap_path
;
552 char base_path
[MAX_PATH
];
553 FioGetDirectory(base_path
, sizeof(base_path
), HEIGHTMAP_DIR
);
555 FiosGetFileList(mode
, &FiosGetHeightmapListCallback
, strcmp(base_path
, _fios_path
) == 0 ? HEIGHTMAP_DIR
: NO_DIRECTORY
);
559 * Get the directory for screenshots.
560 * @return path to screenshots
562 const char *FiosGetScreenshotDir()
564 static char *fios_screenshot_path
= NULL
;
566 if (fios_screenshot_path
== NULL
) {
567 fios_screenshot_path
= MallocT
<char>(MAX_PATH
);
568 FioGetDirectory(fios_screenshot_path
, MAX_PATH
, SCREENSHOT_DIR
);
571 return fios_screenshot_path
;
574 #if defined(ENABLE_NETWORK)
575 #include "network/network_content.h"
576 #include "3rdparty/md5/md5.h"
578 /** Basic data to distinguish a scenario. Used in the server list window */
579 struct ScenarioIdentifier
{
580 uint32 scenid
; ///< ID for the scenario (generated by content).
581 uint8 md5sum
[16]; ///< MD5 checksum of file.
582 char filename
[MAX_PATH
]; ///< filename of the file.
584 bool operator == (const ScenarioIdentifier
&other
) const
586 return this->scenid
== other
.scenid
&&
587 memcmp(this->md5sum
, other
.md5sum
, sizeof(this->md5sum
)) == 0;
590 bool operator != (const ScenarioIdentifier
&other
) const
592 return !(*this == other
);
597 * Scanner to find the unique IDs of scenarios
599 class ScenarioScanner
: protected FileScanner
, public SmallVector
<ScenarioIdentifier
, 8> {
600 bool scanned
; ///< Whether we've already scanned
603 ScenarioScanner() : scanned(false) {}
606 * Scan, but only if it's needed.
607 * @param rescan whether to force scanning even when it's not necessary
609 void Scan(bool rescan
)
611 if (this->scanned
&& !rescan
) return;
613 this->FileScanner::Scan(".id", SCENARIO_DIR
, true, true);
614 this->scanned
= true;
617 /* virtual */ bool AddFile(const char *filename
, size_t basepath_length
, const char *tar_filename
)
619 FILE *f
= FioFOpenFile(filename
, "r", SCENARIO_DIR
);
620 if (f
== NULL
) return false;
622 ScenarioIdentifier id
;
623 int fret
= fscanf(f
, "%i", &id
.scenid
);
625 if (fret
!= 1) return false;
626 strecpy(id
.filename
, filename
, lastof(id
.filename
));
630 char basename
[MAX_PATH
]; ///< \a filename without the extension.
633 /* open the scenario file, but first get the name.
634 * This is safe as we check on extension which
635 * must always exist. */
636 strecpy(basename
, filename
, lastof(basename
));
637 *strrchr(basename
, '.') = '\0';
638 f
= FioFOpenFile(basename
, "rb", SCENARIO_DIR
, &size
);
639 if (f
== NULL
) return false;
641 /* calculate md5sum */
642 while ((len
= fread(buffer
, 1, (size
> sizeof(buffer
)) ? sizeof(buffer
) : size
, f
)) != 0 && size
!= 0) {
644 checksum
.Append(buffer
, len
);
646 checksum
.Finish(id
.md5sum
);
655 /** Scanner for scenarios */
656 static ScenarioScanner _scanner
;
659 * Find a given scenario based on its unique ID.
660 * @param ci The content info to compare it to.
661 * @param md5sum Whether to look at the md5sum or the id.
662 * @return The filename of the file, else \c NULL.
664 const char *FindScenario(const ContentInfo
*ci
, bool md5sum
)
666 _scanner
.Scan(false);
668 for (ScenarioIdentifier
*id
= _scanner
.Begin(); id
!= _scanner
.End(); id
++) {
669 if (md5sum
? (memcmp(id
->md5sum
, ci
->md5sum
, sizeof(id
->md5sum
)) == 0)
670 : (id
->scenid
== ci
->unique_id
)) {
679 * Check whether we've got a given scenario based on its unique ID.
680 * @param ci The content info to compare it to.
681 * @param md5sum Whether to look at the md5sum or the id.
682 * @return True iff we've got the scenario.
684 bool HasScenario(const ContentInfo
*ci
, bool md5sum
)
686 return (FindScenario(ci
, md5sum
) != NULL
);
690 * Force a (re)scan of the scenarios.
697 #endif /* ENABLE_NETWORK */