Update readme and changelog for v1.27.0
[openttd-joker.git] / src / fios.cpp
blob53b451268871f61f9655e3e0e331156cf0976496
1 /* $Id: fios.cpp 26423 2014-03-23 14:55:32Z planetmaker $ */
3 /*
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/>.
8 */
10 /**
11 * @file fios.cpp
12 * This file contains functions for building file lists for the save/load dialogs.
15 #include "stdafx.h"
16 #include "fios.h"
17 #include "fileio_func.h"
18 #include "tar_type.h"
19 #include "screenshot.h"
20 #include "string_func.h"
21 #include <sys/stat.h>
23 #ifndef WIN32
24 # include <unistd.h>
25 #endif /* WIN32 */
27 #include "table/strings.h"
29 #include "safeguards.h"
31 /* Variables to display file lists */
32 static char *_fios_path;
33 static const char *_fios_path_last;
34 SortingBits _savegame_sort_order = SORT_BY_DATE | SORT_DESCENDING;
36 /* OS-specific functions are taken from their respective files (win32/unix/os2 .c) */
37 extern bool FiosIsRoot(const char *path);
38 extern bool FiosIsValidFile(const char *path, const struct dirent *ent, struct stat *sb);
39 extern bool FiosIsHiddenFile(const struct dirent *ent);
40 extern void FiosGetDrives(FileList &file_list);
41 extern bool FiosGetDiskFreeSpace(const char *path, uint64 *tot);
43 /* get the name of an oldstyle savegame */
44 extern void GetOldSaveGameName(const char *file, char *title, const char *last);
46 /**
47 * Compare two FiosItem's. Used with sort when sorting the file list.
48 * @param da A pointer to the first FiosItem to compare.
49 * @param db A pointer to the second FiosItem to compare.
50 * @return -1, 0 or 1, depending on how the two items should be sorted.
52 int CDECL CompareFiosItems(const FiosItem *da, const FiosItem *db)
54 int r = 0;
56 if ((_savegame_sort_order & SORT_BY_NAME) == 0 && da->mtime != db->mtime) {
57 r = da->mtime < db->mtime ? -1 : 1;
58 } else {
59 r = strcasecmp(da->title, db->title);
62 if (_savegame_sort_order & SORT_DESCENDING) r = -r;
63 return r;
66 FileList::~FileList()
68 this->Clear();
71 /**
72 * Construct a file list with the given kind of files, for the stated purpose.
73 * @param abstract_filetype Kind of files to collect.
74 * @param fop Purpose of the collection, either #SLO_LOAD or #SLO_SAVE.
76 void FileList::BuildFileList(AbstractFileType abstract_filetype, SaveLoadOperation fop)
78 this->Clear();
80 assert(fop == SLO_LOAD || fop == SLO_SAVE);
81 switch (abstract_filetype) {
82 case FT_NONE:
83 break;
85 case FT_SAVEGAME:
86 FiosGetSavegameList(fop, *this);
87 break;
89 case FT_SCENARIO:
90 FiosGetScenarioList(fop, *this);
91 break;
93 case FT_HEIGHTMAP:
94 FiosGetHeightmapList(fop, *this);
95 break;
97 default:
98 NOT_REACHED();
103 * Find file information of a file by its name from the file list.
104 * @param file The filename to return information about. Can be the actual name
105 * or a numbered entry into the filename list.
106 * @return The information on the file, or \c nullptr if the file is not available.
108 const FiosItem *FileList::FindItem(const char *file)
110 for (const FiosItem *item = this->Begin(); item != this->End(); item++) {
111 if (strcmp(file, item->name) == 0) return item;
112 if (strcmp(file, item->title) == 0) return item;
115 /* If no name matches, try to parse it as number */
116 char *endptr;
117 int i = strtol(file, &endptr, 10);
118 if (file == endptr || *endptr != '\0') i = -1;
120 if (IsInsideMM(i, 0, this->Length())) return this->Get(i);
122 /* As a last effort assume it is an OpenTTD savegame and
123 * that the ".sav" part was not given. */
124 char long_file[MAX_PATH];
125 seprintf(long_file, lastof(long_file), "%s.sav", file);
126 for (const FiosItem *item = this->Begin(); item != this->End(); item++) {
127 if (strcmp(long_file, item->name) == 0) return item;
128 if (strcmp(long_file, item->title) == 0) return item;
131 return nullptr;
135 * Get descriptive texts. Returns the path and free space
136 * left on the device
137 * @param path string describing the path
138 * @param total_free total free space in megabytes, optional (can be nullptr)
139 * @return StringID describing the path (free space or failure)
141 StringID FiosGetDescText(const char **path, uint64 *total_free)
143 *path = _fios_path;
144 return FiosGetDiskFreeSpace(*path, total_free) ? STR_SAVELOAD_BYTES_FREE : STR_ERROR_UNABLE_TO_READ_DRIVE;
148 * Browse to a new path based on the passed \a item, starting at #_fios_path.
149 * @param *item Item telling us what to do.
150 * @return A filename w/path if we reached a file, otherwise \c nullptr.
152 const char *FiosBrowseTo(const FiosItem *item)
154 switch (item->type) {
155 case FIOS_TYPE_DRIVE:
156 #if defined(WINCE)
157 seprintf(_fios_path, _fios_path_last, PATHSEP "");
158 #elif defined(WIN32) || defined(__OS2__)
159 seprintf(_fios_path, _fios_path_last, "%c:" PATHSEP, item->title[0]);
160 #endif
161 break;
163 case FIOS_TYPE_INVALID:
164 break;
166 case FIOS_TYPE_PARENT: {
167 /* Check for possible nullptr ptr (not required for UNIXes, but AmigaOS-alikes) */
168 char *s = strrchr(_fios_path, PATHSEPCHAR);
169 if (s != nullptr && s != _fios_path) {
170 s[0] = '\0'; // Remove last path separator character, so we can go up one level.
172 s = strrchr(_fios_path, PATHSEPCHAR);
173 if (s != nullptr) {
174 s[1] = '\0'; // go up a directory
175 #if defined(__MORPHOS__) || defined(__AMIGAOS__)
176 /* On MorphOS or AmigaOS paths look like: "Volume:directory/subdirectory" */
177 } else if ((s = strrchr(_fios_path, ':')) != nullptr) {
178 s[1] = '\0';
179 #endif
181 break;
184 case FIOS_TYPE_DIR:
185 strecat(_fios_path, item->name, _fios_path_last);
186 strecat(_fios_path, PATHSEP, _fios_path_last);
187 break;
189 case FIOS_TYPE_DIRECT:
190 seprintf(_fios_path, _fios_path_last, "%s", item->name);
191 break;
193 case FIOS_TYPE_FILE:
194 case FIOS_TYPE_OLDFILE:
195 case FIOS_TYPE_SCENARIO:
196 case FIOS_TYPE_OLD_SCENARIO:
197 case FIOS_TYPE_PNG:
198 case FIOS_TYPE_BMP:
199 return item->name;
202 return nullptr;
206 * Construct a filename from its components in destination buffer \a buf.
207 * @param buf Destination buffer.
208 * @param path Directory path, may be \c nullptr.
209 * @param name Filename.
210 * @param ext Filename extension (use \c "" for no extension).
211 * @param last Last element of buffer \a buf.
213 static void FiosMakeFilename(char *buf, const char *path, const char *name, const char *ext, const char *last)
215 const char *period;
217 /* Don't append the extension if it is already there */
218 period = strrchr(name, '.');
219 if (period != nullptr && strcasecmp(period, ext) == 0) ext = "";
220 #if defined(__MORPHOS__) || defined(__AMIGAOS__)
221 if (path != nullptr) {
222 unsigned char sepchar = path[(strlen(path) - 1)];
224 if (sepchar != ':' && sepchar != '/') {
225 seprintf(buf, last, "%s" PATHSEP "%s%s", path, name, ext);
226 } else {
227 seprintf(buf, last, "%s%s%s", path, name, ext);
229 } else {
230 seprintf(buf, last, "%s%s", name, ext);
232 #else
233 seprintf(buf, last, "%s" PATHSEP "%s%s", path, name, ext);
234 #endif
238 * Make a save game or scenario filename from a name.
239 * @param buf Destination buffer for saving the filename.
240 * @param name Name of the file.
241 * @param last Last element of buffer \a buf.
243 void FiosMakeSavegameName(char *buf, const char *name, const char *last)
245 const char *extension = (_game_mode == GM_EDITOR) ? ".scn" : ".sav";
247 FiosMakeFilename(buf, _fios_path, name, extension, last);
251 * Construct a filename for a height map.
252 * @param buf Destination buffer.
253 * @param name Filename.
254 * @param last Last element of buffer \a buf.
256 void FiosMakeHeightmapName(char *buf, const char *name, const char *last)
258 char ext[5];
259 ext[0] = '.';
260 strecpy(ext + 1, GetCurrentScreenshotExtension(), lastof(ext));
262 FiosMakeFilename(buf, _fios_path, name, ext, last);
266 * Delete a file.
267 * @param name Filename to delete.
268 * @return Whether the file deletion was successful.
270 bool FiosDelete(const char *name)
272 char filename[512];
274 FiosMakeSavegameName(filename, name, lastof(filename));
275 return unlink(filename) == 0;
278 typedef FiosType fios_getlist_callback_proc(SaveLoadOperation fop, const char *filename, const char *ext, char *title, const char *last);
281 * Scanner to scan for a particular type of FIOS file.
283 class FiosFileScanner : public FileScanner {
284 SaveLoadOperation fop; ///< The kind of file we are looking for.
285 fios_getlist_callback_proc *callback_proc; ///< Callback to check whether the file may be added
286 FileList &file_list; ///< Destination of the found files.
287 public:
289 * Create the scanner
290 * @param fop Purpose of collecting the list.
291 * @param callback_proc The function that is called where you need to do the filtering.
292 * @param file_list Destination of the found files.
294 FiosFileScanner(SaveLoadOperation fop, fios_getlist_callback_proc *callback_proc, FileList &file_list) :
295 fop(fop), callback_proc(callback_proc), file_list(file_list)
298 /* virtual */ bool AddFile(const char *filename, size_t basepath_length, const char *tar_filename);
302 * Try to add a fios item set with the given filename.
303 * @param filename the full path to the file to read
304 * @param basepath_length amount of characters to chop of before to get a relative filename
305 * @return true if the file is added.
307 bool FiosFileScanner::AddFile(const char *filename, size_t basepath_length, const char *tar_filename)
309 const char *ext = strrchr(filename, '.');
310 if (ext == nullptr) return false;
312 char fios_title[64];
313 fios_title[0] = '\0'; // reset the title;
315 FiosType type = this->callback_proc(this->fop, filename, ext, fios_title, lastof(fios_title));
316 if (type == FIOS_TYPE_INVALID) return false;
318 for (const FiosItem *fios = file_list.Begin(); fios != file_list.End(); fios++) {
319 if (strcmp(fios->name, filename) == 0) return false;
322 FiosItem *fios = file_list.Append();
323 #ifdef WIN32
324 struct _stat sb;
325 if (_tstat(OTTD2FS(filename), &sb) == 0) {
326 #else
327 struct stat sb;
328 if (stat(filename, &sb) == 0) {
329 #endif
330 fios->mtime = sb.st_mtime;
331 } else {
332 fios->mtime = 0;
335 fios->type = type;
336 strecpy(fios->name, filename, lastof(fios->name));
338 /* If the file doesn't have a title, use its filename */
339 const char *t = fios_title;
340 if (StrEmpty(fios_title)) {
341 t = strrchr(filename, PATHSEPCHAR);
342 t = (t == nullptr) ? filename : (t + 1);
344 strecpy(fios->title, t, lastof(fios->title));
345 str_validate(fios->title, lastof(fios->title));
347 return true;
352 * Fill the list of the files in a directory, according to some arbitrary rule.
353 * @param fop Purpose of collecting the list.
354 * @param callback_proc The function that is called where you need to do the filtering.
355 * @param subdir The directory from where to start (global) searching.
356 * @param file_list Destination of the found files.
358 static void FiosGetFileList(SaveLoadOperation fop, fios_getlist_callback_proc *callback_proc, Subdirectory subdir, FileList &file_list)
360 struct stat sb;
361 struct dirent *dirent;
362 DIR *dir;
363 FiosItem *fios;
364 int sort_start;
365 char d_name[sizeof(fios->name)];
367 file_list.Clear();
369 /* A parent directory link exists if we are not in the root directory */
370 if (!FiosIsRoot(_fios_path)) {
371 fios = file_list.Append();
372 fios->type = FIOS_TYPE_PARENT;
373 fios->mtime = 0;
374 strecpy(fios->name, "..", lastof(fios->name));
375 strecpy(fios->title, ".. (Parent directory)", lastof(fios->title));
378 /* Show subdirectories */
379 if ((dir = ttd_opendir(_fios_path)) != nullptr) {
380 while ((dirent = readdir(dir)) != nullptr) {
381 strecpy(d_name, FS2OTTD(dirent->d_name), lastof(d_name));
383 /* found file must be directory, but not '.' or '..' */
384 if (FiosIsValidFile(_fios_path, dirent, &sb) && S_ISDIR(sb.st_mode) &&
385 (!FiosIsHiddenFile(dirent) || strncasecmp(d_name, PERSONAL_DIR, strlen(d_name)) == 0) &&
386 strcmp(d_name, ".") != 0 && strcmp(d_name, "..") != 0) {
387 fios = file_list.Append();
388 fios->type = FIOS_TYPE_DIR;
389 fios->mtime = 0;
390 strecpy(fios->name, d_name, lastof(fios->name));
391 seprintf(fios->title, lastof(fios->title), "%s" PATHSEP " (Directory)", d_name);
392 str_validate(fios->title, lastof(fios->title));
395 closedir(dir);
398 /* Sort the subdirs always by name, ascending, remember user-sorting order */
400 SortingBits order = _savegame_sort_order;
401 _savegame_sort_order = SORT_BY_NAME | SORT_ASCENDING;
402 QSortT(file_list.files.Begin(), file_list.files.Length(), CompareFiosItems);
403 _savegame_sort_order = order;
406 /* This is where to start sorting for the filenames */
407 sort_start = file_list.Length();
409 /* Show files */
410 FiosFileScanner scanner(fop, callback_proc, file_list);
411 if (subdir == NO_DIRECTORY) {
412 scanner.Scan(nullptr, _fios_path, false);
413 } else {
414 scanner.Scan(nullptr, subdir, true, true);
417 QSortT(file_list.Get(sort_start), file_list.Length() - sort_start, CompareFiosItems);
419 /* Show drives */
420 FiosGetDrives(file_list);
422 file_list.Compact();
426 * Get the title of a file, which (if exists) is stored in a file named
427 * the same as the data file but with '.title' added to it.
428 * @param file filename to get the title for
429 * @param title the title buffer to fill
430 * @param last the last element in the title buffer
431 * @param subdir the sub directory to search in
433 static void GetFileTitle(const char *file, char *title, const char *last, Subdirectory subdir)
435 char buf[MAX_PATH];
436 strecpy(buf, file, lastof(buf));
437 strecat(buf, ".title", lastof(buf));
439 FILE *f = FioFOpenFile(buf, "r", subdir);
440 if (f == nullptr) return;
442 size_t read = fread(title, 1, last - title, f);
443 assert(title + read <= last);
444 title[read] = '\0';
445 str_validate(title, last);
446 FioFCloseFile(f);
450 * Callback for FiosGetFileList. It tells if a file is a savegame or not.
451 * @param fop Purpose of collecting the list.
452 * @param file Name of the file to check.
453 * @param ext A pointer to the extension identifier inside file
454 * @param title Buffer if a callback wants to lookup the title of the file; nullptr to skip the lookup
455 * @param last Last available byte in buffer (to prevent buffer overflows); not used when title == nullptr
456 * @return a FIOS_TYPE_* type of the found file, FIOS_TYPE_INVALID if not a savegame
457 * @see FiosGetFileList
458 * @see FiosGetSavegameList
460 FiosType FiosGetSavegameListCallback(SaveLoadOperation fop, const char *file, const char *ext, char *title, const char *last)
462 /* Show savegame files
463 * .SAV OpenTTD saved game
464 * .SS1 Transport Tycoon Deluxe preset game
465 * .SV1 Transport Tycoon Deluxe (Patch) saved game
466 * .SV2 Transport Tycoon Deluxe (Patch) saved 2-player game */
468 /* Don't crash if we supply no extension */
469 if (ext == nullptr) return FIOS_TYPE_INVALID;
471 if (strcasecmp(ext, ".sav") == 0) {
472 GetFileTitle(file, title, last, SAVE_DIR);
473 return FIOS_TYPE_FILE;
476 if (fop == SLO_LOAD) {
477 if (strcasecmp(ext, ".ss1") == 0 || strcasecmp(ext, ".sv1") == 0 ||
478 strcasecmp(ext, ".sv2") == 0) {
479 if (title != nullptr) GetOldSaveGameName(file, title, last);
480 return FIOS_TYPE_OLDFILE;
484 return FIOS_TYPE_INVALID;
488 * Get a list of savegames.
489 * @param fop Purpose of collecting the list.
490 * @param file_list Destination of the found files.
491 * @see FiosGetFileList
493 void FiosGetSavegameList(SaveLoadOperation fop, FileList &file_list)
495 static char *fios_save_path = nullptr;
496 static char *fios_save_path_last = nullptr;
498 if (fios_save_path == nullptr) {
499 fios_save_path = MallocT<char>(MAX_PATH);
500 fios_save_path_last = fios_save_path + MAX_PATH - 1;
501 FioGetDirectory(fios_save_path, fios_save_path_last, SAVE_DIR);
504 _fios_path = fios_save_path;
505 _fios_path_last = fios_save_path_last;
507 FiosGetFileList(fop, &FiosGetSavegameListCallback, NO_DIRECTORY, file_list);
511 * Callback for FiosGetFileList. It tells if a file is a scenario or not.
512 * @param fop Purpose of collecting the list.
513 * @param file Name of the file to check.
514 * @param ext A pointer to the extension identifier inside file
515 * @param title Buffer if a callback wants to lookup the title of the file
516 * @param last Last available byte in buffer (to prevent buffer overflows)
517 * @return a FIOS_TYPE_* type of the found file, FIOS_TYPE_INVALID if not a scenario
518 * @see FiosGetFileList
519 * @see FiosGetScenarioList
521 static FiosType FiosGetScenarioListCallback(SaveLoadOperation fop, const char *file, const char *ext, char *title, const char *last)
523 /* Show scenario files
524 * .SCN OpenTTD style scenario file
525 * .SV0 Transport Tycoon Deluxe (Patch) scenario
526 * .SS0 Transport Tycoon Deluxe preset scenario */
527 if (strcasecmp(ext, ".scn") == 0) {
528 GetFileTitle(file, title, last, SCENARIO_DIR);
529 return FIOS_TYPE_SCENARIO;
532 if (fop == SLO_LOAD) {
533 if (strcasecmp(ext, ".sv0") == 0 || strcasecmp(ext, ".ss0") == 0 ) {
534 GetOldSaveGameName(file, title, last);
535 return FIOS_TYPE_OLD_SCENARIO;
539 return FIOS_TYPE_INVALID;
543 * Get a list of scenarios.
544 * @param fop Purpose of collecting the list.
545 * @param file_list Destination of the found files.
546 * @see FiosGetFileList
548 void FiosGetScenarioList(SaveLoadOperation fop, FileList &file_list)
550 static char *fios_scn_path = nullptr;
551 static char *fios_scn_path_last = nullptr;
553 /* Copy the default path on first run or on 'New Game' */
554 if (fios_scn_path == nullptr) {
555 fios_scn_path = MallocT<char>(MAX_PATH);
556 fios_scn_path_last = fios_scn_path + MAX_PATH - 1;
557 FioGetDirectory(fios_scn_path, fios_scn_path_last, SCENARIO_DIR);
560 _fios_path = fios_scn_path;
561 _fios_path_last = fios_scn_path_last;
563 char base_path[MAX_PATH];
564 FioGetDirectory(base_path, lastof(base_path), SCENARIO_DIR);
566 Subdirectory subdir = (fop == SLO_LOAD && strcmp(base_path, _fios_path) == 0) ? SCENARIO_DIR : NO_DIRECTORY;
567 FiosGetFileList(fop, &FiosGetScenarioListCallback, subdir, file_list);
570 static FiosType FiosGetHeightmapListCallback(SaveLoadOperation fop, const char *file, const char *ext, char *title, const char *last)
572 /* Show heightmap files
573 * .PNG PNG Based heightmap files
574 * .BMP BMP Based heightmap files
577 FiosType type = FIOS_TYPE_INVALID;
579 #ifdef WITH_PNG
580 if (strcasecmp(ext, ".png") == 0) type = FIOS_TYPE_PNG;
581 #endif /* WITH_PNG */
583 if (strcasecmp(ext, ".bmp") == 0) type = FIOS_TYPE_BMP;
585 if (type == FIOS_TYPE_INVALID) return FIOS_TYPE_INVALID;
587 TarFileList::iterator it = _tar_filelist[SCENARIO_DIR].find(file);
588 if (it != _tar_filelist[SCENARIO_DIR].end()) {
589 /* If the file is in a tar and that tar is not in a heightmap
590 * directory we are for sure not supposed to see it.
591 * Examples of this are pngs part of documentation within
592 * collections of NewGRFs or 32 bpp graphics replacement PNGs.
594 bool match = false;
595 Searchpath sp;
596 FOR_ALL_SEARCHPATHS(sp) {
597 char buf[MAX_PATH];
598 FioAppendDirectory(buf, lastof(buf), sp, HEIGHTMAP_DIR);
600 if (strncmp(buf, it->second.tar_filename, strlen(buf)) == 0) {
601 match = true;
602 break;
606 if (!match) return FIOS_TYPE_INVALID;
609 GetFileTitle(file, title, last, HEIGHTMAP_DIR);
611 return type;
615 * Get a list of heightmaps.
616 * @param fop Purpose of collecting the list.
617 * @param file_list Destination of the found files.
619 void FiosGetHeightmapList(SaveLoadOperation fop, FileList &file_list)
621 static char *fios_hmap_path = nullptr;
622 static char *fios_hmap_path_last = nullptr;
624 if (fios_hmap_path == nullptr) {
625 fios_hmap_path = MallocT<char>(MAX_PATH);
626 fios_hmap_path_last = fios_hmap_path + MAX_PATH - 1;
627 FioGetDirectory(fios_hmap_path, fios_hmap_path_last, HEIGHTMAP_DIR);
630 _fios_path = fios_hmap_path;
631 _fios_path_last = fios_hmap_path_last;
633 char base_path[MAX_PATH];
634 FioGetDirectory(base_path, lastof(base_path), HEIGHTMAP_DIR);
636 Subdirectory subdir = strcmp(base_path, _fios_path) == 0 ? HEIGHTMAP_DIR : NO_DIRECTORY;
637 FiosGetFileList(fop, &FiosGetHeightmapListCallback, subdir, file_list);
641 * Get the directory for screenshots.
642 * @return path to screenshots
644 const char *FiosGetScreenshotDir()
646 static char *fios_screenshot_path = nullptr;
648 if (fios_screenshot_path == nullptr) {
649 fios_screenshot_path = MallocT<char>(MAX_PATH);
650 FioGetDirectory(fios_screenshot_path, fios_screenshot_path + MAX_PATH - 1, SCREENSHOT_DIR);
653 return fios_screenshot_path;
656 #if defined(ENABLE_NETWORK)
657 #include "network/network_content.h"
658 #include "3rdparty/md5/md5.h"
660 /** Basic data to distinguish a scenario. Used in the server list window */
661 struct ScenarioIdentifier {
662 uint32 scenid; ///< ID for the scenario (generated by content).
663 uint8 md5sum[16]; ///< MD5 checksum of file.
664 char filename[MAX_PATH]; ///< filename of the file.
666 bool operator == (const ScenarioIdentifier &other) const
668 return this->scenid == other.scenid &&
669 memcmp(this->md5sum, other.md5sum, sizeof(this->md5sum)) == 0;
672 bool operator != (const ScenarioIdentifier &other) const
674 return !(*this == other);
679 * Scanner to find the unique IDs of scenarios
681 class ScenarioScanner : protected FileScanner, public SmallVector<ScenarioIdentifier, 8> {
682 bool scanned; ///< Whether we've already scanned
683 public:
684 /** Initialise */
685 ScenarioScanner() : scanned(false) {}
688 * Scan, but only if it's needed.
689 * @param rescan whether to force scanning even when it's not necessary
691 void Scan(bool rescan)
693 if (this->scanned && !rescan) return;
695 this->FileScanner::Scan(".id", SCENARIO_DIR, true, true);
696 this->scanned = true;
699 /* virtual */ bool AddFile(const char *filename, size_t basepath_length, const char *tar_filename)
701 FILE *f = FioFOpenFile(filename, "r", SCENARIO_DIR);
702 if (f == nullptr) return false;
704 ScenarioIdentifier id;
705 int fret = fscanf(f, "%i", &id.scenid);
706 FioFCloseFile(f);
707 if (fret != 1) return false;
708 strecpy(id.filename, filename, lastof(id.filename));
710 Md5 checksum;
711 uint8 buffer[1024];
712 char basename[MAX_PATH]; ///< \a filename without the extension.
713 size_t len, size;
715 /* open the scenario file, but first get the name.
716 * This is safe as we check on extension which
717 * must always exist. */
718 strecpy(basename, filename, lastof(basename));
719 *strrchr(basename, '.') = '\0';
720 f = FioFOpenFile(basename, "rb", SCENARIO_DIR, &size);
721 if (f == nullptr) return false;
723 /* calculate md5sum */
724 while ((len = fread(buffer, 1, (size > sizeof(buffer)) ? sizeof(buffer) : size, f)) != 0 && size != 0) {
725 size -= len;
726 checksum.Append(buffer, len);
728 checksum.Finish(id.md5sum);
730 FioFCloseFile(f);
732 this->Include(id);
733 return true;
737 /** Scanner for scenarios */
738 static ScenarioScanner _scanner;
741 * Find a given scenario based on its unique ID.
742 * @param ci The content info to compare it to.
743 * @param md5sum Whether to look at the md5sum or the id.
744 * @return The filename of the file, else \c nullptr.
746 const char *FindScenario(const ContentInfo *ci, bool md5sum)
748 _scanner.Scan(false);
750 for (ScenarioIdentifier *id = _scanner.Begin(); id != _scanner.End(); id++) {
751 if (md5sum ? (memcmp(id->md5sum, ci->md5sum, sizeof(id->md5sum)) == 0)
752 : (id->scenid == ci->unique_id)) {
753 return id->filename;
757 return nullptr;
761 * Check whether we've got a given scenario based on its unique ID.
762 * @param ci The content info to compare it to.
763 * @param md5sum Whether to look at the md5sum or the id.
764 * @return True iff we've got the scenario.
766 bool HasScenario(const ContentInfo *ci, bool md5sum)
768 return (FindScenario(ci, md5sum) != nullptr);
772 * Force a (re)scan of the scenarios.
774 void ScanScenarios()
776 _scanner.Scan(true);
779 #endif /* ENABLE_NETWORK */