1 // Copyright (C) 2002-2012 Nikolaus Gebhardt
\r
2 // This file is part of the "Irrlicht Engine".
\r
3 // For conditions of distribution and use, see copyright notice in irrlicht.h
\r
5 #include "IrrCompileConfig.h"
\r
7 #include "CFileSystem.h"
\r
8 #include "IReadFile.h"
\r
9 #include "IWriteFile.h"
\r
10 #include "CZipReader.h"
\r
11 #include "CMountPointReader.h"
\r
12 #include "CFileList.h"
\r
15 #include "CReadFile.h"
\r
16 #include "CMemoryFile.h"
\r
17 #include "CLimitReadFile.h"
\r
18 #include "CWriteFile.h"
\r
21 #if defined (__STRICT_ANSI__)
\r
22 #error Compiling with __STRICT_ANSI__ not supported. g++ does set this when compiling with -std=c++11 or -std=c++0x. Use instead -std=gnu++11 or -std=gnu++0x. Or use -U__STRICT_ANSI__ to disable strict ansi.
\r
25 #if defined (_IRR_WINDOWS_API_)
\r
26 #include <direct.h> // for _chdir
\r
27 #include <io.h> // for _access
\r
29 #elif (defined(_IRR_POSIX_API_) || defined(_IRR_OSX_PLATFORM_) || defined(_IRR_IOS_PLATFORM_) || defined(_IRR_ANDROID_PLATFORM_))
\r
34 #include <sys/types.h>
\r
36 #include <sys/stat.h>
\r
38 #elif defined(_IRR_EMSCRIPTEN_PLATFORM_)
\r
48 CFileSystem::CFileSystem()
\r
51 setDebugName("CFileSystem");
\r
54 setFileListSystem(FILESYSTEM_NATIVE);
\r
55 //! reset current working directory
\r
56 getWorkingDirectory();
\r
58 #ifdef __IRR_COMPILE_WITH_PAK_ARCHIVE_LOADER_
\r
59 ArchiveLoader.push_back(new CArchiveLoaderPAK(this));
\r
62 #ifdef __IRR_COMPILE_WITH_NPK_ARCHIVE_LOADER_
\r
63 ArchiveLoader.push_back(new CArchiveLoaderNPK(this));
\r
66 #ifdef __IRR_COMPILE_WITH_TAR_ARCHIVE_LOADER_
\r
67 ArchiveLoader.push_back(new CArchiveLoaderTAR(this));
\r
70 #ifdef __IRR_COMPILE_WITH_WAD_ARCHIVE_LOADER_
\r
71 ArchiveLoader.push_back(new CArchiveLoaderWAD(this));
\r
74 #ifdef __IRR_COMPILE_WITH_MOUNT_ARCHIVE_LOADER_
\r
75 ArchiveLoader.push_back(new CArchiveLoaderMount(this));
\r
78 #ifdef __IRR_COMPILE_WITH_ZIP_ARCHIVE_LOADER_
\r
79 ArchiveLoader.push_back(new CArchiveLoaderZIP(this));
\r
86 CFileSystem::~CFileSystem()
\r
90 for ( i=0; i < FileArchives.size(); ++i)
\r
92 FileArchives[i]->drop();
\r
95 for ( i=0; i < ArchiveLoader.size(); ++i)
\r
97 ArchiveLoader[i]->drop();
\r
102 //! opens a file for read access
\r
103 IReadFile* CFileSystem::createAndOpenFile(const io::path& filename)
\r
105 if ( filename.empty() )
\r
108 IReadFile* file = 0;
\r
111 for (i=0; i< FileArchives.size(); ++i)
\r
113 file = FileArchives[i]->createAndOpenFile(filename);
\r
118 // Create the file using an absolute path so that it matches
\r
119 // the scheme used by CNullDriver::getTexture().
\r
120 return CReadFile::createReadFile(getAbsolutePath(filename));
\r
124 //! Creates an IReadFile interface for treating memory like a file.
\r
125 IReadFile* CFileSystem::createMemoryReadFile(const void* memory, s32 len,
\r
126 const io::path& fileName, bool deleteMemoryWhenDropped)
\r
131 return new CMemoryReadFile(memory, len, fileName, deleteMemoryWhenDropped);
\r
135 //! Creates an IReadFile interface for reading files inside files
\r
136 IReadFile* CFileSystem::createLimitReadFile(const io::path& fileName,
\r
137 IReadFile* alreadyOpenedFile, long pos, long areaSize)
\r
139 if (!alreadyOpenedFile)
\r
142 return new CLimitReadFile(alreadyOpenedFile, pos, areaSize, fileName);
\r
146 //! Creates an IReadFile interface for treating memory like a file.
\r
147 IWriteFile* CFileSystem::createMemoryWriteFile(void* memory, s32 len,
\r
148 const io::path& fileName, bool deleteMemoryWhenDropped)
\r
153 return new CMemoryWriteFile(memory, len, fileName, deleteMemoryWhenDropped);
\r
157 //! Opens a file for write access.
\r
158 IWriteFile* CFileSystem::createAndWriteFile(const io::path& filename, bool append)
\r
160 return CWriteFile::createWriteFile(filename, append);
\r
164 //! Adds an external archive loader to the engine.
\r
165 void CFileSystem::addArchiveLoader(IArchiveLoader* loader)
\r
171 ArchiveLoader.push_back(loader);
\r
174 //! Returns the total number of archive loaders added.
\r
175 u32 CFileSystem::getArchiveLoaderCount() const
\r
177 return ArchiveLoader.size();
\r
180 //! Gets the archive loader by index.
\r
181 IArchiveLoader* CFileSystem::getArchiveLoader(u32 index) const
\r
183 if (index < ArchiveLoader.size())
\r
184 return ArchiveLoader[index];
\r
189 //! move the hirarchy of the filesystem. moves sourceIndex relative up or down
\r
190 bool CFileSystem::moveFileArchive(u32 sourceIndex, s32 relative)
\r
193 const s32 dest = (s32) sourceIndex + relative;
\r
194 const s32 dir = relative < 0 ? -1 : 1;
\r
195 const s32 sourceEnd = ((s32) FileArchives.size() ) - 1;
\r
198 for (s32 s = (s32) sourceIndex;s != dest; s += dir)
\r
200 if (s < 0 || s > sourceEnd || s + dir < 0 || s + dir > sourceEnd)
\r
203 t = FileArchives[s + dir];
\r
204 FileArchives[s + dir] = FileArchives[s];
\r
205 FileArchives[s] = t;
\r
212 //! Adds an archive to the file system.
\r
213 bool CFileSystem::addFileArchive(const io::path& filename, bool ignoreCase,
\r
214 bool ignorePaths, E_FILE_ARCHIVE_TYPE archiveType,
\r
215 const core::stringc& password,
\r
216 IFileArchive** retArchive)
\r
218 IFileArchive* archive = 0;
\r
221 // see if archive is already added
\r
222 if (changeArchivePassword(filename, password, retArchive))
\r
227 // do we know what type it should be?
\r
228 if (archiveType == EFAT_UNKNOWN || archiveType == EFAT_FOLDER)
\r
230 // try to load archive based on file name
\r
231 for (i = ArchiveLoader.size()-1; i >=0 ; --i)
\r
233 if (ArchiveLoader[i]->isALoadableFileFormat(filename))
\r
235 archive = ArchiveLoader[i]->createArchive(filename, ignoreCase, ignorePaths);
\r
241 // try to load archive based on content
\r
244 io::IReadFile* file = createAndOpenFile(filename);
\r
247 for (i = ArchiveLoader.size()-1; i >= 0; --i)
\r
250 if (ArchiveLoader[i]->isALoadableFileFormat(file))
\r
253 archive = ArchiveLoader[i]->createArchive(file, ignoreCase, ignorePaths);
\r
264 // try to open archive based on archive loader type
\r
266 io::IReadFile* file = 0;
\r
268 for (i = ArchiveLoader.size()-1; i >= 0; --i)
\r
270 if (ArchiveLoader[i]->isALoadableFileFormat(archiveType))
\r
272 // attempt to open file
\r
274 file = createAndOpenFile(filename);
\r
276 // is the file open?
\r
279 // attempt to open archive
\r
281 if (ArchiveLoader[i]->isALoadableFileFormat(file))
\r
284 archive = ArchiveLoader[i]->createArchive(file, ignoreCase, ignorePaths);
\r
291 // couldn't open file
\r
297 // if open, close the file
\r
304 FileArchives.push_back(archive);
\r
305 if (password.size())
\r
306 archive->Password=password;
\r
308 *retArchive = archive;
\r
313 os::Printer::log("Could not create archive for", filename, ELL_ERROR);
\r
320 bool CFileSystem::changeArchivePassword(const path& filename,
\r
321 const core::stringc& password,
\r
322 IFileArchive** archive)
\r
324 for (s32 idx = 0; idx < (s32)FileArchives.size(); ++idx)
\r
326 // TODO: This should go into a path normalization method
\r
327 // We need to check for directory names with trailing slash and without
\r
328 const path absPath = getAbsolutePath(filename);
\r
329 const path arcPath = FileArchives[idx]->getFileList()->getPath();
\r
330 if ((absPath == arcPath) || ((absPath+_IRR_TEXT("/")) == arcPath))
\r
332 if (password.size())
\r
333 FileArchives[idx]->Password=password;
\r
335 *archive = FileArchives[idx];
\r
343 bool CFileSystem::addFileArchive(IReadFile* file, bool ignoreCase,
\r
344 bool ignorePaths, E_FILE_ARCHIVE_TYPE archiveType,
\r
345 const core::stringc& password, IFileArchive** retArchive)
\r
347 if (!file || archiveType == EFAT_FOLDER)
\r
352 if (changeArchivePassword(file->getFileName(), password, retArchive))
\r
355 IFileArchive* archive = 0;
\r
358 if (archiveType == EFAT_UNKNOWN)
\r
360 // try to load archive based on file name
\r
361 for (i = ArchiveLoader.size()-1; i >=0 ; --i)
\r
363 if (ArchiveLoader[i]->isALoadableFileFormat(file->getFileName()))
\r
365 archive = ArchiveLoader[i]->createArchive(file, ignoreCase, ignorePaths);
\r
371 // try to load archive based on content
\r
374 for (i = ArchiveLoader.size()-1; i >= 0; --i)
\r
377 if (ArchiveLoader[i]->isALoadableFileFormat(file))
\r
380 archive = ArchiveLoader[i]->createArchive(file, ignoreCase, ignorePaths);
\r
389 // try to open archive based on archive loader type
\r
390 for (i = ArchiveLoader.size()-1; i >= 0; --i)
\r
392 if (ArchiveLoader[i]->isALoadableFileFormat(archiveType))
\r
394 // attempt to open archive
\r
396 if (ArchiveLoader[i]->isALoadableFileFormat(file))
\r
399 archive = ArchiveLoader[i]->createArchive(file, ignoreCase, ignorePaths);
\r
409 FileArchives.push_back(archive);
\r
410 if (password.size())
\r
411 archive->Password=password;
\r
413 *retArchive = archive;
\r
418 os::Printer::log("Could not create archive for", file->getFileName(), ELL_ERROR);
\r
426 //! Adds an archive to the file system.
\r
427 bool CFileSystem::addFileArchive(IFileArchive* archive)
\r
431 for (u32 i=0; i < FileArchives.size(); ++i)
\r
433 if (archive == FileArchives[i])
\r
438 FileArchives.push_back(archive);
\r
448 //! removes an archive from the file system.
\r
449 bool CFileSystem::removeFileArchive(u32 index)
\r
452 if (index < FileArchives.size())
\r
454 FileArchives[index]->drop();
\r
455 FileArchives.erase(index);
\r
462 //! removes an archive from the file system.
\r
463 bool CFileSystem::removeFileArchive(const io::path& filename)
\r
465 const path absPath = getAbsolutePath(filename);
\r
466 for (u32 i=0; i < FileArchives.size(); ++i)
\r
468 if (absPath == FileArchives[i]->getFileList()->getPath())
\r
469 return removeFileArchive(i);
\r
475 //! Removes an archive from the file system.
\r
476 bool CFileSystem::removeFileArchive(const IFileArchive* archive)
\r
478 for (u32 i=0; i < FileArchives.size(); ++i)
\r
480 if (archive == FileArchives[i])
\r
482 return removeFileArchive(i);
\r
489 //! gets an archive
\r
490 u32 CFileSystem::getFileArchiveCount() const
\r
492 return FileArchives.size();
\r
496 IFileArchive* CFileSystem::getFileArchive(u32 index)
\r
498 return index < getFileArchiveCount() ? FileArchives[index] : 0;
\r
502 //! Returns the string of the current working directory
\r
503 const io::path& CFileSystem::getWorkingDirectory()
\r
505 EFileSystemType type = FileSystemType;
\r
507 if (type != FILESYSTEM_NATIVE)
\r
509 type = FILESYSTEM_VIRTUAL;
\r
513 #if defined(_IRR_WINDOWS_API_)
\r
514 fschar_t tmp[_MAX_PATH];
\r
515 _getcwd(tmp, _MAX_PATH);
\r
516 WorkingDirectory[FILESYSTEM_NATIVE] = tmp;
\r
517 WorkingDirectory[FILESYSTEM_NATIVE].replace('\\', '/');
\r
520 #if (defined(_IRR_POSIX_API_) || defined(_IRR_OSX_PLATFORM_))
\r
522 // getting the CWD is rather complex as we do not know the size
\r
523 // so try it until the call was successful
\r
524 // Note that neither the first nor the second parameter may be 0 according to POSIX
\r
527 char *tmpPath = new char[pathSize];
\r
528 while ((pathSize < (1<<16)) && !(getcwd(tmpPath,pathSize)))
\r
532 tmpPath = new char[pathSize];
\r
536 WorkingDirectory[FILESYSTEM_NATIVE] = tmpPath;
\r
541 WorkingDirectory[type].validate();
\r
544 return WorkingDirectory[type];
\r
548 //! Changes the current Working Directory to the given string.
\r
549 bool CFileSystem::changeWorkingDirectoryTo(const io::path& newDirectory)
\r
551 bool success=false;
\r
553 if (FileSystemType != FILESYSTEM_NATIVE)
\r
555 WorkingDirectory[FILESYSTEM_VIRTUAL] = newDirectory;
\r
556 // is this empty string constant really intended?
\r
557 flattenFilename(WorkingDirectory[FILESYSTEM_VIRTUAL], _IRR_TEXT(""));
\r
562 WorkingDirectory[FILESYSTEM_NATIVE] = newDirectory;
\r
564 #if defined(_MSC_VER)
\r
565 success = (_chdir(newDirectory.c_str()) == 0);
\r
567 success = (chdir(newDirectory.c_str()) == 0);
\r
575 io::path CFileSystem::getAbsolutePath(const io::path& filename) const
\r
577 if ( filename.empty() )
\r
579 #if defined(_IRR_WINDOWS_API_)
\r
581 fschar_t fpath[_MAX_PATH];
\r
582 p = _fullpath(fpath, filename.c_str(), _MAX_PATH);
\r
583 core::stringc tmp(p);
\r
584 tmp.replace('\\', '/');
\r
586 #elif (defined(_IRR_POSIX_API_) || defined(_IRR_OSX_PLATFORM_))
\r
590 p = realpath(filename.c_str(), fpath);
\r
593 // content in fpath is unclear at this point
\r
594 if (!fpath[0]) // seems like fpath wasn't altered, use our best guess
\r
596 io::path tmp(filename);
\r
597 return flattenFilename(tmp);
\r
600 return io::path(fpath);
\r
602 if (filename[filename.size()-1]=='/')
\r
603 return io::path(p)+_IRR_TEXT("/");
\r
605 return io::path(p);
\r
607 return io::path(filename);
\r
612 //! returns the directory part of a filename, i.e. all until the first
\r
613 //! slash or backslash, excluding it. If no directory path is prefixed, a '.'
\r
615 io::path CFileSystem::getFileDir(const io::path& filename) const
\r
617 // find last forward or backslash
\r
618 s32 lastSlash = filename.findLast('/');
\r
619 const s32 lastBackSlash = filename.findLast('\\');
\r
620 lastSlash = lastSlash > lastBackSlash ? lastSlash : lastBackSlash;
\r
622 if ((u32)lastSlash < filename.size())
\r
623 return filename.subString(0, lastSlash);
\r
625 return _IRR_TEXT(".");
\r
629 //! returns the base part of a filename, i.e. all except for the directory
\r
630 //! part. If no directory path is prefixed, the full name is returned.
\r
631 io::path CFileSystem::getFileBasename(const io::path& filename, bool keepExtension) const
\r
633 // find last forward or backslash
\r
634 s32 lastSlash = filename.findLast('/');
\r
635 const s32 lastBackSlash = filename.findLast('\\');
\r
636 lastSlash = core::max_(lastSlash, lastBackSlash);
\r
638 // get number of chars after last dot
\r
640 if (!keepExtension)
\r
642 // take care to search only after last slash to check only for
\r
643 // dots in the filename
\r
644 end = filename.findLast('.');
\r
645 if (end == -1 || end < lastSlash)
\r
648 end = filename.size()-end;
\r
651 if ((u32)lastSlash < filename.size())
\r
652 return filename.subString(lastSlash+1, filename.size()-lastSlash-1-end);
\r
654 return filename.subString(0, filename.size()-end);
\r
660 //! flatten a path and file name for example: "/you/me/../." becomes "/you"
\r
661 io::path& CFileSystem::flattenFilename(io::path& directory, const io::path& root) const
\r
663 directory.replace('\\', '/');
\r
664 if (directory.lastChar() != '/')
\r
665 directory.append('/');
\r
672 bool lastWasRealDir=false;
\r
674 while ((pos = directory.findNext('/', lastpos)) >= 0)
\r
676 subdir = directory.subString(lastpos, pos - lastpos + 1);
\r
678 if (subdir == _IRR_TEXT("../"))
\r
680 if (lastWasRealDir)
\r
682 deletePathFromPath(dir, 2);
\r
683 lastWasRealDir=(dir.size()!=0);
\r
687 dir.append(subdir);
\r
688 lastWasRealDir=false;
\r
691 else if (subdir == _IRR_TEXT("/"))
\r
695 else if (subdir != _IRR_TEXT("./"))
\r
697 dir.append(subdir);
\r
698 lastWasRealDir=true;
\r
708 //! Get the relative filename, relative to the given directory
\r
709 path CFileSystem::getRelativeFilename(const path& filename, const path& directory) const
\r
711 if ( filename.empty() || directory.empty() )
\r
714 io::path path1, file, ext;
\r
715 core::splitFilename(getAbsolutePath(filename), &path1, &file, &ext);
\r
716 io::path path2(getAbsolutePath(directory));
\r
717 std::list<io::path> list1, list2;
\r
718 path1.split(list1, _IRR_TEXT("/\\"), 2);
\r
719 path2.split(list2, _IRR_TEXT("/\\"), 2);
\r
720 std::list<io::path>::const_iterator it1,it2;
\r
724 #if defined (_IRR_WINDOWS_API_)
\r
725 fschar_t partition1 = 0, partition2 = 0;
\r
726 io::path prefix1, prefix2;
\r
727 if ( it1 != list1.end() )
\r
729 if ( it2 != list2.end() )
\r
731 if ( prefix1.size() > 1 && prefix1[1] == _IRR_TEXT(':') )
\r
732 partition1 = core::locale_lower(prefix1[0]);
\r
733 if ( prefix2.size() > 1 && prefix2[1] == _IRR_TEXT(':') )
\r
734 partition2 = core::locale_lower(prefix2[0]);
\r
736 // must have the same prefix or we can't resolve it to a relative filename
\r
737 if ( partition1 != partition2 )
\r
744 for (; it1 != list1.end() && it2 != list2.end()
\r
745 #if defined (_IRR_WINDOWS_API_)
\r
746 && (io::path(*it1).make_lower()==io::path(*it2).make_lower())
\r
755 path1=_IRR_TEXT("");
\r
756 for (; it2 != list2.end(); ++it2)
\r
757 path1 += _IRR_TEXT("../");
\r
758 while (it1 != list1.end())
\r
761 path1 += _IRR_TEXT('/');
\r
766 path1 += _IRR_TEXT('.');
\r
773 //! Sets the current file systen type
\r
774 EFileSystemType CFileSystem::setFileListSystem(EFileSystemType listType)
\r
776 EFileSystemType current = FileSystemType;
\r
777 FileSystemType = listType;
\r
782 //! Creates a list of files and directories in the current working directory
\r
783 IFileList* CFileSystem::createFileList()
\r
786 io::path Path = getWorkingDirectory();
\r
787 Path.replace('\\', '/');
\r
788 if (!Path.empty() && Path.lastChar() != '/')
\r
791 //! Construct from native filesystem
\r
792 if (FileSystemType == FILESYSTEM_NATIVE)
\r
794 // --------------------------------------------
\r
795 //! Windows version
\r
796 #ifdef _IRR_WINDOWS_API_
\r
798 r = new CFileList(Path, true, false);
\r
800 // TODO: Should be unified once mingw adapts the proper types
\r
801 #if defined(__GNUC__)
\r
802 long hFile; //mingw return type declaration
\r
807 struct _tfinddata_t c_file;
\r
808 if( (hFile = _tfindfirst( _T("*"), &c_file )) != -1L )
\r
812 r->addItem(Path + c_file.name, 0, c_file.size, (_A_SUBDIR & c_file.attrib) != 0, 0);
\r
814 while( _tfindnext( hFile, &c_file ) == 0 );
\r
816 _findclose( hFile );
\r
821 // --------------------------------------------
\r
823 #if (defined(_IRR_POSIX_API_) || defined(_IRR_OSX_PLATFORM_))
\r
826 r = new CFileList(Path, false, false);
\r
828 r->addItem(Path + _IRR_TEXT(".."), 0, 0, true, 0);
\r
830 //! We use the POSIX compliant methods instead of scandir
\r
831 DIR* dirHandle=opendir(Path.c_str());
\r
834 struct dirent *dirEntry;
\r
835 while ((dirEntry=readdir(dirHandle)))
\r
838 bool isDirectory = false;
\r
840 if((strcmp(dirEntry->d_name, ".")==0) ||
\r
841 (strcmp(dirEntry->d_name, "..")==0))
\r
846 if (stat(dirEntry->d_name, &buf)==0)
\r
848 size = buf.st_size;
\r
849 isDirectory = S_ISDIR(buf.st_mode);
\r
851 #if !defined(_IRR_SOLARIS_PLATFORM_) && !defined(__CYGWIN__)
\r
852 // only available on some systems
\r
855 isDirectory = dirEntry->d_type == DT_DIR;
\r
859 r->addItem(Path + dirEntry->d_name, 0, size, isDirectory, 0);
\r
861 closedir(dirHandle);
\r
867 //! create file list for the virtual filesystem
\r
868 r = new CFileList(Path, false, false);
\r
870 //! add relative navigation
\r
875 r->addItem(Path + _IRR_TEXT("."), 0, 0, true, 0);
\r
878 r->addItem(Path + _IRR_TEXT(".."), 0, 0, true, 0);
\r
881 for (u32 i=0; i < FileArchives.size(); ++i)
\r
883 const IFileList *merge = FileArchives[i]->getFileList();
\r
885 for (u32 j=0; j < merge->getFileCount(); ++j)
\r
887 if (core::isInSameDirectory(Path, merge->getFullFileName(j)) == 0)
\r
889 r->addItem(merge->getFullFileName(j), merge->getFileOffset(j), merge->getFileSize(j), merge->isDirectory(j), 0);
\r
900 //! Creates an empty filelist
\r
901 IFileList* CFileSystem::createEmptyFileList(const io::path& path, bool ignoreCase, bool ignorePaths)
\r
903 return new CFileList(path, ignoreCase, ignorePaths);
\r
907 //! determines if a file exists and would be able to be opened.
\r
908 bool CFileSystem::existFile(const io::path& filename) const
\r
910 for (u32 i=0; i < FileArchives.size(); ++i)
\r
911 if (FileArchives[i]->getFileList()->findFile(filename)!=-1)
\r
914 #if defined(_MSC_VER)
\r
915 return (_access(filename.c_str(), 0) != -1);
\r
916 #elif defined(F_OK)
\r
917 return (access(filename.c_str(), F_OK) != -1);
\r
919 return (access(filename.c_str(), 0) != -1);
\r
924 //! creates a filesystem which is able to open files from the ordinary file system,
\r
925 //! and out of zipfiles, which are able to be added to the filesystem.
\r
926 IFileSystem* createFileSystem()
\r
928 return new CFileSystem();
\r
932 } // end namespace irr
\r
933 } // end namespace io
\r