/
fs_main.cpp
1730 lines (1479 loc) · 48.3 KB
/
fs_main.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* @file fs_main.cpp
*
* @ingroup fs
*
* @author Copyright © 2003-2012 Jaakko Keränen <jaakko.keranen@iki.fi>
* @author Copyright © 2006-2012 Daniel Swanson <danij@dengine.net>
* @author Copyright © 2006 Jamie Jones <jamie_jones_au@yahoo.com.au>
* @author Copyright © 1993-1996 by id Software, Inc.
*
* @par License
* GPL: http://www.gnu.org/licenses/gpl.html
*
* <small>This program 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; either version 2 of the License, or (at your
* option) any later version. This program 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. See the GNU General
* Public License for more details. You should have received a copy of the GNU
* General Public License along with this program; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA</small>
*/
#include <ctime>
#include <QDir>
#include <QList>
#include <QtAlgorithms>
#include <de/App>
#include <de/Log>
#include <de/NativePath>
#include <de/memory.h>
#include "de_base.h"
#include "de_console.h"
#include "de_filesys.h"
#include "filesys/file.h"
#include "filesys/fileid.h"
#include "filesys/fileinfo.h"
#include "filesys/lumpindex.h"
#include "resource/wad.h"
#include "resource/zip.h"
#include "game.h"
using namespace de;
D_CMD(Dir);
D_CMD(DumpLump);
D_CMD(ListFiles);
D_CMD(ListLumps);
static FS1* fileSystem;
typedef QList<FileId> FileIds;
/**
* Virtual (file) path => Lump name mapping.
*
* @todo We can't presently use a Map or Hash for these. Although the paths are
* unique, several of the existing algorithms which match using patterns
* assume they are sorted in a quasi load ordering.
*/
typedef QPair<QString, QString> LumpMapping;
typedef QList<LumpMapping> LumpMappings;
/**
* Virtual file-directory mapping.
* Maps one (absolute) path in the virtual file system to another.
*
* @todo We can't presently use a Map or Hash for these. Although the paths are
* unique, several of the existing algorithms which match using patterns
* assume they are sorted in a quasi load ordering.
*/
typedef QPair<QString, QString> PathMapping;
typedef QList<PathMapping> PathMappings;
static bool applyPathMapping(ddstring_t* path, PathMapping const& vdm);
struct FS1::Instance
{
FS1& self;
/// @c true= Flag newly opened files as "startup".
bool loadingForStartup;
/// List of currently opened files.
FileList openFiles;
/// List of all loaded files present in the system.
FileList loadedFiles;
/// Database of unique identifiers for all loaded/opened files.
FileIds fileIds;
/// Primary index of all files in the system.
LumpIndex primaryIndex;
/// Type-specific index for ZipFiles.
LumpIndex zipFileIndex;
/// Virtual (file) path => Lump name mapping.
LumpMappings lumpMappings;
/// Virtual file-directory mapping.
PathMappings pathMappings;
/// System subspace schemes containing subsets of the total files.
Schemes schemes;
Instance(FS1* d) : self(*d), loadingForStartup(true),
openFiles(), loadedFiles(), fileIds(),
primaryIndex(), zipFileIndex(LIF_UNIQUE_PATHS)
{}
~Instance()
{
clearLoadedFiles();
clearOpenFiles();
clearIndexes();
fileIds.clear(); // Should be null-op if bookkeeping is correct.
pathMappings.clear();
lumpMappings.clear();
clearAllSchemes();
}
void clearAllSchemes()
{
DENG2_FOR_EACH(Schemes, i, schemes)
{
delete *i;
}
schemes.clear();
}
/// @return @c true if the FileId associated with @a path was released.
bool releaseFileId(String path)
{
if(!path.isEmpty())
{
FileId fileId = FileId::fromPath(path);
FileIds::iterator place = qLowerBound(fileIds.begin(), fileIds.end(), fileId);
if(place != fileIds.end() && *place == fileId)
{
#if _DEBUG
LOG_VERBOSE("Released FileId %s - \"%s\"") << *place << fileId.path();
#endif
fileIds.erase(place);
return true;
}
}
return false;
}
void clearLoadedFiles(de::LumpIndex* index = 0)
{
// Unload in reverse load order.
for(int i = loadedFiles.size() - 1; i >= 0; i--)
{
File1& file = loadedFiles[i]->file();
if(!index || index->catalogues(file))
{
self.deindex(file);
delete &file;
}
}
}
void clearOpenFiles()
{
while(!openFiles.empty())
{ delete openFiles.back(); }
}
void clearIndexes()
{
primaryIndex.clear();
zipFileIndex.clear();
}
String findPath(de::Uri const& search)
{
// Within a subspace scheme?
try
{
FS1::Scheme& scheme = self.scheme(search.scheme());
LOG_TRACE("Using scheme '%s'...") << scheme.name();
// Ensure the scheme's index is up to date.
scheme.rebuild();
// The in-scheme name is the file name sans extension.
String name = search.path().lastSegment().toString().fileNameWithoutExtension();
// Perform the search.
FS1::Scheme::FoundNodes foundNodes;
if(scheme.findAll(name, foundNodes))
{
// At least one node name was matched (perhaps partially).
DENG2_FOR_EACH_CONST(FS1::Scheme::FoundNodes, i, foundNodes)
{
PathTree::Node& node = **i;
if(!node.comparePath(search.path(), PathTree::NoBranch))
{
// This is the file we are looking for.
return node.composePath();
}
}
}
/// @todo Should return not-found here but some searches are still dependent
/// on falling back to a wider search. -ds
}
catch(FS1::UnknownSchemeError const&)
{} // Ignore this error.
// Try a wider search of the whole virtual file system.
de::File1* file = openFile(search.path(), "rb", 0, true /* allow duplicates */);
if(file)
{
String found = file->composePath();
delete file;
return found;
}
return ""; // Not found.
}
File1* findLump(String path, String const& /*mode*/)
{
if(path.isEmpty()) return 0;
// We must have an absolute path - prepend the base path if necessary.
if(QDir::isRelativePath(path))
{
path = App_BasePath() / path;
}
// First check the Zip lump index.
lumpnum_t lumpNum = zipFileIndex.lastIndexForPath(path);
if(lumpNum >= 0)
{
return &zipFileIndex.lump(lumpNum);
}
// Nope. Any applicable dir/WAD redirects?
if(!lumpMappings.empty())
{
DENG2_FOR_EACH_CONST(LumpMappings, i, lumpMappings)
{
LumpMapping const& mapping = *i;
if(mapping.first.compare(path)) continue;
lumpnum_t lumpNum = self.lumpNumForName(mapping.second);
if(lumpNum < 0) continue;
return &self.nameIndex().lump(lumpNum);
}
}
return 0;
}
FILE* findAndOpenNativeFile(String path, String const& mymode, String& foundPath)
{
DENG_ASSERT(!path.isEmpty());
// We must have an absolute path - prepend the CWD if necessary.
if(QDir::isRelativePath(path))
{
path = NativePath::workPath() / path;
}
// Translate mymode to the C-lib's fopen() mode specifiers.
char mode[8] = "";
if(mymode.contains('r')) strcat(mode, "r");
else if(mymode.contains('w')) strcat(mode, "w");
if(mymode.contains('b')) strcat(mode, "b");
else if(mymode.contains('t')) strcat(mode, "t");
// First try a real native file at this absolute path.
NativePath nativePath = NativePath(path);
FILE* nativeFile = fopen(nativePath.toUtf8().constData(), mode);
if(nativeFile)
{
foundPath = nativePath.expand().withSeparators('/');
return nativeFile;
}
// Nope. Any applicable virtual directory mappings?
if(!pathMappings.empty())
{
QByteArray pathUtf8 = path.toUtf8();
AutoStr* mapped = AutoStr_NewStd();
DENG2_FOR_EACH_CONST(PathMappings, i, pathMappings)
{
Str_Set(mapped, pathUtf8.constData());
if(!applyPathMapping(mapped, *i)) continue;
// The mapping was successful.
nativePath = NativePath(Str_Text(mapped));
nativeFile = fopen(nativePath.toUtf8().constData(), mode);
if(nativeFile)
{
foundPath = nativePath.expand().withSeparators('/');
return nativeFile;
}
}
}
return 0;
}
de::File1* openFile(String path, String const& mode, size_t baseOffset,
bool allowDuplicate)
{
if(path.isEmpty()) return 0;
LOG_AS("FS1::openFile");
// We must have an absolute path.
if(QDir::isRelativePath(path))
{
path = App_BasePath() / path;
}
LOG_TRACE("Trying \"%s\"...") << NativePath(path).pretty();
bool const reqNativeFile = mode.contains('f');
FileHandle* hndl = 0;
FileInfo info; // The temporary info descriptor.
// First check for lumps?
if(!reqNativeFile)
{
if(File1* found = findLump(path, mode))
{
// Do not read files twice.
if(!allowDuplicate && !self.checkFileId(found->composeUri())) return 0;
// Get a handle to the lump we intend to open.
/// @todo The way this buffering works is nonsensical it should not be done here
/// but should instead be deferred until the content of the lump is read.
hndl = FileHandleBuilder::fromLump(*found, /*baseOffset,*/ false/*dontBuffer*/);
// Prepare a temporary info descriptor.
info = found->info();
}
}
// Not found? - try a native file.
if(!hndl)
{
String foundPath;
if(FILE* found = findAndOpenNativeFile(path, mode, foundPath))
{
// Do not read files twice.
if(!allowDuplicate && !self.checkFileId(de::Uri(foundPath, RC_NULL)))
{
fclose(found);
return 0;
}
// Acquire a handle on the file we intend to open.
hndl = FileHandleBuilder::fromNativeFile(*found, baseOffset);
// Prepare the temporary info descriptor.
info = FileInfo(F_GetLastModified(foundPath.toUtf8().constData()));
}
}
// Nothing?
if(!hndl) return 0;
// Search path is used here rather than found path as the latter may have
// been mapped to another location. We want the file to be attributed with
// the path it is to be known by throughout the virtual file system.
File1& file = self.interpret(*hndl, path, info);
if(loadingForStartup)
{
file.setStartup(true);
}
return &file;
}
};
FS1::FS1()
{
d = new Instance(this);
FileHandleBuilder::init();
}
FS1::~FS1()
{
delete d;
FileHandleBuilder::shutdown();
}
FS1::Scheme& FS1::createScheme(String name, Scheme::Flags flags)
{
DENG_ASSERT(name.length() >= Scheme::min_name_length);
// Ensure this is a unique name.
if(knownScheme(name)) return scheme(name);
// Create a new scheme.
Scheme* newScheme = new Scheme(name, flags);
d->schemes.insert(name.toLower(), newScheme);
return *newScheme;
}
void FS1::consoleRegister()
{
C_CMD("dir", "", Dir);
C_CMD("ls", "", Dir); // Alias
C_CMD("dir", "s*", Dir);
C_CMD("ls", "s*", Dir); // Alias
C_CMD("dump", "s", DumpLump);
C_CMD("listfiles", "", ListFiles);
C_CMD("listlumps", "", ListLumps);
}
/**
* @note Performance is O(n).
* @return @c iterator pointing to list->end() if not found.
*/
static FS1::FileList::iterator findListFile(FS1::FileList& list, de::File1& file)
{
if(list.empty()) return list.end();
// Perform the search.
FS1::FileList::iterator i;
for(i = list.begin(); i != list.end(); ++i)
{
if(&file == &(*i)->file())
{
break; // This is the node we are looking for.
}
}
return i;
}
/**
* @note Performance is O(n).
* @return @c iterator pointing to list->end() if not found.
*/
static FS1::FileList::iterator findListFileByPath(FS1::FileList& list, String path)
{
if(list.empty()) return list.end();
if(path.isEmpty()) return list.end();
// Perform the search.
FS1::FileList::iterator i;
for(i = list.begin(); i != list.end(); ++i)
{
de::File1& file = (*i)->file();
if(!file.composePath().compare(path, Qt::CaseInsensitive))
{
break; // This is the node we are looking for.
}
}
return i;
}
void FS1::index(de::File1& file)
{
#ifdef DENG_DEBUG
// Ensure this hasn't yet been indexed.
FileList::const_iterator found = findListFile(d->loadedFiles, file);
if(found != d->loadedFiles.end())
throw Error("FS1::index", "File \"" + NativePath(file.composePath()).pretty() + "\" has already been indexed");
#endif
// Publish lumps to one or more indexes?
if(Zip* zip = dynamic_cast<Zip*>(&file))
{
if(!zip->empty())
{
// Insert the lumps into their rightful places in the index.
for(int i = 0; i < zip->lumpCount(); ++i)
{
File1& lump = zip->lump(i);
d->primaryIndex.catalogLump(lump);
// Zip files go into a special ZipFile index as well.
d->zipFileIndex.catalogLump(lump);
}
}
}
else if(Wad* wad = dynamic_cast<Wad*>(&file))
{
if(!wad->empty())
{
// Insert the lumps into their rightful places in the index.
for(int i = 0; i < wad->lumpCount(); ++i)
{
File1& lump = wad->lump(i);
d->primaryIndex.catalogLump(lump);
}
}
}
// Add a handle to the loaded files list.
FileHandle* loadedFilesHndl = FileHandleBuilder::fromFile(file);
d->loadedFiles.push_back(loadedFilesHndl); loadedFilesHndl->setList(reinterpret_cast<struct filelist_s*>(&d->loadedFiles));
}
void FS1::deindex(de::File1& file)
{
FileList::iterator found = findListFile(d->loadedFiles, file);
if(found == d->loadedFiles.end()) return; // Most peculiar..
QByteArray path = file.composePath().toUtf8();
d->releaseFileId(path.constData());
d->zipFileIndex.pruneByFile(file);
d->primaryIndex.pruneByFile(file);
d->loadedFiles.erase(found);
delete *found;
}
de::File1& FS1::find(de::Uri const& search)
{
LOG_AS("FS1::find");
if(!search.isEmpty())
{
try
{
String searchPath = search.resolved();
// Convert to an absolute path.
if(!QDir::isAbsolutePath(searchPath))
{
searchPath = App_BasePath() / searchPath;
}
FileList::iterator found = findListFileByPath(d->loadedFiles, searchPath);
if(found != d->loadedFiles.end())
{
DENG_ASSERT((*found)->hasFile());
return (*found)->file();
}
}
catch(de::Uri::ResolveError const& er)
{
// Log but otherwise ignore unresolved paths.
LOG_DEBUG(er.asText());
}
}
/// @throw NotFoundError No files found matching the search term.
throw NotFoundError("FS1::find", "No files found matching '" + search.compose() + "'");
}
String FS1::findPath(de::Uri const& search, int flags, ResourceClass& rclass)
{
LOG_AS("FS1::findPath");
if(!search.isEmpty())
{
try
{
String searchPath = search.resolved();
// If an extension was specified, first look for files of the same type.
String ext = searchPath.fileNameExtension();
if(!ext.isEmpty() && ext.compare(".*"))
{
String found = d->findPath(de::Uri(searchPath, RC_NULL).setScheme(search.scheme()));
if(!found.isEmpty()) return found;
// If we are looking for a particular file type, get out of here.
if(flags & RLF_MATCH_EXTENSION) return "";
}
if(isNullResourceClass(rclass) || !rclass.fileTypeCount()) return "";
/*
* Try each expected file type name extension for this resource class.
*/
String searchPathWithoutFileNameExtension = searchPath.fileNamePath() / searchPath.fileNameWithoutExtension();
DENG2_FOR_EACH_CONST(ResourceClass::FileTypes, typeIt, rclass.fileTypes())
{
DENG2_FOR_EACH_CONST(QStringList, i, (*typeIt)->knownFileNameExtensions())
{
String const& ext = *i;
String found = d->findPath(de::Uri(searchPathWithoutFileNameExtension + ext, RC_NULL).setScheme(search.scheme()));
if(!found.isEmpty()) return found;
}
};
}
catch(de::Uri::ResolveError const& er)
{
// Log but otherwise ignore unresolved paths.
LOG_DEBUG(er.asText());
}
}
/// @throw NotFoundError No files found matching the search term.
throw NotFoundError("FS1::findPath", "No paths found matching '" + search.compose() + "'");
}
String FS1::findPath(de::Uri const& search, int flags)
{
return findPath(search, flags, DD_ResourceClassById(RC_NULL));
}
#if _DEBUG
static void printFileIds(FileIds const& fileIds)
{
uint idx = 0;
DENG2_FOR_EACH_CONST(FileIds, i, fileIds)
{
LOG_MSG(" %u - %s : \"%s\"") << idx << *i << i->path();
++idx;
}
}
#endif
#if _DEBUG
static void printFileList(FS1::FileList& list)
{
uint idx = 0;
DENG2_FOR_EACH_CONST(FS1::FileList, i, list)
{
de::FileHandle& hndl = **i;
de::File1& file = hndl.file();
QByteArray path = file.composePath().toUtf8();
FileId fileId = FileId::fromPath(path.constData());
LOG_MSG(" %c%d: %s - \"%s\" (handle: %p)")
<< (file.hasStartup()? '*' : ' ') << idx
<< fileId << fileId.path() << (void*)&hndl;
++idx;
}
}
#endif
int FS1::unloadAllNonStartupFiles()
{
#if _DEBUG
// List all open files with their identifiers.
if(verbose)
{
LOG_MSG("Open files at reset:");
printFileList(d->openFiles);
LOG_MSG("End\n");
}
#endif
// Perform non-startup file unloading (in reverse load order).
int numUnloadedFiles = 0;
for(int i = d->loadedFiles.size() - 1; i >= 0; i--)
{
File1& file = d->loadedFiles[i]->file();
if(file.hasStartup()) continue;
deindex(file);
delete &file;
numUnloadedFiles += 1;
}
#if _DEBUG
// Sanity check: look for orphaned identifiers.
if(!d->fileIds.empty())
{
LOG_MSG("Warning: Orphan FileIds:");
printFileIds(d->fileIds);
}
#endif
return numUnloadedFiles;
}
bool FS1::checkFileId(de::Uri const& path)
{
if(!accessFile(path)) return false;
// Calculate the identifier.
FileId fileId = FileId::fromPath(path.compose());
FileIds::iterator place = qLowerBound(d->fileIds.begin(), d->fileIds.end(), fileId);
if(place != d->fileIds.end() && *place == fileId) return false;
#ifdef _DEBUG
LOG_DEBUG("Added FileId %s - \"%s\"") << fileId << fileId.path(); /* path() is debug-only */
#endif
d->fileIds.insert(place, fileId);
return true;
}
void FS1::resetFileIds()
{
d->fileIds.clear();
}
void FS1::endStartup()
{
d->loadingForStartup = false;
}
LumpIndex const& FS1::nameIndex() const
{
return d->primaryIndex;
}
lumpnum_t FS1::lumpNumForName(String name)
{
LOG_AS("FS1::lumpNumForName");
if(name.isEmpty()) return -1;
// Append a .lmp extension if none is specified.
if(name.fileNameExtension().isEmpty())
{
name += ".lmp";
}
// Perform the search.
return d->primaryIndex.lastIndexForPath(Path(name));
}
void FS1::releaseFile(de::File1& file)
{
for(int i = d->openFiles.size() - 1; i >= 0; i--)
{
FileHandle& hndl = *(d->openFiles[i]);
if(&hndl.file() == &file)
{
d->openFiles.removeAt(i);
}
}
}
/// @return @c NULL= Not found.
static Wad* findFirstWadFile(FS1::FileList& list, bool custom)
{
if(list.empty()) return 0;
DENG2_FOR_EACH(FS1::FileList, i, list)
{
de::File1& file = (*i)->file();
if(custom != file.hasCustom()) continue;
Wad* wad = dynamic_cast<Wad*>(&file);
if(wad) return wad;
}
return 0;
}
uint FS1::loadedFilesCRC()
{
/**
* We define the CRC as that of the lump directory of the first loaded IWAD.
* @todo Really kludgy...
*/
Wad* iwad = findFirstWadFile(d->loadedFiles, false/*not-custom*/);
if(!iwad) return 0;
return iwad->calculateCRC();
}
int FS1::findAll(FS1::FileList& found) const
{
int numFound = 0;
DENG2_FOR_EACH_CONST(FS1::FileList, i, d->loadedFiles)
{
found.push_back(*i);
numFound += 1;
}
return numFound;
}
int FS1::findAll(bool (*predicate)(de::File1& file, void* parameters), void* parameters,
FS1::FileList& found) const
{
int numFound = 0;
DENG2_FOR_EACH_CONST(FS1::FileList, i, d->loadedFiles)
{
// Interested in this file?
if(predicate && !predicate((*i)->file(), parameters)) continue; // Nope.
found.push_back(*i);
numFound += 1;
}
return numFound;
}
int FS1::findAllPaths(String searchPattern, int flags, FS1::PathList& found)
{
int const numFoundSoFar = found.count();
// We must have an absolute path - prepend the base path if necessary.
if(!QDir::isAbsolutePath(searchPattern))
{
searchPattern = App_BasePath() / searchPattern;
}
de::Uri patternMap = de::Uri(searchPattern, RC_NULL);
QByteArray searchPatternUtf8 = searchPattern.toUtf8();
/*
* Check the Zip directory.
*/
DENG2_FOR_EACH_CONST(LumpIndex::Lumps, i, d->zipFileIndex.lumps())
{
File1 const& lump = **i;
PathTree::Node const& node = lump.directoryNode();
String* filePath = 0;
bool patternMatched;
if(!(flags & SearchPath::NoDescend))
{
filePath = new String(lump.composePath());
QByteArray filePathUtf8 = filePath->toUtf8();
patternMatched = F_MatchFileName(filePathUtf8.constData(), searchPatternUtf8.constData());
}
else
{
patternMatched = !node.comparePath(patternMap.path(), PathTree::MatchFull);
}
if(!patternMatched) continue;
// Not yet composed the path?
if(!filePath)
{
filePath = new String(lump.composePath());
}
found.push_back(PathListItem(*filePath, !node.isLeaf()? A_SUBDIR : 0));
delete filePath;
}
/*
* Check the dir/WAD direcs.
*/
if(!d->lumpMappings.empty())
{
DENG2_FOR_EACH_CONST(LumpMappings, i, d->lumpMappings)
{
if(!F_MatchFileName(i->first.toUtf8().constData(), searchPatternUtf8.constData())) continue;
found.push_back(PathListItem(i->first, 0 /*only filepaths (i.e., leaves) can be mapped to lumps*/));
}
/// @todo Shouldn't these be sorted? -ds
}
/*
* Check native paths.
*/
String searchDirectory = searchPattern.fileNamePath();
if(!searchDirectory.isEmpty())
{
QByteArray searchDirectoryUtf8 = searchDirectory.toUtf8();
PathList nativeFilePaths;
AutoStr* wildPath = AutoStr_NewStd();
Str_Reserve(wildPath, searchDirectory.length() + 2 + 16); // Conservative estimate.
for(int i = -1; i < (int)d->pathMappings.count(); ++i)
{
Str_Clear(wildPath);
Str_Appendf(wildPath, "%s/", searchDirectoryUtf8.constData());
if(i > -1)
{
// Possible mapping?
if(!applyPathMapping(wildPath, d->pathMappings[i])) continue;
}
Str_AppendChar(wildPath, '*');
finddata_t fd;
if(!myfindfirst(Str_Text(wildPath), &fd))
{
// First path found.
do
{
// Ignore relative directory symbolics.
if(Str_Compare(&fd.name, ".") && Str_Compare(&fd.name, ".."))
{
String foundPath = searchDirectory / NativePath(Str_Text(&fd.name)).withSeparators('/');
QByteArray foundPathUtf8 = foundPath.toUtf8();
if(!F_MatchFileName(foundPathUtf8.constData(), searchPatternUtf8.constData())) continue;
nativeFilePaths.push_back(PathListItem(foundPath, fd.attrib));
}
} while(!myfindnext(&fd));
}
myfindend(&fd);
}
// Sort the native file paths.
qSort(nativeFilePaths.begin(), nativeFilePaths.end());
// Add the native file paths to the found results.
found.append(nativeFilePaths);
}
return found.count() - numFoundSoFar;
}
de::File1& FS1::interpret(de::FileHandle& hndl, String filePath, FileInfo const& info)
{
DENG_ASSERT(!filePath.isEmpty());
de::File1* interpretedFile = 0;
// Firstly try the interpreter for the guessed resource types.
FileType const& ftypeGuess = DD_GuessFileTypeFromFileName(filePath);
if(NativeFileType const* fileType = dynamic_cast<NativeFileType const*>(&ftypeGuess))
{
interpretedFile = fileType->interpret(hndl, filePath, info);
}
// If not yet interpreted - try each recognisable format in order.
if(!interpretedFile)
{
FileTypes const& fileTypes = DD_FileTypes();
DENG2_FOR_EACH_CONST(FileTypes, i, fileTypes)
{
if(NativeFileType const* fileType = dynamic_cast<NativeFileType const*>(*i))
{
// Already tried this?
if(fileType == &ftypeGuess) continue;
interpretedFile = fileType->interpret(hndl, filePath, info);
if(interpretedFile) break;
}
}
}
// Still not interpreted?
if(!interpretedFile)
{
// Use a generic file.
File1* container = (hndl.hasFile() && hndl.file().isContained())? &hndl.file().container() : 0;
interpretedFile = new File1(hndl, filePath, info, container);
}
DENG_ASSERT(interpretedFile);
return *interpretedFile;
}
de::FileHandle& FS1::openFile(String const& path, String const& mode, size_t baseOffset, bool allowDuplicate)
{
#if _DEBUG
for(int i = 0; i < mode.length(); ++i)
{
if(mode[i] != 'r' && mode[i] != 't' && mode[i] != 'b' && mode[i] != 'f')
throw Error("FS1::openFile", "Unknown argument in mode string '" + mode + "'");
}
#endif
File1* file = d->openFile(path, mode, baseOffset, allowDuplicate);
if(!file) throw NotFoundError("FS1::openFile", "No files found matching '" + path + "'");
// Add a handle to the opened files list.
FileHandle& openFilesHndl = *FileHandleBuilder::fromFile(*file);
d->openFiles.push_back(&openFilesHndl); openFilesHndl.setList(reinterpret_cast<struct filelist_s*>(&d->openFiles));
return openFilesHndl;
}
de::FileHandle& FS1::openLump(de::File1& lump)
{
// Add a handle to the opened files list.
FileHandle& openFilesHndl = *FileHandleBuilder::fromLump(lump, false/*do buffer*/);
d->openFiles.push_back(&openFilesHndl); openFilesHndl.setList(reinterpret_cast<struct filelist_s*>(&d->openFiles));
return openFilesHndl;
}
bool FS1::accessFile(de::Uri const& search)
{
try
{
String searchPath = search.resolved();
de::File1* file = d->openFile(searchPath, "rb", 0, true /* allow duplicates */);
if(file)
{
delete file;
return true;
}
}
catch(de::Uri::ResolveError const& er)
{
// Log but otherwise ignore unresolved paths.
LOG_DEBUG(er.asText());