Translations update
[openttd/fttd.git] / src / fios.cpp
blobe79b5efec7b219d7f5a164ef7f3ef5d660b20e81
1 /* $Id$ */
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.h"
21 #include <sys/stat.h>
23 #ifndef WIN32
24 # include <unistd.h>
25 #endif /* WIN32 */
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, stringb *title);
45 /**
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)
53 int r = 0;
55 if ((_savegame_sort_order & SORT_BY_NAME) == 0 && da->mtime != db->mtime) {
56 r = da->mtime < db->mtime ? -1 : 1;
57 } else {
58 r = strcasecmp(da->title, db->title);
61 if (_savegame_sort_order & SORT_DESCENDING) r = -r;
62 return r;
65 /** Free the list of savegames. */
66 void FiosFreeSavegameList()
68 _fios_items.Clear();
69 _fios_items.Compact();
72 /**
73 * Get descriptive texts. Returns the path and free space
74 * left on the device
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)
81 *path = _fios_path;
82 return FiosGetDiskFreeSpace(*path, total_free) ? STR_SAVELOAD_BYTES_FREE : STR_ERROR_UNABLE_TO_READ_DRIVE;
85 /**
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;
94 switch (item->type) {
95 case FIOS_TYPE_DRIVE:
96 #if defined(WINCE)
97 snprintf(path, MAX_PATH, PATHSEP "");
98 #elif defined(WIN32) || defined(__OS2__)
99 snprintf(path, MAX_PATH, "%c:" PATHSEP, item->title[0]);
100 #endif
101 /* FALL THROUGH */
102 case FIOS_TYPE_INVALID:
103 break;
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);
112 if (s != NULL) {
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) {
117 s[1] = '\0';
118 #endif
120 break;
123 case FIOS_TYPE_DIR:
124 strcat(path, item->name);
125 strcat(path, PATHSEP);
126 break;
128 case FIOS_TYPE_DIRECT:
129 snprintf(path, MAX_PATH, "%s", item->name);
130 break;
132 case FIOS_TYPE_FILE:
133 case FIOS_TYPE_OLDFILE:
134 case FIOS_TYPE_SCENARIO:
135 case FIOS_TYPE_OLD_SCENARIO:
136 case FIOS_TYPE_PNG:
137 case FIOS_TYPE_BMP:
138 return item->name;
141 return NULL;
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)
154 const char *period;
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__)
160 if (path != NULL) {
161 unsigned char sepchar = path[(strlen(path) - 1)];
163 if (sepchar != ':' && sepchar != '/') {
164 snprintf(buf, size, "%s" PATHSEP "%s%s", path, name, ext);
165 } else {
166 snprintf(buf, size, "%s%s%s", path, name, ext);
168 } else {
169 snprintf(buf, size, "%s%s", name, ext);
171 #else
172 snprintf(buf, size, "%s" PATHSEP "%s%s", path, name, ext);
173 #endif
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)
197 FiosMakeFilename (buf, _fios_path, name, GetCurrentScreenshotExtension(), size);
201 * Delete a file.
202 * @param name Filename to delete.
204 bool FiosDelete(const char *name)
206 char filename[512];
208 FiosMakeSavegameName(filename, name, lengthof(filename));
209 return unlink(filename) == 0;
212 typedef FiosType fios_getlist_callback_proc (SaveLoadDialogMode mode, const char *filename, const char *ext, stringb *title);
215 * Scanner to scan for a particular type of FIOS file.
217 class FiosFileScanner : public FileScanner {
218 SaveLoadDialogMode mode; ///< The mode we want to search for
219 fios_getlist_callback_proc *callback_proc; ///< Callback to check whether the file may be added
220 public:
222 * Create the scanner
223 * @param mode The mode we are in. Some modes don't allow 'parent'.
224 * @param callback_proc The function that is called where you need to do the filtering.
226 FiosFileScanner(SaveLoadDialogMode mode, fios_getlist_callback_proc *callback_proc) :
227 mode(mode),
228 callback_proc(callback_proc)
231 /* virtual */ bool AddFile(const char *filename, size_t basepath_length, const char *tar_filename);
235 * Try to add a fios item set with the given filename.
236 * @param filename the full path to the file to read
237 * @param basepath_length amount of characters to chop of before to get a relative filename
238 * @return true if the file is added.
240 bool FiosFileScanner::AddFile(const char *filename, size_t basepath_length, const char *tar_filename)
242 const char *ext = strrchr(filename, '.');
243 if (ext == NULL) return false;
245 sstring<64> fios_title;
247 FiosType type = this->callback_proc(this->mode, filename, ext, &fios_title);
248 if (type == FIOS_TYPE_INVALID) return false;
250 for (const FiosItem *fios = _fios_items.Begin(); fios != _fios_items.End(); fios++) {
251 if (strcmp(fios->name, filename) == 0) return false;
254 FiosItem *fios = _fios_items.Append();
255 #ifdef WIN32
256 struct _stat sb;
257 if (_tstat(OTTD2FS(filename), &sb) == 0) {
258 #else
259 struct stat sb;
260 if (stat(filename, &sb) == 0) {
261 #endif
262 fios->mtime = sb.st_mtime;
263 } else {
264 fios->mtime = 0;
267 fios->type = type;
268 bstrcpy (fios->name, filename);
270 /* If the file doesn't have a title, use its filename */
271 const char *t = fios_title.c_str();
272 if (fios_title.empty()) {
273 t = strrchr(filename, PATHSEPCHAR);
274 t = (t == NULL) ? filename : (t + 1);
276 bstrcpy (fios->title, t);
277 str_validate(fios->title, lastof(fios->title));
279 return true;
284 * Fill the list of the files in a directory, according to some arbitrary rule.
285 * @param mode The mode we are in. Some modes don't allow 'parent'.
286 * @param callback_proc The function that is called where you need to do the filtering.
287 * @param subdir The directory from where to start (global) searching.
289 static void FiosGetFileList(SaveLoadDialogMode mode, fios_getlist_callback_proc *callback_proc, Subdirectory subdir)
291 struct stat sb;
292 struct dirent *dirent;
293 DIR *dir;
294 FiosItem *fios;
295 int sort_start;
296 char d_name[sizeof(fios->name)];
298 _fios_items.Clear();
300 /* A parent directory link exists if we are not in the root directory */
301 if (!FiosIsRoot(_fios_path)) {
302 fios = _fios_items.Append();
303 fios->type = FIOS_TYPE_PARENT;
304 fios->mtime = 0;
305 bstrcpy (fios->name, "..");
306 bstrcpy (fios->title, ".. (Parent directory)");
309 /* Show subdirectories */
310 if ((dir = ttd_opendir(_fios_path)) != NULL) {
311 while ((dirent = readdir(dir)) != NULL) {
312 bstrcpy (d_name, FS2OTTD(dirent->d_name));
314 /* found file must be directory, but not '.' or '..' */
315 if (FiosIsValidFile(_fios_path, dirent, &sb) && S_ISDIR(sb.st_mode) &&
316 (!FiosIsHiddenFile(dirent) || strncasecmp(d_name, PERSONAL_DIR, strlen(d_name)) == 0) &&
317 strcmp(d_name, ".") != 0 && strcmp(d_name, "..") != 0) {
318 fios = _fios_items.Append();
319 fios->type = FIOS_TYPE_DIR;
320 fios->mtime = 0;
321 bstrcpy (fios->name, d_name);
322 bstrfmt (fios->title, "%s" PATHSEP " (Directory)", d_name);
323 str_validate(fios->title, lastof(fios->title));
326 closedir(dir);
329 /* Sort the subdirs always by name, ascending, remember user-sorting order */
331 SortingBits order = _savegame_sort_order;
332 _savegame_sort_order = SORT_BY_NAME | SORT_ASCENDING;
333 QSortT(_fios_items.Begin(), _fios_items.Length(), CompareFiosItems);
334 _savegame_sort_order = order;
337 /* This is where to start sorting for the filenames */
338 sort_start = _fios_items.Length();
340 /* Show files */
341 FiosFileScanner scanner(mode, callback_proc);
342 if (subdir == NO_DIRECTORY) {
343 scanner.Scan(NULL, _fios_path, NULL, false);
344 } else {
345 scanner.Scan(NULL, subdir, true, true);
348 QSortT(_fios_items.Get(sort_start), _fios_items.Length() - sort_start, CompareFiosItems);
350 /* Show drives */
351 FiosGetDrives();
353 _fios_items.Compact();
357 * Get the title of a file, which (if exists) is stored in a file named
358 * the same as the data file but with '.title' added to it.
359 * @param file filename to get the title for
360 * @param title the title buffer to fill
361 * @param subdir the sub directory to search in
363 static void GetFileTitle (const char *file, stringb *title, Subdirectory subdir)
365 char buf[MAX_PATH];
366 bstrfmt (buf, "%s.title", file);
368 FILE *f = FioFOpenFile(buf, "r", subdir);
369 if (f == NULL) return;
371 title->len = fread (title->buffer, 1, title->capacity - 1, f);
372 assert (title->len < title->capacity);
373 title->buffer[title->len] = '\0';
374 title->validate();
375 FioFCloseFile(f);
379 * Callback for FiosGetFileList. It tells if a file is a savegame or not.
380 * @param mode Save/load mode.
381 * @param file Name of the file to check.
382 * @param ext A pointer to the extension identifier inside file
383 * @param title Buffer if a callback wants to lookup the title of the file; NULL to skip the lookup
384 * @return a FIOS_TYPE_* type of the found file, FIOS_TYPE_INVALID if not a savegame
385 * @see FiosGetFileList
386 * @see FiosGetSavegameList
388 FiosType FiosGetSavegameListCallback (SaveLoadDialogMode mode, const char *file, const char *ext, stringb *title)
390 /* Show savegame files
391 * .SAV OpenTTD saved game
392 * .SS1 Transport Tycoon Deluxe preset game
393 * .SV1 Transport Tycoon Deluxe (Patch) saved game
394 * .SV2 Transport Tycoon Deluxe (Patch) saved 2-player game */
396 /* Don't crash if we supply no extension */
397 if (ext == NULL) return FIOS_TYPE_INVALID;
399 if (strcasecmp(ext, ".sav") == 0) {
400 GetFileTitle (file, title, SAVE_DIR);
401 return FIOS_TYPE_FILE;
404 if (mode == SLD_LOAD_GAME || mode == SLD_LOAD_SCENARIO) {
405 if (strcasecmp(ext, ".ss1") == 0 || strcasecmp(ext, ".sv1") == 0 ||
406 strcasecmp(ext, ".sv2") == 0) {
407 if (title != NULL) GetOldSaveGameName (file, title);
408 return FIOS_TYPE_OLDFILE;
412 return FIOS_TYPE_INVALID;
416 * Get a list of savegames.
417 * @param mode Save/load mode.
418 * @see FiosGetFileList
420 void FiosGetSavegameList(SaveLoadDialogMode mode)
422 static char *fios_save_path = NULL;
424 if (fios_save_path == NULL) {
425 fios_save_path = xmalloc (MAX_PATH);
426 FioGetDirectory(fios_save_path, MAX_PATH, SAVE_DIR);
429 _fios_path = fios_save_path;
431 FiosGetFileList(mode, &FiosGetSavegameListCallback, NO_DIRECTORY);
435 * Callback for FiosGetFileList. It tells if a file is a scenario or not.
436 * @param mode Save/load mode.
437 * @param file Name of the file to check.
438 * @param ext A pointer to the extension identifier inside file
439 * @param title Buffer if a callback wants to lookup the title of the file
440 * @return a FIOS_TYPE_* type of the found file, FIOS_TYPE_INVALID if not a scenario
441 * @see FiosGetFileList
442 * @see FiosGetScenarioList
444 static FiosType FiosGetScenarioListCallback (SaveLoadDialogMode mode, const char *file, const char *ext, stringb *title)
446 /* Show scenario files
447 * .SCN OpenTTD style scenario file
448 * .SV0 Transport Tycoon Deluxe (Patch) scenario
449 * .SS0 Transport Tycoon Deluxe preset scenario */
450 if (strcasecmp(ext, ".scn") == 0) {
451 GetFileTitle (file, title, SCENARIO_DIR);
452 return FIOS_TYPE_SCENARIO;
455 if (mode == SLD_LOAD_GAME || mode == SLD_LOAD_SCENARIO) {
456 if (strcasecmp(ext, ".sv0") == 0 || strcasecmp(ext, ".ss0") == 0 ) {
457 GetOldSaveGameName (file, title);
458 return FIOS_TYPE_OLD_SCENARIO;
462 return FIOS_TYPE_INVALID;
466 * Get a list of scenarios.
467 * @param mode Save/load mode.
468 * @see FiosGetFileList
470 void FiosGetScenarioList(SaveLoadDialogMode mode)
472 static char *fios_scn_path = NULL;
474 /* Copy the default path on first run or on 'New Game' */
475 if (fios_scn_path == NULL) {
476 fios_scn_path = xmalloc (MAX_PATH);
477 FioGetDirectory(fios_scn_path, MAX_PATH, SCENARIO_DIR);
480 _fios_path = fios_scn_path;
482 char base_path[MAX_PATH];
483 FioGetDirectory(base_path, sizeof(base_path), SCENARIO_DIR);
485 FiosGetFileList(mode, &FiosGetScenarioListCallback, (mode == SLD_LOAD_SCENARIO && strcmp(base_path, _fios_path) == 0) ? SCENARIO_DIR : NO_DIRECTORY);
488 static FiosType FiosGetHeightmapListCallback (SaveLoadDialogMode mode, const char *file, const char *ext, stringb *title)
490 /* Show heightmap files
491 * .PNG PNG Based heightmap files
492 * .BMP BMP Based heightmap files
495 FiosType type = FIOS_TYPE_INVALID;
497 #ifdef WITH_PNG
498 if (strcasecmp(ext, ".png") == 0) type = FIOS_TYPE_PNG;
499 #endif /* WITH_PNG */
501 if (strcasecmp(ext, ".bmp") == 0) type = FIOS_TYPE_BMP;
503 if (type == FIOS_TYPE_INVALID) return FIOS_TYPE_INVALID;
505 TarFileList::iterator it = TarCache::cache[SCENARIO_DIR].files.find(file);
506 if (it != TarCache::cache[SCENARIO_DIR].files.end()) {
507 /* If the file is in a tar and that tar is not in a heightmap
508 * directory we are for sure not supposed to see it.
509 * Examples of this are pngs part of documentation within
510 * collections of NewGRFs or 32 bpp graphics replacement PNGs.
512 bool match = false;
513 Searchpath sp;
514 FOR_ALL_SEARCHPATHS(sp) {
515 char buf[MAX_PATH];
516 FioGetFullPath (buf, sizeof(buf), sp, HEIGHTMAP_DIR);
518 if (strncmp(buf, it->second.tar_filename, strlen(buf)) == 0) {
519 match = true;
520 break;
524 if (!match) return FIOS_TYPE_INVALID;
527 GetFileTitle (file, title, HEIGHTMAP_DIR);
529 return type;
533 * Get a list of heightmaps.
534 * @param mode Save/load mode.
536 void FiosGetHeightmapList(SaveLoadDialogMode mode)
538 static char *fios_hmap_path = NULL;
540 if (fios_hmap_path == NULL) {
541 fios_hmap_path = xmalloc (MAX_PATH);
542 FioGetDirectory(fios_hmap_path, MAX_PATH, HEIGHTMAP_DIR);
545 _fios_path = fios_hmap_path;
547 char base_path[MAX_PATH];
548 FioGetDirectory(base_path, sizeof(base_path), HEIGHTMAP_DIR);
550 FiosGetFileList(mode, &FiosGetHeightmapListCallback, strcmp(base_path, _fios_path) == 0 ? HEIGHTMAP_DIR : NO_DIRECTORY);
554 * Get the directory for screenshots.
555 * @return path to screenshots
557 const char *FiosGetScreenshotDir()
559 static char *fios_screenshot_path = NULL;
561 if (fios_screenshot_path == NULL) {
562 fios_screenshot_path = xmalloc (MAX_PATH);
563 FioGetDirectory(fios_screenshot_path, MAX_PATH, SCREENSHOT_DIR);
566 return fios_screenshot_path;
569 #if defined(ENABLE_NETWORK)
570 #include "network/network_content.h"
571 #include "3rdparty/md5/md5.h"
573 /** Basic data to distinguish a scenario. Used in the server list window */
574 struct ScenarioIdentifier {
575 uint32 scenid; ///< ID for the scenario (generated by content).
576 uint8 md5sum[16]; ///< MD5 checksum of file.
577 char filename[MAX_PATH]; ///< filename of the file.
579 bool operator == (const ScenarioIdentifier &other) const
581 return this->scenid == other.scenid &&
582 memcmp(this->md5sum, other.md5sum, sizeof(this->md5sum)) == 0;
585 bool operator != (const ScenarioIdentifier &other) const
587 return !(*this == other);
592 * Scanner to find the unique IDs of scenarios
594 class ScenarioScanner : protected FileScanner, public SmallVector<ScenarioIdentifier, 8> {
595 bool scanned; ///< Whether we've already scanned
596 public:
597 /** Initialise */
598 ScenarioScanner() : scanned(false) {}
601 * Scan, but only if it's needed.
602 * @param rescan whether to force scanning even when it's not necessary
604 void Scan(bool rescan)
606 if (this->scanned && !rescan) return;
608 this->FileScanner::Scan(".id", SCENARIO_DIR, true, true);
609 this->scanned = true;
612 /* virtual */ bool AddFile(const char *filename, size_t basepath_length, const char *tar_filename)
614 FILE *f = FioFOpenFile(filename, "r", SCENARIO_DIR);
615 if (f == NULL) return false;
617 ScenarioIdentifier id;
618 int fret = fscanf(f, "%i", &id.scenid);
619 FioFCloseFile(f);
620 if (fret != 1) return false;
621 bstrcpy (id.filename, filename);
623 Md5 checksum;
624 uint8 buffer[1024];
625 char basename[MAX_PATH]; ///< \a filename without the extension.
626 size_t len, size;
628 /* open the scenario file, but first get the name.
629 * This is safe as we check on extension which
630 * must always exist. */
631 bstrcpy (basename, filename);
632 *strrchr(basename, '.') = '\0';
633 f = FioFOpenFile(basename, "rb", SCENARIO_DIR, &size);
634 if (f == NULL) return false;
636 /* calculate md5sum */
637 while ((len = fread(buffer, 1, (size > sizeof(buffer)) ? sizeof(buffer) : size, f)) != 0 && size != 0) {
638 size -= len;
639 checksum.Append(buffer, len);
641 checksum.Finish(id.md5sum);
643 FioFCloseFile(f);
645 this->Include(id);
646 return true;
650 /** Scanner for scenarios */
651 static ScenarioScanner _scanner;
654 * Find a given scenario based on its unique ID.
655 * @param ci The content info to compare it to.
656 * @param md5sum Whether to look at the md5sum or the id.
657 * @return The filename of the file, else \c NULL.
659 const char *FindScenario(const ContentInfo *ci, bool md5sum)
661 _scanner.Scan(false);
663 for (ScenarioIdentifier *id = _scanner.Begin(); id != _scanner.End(); id++) {
664 if (md5sum ? (memcmp(id->md5sum, ci->md5sum, sizeof(id->md5sum)) == 0)
665 : (id->scenid == ci->unique_id)) {
666 return id->filename;
670 return NULL;
674 * Check whether we've got a given scenario based on its unique ID.
675 * @param ci The content info to compare it to.
676 * @param md5sum Whether to look at the md5sum or the id.
677 * @return True iff we've got the scenario.
679 bool HasScenario(const ContentInfo *ci, bool md5sum)
681 return (FindScenario(ci, md5sum) != NULL);
685 * Force a (re)scan of the scenarios.
687 void ScanScenarios()
689 _scanner.Scan(true);
692 #endif /* ENABLE_NETWORK */