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 "CFileList.h"
\r
14 #include "CReadFile.h"
\r
15 #include "CMemoryFile.h"
\r
16 #include "CLimitReadFile.h"
\r
17 #include "CWriteFile.h"
\r
20 #if defined (__STRICT_ANSI__)
\r
21 #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
24 #if defined (_IRR_WINDOWS_API_)
\r
25 #include <direct.h> // for _chdir
\r
26 #include <io.h> // for _access
\r
28 #elif (defined(_IRR_POSIX_API_) || defined(_IRR_OSX_PLATFORM_) || defined(_IRR_IOS_PLATFORM_) || defined(_IRR_ANDROID_PLATFORM_))
\r
33 #include <sys/types.h>
\r
35 #include <sys/stat.h>
\r
37 #elif defined(_IRR_EMSCRIPTEN_PLATFORM_)
\r
47 CFileSystem::CFileSystem()
\r
50 setDebugName("CFileSystem");
\r
53 setFileListSystem(FILESYSTEM_NATIVE);
\r
54 //! reset current working directory
\r
55 getWorkingDirectory();
\r
57 ArchiveLoader.push_back(new CArchiveLoaderZIP(this));
\r
63 CFileSystem::~CFileSystem()
\r
67 for ( i=0; i < FileArchives.size(); ++i)
\r
69 FileArchives[i]->drop();
\r
72 for ( i=0; i < ArchiveLoader.size(); ++i)
\r
74 ArchiveLoader[i]->drop();
\r
79 //! opens a file for read access
\r
80 IReadFile* CFileSystem::createAndOpenFile(const io::path& filename)
\r
82 if ( filename.empty() )
\r
85 IReadFile* file = 0;
\r
88 for (i=0; i< FileArchives.size(); ++i)
\r
90 file = FileArchives[i]->createAndOpenFile(filename);
\r
95 // Create the file using an absolute path so that it matches
\r
96 // the scheme used by CNullDriver::getTexture().
\r
97 return CReadFile::createReadFile(getAbsolutePath(filename));
\r
101 //! Creates an IReadFile interface for treating memory like a file.
\r
102 IReadFile* CFileSystem::createMemoryReadFile(const void* memory, s32 len,
\r
103 const io::path& fileName, bool deleteMemoryWhenDropped)
\r
108 return new CMemoryReadFile(memory, len, fileName, deleteMemoryWhenDropped);
\r
112 //! Creates an IReadFile interface for reading files inside files
\r
113 IReadFile* CFileSystem::createLimitReadFile(const io::path& fileName,
\r
114 IReadFile* alreadyOpenedFile, long pos, long areaSize)
\r
116 if (!alreadyOpenedFile)
\r
119 return new CLimitReadFile(alreadyOpenedFile, pos, areaSize, fileName);
\r
123 //! Creates an IReadFile interface for treating memory like a file.
\r
124 IWriteFile* CFileSystem::createMemoryWriteFile(void* memory, s32 len,
\r
125 const io::path& fileName, bool deleteMemoryWhenDropped)
\r
130 return new CMemoryWriteFile(memory, len, fileName, deleteMemoryWhenDropped);
\r
134 //! Opens a file for write access.
\r
135 IWriteFile* CFileSystem::createAndWriteFile(const io::path& filename, bool append)
\r
137 return CWriteFile::createWriteFile(filename, append);
\r
141 //! Adds an external archive loader to the engine.
\r
142 void CFileSystem::addArchiveLoader(IArchiveLoader* loader)
\r
148 ArchiveLoader.push_back(loader);
\r
151 //! Returns the total number of archive loaders added.
\r
152 u32 CFileSystem::getArchiveLoaderCount() const
\r
154 return ArchiveLoader.size();
\r
157 //! Gets the archive loader by index.
\r
158 IArchiveLoader* CFileSystem::getArchiveLoader(u32 index) const
\r
160 if (index < ArchiveLoader.size())
\r
161 return ArchiveLoader[index];
\r
166 //! move the hirarchy of the filesystem. moves sourceIndex relative up or down
\r
167 bool CFileSystem::moveFileArchive(u32 sourceIndex, s32 relative)
\r
170 const s32 dest = (s32) sourceIndex + relative;
\r
171 const s32 dir = relative < 0 ? -1 : 1;
\r
172 const s32 sourceEnd = ((s32) FileArchives.size() ) - 1;
\r
175 for (s32 s = (s32) sourceIndex;s != dest; s += dir)
\r
177 if (s < 0 || s > sourceEnd || s + dir < 0 || s + dir > sourceEnd)
\r
180 t = FileArchives[s + dir];
\r
181 FileArchives[s + dir] = FileArchives[s];
\r
182 FileArchives[s] = t;
\r
189 //! Adds an archive to the file system.
\r
190 bool CFileSystem::addFileArchive(const io::path& filename, bool ignoreCase,
\r
191 bool ignorePaths, E_FILE_ARCHIVE_TYPE archiveType,
\r
192 const core::stringc& password,
\r
193 IFileArchive** retArchive)
\r
195 IFileArchive* archive = 0;
\r
198 // see if archive is already added
\r
202 // do we know what type it should be?
\r
203 if (archiveType == EFAT_UNKNOWN || archiveType == EFAT_FOLDER)
\r
205 // try to load archive based on file name
\r
206 for (i = ArchiveLoader.size()-1; i >=0 ; --i)
\r
208 if (ArchiveLoader[i]->isALoadableFileFormat(filename))
\r
210 archive = ArchiveLoader[i]->createArchive(filename, ignoreCase, ignorePaths);
\r
216 // try to load archive based on content
\r
219 io::IReadFile* file = createAndOpenFile(filename);
\r
222 for (i = ArchiveLoader.size()-1; i >= 0; --i)
\r
225 if (ArchiveLoader[i]->isALoadableFileFormat(file))
\r
228 archive = ArchiveLoader[i]->createArchive(file, ignoreCase, ignorePaths);
\r
239 // try to open archive based on archive loader type
\r
241 io::IReadFile* file = 0;
\r
243 for (i = ArchiveLoader.size()-1; i >= 0; --i)
\r
245 if (ArchiveLoader[i]->isALoadableFileFormat(archiveType))
\r
247 // attempt to open file
\r
249 file = createAndOpenFile(filename);
\r
251 // is the file open?
\r
254 // attempt to open archive
\r
256 if (ArchiveLoader[i]->isALoadableFileFormat(file))
\r
259 archive = ArchiveLoader[i]->createArchive(file, ignoreCase, ignorePaths);
\r
266 // couldn't open file
\r
272 // if open, close the file
\r
279 FileArchives.push_back(archive);
\r
280 if (password.size())
\r
281 archive->Password=password;
\r
283 *retArchive = archive;
\r
288 os::Printer::log("Could not create archive for", filename, ELL_ERROR);
\r
295 bool CFileSystem::addFileArchive(IReadFile* file, bool ignoreCase,
\r
296 bool ignorePaths, E_FILE_ARCHIVE_TYPE archiveType,
\r
297 const core::stringc& password, IFileArchive** retArchive)
\r
299 if (!file || archiveType == EFAT_FOLDER)
\r
304 IFileArchive* archive = 0;
\r
307 if (archiveType == EFAT_UNKNOWN)
\r
309 // try to load archive based on file name
\r
310 for (i = ArchiveLoader.size()-1; i >=0 ; --i)
\r
312 if (ArchiveLoader[i]->isALoadableFileFormat(file->getFileName()))
\r
314 archive = ArchiveLoader[i]->createArchive(file, ignoreCase, ignorePaths);
\r
320 // try to load archive based on content
\r
323 for (i = ArchiveLoader.size()-1; i >= 0; --i)
\r
326 if (ArchiveLoader[i]->isALoadableFileFormat(file))
\r
329 archive = ArchiveLoader[i]->createArchive(file, ignoreCase, ignorePaths);
\r
338 // try to open archive based on archive loader type
\r
339 for (i = ArchiveLoader.size()-1; i >= 0; --i)
\r
341 if (ArchiveLoader[i]->isALoadableFileFormat(archiveType))
\r
343 // attempt to open archive
\r
345 if (ArchiveLoader[i]->isALoadableFileFormat(file))
\r
348 archive = ArchiveLoader[i]->createArchive(file, ignoreCase, ignorePaths);
\r
358 FileArchives.push_back(archive);
\r
359 if (password.size())
\r
360 archive->Password=password;
\r
362 *retArchive = archive;
\r
367 os::Printer::log("Could not create archive for", file->getFileName(), ELL_ERROR);
\r
375 //! Adds an archive to the file system.
\r
376 bool CFileSystem::addFileArchive(IFileArchive* archive)
\r
380 for (u32 i=0; i < FileArchives.size(); ++i)
\r
382 if (archive == FileArchives[i])
\r
387 FileArchives.push_back(archive);
\r
397 //! removes an archive from the file system.
\r
398 bool CFileSystem::removeFileArchive(u32 index)
\r
401 if (index < FileArchives.size())
\r
403 FileArchives[index]->drop();
\r
404 FileArchives.erase(index);
\r
411 //! removes an archive from the file system.
\r
412 bool CFileSystem::removeFileArchive(const io::path& filename)
\r
414 const path absPath = getAbsolutePath(filename);
\r
415 for (u32 i=0; i < FileArchives.size(); ++i)
\r
417 if (absPath == FileArchives[i]->getFileList()->getPath())
\r
418 return removeFileArchive(i);
\r
424 //! Removes an archive from the file system.
\r
425 bool CFileSystem::removeFileArchive(const IFileArchive* archive)
\r
427 for (u32 i=0; i < FileArchives.size(); ++i)
\r
429 if (archive == FileArchives[i])
\r
431 return removeFileArchive(i);
\r
438 //! gets an archive
\r
439 u32 CFileSystem::getFileArchiveCount() const
\r
441 return FileArchives.size();
\r
445 IFileArchive* CFileSystem::getFileArchive(u32 index)
\r
447 return index < getFileArchiveCount() ? FileArchives[index] : 0;
\r
451 //! Returns the string of the current working directory
\r
452 const io::path& CFileSystem::getWorkingDirectory()
\r
454 EFileSystemType type = FileSystemType;
\r
456 if (type != FILESYSTEM_NATIVE)
\r
458 type = FILESYSTEM_VIRTUAL;
\r
462 #if defined(_IRR_WINDOWS_API_)
\r
463 fschar_t tmp[_MAX_PATH];
\r
464 _getcwd(tmp, _MAX_PATH);
\r
465 WorkingDirectory[FILESYSTEM_NATIVE] = tmp;
\r
466 WorkingDirectory[FILESYSTEM_NATIVE].replace('\\', '/');
\r
469 #if (defined(_IRR_POSIX_API_) || defined(_IRR_OSX_PLATFORM_))
\r
471 // getting the CWD is rather complex as we do not know the size
\r
472 // so try it until the call was successful
\r
473 // Note that neither the first nor the second parameter may be 0 according to POSIX
\r
476 char *tmpPath = new char[pathSize];
\r
477 while ((pathSize < (1<<16)) && !(getcwd(tmpPath,pathSize)))
\r
481 tmpPath = new char[pathSize];
\r
485 WorkingDirectory[FILESYSTEM_NATIVE] = tmpPath;
\r
490 WorkingDirectory[type].validate();
\r
493 return WorkingDirectory[type];
\r
497 //! Changes the current Working Directory to the given string.
\r
498 bool CFileSystem::changeWorkingDirectoryTo(const io::path& newDirectory)
\r
500 bool success=false;
\r
502 if (FileSystemType != FILESYSTEM_NATIVE)
\r
504 WorkingDirectory[FILESYSTEM_VIRTUAL] = newDirectory;
\r
505 // is this empty string constant really intended?
\r
506 flattenFilename(WorkingDirectory[FILESYSTEM_VIRTUAL], _IRR_TEXT(""));
\r
511 WorkingDirectory[FILESYSTEM_NATIVE] = newDirectory;
\r
513 #if defined(_MSC_VER)
\r
514 success = (_chdir(newDirectory.c_str()) == 0);
\r
516 success = (chdir(newDirectory.c_str()) == 0);
\r
524 io::path CFileSystem::getAbsolutePath(const io::path& filename) const
\r
526 if ( filename.empty() )
\r
528 #if defined(_IRR_WINDOWS_API_)
\r
530 fschar_t fpath[_MAX_PATH];
\r
531 p = _fullpath(fpath, filename.c_str(), _MAX_PATH);
\r
532 core::stringc tmp(p);
\r
533 tmp.replace('\\', '/');
\r
535 #elif (defined(_IRR_POSIX_API_) || defined(_IRR_OSX_PLATFORM_))
\r
539 p = realpath(filename.c_str(), fpath);
\r
542 // content in fpath is unclear at this point
\r
543 if (!fpath[0]) // seems like fpath wasn't altered, use our best guess
\r
545 io::path tmp(filename);
\r
546 return flattenFilename(tmp);
\r
549 return io::path(fpath);
\r
551 if (filename[filename.size()-1]=='/')
\r
552 return io::path(p)+_IRR_TEXT("/");
\r
554 return io::path(p);
\r
556 return io::path(filename);
\r
561 //! returns the directory part of a filename, i.e. all until the first
\r
562 //! slash or backslash, excluding it. If no directory path is prefixed, a '.'
\r
564 io::path CFileSystem::getFileDir(const io::path& filename) const
\r
566 // find last forward or backslash
\r
567 s32 lastSlash = filename.findLast('/');
\r
568 const s32 lastBackSlash = filename.findLast('\\');
\r
569 lastSlash = lastSlash > lastBackSlash ? lastSlash : lastBackSlash;
\r
571 if ((u32)lastSlash < filename.size())
\r
572 return filename.subString(0, lastSlash);
\r
574 return _IRR_TEXT(".");
\r
578 //! returns the base part of a filename, i.e. all except for the directory
\r
579 //! part. If no directory path is prefixed, the full name is returned.
\r
580 io::path CFileSystem::getFileBasename(const io::path& filename, bool keepExtension) const
\r
582 // find last forward or backslash
\r
583 s32 lastSlash = filename.findLast('/');
\r
584 const s32 lastBackSlash = filename.findLast('\\');
\r
585 lastSlash = core::max_(lastSlash, lastBackSlash);
\r
587 // get number of chars after last dot
\r
589 if (!keepExtension)
\r
591 // take care to search only after last slash to check only for
\r
592 // dots in the filename
\r
593 end = filename.findLast('.');
\r
594 if (end == -1 || end < lastSlash)
\r
597 end = filename.size()-end;
\r
600 if ((u32)lastSlash < filename.size())
\r
601 return filename.subString(lastSlash+1, filename.size()-lastSlash-1-end);
\r
603 return filename.subString(0, filename.size()-end);
\r
609 //! flatten a path and file name for example: "/you/me/../." becomes "/you"
\r
610 io::path& CFileSystem::flattenFilename(io::path& directory, const io::path& root) const
\r
612 directory.replace('\\', '/');
\r
613 if (directory.lastChar() != '/')
\r
614 directory.append('/');
\r
621 bool lastWasRealDir=false;
\r
623 while ((pos = directory.findNext('/', lastpos)) >= 0)
\r
625 subdir = directory.subString(lastpos, pos - lastpos + 1);
\r
627 if (subdir == _IRR_TEXT("../"))
\r
629 if (lastWasRealDir)
\r
631 deletePathFromPath(dir, 2);
\r
632 lastWasRealDir=(dir.size()!=0);
\r
636 dir.append(subdir);
\r
637 lastWasRealDir=false;
\r
640 else if (subdir == _IRR_TEXT("/"))
\r
644 else if (subdir != _IRR_TEXT("./"))
\r
646 dir.append(subdir);
\r
647 lastWasRealDir=true;
\r
657 //! Get the relative filename, relative to the given directory
\r
658 path CFileSystem::getRelativeFilename(const path& filename, const path& directory) const
\r
660 if ( filename.empty() || directory.empty() )
\r
663 io::path path1, file, ext;
\r
664 core::splitFilename(getAbsolutePath(filename), &path1, &file, &ext);
\r
665 io::path path2(getAbsolutePath(directory));
\r
666 std::list<io::path> list1, list2;
\r
667 path1.split(list1, _IRR_TEXT("/\\"), 2);
\r
668 path2.split(list2, _IRR_TEXT("/\\"), 2);
\r
669 std::list<io::path>::const_iterator it1,it2;
\r
673 #if defined (_IRR_WINDOWS_API_)
\r
674 fschar_t partition1 = 0, partition2 = 0;
\r
675 io::path prefix1, prefix2;
\r
676 if ( it1 != list1.end() )
\r
678 if ( it2 != list2.end() )
\r
680 if ( prefix1.size() > 1 && prefix1[1] == _IRR_TEXT(':') )
\r
681 partition1 = core::locale_lower(prefix1[0]);
\r
682 if ( prefix2.size() > 1 && prefix2[1] == _IRR_TEXT(':') )
\r
683 partition2 = core::locale_lower(prefix2[0]);
\r
685 // must have the same prefix or we can't resolve it to a relative filename
\r
686 if ( partition1 != partition2 )
\r
693 for (; it1 != list1.end() && it2 != list2.end()
\r
694 #if defined (_IRR_WINDOWS_API_)
\r
695 && (io::path(*it1).make_lower()==io::path(*it2).make_lower())
\r
704 path1=_IRR_TEXT("");
\r
705 for (; it2 != list2.end(); ++it2)
\r
706 path1 += _IRR_TEXT("../");
\r
707 while (it1 != list1.end())
\r
710 path1 += _IRR_TEXT('/');
\r
715 path1 += _IRR_TEXT('.');
\r
722 //! Sets the current file systen type
\r
723 EFileSystemType CFileSystem::setFileListSystem(EFileSystemType listType)
\r
725 EFileSystemType current = FileSystemType;
\r
726 FileSystemType = listType;
\r
731 //! Creates a list of files and directories in the current working directory
\r
732 IFileList* CFileSystem::createFileList()
\r
735 io::path Path = getWorkingDirectory();
\r
736 Path.replace('\\', '/');
\r
737 if (!Path.empty() && Path.lastChar() != '/')
\r
740 //! Construct from native filesystem
\r
741 if (FileSystemType == FILESYSTEM_NATIVE)
\r
743 // --------------------------------------------
\r
744 //! Windows version
\r
745 #ifdef _IRR_WINDOWS_API_
\r
747 r = new CFileList(Path, true, false);
\r
749 // TODO: Should be unified once mingw adapts the proper types
\r
750 #if defined(__GNUC__)
\r
751 long hFile; //mingw return type declaration
\r
756 struct _tfinddata_t c_file;
\r
757 if( (hFile = _tfindfirst( _T("*"), &c_file )) != -1L )
\r
761 r->addItem(Path + c_file.name, 0, c_file.size, (_A_SUBDIR & c_file.attrib) != 0, 0);
\r
763 while( _tfindnext( hFile, &c_file ) == 0 );
\r
765 _findclose( hFile );
\r
770 // --------------------------------------------
\r
772 #if (defined(_IRR_POSIX_API_) || defined(_IRR_OSX_PLATFORM_))
\r
775 r = new CFileList(Path, false, false);
\r
777 r->addItem(Path + _IRR_TEXT(".."), 0, 0, true, 0);
\r
779 //! We use the POSIX compliant methods instead of scandir
\r
780 DIR* dirHandle=opendir(Path.c_str());
\r
783 struct dirent *dirEntry;
\r
784 while ((dirEntry=readdir(dirHandle)))
\r
787 bool isDirectory = false;
\r
789 if((strcmp(dirEntry->d_name, ".")==0) ||
\r
790 (strcmp(dirEntry->d_name, "..")==0))
\r
795 if (stat(dirEntry->d_name, &buf)==0)
\r
797 size = buf.st_size;
\r
798 isDirectory = S_ISDIR(buf.st_mode);
\r
800 #if !defined(_IRR_SOLARIS_PLATFORM_) && !defined(__CYGWIN__)
\r
801 // only available on some systems
\r
804 isDirectory = dirEntry->d_type == DT_DIR;
\r
808 r->addItem(Path + dirEntry->d_name, 0, size, isDirectory, 0);
\r
810 closedir(dirHandle);
\r
816 //! create file list for the virtual filesystem
\r
817 r = new CFileList(Path, false, false);
\r
819 //! add relative navigation
\r
824 r->addItem(Path + _IRR_TEXT("."), 0, 0, true, 0);
\r
827 r->addItem(Path + _IRR_TEXT(".."), 0, 0, true, 0);
\r
830 for (u32 i=0; i < FileArchives.size(); ++i)
\r
832 const IFileList *merge = FileArchives[i]->getFileList();
\r
834 for (u32 j=0; j < merge->getFileCount(); ++j)
\r
836 if (core::isInSameDirectory(Path, merge->getFullFileName(j)) == 0)
\r
838 r->addItem(merge->getFullFileName(j), merge->getFileOffset(j), merge->getFileSize(j), merge->isDirectory(j), 0);
\r
849 //! Creates an empty filelist
\r
850 IFileList* CFileSystem::createEmptyFileList(const io::path& path, bool ignoreCase, bool ignorePaths)
\r
852 return new CFileList(path, ignoreCase, ignorePaths);
\r
856 //! determines if a file exists and would be able to be opened.
\r
857 bool CFileSystem::existFile(const io::path& filename) const
\r
859 for (u32 i=0; i < FileArchives.size(); ++i)
\r
860 if (FileArchives[i]->getFileList()->findFile(filename)!=-1)
\r
863 #if defined(_MSC_VER)
\r
864 return (_access(filename.c_str(), 0) != -1);
\r
865 #elif defined(F_OK)
\r
866 return (access(filename.c_str(), F_OK) != -1);
\r
868 return (access(filename.c_str(), 0) != -1);
\r
873 //! creates a filesystem which is able to open files from the ordinary file system,
\r
874 //! and out of zipfiles, which are able to be added to the filesystem.
\r
875 IFileSystem* createFileSystem()
\r
877 return new CFileSystem();
\r
881 } // end namespace irr
\r
882 } // end namespace io
\r