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"
27 #include "table/strings.h"
29 /* Variables to display file lists */
30 static char *_fios_path
;
31 SortingBits _savegame_sort_order
= SORT_BY_DATE
| SORT_DESCENDING
;
33 /* OS-specific functions are taken from their respective files (win32/unix/os2 .c) */
34 extern bool FiosIsRoot(const char *path
);
35 extern bool FiosIsValidFile(const char *path
, const struct dirent
*ent
, struct stat
*sb
);
36 extern bool FiosIsHiddenFile(const struct dirent
*ent
);
37 extern void FiosGetDrives(FileList
&file_list
);
39 /* get the name of an oldstyle savegame */
40 extern void GetOldSaveGameName (const char *file
, stringb
*title
);
43 * Compare two FiosItem's. Used with sort when sorting the file list.
44 * @param da A pointer to the first FiosItem to compare.
45 * @param db A pointer to the second FiosItem to compare.
46 * @return -1, 0 or 1, depending on how the two items should be sorted.
48 int CDECL
CompareFiosItems(const FiosItem
*da
, const FiosItem
*db
)
52 if ((_savegame_sort_order
& SORT_BY_NAME
) == 0 && da
->mtime
!= db
->mtime
) {
53 r
= da
->mtime
< db
->mtime
? -1 : 1;
55 r
= strcasecmp(da
->title
, db
->title
);
58 if (_savegame_sort_order
& SORT_DESCENDING
) r
= -r
;
68 * Construct a file list with the given kind of files, for the stated purpose.
69 * @param abstract_filetype Kind of files to collect.
70 * @param fop Purpose of the collection, either #SLO_LOAD or #SLO_SAVE.
72 void FileList::BuildFileList(AbstractFileType abstract_filetype
, SaveLoadOperation fop
)
76 assert(fop
== SLO_LOAD
|| SLO_SAVE
);
77 switch (abstract_filetype
) {
82 FiosGetSavegameList(fop
, *this);
86 FiosGetScenarioList(fop
, *this);
90 FiosGetHeightmapList(fop
, *this);
99 * Find file information of a file by its name from the file list.
100 * @param file The filename to return information about. Can be the actual name
101 * or a numbered entry into the filename list.
102 * @return The information on the file, or \c NULL if the file is not available.
104 const FiosItem
*FileList::FindItem(const char *file
)
106 for (const FiosItem
*item
= this->Begin(); item
!= this->End(); item
++) {
107 if (strcmp(file
, item
->name
) == 0) return item
;
108 if (strcmp(file
, item
->title
) == 0) return item
;
111 /* If no name matches, try to parse it as number */
113 int i
= strtol(file
, &endptr
, 10);
114 if (file
== endptr
|| *endptr
!= '\0') i
= -1;
116 if (IsInsideMM(i
, 0, this->Length())) return this->Get(i
);
118 /* As a last effort assume it is an OpenTTD savegame and
119 * that the ".sav" part was not given. */
120 char long_file
[MAX_PATH
];
121 bstrfmt (long_file
, "%s.sav", file
);
122 for (const FiosItem
*item
= this->Begin(); item
!= this->End(); item
++) {
123 if (strcmp(long_file
, item
->name
) == 0) return item
;
124 if (strcmp(long_file
, item
->title
) == 0) return item
;
130 /** Get the current value of #_fios_path. */
131 const char *FiosGetPath (void)
137 * Browse to a new path based on the passed \a item, starting at #_fios_path.
138 * @param *item Item telling us what to do.
139 * @return A filename w/path if we reached a file, otherwise \c NULL.
141 const char *FiosBrowseTo(const FiosItem
*item
)
143 char *path
= _fios_path
;
145 switch (item
->type
) {
146 case FIOS_TYPE_DRIVE
:
148 snprintf(path
, MAX_PATH
, PATHSEP
"");
149 #elif defined(WIN32) || defined(__OS2__)
150 snprintf(path
, MAX_PATH
, "%c:" PATHSEP
, item
->title
[0]);
153 case FIOS_TYPE_INVALID
:
156 case FIOS_TYPE_PARENT
: {
157 /* Check for possible NULL ptr (not required for UNIXes, but AmigaOS-alikes) */
158 char *s
= strrchr(path
, PATHSEPCHAR
);
159 if (s
!= NULL
&& s
!= path
) {
160 s
[0] = '\0'; // Remove last path separator character, so we can go up one level.
162 s
= strrchr(path
, PATHSEPCHAR
);
164 s
[1] = '\0'; // go up a directory
165 #if defined(__MORPHOS__) || defined(__AMIGAOS__)
166 /* On MorphOS or AmigaOS paths look like: "Volume:directory/subdirectory" */
167 } else if ((s
= strrchr(path
, ':')) != NULL
) {
175 strcat(path
, item
->name
);
176 strcat(path
, PATHSEP
);
179 case FIOS_TYPE_DIRECT
:
180 snprintf(path
, MAX_PATH
, "%s", item
->name
);
184 case FIOS_TYPE_OLDFILE
:
185 case FIOS_TYPE_SCENARIO
:
186 case FIOS_TYPE_OLD_SCENARIO
:
196 * Construct a filename from its components in destination buffer \a buf.
197 * @param buf Destination buffer.
198 * @param path Directory path, may be \c NULL.
199 * @param name Filename.
200 * @param ext Filename extension (use \c "" for no extension).
201 * @param size Size of \a buf.
203 static void FiosMakeFilename(char *buf
, const char *path
, const char *name
, const char *ext
, size_t size
)
207 /* Don't append the extension if it is already there */
208 period
= strrchr(name
, '.');
209 if (period
!= NULL
&& strcasecmp(period
, ext
) == 0) ext
= "";
210 #if defined(__MORPHOS__) || defined(__AMIGAOS__)
212 unsigned char sepchar
= path
[(strlen(path
) - 1)];
214 if (sepchar
!= ':' && sepchar
!= '/') {
215 snprintf(buf
, size
, "%s" PATHSEP
"%s%s", path
, name
, ext
);
217 snprintf(buf
, size
, "%s%s%s", path
, name
, ext
);
220 snprintf(buf
, size
, "%s%s", name
, ext
);
223 snprintf(buf
, size
, "%s" PATHSEP
"%s%s", path
, name
, ext
);
228 * Make a save game or scenario filename from a name.
229 * @param buf Destination buffer for saving the filename.
230 * @param name Name of the file.
231 * @param size Length of buffer \a buf.
233 void FiosMakeSavegameName(char *buf
, const char *name
, size_t size
)
235 const char *extension
= (_game_mode
== GM_EDITOR
) ? ".scn" : ".sav";
237 FiosMakeFilename(buf
, _fios_path
, name
, extension
, size
);
241 * Construct a filename for a height map.
242 * @param buf Destination buffer.
243 * @param name Filename.
244 * @param size Size of \a buf.
246 void FiosMakeHeightmapName(char *buf
, const char *name
, size_t size
)
248 FiosMakeFilename (buf
, _fios_path
, name
, GetCurrentScreenshotExtension(), size
);
253 * @param name Filename to delete.
255 bool FiosDelete(const char *name
)
259 FiosMakeSavegameName(filename
, name
, lengthof(filename
));
260 return unlink(filename
) == 0;
263 typedef FiosType
fios_getlist_callback_proc (SaveLoadOperation fop
, const char *filename
, const char *ext
, stringb
*title
);
266 * Scanner to scan for a particular type of FIOS file.
268 class FiosFileScanner
: public FileScanner
{
269 SaveLoadOperation fop
; ///< The kind of file we are looking for.
270 fios_getlist_callback_proc
*callback_proc
; ///< Callback to check whether the file may be added
271 FileList
&file_list
; ///< Destination of the found files.
275 * @param fop Purpose of collecting the list.
276 * @param callback_proc The function that is called where you need to do the filtering.
277 * @param file_list Destination of the found files.
279 FiosFileScanner(SaveLoadOperation fop
, fios_getlist_callback_proc
*callback_proc
, FileList
&file_list
) :
280 fop(fop
), callback_proc(callback_proc
), file_list(file_list
)
283 /* virtual */ bool AddFile(const char *filename
, size_t basepath_length
, const char *tar_filename
);
287 * Try to add a fios item set with the given filename.
288 * @param filename the full path to the file to read
289 * @param basepath_length amount of characters to chop of before to get a relative filename
290 * @return true if the file is added.
292 bool FiosFileScanner::AddFile(const char *filename
, size_t basepath_length
, const char *tar_filename
)
294 const char *ext
= strrchr(filename
, '.');
295 if (ext
== NULL
) return false;
297 sstring
<64> fios_title
;
299 FiosType type
= this->callback_proc(this->fop
, filename
, ext
, &fios_title
);
300 if (type
== FIOS_TYPE_INVALID
) return false;
302 for (const FiosItem
*fios
= file_list
.Begin(); fios
!= file_list
.End(); fios
++) {
303 if (strcmp(fios
->name
, filename
) == 0) return false;
306 FiosItem
*fios
= file_list
.Append();
309 if (_tstat(OTTD2FS(filename
), &sb
) == 0) {
312 if (stat(filename
, &sb
) == 0) {
314 fios
->mtime
= sb
.st_mtime
;
320 bstrcpy (fios
->name
, filename
);
322 /* If the file doesn't have a title, use its filename */
323 const char *t
= fios_title
.c_str();
324 if (fios_title
.empty()) {
325 t
= strrchr(filename
, PATHSEPCHAR
);
326 t
= (t
== NULL
) ? filename
: (t
+ 1);
328 bstrcpy (fios
->title
, t
);
329 str_validate(fios
->title
, lastof(fios
->title
));
336 * Fill the list of the files in a directory, according to some arbitrary rule.
337 * @param fop Purpose of collecting the list.
338 * @param callback_proc The function that is called where you need to do the filtering.
339 * @param subdir The directory from where to start (global) searching.
340 * @param file_list Destination of the found files.
342 static void FiosGetFileList(SaveLoadOperation fop
, fios_getlist_callback_proc
*callback_proc
, Subdirectory subdir
, FileList
&file_list
)
345 struct dirent
*dirent
;
349 char d_name
[sizeof(fios
->name
)];
353 /* A parent directory link exists if we are not in the root directory */
354 if (!FiosIsRoot(_fios_path
)) {
355 fios
= file_list
.Append();
356 fios
->type
= FIOS_TYPE_PARENT
;
358 bstrcpy (fios
->name
, "..");
359 bstrcpy (fios
->title
, ".. (Parent directory)");
362 /* Show subdirectories */
363 if ((dir
= ttd_opendir(_fios_path
)) != NULL
) {
364 while ((dirent
= readdir(dir
)) != NULL
) {
365 bstrcpy (d_name
, FS2OTTD(dirent
->d_name
));
367 /* found file must be directory, but not '.' or '..' */
368 if (FiosIsValidFile(_fios_path
, dirent
, &sb
) && S_ISDIR(sb
.st_mode
) &&
369 (!FiosIsHiddenFile(dirent
) || strncasecmp(d_name
, PERSONAL_DIR
, strlen(d_name
)) == 0) &&
370 strcmp(d_name
, ".") != 0 && strcmp(d_name
, "..") != 0) {
371 fios
= file_list
.Append();
372 fios
->type
= FIOS_TYPE_DIR
;
374 bstrcpy (fios
->name
, d_name
);
375 bstrfmt (fios
->title
, "%s" PATHSEP
" (Directory)", d_name
);
376 str_validate(fios
->title
, lastof(fios
->title
));
382 /* Sort the subdirs always by name, ascending, remember user-sorting order */
384 SortingBits order
= _savegame_sort_order
;
385 _savegame_sort_order
= SORT_BY_NAME
| SORT_ASCENDING
;
386 file_list
.files
.Sort (CompareFiosItems
);
387 _savegame_sort_order
= order
;
390 /* This is where to start sorting for the filenames */
391 sort_start
= file_list
.Length();
394 FiosFileScanner
scanner(fop
, callback_proc
, file_list
);
395 if (subdir
== NO_DIRECTORY
) {
396 scanner
.Scan(NULL
, _fios_path
, NULL
, false);
398 scanner
.Scan(NULL
, subdir
, true, true);
401 file_list
.files
.Sort (CompareFiosItems
, sort_start
);
404 FiosGetDrives(file_list
);
410 * Get the title of a file, which (if exists) is stored in a file named
411 * the same as the data file but with '.title' added to it.
412 * @param file filename to get the title for
413 * @param title the title buffer to fill
414 * @param subdir the sub directory to search in
416 static void GetFileTitle (const char *file
, stringb
*title
, Subdirectory subdir
)
419 bstrfmt (buf
, "%s.title", file
);
421 FILE *f
= FioFOpenFile(buf
, "r", subdir
);
422 if (f
== NULL
) return;
424 title
->len
= fread (title
->buffer
, 1, title
->capacity
- 1, f
);
425 assert (title
->len
< title
->capacity
);
426 title
->buffer
[title
->len
] = '\0';
432 * Callback for FiosGetFileList. It tells if a file is a savegame or not.
433 * @param fop Purpose of collecting the list.
434 * @param file Name of the file to check.
435 * @param ext A pointer to the extension identifier inside file
436 * @param title Buffer if a callback wants to lookup the title of the file; NULL to skip the lookup
437 * @return a FIOS_TYPE_* type of the found file, FIOS_TYPE_INVALID if not a savegame
438 * @see FiosGetFileList
439 * @see FiosGetSavegameList
441 FiosType
FiosGetSavegameListCallback (SaveLoadOperation fop
, const char *file
, const char *ext
, stringb
*title
)
443 /* Show savegame files
444 * .SAV OpenTTD saved game
445 * .SS1 Transport Tycoon Deluxe preset game
446 * .SV1 Transport Tycoon Deluxe (Patch) saved game
447 * .SV2 Transport Tycoon Deluxe (Patch) saved 2-player game */
449 /* Don't crash if we supply no extension */
450 if (ext
== NULL
) return FIOS_TYPE_INVALID
;
452 if (strcasecmp(ext
, ".sav") == 0) {
453 GetFileTitle (file
, title
, SAVE_DIR
);
454 return FIOS_TYPE_FILE
;
457 if (fop
== SLO_LOAD
) {
458 if (strcasecmp(ext
, ".ss1") == 0 || strcasecmp(ext
, ".sv1") == 0 ||
459 strcasecmp(ext
, ".sv2") == 0) {
460 if (title
!= NULL
) GetOldSaveGameName (file
, title
);
461 return FIOS_TYPE_OLDFILE
;
465 return FIOS_TYPE_INVALID
;
469 * Get a list of savegames.
470 * @param fop Purpose of collecting the list.
471 * @param file_list Destination of the found files.
472 * @see FiosGetFileList
474 void FiosGetSavegameList(SaveLoadOperation fop
, FileList
&file_list
)
476 static char *fios_save_path
= NULL
;
478 if (fios_save_path
== NULL
) {
479 fios_save_path
= xmalloc (MAX_PATH
);
480 FioGetDirectory(fios_save_path
, MAX_PATH
, SAVE_DIR
);
483 _fios_path
= fios_save_path
;
485 FiosGetFileList(fop
, &FiosGetSavegameListCallback
, NO_DIRECTORY
, file_list
);
489 * Callback for FiosGetFileList. It tells if a file is a scenario or not.
490 * @param fop Purpose of collecting the list.
491 * @param file Name of the file to check.
492 * @param ext A pointer to the extension identifier inside file
493 * @param title Buffer if a callback wants to lookup the title of the file
494 * @return a FIOS_TYPE_* type of the found file, FIOS_TYPE_INVALID if not a scenario
495 * @see FiosGetFileList
496 * @see FiosGetScenarioList
498 static FiosType
FiosGetScenarioListCallback (SaveLoadOperation fop
, const char *file
, const char *ext
, stringb
*title
)
500 /* Show scenario files
501 * .SCN OpenTTD style scenario file
502 * .SV0 Transport Tycoon Deluxe (Patch) scenario
503 * .SS0 Transport Tycoon Deluxe preset scenario */
504 if (strcasecmp(ext
, ".scn") == 0) {
505 GetFileTitle (file
, title
, SCENARIO_DIR
);
506 return FIOS_TYPE_SCENARIO
;
509 if (fop
== SLO_LOAD
) {
510 if (strcasecmp(ext
, ".sv0") == 0 || strcasecmp(ext
, ".ss0") == 0 ) {
511 GetOldSaveGameName (file
, title
);
512 return FIOS_TYPE_OLD_SCENARIO
;
516 return FIOS_TYPE_INVALID
;
520 * Get a list of scenarios.
521 * @param fop Purpose of collecting the list.
522 * @param file_list Destination of the found files.
523 * @see FiosGetFileList
525 void FiosGetScenarioList(SaveLoadOperation fop
, FileList
&file_list
)
527 static char *fios_scn_path
= NULL
;
529 /* Copy the default path on first run or on 'New Game' */
530 if (fios_scn_path
== NULL
) {
531 fios_scn_path
= xmalloc (MAX_PATH
);
532 FioGetDirectory(fios_scn_path
, MAX_PATH
, SCENARIO_DIR
);
535 _fios_path
= fios_scn_path
;
537 char base_path
[MAX_PATH
];
538 FioGetDirectory(base_path
, sizeof(base_path
), SCENARIO_DIR
);
540 Subdirectory subdir
= (fop
== SLO_LOAD
&& strcmp(base_path
, _fios_path
) == 0) ? SCENARIO_DIR
: NO_DIRECTORY
;
541 FiosGetFileList(fop
, &FiosGetScenarioListCallback
, subdir
, file_list
);
544 static FiosType
FiosGetHeightmapListCallback (SaveLoadOperation fop
, const char *file
, const char *ext
, stringb
*title
)
546 /* Show heightmap files
547 * .PNG PNG Based heightmap files
548 * .BMP BMP Based heightmap files
551 FiosType type
= FIOS_TYPE_INVALID
;
554 if (strcasecmp(ext
, ".png") == 0) type
= FIOS_TYPE_PNG
;
555 #endif /* WITH_PNG */
557 if (strcasecmp(ext
, ".bmp") == 0) type
= FIOS_TYPE_BMP
;
559 if (type
== FIOS_TYPE_INVALID
) return FIOS_TYPE_INVALID
;
561 TarFileList::iterator it
= TarCache::cache
[SCENARIO_DIR
].files
.find(file
);
562 if (it
!= TarCache::cache
[SCENARIO_DIR
].files
.end()) {
563 /* If the file is in a tar and that tar is not in a heightmap
564 * directory we are for sure not supposed to see it.
565 * Examples of this are pngs part of documentation within
566 * collections of NewGRFs or 32 bpp graphics replacement PNGs.
570 FOR_ALL_SEARCHPATHS(sp
) {
572 FioGetFullPath (buf
, sizeof(buf
), sp
, HEIGHTMAP_DIR
);
574 if (strncmp(buf
, it
->second
.tar_filename
, strlen(buf
)) == 0) {
580 if (!match
) return FIOS_TYPE_INVALID
;
583 GetFileTitle (file
, title
, HEIGHTMAP_DIR
);
589 * Get a list of heightmaps.
590 * @param fop Purpose of collecting the list.
591 * @param file_list Destination of the found files.
593 void FiosGetHeightmapList(SaveLoadOperation fop
, FileList
&file_list
)
595 static char *fios_hmap_path
= NULL
;
597 if (fios_hmap_path
== NULL
) {
598 fios_hmap_path
= xmalloc (MAX_PATH
);
599 FioGetDirectory(fios_hmap_path
, MAX_PATH
, HEIGHTMAP_DIR
);
602 _fios_path
= fios_hmap_path
;
604 char base_path
[MAX_PATH
];
605 FioGetDirectory(base_path
, sizeof(base_path
), HEIGHTMAP_DIR
);
607 Subdirectory subdir
= strcmp(base_path
, _fios_path
) == 0 ? HEIGHTMAP_DIR
: NO_DIRECTORY
;
608 FiosGetFileList(fop
, &FiosGetHeightmapListCallback
, subdir
, file_list
);
612 * Get the directory for screenshots.
613 * @return path to screenshots
615 const char *FiosGetScreenshotDir()
617 static char *fios_screenshot_path
= NULL
;
619 if (fios_screenshot_path
== NULL
) {
620 fios_screenshot_path
= xmalloc (MAX_PATH
);
621 FioGetDirectory(fios_screenshot_path
, MAX_PATH
, SCREENSHOT_DIR
);
624 return fios_screenshot_path
;
627 #if defined(ENABLE_NETWORK)
628 #include "network/network_content.h"
629 #include "3rdparty/md5/md5.h"
631 /** Basic data to distinguish a scenario. Used in the server list window */
632 struct ScenarioIdentifier
{
633 uint32 scenid
; ///< ID for the scenario (generated by content).
634 uint8 md5sum
[16]; ///< MD5 checksum of file.
635 char filename
[MAX_PATH
]; ///< filename of the file.
637 bool operator == (const ScenarioIdentifier
&other
) const
639 return this->scenid
== other
.scenid
&&
640 memcmp(this->md5sum
, other
.md5sum
, sizeof(this->md5sum
)) == 0;
643 bool operator != (const ScenarioIdentifier
&other
) const
645 return !(*this == other
);
650 * Scanner to find the unique IDs of scenarios
652 class ScenarioScanner
: protected FileScanner
, public SmallVector
<ScenarioIdentifier
, 8> {
653 bool scanned
; ///< Whether we've already scanned
656 ScenarioScanner() : scanned(false) {}
659 * Scan, but only if it's needed.
660 * @param rescan whether to force scanning even when it's not necessary
662 void Scan(bool rescan
)
664 if (this->scanned
&& !rescan
) return;
666 this->FileScanner::Scan(".id", SCENARIO_DIR
, true, true);
667 this->scanned
= true;
670 /* virtual */ bool AddFile(const char *filename
, size_t basepath_length
, const char *tar_filename
)
672 FILE *f
= FioFOpenFile(filename
, "r", SCENARIO_DIR
);
673 if (f
== NULL
) return false;
675 ScenarioIdentifier id
;
676 int fret
= fscanf(f
, "%i", &id
.scenid
);
678 if (fret
!= 1) return false;
679 bstrcpy (id
.filename
, filename
);
683 char basename
[MAX_PATH
]; ///< \a filename without the extension.
686 /* open the scenario file, but first get the name.
687 * This is safe as we check on extension which
688 * must always exist. */
689 bstrcpy (basename
, filename
);
690 *strrchr(basename
, '.') = '\0';
691 f
= FioFOpenFile(basename
, "rb", SCENARIO_DIR
, &size
);
692 if (f
== NULL
) return false;
694 /* calculate md5sum */
695 while ((len
= fread(buffer
, 1, (size
> sizeof(buffer
)) ? sizeof(buffer
) : size
, f
)) != 0 && size
!= 0) {
697 checksum
.Append(buffer
, len
);
699 checksum
.Finish(id
.md5sum
);
708 /** Scanner for scenarios */
709 static ScenarioScanner _scanner
;
712 * Find a given scenario based on its unique ID.
713 * @param ci The content info to compare it to.
714 * @param md5sum Whether to look at the md5sum or the id.
715 * @return The filename of the file, else \c NULL.
717 const char *FindScenario(const ContentInfo
*ci
, bool md5sum
)
719 _scanner
.Scan(false);
721 for (ScenarioIdentifier
*id
= _scanner
.Begin(); id
!= _scanner
.End(); id
++) {
722 if (md5sum
? (memcmp(id
->md5sum
, ci
->md5sum
, sizeof(id
->md5sum
)) == 0)
723 : (id
->scenid
== ci
->unique_id
)) {
732 * Check whether we've got a given scenario based on its unique ID.
733 * @param ci The content info to compare it to.
734 * @param md5sum Whether to look at the md5sum or the id.
735 * @return True iff we've got the scenario.
737 bool HasScenario(const ContentInfo
*ci
, bool md5sum
)
739 return (FindScenario(ci
, md5sum
) != NULL
);
743 * Force a (re)scan of the scenarios.
750 #endif /* ENABLE_NETWORK */