OpenTTD: src/fios.cpp Source File

OpenTTD

- Main Page
- Related Pages
- Modules
- Namespaces
- Data Structures
- Files

- File List
- Globals

fios.cpp
Go to the documentation of this file.
1 /* $Id: fios.cpp 27653 2016-09-04 16:06:50Z alberth $ */
2
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 */
9
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>
22
23 #ifndef WIN32
24 # include <unistd.h>
25 #endif /* WIN32 */
26
27 #include "table/strings.h"
28
29 #include "safeguards.h"
30
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;
35
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);
42
43 /* get the name of an oldstyle savegame */
44 extern void GetOldSaveGameName(const char *file, char *title, const char *last);
45
52 int CDECL CompareFiosItems(const FiosItem *da, const FiosItem *db)
53 {
54 int r = 0;
55
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);
60 }
61
62 if (_savegame_sort_order & SORT_DESCENDING) r = -r;
63 return r;
64 }
65
66 FileList::~FileList()
67 {
68 this->Clear();
69 }
70
76 void FileList::BuildFileList(AbstractFileType abstract_filetype, SaveLoadOperation fop)
77 {
78 this->Clear();
79
80 assert(fop == SLO_LOAD || SLO_SAVE);
81 switch (abstract_filetype) {
82 case FT_NONE:
83 break;
84
85 case FT_SAVEGAME:
86 FiosGetSavegameList(fop, *this);
87 break;
88
89 case FT_SCENARIO:
90 FiosGetScenarioList(fop, *this);
91 break;
92
93 case FT_HEIGHTMAP:
94 FiosGetHeightmapList(fop, *this);
95 break;
96
97 default:
98 NOT_REACHED();
99 }
100 }
101
108 const FiosItem *FileList::FindItem(const char *file)
109 {
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;
113 }
114
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;
119
120 if (IsInsideMM(i, 0, this->Length())) return this->Get(i);
121
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;
129 }
130
131 return NULL;
132 }
133
141 StringID FiosGetDescText(const char **path, uint64 *total_free)
142 {
143 *path = _fios_path;
144 return FiosGetDiskFreeSpace(*path, total_free) ? STR_SAVELOAD_BYTES_FREE : STR_ERROR_UNABLE_TO_READ_DRIVE;
145 }
146
152 const char *FiosBrowseTo(const FiosItem *item)
153 {
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 /* FALL THROUGH */
162 case FIOS_TYPE_INVALID:
163 break;
164
165 case FIOS_TYPE_PARENT: {
166 /* Check for possible NULL ptr (not required for UNIXes, but AmigaOS-alikes) */
167 char *s = strrchr(_fios_path, PATHSEPCHAR);
168 if (s != NULL && s != _fios_path) {
169 s[0] = '\0'; // Remove last path separator character, so we can go up one level.
170 }
171 s = strrchr(_fios_path, PATHSEPCHAR);
172 if (s != NULL) {
173 s[1] = '\0'; // go up a directory
174 #if defined(__MORPHOS__) || defined(__AMIGAOS__)
175 /* On MorphOS or AmigaOS paths look like: "Volume:directory/subdirectory" */
176 } else if ((s = strrchr(_fios_path, ':')) != NULL) {
177 s[1] = '\0';
178 #endif
179 }
180 break;
181 }
182
183 case FIOS_TYPE_DIR:
184 strecat(_fios_path, item->name, _fios_path_last);
185 strecat(_fios_path, PATHSEP, _fios_path_last);
186 break;
187
188 case FIOS_TYPE_DIRECT:
189 seprintf(_fios_path, _fios_path_last, "%s", item->name);
190 break;
191
192 case FIOS_TYPE_FILE:
193 case FIOS_TYPE_OLDFILE:
194 case FIOS_TYPE_SCENARIO:
195 case FIOS_TYPE_OLD_SCENARIO:
196 case FIOS_TYPE_PNG:
197 case FIOS_TYPE_BMP:
198 return item->name;
199 }
200
201 return NULL;
202 }
203
212 static void FiosMakeFilename(char *buf, const char *path, const char *name, const char *ext, const char *last)
213 {
214 const char *period;
215
216 /* Don't append the extension if it is already there */
217 period = strrchr(name, '.');
218 if (period != NULL && strcasecmp(period, ext) == 0) ext = "";
219 #if defined(__MORPHOS__) || defined(__AMIGAOS__)
220 if (path != NULL) {
221 unsigned char sepchar = path[(strlen(path) - 1)];
222
223 if (sepchar != ':' && sepchar != '/') {
224 seprintf(buf, last, "%s" PATHSEP "%s%s", path, name, ext);
225 } else {
226 seprintf(buf, last, "%s%s%s", path, name, ext);
227 }
228 } else {
229 seprintf(buf, last, "%s%s", name, ext);
230 }
231 #else
232 seprintf(buf, last, "%s" PATHSEP "%s%s", path, name, ext);
233 #endif
234 }
235
242 void FiosMakeSavegameName(char *buf, const char *name, const char *last)
243 {
244 const char *extension = (_game_mode == GM_EDITOR) ? ".scn" : ".sav";
245
246 FiosMakeFilename(buf, _fios_path, name, extension, last);
247 }
248
255 void FiosMakeHeightmapName(char *buf, const char *name, const char *last)
256 {
257 char ext[5];
258 ext[0] = '.';
259 strecpy(ext + 1, GetCurrentScreenshotExtension(), lastof(ext));
260
261 FiosMakeFilename(buf, _fios_path, name, ext, last);
262 }
263
269 bool FiosDelete(const char *name)
270 {
271 char filename[512];
272
273 FiosMakeSavegameName(filename, name, lastof(filename));
274 return unlink(filename) == 0;
275 }
276
277 typedef FiosType fios_getlist_callback_proc(SaveLoadOperation fop, const char *filename, const char *ext, char *title, const char *last);
278
282 class FiosFileScanner : public FileScanner {
283 SaveLoadOperation fop;
284 fios_getlist_callback_proc *callback_proc;
285 FileList &file_list;
286 public:
293 FiosFileScanner(SaveLoadOperation fop, fios_getlist_callback_proc *callback_proc, FileList &file_list) :
294 fop(fop), callback_proc(callback_proc), file_list(file_list)
295 {}
296
297 /* virtual */ bool AddFile(const char *filename, size_t basepath_length, const char *tar_filename);
298 };
299
306 bool FiosFileScanner::AddFile(const char *filename, size_t basepath_length, const char *tar_filename)
307 {
308 const char *ext = strrchr(filename, '.');
309 if (ext == NULL) return false;
310
311 char fios_title[64];
312 fios_title[0] = '\0'; // reset the title;
313
314 FiosType type = this->callback_proc(this->fop, filename, ext, fios_title, lastof(fios_title));
315 if (type == FIOS_TYPE_INVALID) return false;
316
317 for (const FiosItem *fios = file_list.Begin(); fios != file_list.End(); fios++) {
318 if (strcmp(fios->name, filename) == 0) return false;
319 }
320
321 FiosItem *fios = file_list.Append();
322 #ifdef WIN32
323 struct _stat sb;
324 if (_tstat(OTTD2FS(filename), &sb) == 0) {
325 #else
326 struct stat sb;
327 if (stat(filename, &sb) == 0) {
328 #endif
329 fios->mtime = sb.st_mtime;
330 } else {
331 fios->mtime = 0;
332 }
333
334 fios->type = type;
335 strecpy(fios->name, filename, lastof(fios->name));
336
337 /* If the file doesn't have a title, use its filename */
338 const char *t = fios_title;
339 if (StrEmpty(fios_title)) {
340 t = strrchr(filename, PATHSEPCHAR);
341 t = (t == NULL) ? filename : (t + 1);
342 }
343 strecpy(fios->title, t, lastof(fios->title));
344 str_validate(fios->title, lastof(fios->title));
345
346 return true;
347 }
348
349
357 static void FiosGetFileList(SaveLoadOperation fop, fios_getlist_callback_proc *callback_proc, Subdirectory subdir, FileList &file_list)
358 {
359 struct stat sb;
360 struct dirent *dirent;
361 DIR *dir;
362 FiosItem *fios;
363 int sort_start;
364 char d_name[sizeof(fios->name)];
365
366 file_list.Clear();
367
368 /* A parent directory link exists if we are not in the root directory */
369 if (!FiosIsRoot(_fios_path)) {
370 fios = file_list.Append();
371 fios->type = FIOS_TYPE_PARENT;
372 fios->mtime = 0;
373 strecpy(fios->name, "..", lastof(fios->name));
374 strecpy(fios->title, ".. (Parent directory)", lastof(fios->title));
375 }
376
377 /* Show subdirectories */
378 if ((dir = ttd_opendir(_fios_path)) != NULL) {
379 while ((dirent = readdir(dir)) != NULL) {
380 strecpy(d_name, FS2OTTD(dirent->d_name), lastof(d_name));
381
382 /* found file must be directory, but not '.' or '..' */
383 if (FiosIsValidFile(_fios_path, dirent, &sb) && S_ISDIR(sb.st_mode) &&
384 (!FiosIsHiddenFile(dirent) || strncasecmp(d_name, PERSONAL_DIR, strlen(d_name)) == 0) &&
385 strcmp(d_name, ".") != 0 && strcmp(d_name, "..") != 0) {
386 fios = file_list.Append();
387 fios->type = FIOS_TYPE_DIR;
388 fios->mtime = 0;
389 strecpy(fios->name, d_name, lastof(fios->name));
390 seprintf(fios->title, lastof(fios->title), "%s" PATHSEP " (Directory)", d_name);
391 str_validate(fios->title, lastof(fios->title));
392 }
393 }
394 closedir(dir);
395 }
396
397 /* Sort the subdirs always by name, ascending, remember user-sorting order */
398 {
399 SortingBits order = _savegame_sort_order;
400 _savegame_sort_order = SORT_BY_NAME | SORT_ASCENDING;
401 QSortT(file_list.files.Begin(), file_list.files.Length(), CompareFiosItems);
402 _savegame_sort_order = order;
403 }
404
405 /* This is where to start sorting for the filenames */
406 sort_start = file_list.Length();
407
408 /* Show files */
409 FiosFileScanner scanner(fop, callback_proc, file_list);
410 if (subdir == NO_DIRECTORY) {
411 scanner.Scan(NULL, _fios_path, false);
412 } else {
413 scanner.Scan(NULL, subdir, true, true);
414 }
415
416 QSortT(file_list.Get(sort_start), file_list.Length() - sort_start, CompareFiosItems);
417
418 /* Show drives */
419 FiosGetDrives(file_list);
420
421 file_list.Compact();
422 }
423
432 static void GetFileTitle(const char *file, char *title, const char *last, Subdirectory subdir)
433 {
434 char buf[MAX_PATH];
435 strecpy(buf, file, lastof(buf));
436 strecat(buf, ".title", lastof(buf));
437
438 FILE *f = FioFOpenFile(buf, "r", subdir);
439 if (f == NULL) return;
440
441 size_t read = fread(title, 1, last - title, f);
442 assert(title + read <= last);
443 title[read] = '\0';
444 str_validate(title, last);
445 FioFCloseFile(f);
446 }
447
459 FiosType FiosGetSavegameListCallback(SaveLoadOperation fop, const char *file, const char *ext, char *title, const char *last)
460 {
461 /* Show savegame files
462 * .SAV OpenTTD saved game
463 * .SS1 Transport Tycoon Deluxe preset game
464 * .SV1 Transport Tycoon Deluxe (Patch) saved game
465 * .SV2 Transport Tycoon Deluxe (Patch) saved 2-player game */
466
467 /* Don't crash if we supply no extension */
468 if (ext == NULL) return FIOS_TYPE_INVALID;
469
470 if (strcasecmp(ext, ".sav") == 0) {
471 GetFileTitle(file, title, last, SAVE_DIR);
472 return FIOS_TYPE_FILE;
473 }
474
475 if (fop == SLO_LOAD) {
476 if (strcasecmp(ext, ".ss1") == 0 || strcasecmp(ext, ".sv1") == 0 ||
477 strcasecmp(ext, ".sv2") == 0) {
478 if (title != NULL) GetOldSaveGameName(file, title, last);
479 return FIOS_TYPE_OLDFILE;
480 }
481 }
482
483 return FIOS_TYPE_INVALID;
484 }
485
492 void FiosGetSavegameList(SaveLoadOperation fop, FileList &file_list)
493 {
494 static char *fios_save_path = NULL;
495 static char *fios_save_path_last = NULL;
496
497 if (fios_save_path == NULL) {
498 fios_save_path = MallocT<char>(MAX_PATH);
499 fios_save_path_last = fios_save_path + MAX_PATH - 1;
500 FioGetDirectory(fios_save_path, fios_save_path_last, SAVE_DIR);
501 }
502
503 _fios_path = fios_save_path;
504 _fios_path_last = fios_save_path_last;
505
506 FiosGetFileList(fop, &FiosGetSavegameListCallback, NO_DIRECTORY, file_list);
507 }
508
520 static FiosType FiosGetScenarioListCallback(SaveLoadOperation fop, const char *file, const char *ext, char *title, const char *last)
521 {
522 /* Show scenario files
523 * .SCN OpenTTD style scenario file
524 * .SV0 Transport Tycoon Deluxe (Patch) scenario
525 * .SS0 Transport Tycoon Deluxe preset scenario */
526 if (strcasecmp(ext, ".scn") == 0) {
527 GetFileTitle(file, title, last, SCENARIO_DIR);
528 return FIOS_TYPE_SCENARIO;
529 }
530
531 if (fop == SLO_LOAD) {
532 if (strcasecmp(ext, ".sv0") == 0 || strcasecmp(ext, ".ss0") == 0 ) {
533 GetOldSaveGameName(file, title, last);
534 return FIOS_TYPE_OLD_SCENARIO;
535 }
536 }
537
538 return FIOS_TYPE_INVALID;
539 }
540
547 void FiosGetScenarioList(SaveLoadOperation fop, FileList &file_list)
548 {
549 static char *fios_scn_path = NULL;
550 static char *fios_scn_path_last = NULL;
551
552 /* Copy the default path on first run or on 'New Game' */
553 if (fios_scn_path == NULL) {
554 fios_scn_path = MallocT<char>(MAX_PATH);
555 fios_scn_path_last = fios_scn_path + MAX_PATH - 1;
556 FioGetDirectory(fios_scn_path, fios_scn_path_last, SCENARIO_DIR);
557 }
558
559 _fios_path = fios_scn_path;
560 _fios_path_last = fios_scn_path_last;
561
562 char base_path[MAX_PATH];
563 FioGetDirectory(base_path, lastof(base_path), SCENARIO_DIR);
564
565 Subdirectory subdir = (fop == SLO_LOAD && strcmp(base_path, _fios_path) == 0) ? SCENARIO_DIR : NO_DIRECTORY;
566 FiosGetFileList(fop, &FiosGetScenarioListCallback, subdir, file_list);
567 }
568
569 static FiosType FiosGetHeightmapListCallback(SaveLoadOperation fop, const char *file, const char *ext, char *title, const char *last)
570 {
571 /* Show heightmap files
572 * .PNG PNG Based heightmap files
573 * .BMP BMP Based heightmap files
574 */
575
576 FiosType type = FIOS_TYPE_INVALID;
577
578 #ifdef WITH_PNG
579 if (strcasecmp(ext, ".png") == 0) type = FIOS_TYPE_PNG;
580 #endif /* WITH_PNG */
581
582 if (strcasecmp(ext, ".bmp") == 0) type = FIOS_TYPE_BMP;
583
584 if (type == FIOS_TYPE_INVALID) return FIOS_TYPE_INVALID;
585
586 TarFileList::iterator it = _tar_filelist[SCENARIO_DIR].find(file);
587 if (it != _tar_filelist[SCENARIO_DIR].end()) {
588 /* If the file is in a tar and that tar is not in a heightmap
589 * directory we are for sure not supposed to see it.
590 * Examples of this are pngs part of documentation within
591 * collections of NewGRFs or 32 bpp graphics replacement PNGs.
592 */
593 bool match = false;
594 Searchpath sp;
595 FOR_ALL_SEARCHPATHS(sp) {
596 char buf[MAX_PATH];
597 FioAppendDirectory(buf, lastof(buf), sp, HEIGHTMAP_DIR);
598
599 if (strncmp(buf, it->second.tar_filename, strlen(buf)) == 0) {
600 match = true;
601 break;
602 }
603 }
604
605 if (!match) return FIOS_TYPE_INVALID;
606 }
607
608 GetFileTitle(file, title, last, HEIGHTMAP_DIR);
609
610 return type;
611 }
612
618 void FiosGetHeightmapList(SaveLoadOperation fop, FileList &file_list)
619 {
620 static char *fios_hmap_path = NULL;
621 static char *fios_hmap_path_last = NULL;
622
623 if (fios_hmap_path == NULL) {
624 fios_hmap_path = MallocT<char>(MAX_PATH);
625 fios_hmap_path_last = fios_hmap_path + MAX_PATH - 1;
626 FioGetDirectory(fios_hmap_path, fios_hmap_path_last, HEIGHTMAP_DIR);
627 }
628
629 _fios_path = fios_hmap_path;
630 _fios_path_last = fios_hmap_path_last;
631
632 char base_path[MAX_PATH];
633 FioGetDirectory(base_path, lastof(base_path), HEIGHTMAP_DIR);
634
635 Subdirectory subdir = strcmp(base_path, _fios_path) == 0 ? HEIGHTMAP_DIR : NO_DIRECTORY;
636 FiosGetFileList(fop, &FiosGetHeightmapListCallback, subdir, file_list);
637 }
638
643 const char *FiosGetScreenshotDir()
644 {
645 static char *fios_screenshot_path = NULL;
646
647 if (fios_screenshot_path == NULL) {
648 fios_screenshot_path = MallocT<char>(MAX_PATH);
649 FioGetDirectory(fios_screenshot_path, fios_screenshot_path + MAX_PATH - 1, SCREENSHOT_DIR);
650 }
651
652 return fios_screenshot_path;
653 }
654
655 #if defined(ENABLE_NETWORK)
656 #include "network/network_content.h"
657 #include "3rdparty/md5/md5.h"
658
660 struct ScenarioIdentifier {
661 uint32 scenid;
662 uint8 md5sum[16];
663 char filename[MAX_PATH];
664
665 bool operator == (const ScenarioIdentifier &other) const
666 {
667 return this->scenid == other.scenid &&
668 memcmp(this->md5sum, other.md5sum, sizeof(this->md5sum)) == 0;
669 }
670
671 bool operator != (const ScenarioIdentifier &other) const
672 {
673 return !(*this == other);
674 }
675 };
676
680 class ScenarioScanner : protected FileScanner, public SmallVector<ScenarioIdentifier, 8> {
681 bool scanned;
682 public:
684 ScenarioScanner() : scanned(false) {}
685
690 void Scan(bool rescan)
691 {
692 if (this->scanned && !rescan) return;
693
694 this->FileScanner::Scan(".id", SCENARIO_DIR, true, true);
695 this->scanned = true;
696 }
697
698 /* virtual */ bool AddFile(const char *filename, size_t basepath_length, const char *tar_filename)
699 {
700 FILE *f = FioFOpenFile(filename, "r", SCENARIO_DIR);
701 if (f == NULL) return false;
702
703 ScenarioIdentifier id;
704 int fret = fscanf(f, "%i", &id.scenid);
705 FioFCloseFile(f);
706 if (fret != 1) return false;
707 strecpy(id.filename, filename, lastof(id.filename));
708
709 Md5 checksum;
710 uint8 buffer[1024];
711 char basename[MAX_PATH];
712 size_t len, size;
713
714 /* open the scenario file, but first get the name.
715 * This is safe as we check on extension which
716 * must always exist. */
717 strecpy(basename, filename, lastof(basename));
718 *strrchr(basename, '.') = '\0';
719 f = FioFOpenFile(basename, "rb", SCENARIO_DIR, &size);
720 if (f == NULL) return false;
721
722 /* calculate md5sum */
723 while ((len = fread(buffer, 1, (size > sizeof(buffer)) ? sizeof(buffer) : size, f)) != 0 && size != 0) {
724 size -= len;
725 checksum.Append(buffer, len);
726 }
727 checksum.Finish(id.md5sum);
728
729 FioFCloseFile(f);
730
731 this->Include(id);
732 return true;
733 }
734 };
735
737 static ScenarioScanner _scanner;
738
745 const char *FindScenario(const ContentInfo *ci, bool md5sum)
746 {
747 _scanner.Scan(false);
748
749 for (ScenarioIdentifier *id = _scanner.Begin(); id != _scanner.End(); id++) {
750 if (md5sum ? (memcmp(id->md5sum, ci->md5sum, sizeof(id->md5sum)) == 0)
751 : (id->scenid == ci->unique_id)) {
752 return id->filename;
753 }
754 }
755
756 return NULL;
757 }
758
765 bool HasScenario(const ContentInfo *ci, bool md5sum)
766 {
767 return (FindScenario(ci, md5sum) != NULL);
768 }
769
773 void ScanScenarios()
774 {
775 _scanner.Scan(true);
776 }
777
778 #endif /* ENABLE_NETWORK */