volume.cpp 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197
  1. //-----------------------------------------------------------------------------
  2. // Copyright (c) 2012 GarageGames, LLC
  3. //
  4. // Permission is hereby granted, free of charge, to any person obtaining a copy
  5. // of this software and associated documentation files (the "Software"), to
  6. // deal in the Software without restriction, including without limitation the
  7. // rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
  8. // sell copies of the Software, and to permit persons to whom the Software is
  9. // furnished to do so, subject to the following conditions:
  10. //
  11. // The above copyright notice and this permission notice shall be included in
  12. // all copies or substantial portions of the Software.
  13. //
  14. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  15. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  16. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  17. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  18. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
  19. // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
  20. // IN THE SOFTWARE.
  21. //-----------------------------------------------------------------------------
  22. #include "platform/platform.h"
  23. #include "core/volume.h"
  24. #include "core/virtualMountSystem.h"
  25. #include "core/strings/findMatch.h"
  26. #include "core/util/journal/process.h"
  27. #include "core/util/safeDelete.h"
  28. #include "console/console.h"
  29. namespace Torque
  30. {
  31. using namespace FS;
  32. //-----------------------------------------------------------------------------
  33. bool FileSystemChangeNotifier::addNotification( const Path &path, ChangeDelegate callback )
  34. {
  35. // Notifications are for files... if the path is empty
  36. // then there is nothing to do.
  37. if ( path.isEmpty() )
  38. return false;
  39. // strip the filename and extension - we notify on dirs
  40. Path dir(cleanPath(path));
  41. if (dir.isEmpty())
  42. return false;
  43. dir.setFileName( String() );
  44. dir.setExtension( String () );
  45. // first lookup the dir to see if we already have an entry for it...
  46. DirMap::Iterator itr = mDirMap.find( dir );
  47. FileInfoList *fileList = NULL;
  48. bool addedDir = false;
  49. // Note that GetFileAttributes can fail here if the file doesn't
  50. // exist, but thats ok and expected. You can have notifications
  51. // on files that don't exist yet.
  52. FileNode::Attributes attr;
  53. GetFileAttributes(path, &attr);
  54. if ( itr != mDirMap.end() )
  55. {
  56. fileList = &(itr->value);
  57. // look for the file and return if we find it
  58. for ( U32 i = 0; i < fileList->getSize(); i++ )
  59. {
  60. FileInfo &fInfo = (*fileList)[i];
  61. if ( fInfo.filePath == path )
  62. {
  63. // NOTE: This is bad... we should store the mod
  64. // time for each callback seperately in the future.
  65. //
  66. fInfo.savedLastModTime = attr.mtime;
  67. fInfo.signal.notify(callback);
  68. return true;
  69. }
  70. }
  71. }
  72. else
  73. {
  74. // otherwise we need to add the dir to our map and let the inherited class add it
  75. itr = mDirMap.insert( dir, FileInfoList() );
  76. fileList = &(itr->value);
  77. addedDir = true;
  78. }
  79. FileInfo newInfo;
  80. newInfo.signal.notify(callback);
  81. newInfo.filePath = path;
  82. newInfo.savedLastModTime = attr.mtime;
  83. fileList->pushBack( newInfo );
  84. return addedDir ? internalAddNotification( dir ) : true;
  85. }
  86. bool FileSystemChangeNotifier::removeNotification( const Path &path, ChangeDelegate callback )
  87. {
  88. if (path.isEmpty())
  89. return false;
  90. // strip the filename and extension - we notify on dirs
  91. Path dir(cleanPath(path));
  92. if (dir.isEmpty())
  93. return false;
  94. dir.setFileName( String() );
  95. dir.setExtension( String () );
  96. DirMap::Iterator itr = mDirMap.find( dir );
  97. if ( itr == mDirMap.end() )
  98. return false;
  99. FileInfoList &fileList = itr->value;
  100. // look for the file and return if we find it
  101. for ( U32 i = 0; i < fileList.getSize(); i++ )
  102. {
  103. FileInfo &fInfo = fileList[i];
  104. if ( fInfo.filePath == path )
  105. {
  106. fInfo.signal.remove(callback);
  107. if (fInfo.signal.isEmpty())
  108. fileList.erase( i );
  109. break;
  110. }
  111. }
  112. // IF we removed the last file
  113. // THEN get rid of the dir from our map and notify inherited classes
  114. if ( fileList.getSize() == 0 )
  115. {
  116. mDirMap.erase( dir );
  117. return internalRemoveNotification( dir );
  118. }
  119. return true;
  120. }
  121. void FileSystemChangeNotifier::startNotifier()
  122. {
  123. // update the timestamps of all the files we are managing
  124. DirMap::Iterator itr = mDirMap.begin();
  125. for ( ; itr != mDirMap.end(); ++itr )
  126. {
  127. FileInfoList &fileList = itr->value;
  128. for ( U32 i = 0; i < fileList.getSize(); i++ )
  129. {
  130. FileInfo &fInfo = fileList[i];
  131. // This may fail if the file doesn't exist... thats ok.
  132. FileNode::Attributes attr;
  133. GetFileAttributes(fInfo.filePath, &attr);
  134. fInfo.savedLastModTime = attr.mtime;
  135. }
  136. }
  137. mNotifying = true;
  138. Process::notify( this, &FileSystemChangeNotifier::process, PROCESS_LAST_ORDER );
  139. }
  140. void FileSystemChangeNotifier::process()
  141. {
  142. internalProcessOnce();
  143. }
  144. void FileSystemChangeNotifier::stopNotifier()
  145. {
  146. mNotifying = false;
  147. Process::remove( this, &FileSystemChangeNotifier::process );
  148. }
  149. /// Makes sure paths going in and out of the notifier will have the same format
  150. String FileSystemChangeNotifier::cleanPath(const Path& dir)
  151. {
  152. // This "cleans up" the path, if we don't do this we can get mismatches on the path
  153. // coming from the notifier
  154. FileSystemRef fs = Torque::FS::GetFileSystem(dir);
  155. if (!fs)
  156. return String::EmptyString;
  157. return fs->mapFrom(fs->mapTo(dir));
  158. }
  159. void FileSystemChangeNotifier::internalNotifyDirChanged( const Path &dir )
  160. {
  161. DirMap::Iterator itr = mDirMap.find( dir );
  162. if ( itr == mDirMap.end() )
  163. return;
  164. // Gather the changed file info.
  165. FileInfoList changedList;
  166. FileInfoList &fileList = itr->value;
  167. for ( U32 i = 0; i < fileList.getSize(); i++ )
  168. {
  169. FileInfo &fInfo = fileList[i];
  170. FileNode::Attributes attr;
  171. bool success = GetFileAttributes(fInfo.filePath, &attr);
  172. // Ignore the file if we couldn't get the attributes (it must have
  173. // been deleted) or the last modification time isn't newer.
  174. if ( !success || attr.mtime <= fInfo.savedLastModTime )
  175. continue;
  176. // Store the new mod time.
  177. fInfo.savedLastModTime = attr.mtime;
  178. // We're taking a copy of the FileInfo struct here so that the
  179. // callback can safely remove the notification without crashing.
  180. changedList.pushBack( fInfo );
  181. }
  182. // Now signal all the changed files.
  183. for ( U32 i = 0; i < changedList.getSize(); i++ )
  184. {
  185. FileInfo &fInfo = changedList[i];
  186. Con::warnf( " : file changed [%s]", fInfo.filePath.getFullPath().c_str() );
  187. fInfo.signal.trigger( fInfo.filePath );
  188. }
  189. }
  190. //-----------------------------------------------------------------------------
  191. FileSystem::FileSystem()
  192. : mChangeNotifier( NULL ),
  193. mReadOnly(false)
  194. {
  195. }
  196. FileSystem::~FileSystem()
  197. {
  198. delete mChangeNotifier;
  199. mChangeNotifier = NULL;
  200. }
  201. File::File() {}
  202. File::~File() {}
  203. Directory::Directory() {}
  204. Directory::~Directory() {}
  205. FileNode::FileNode()
  206. : mChecksum(0)
  207. {
  208. }
  209. Time FileNode::getModifiedTime()
  210. {
  211. Attributes attrs;
  212. bool success = getAttributes( &attrs );
  213. if ( !success )
  214. return Time();
  215. return attrs.mtime;
  216. }
  217. Time FileNode::getCreatedTime()
  218. {
  219. Attributes attrs;
  220. bool success = getAttributes(&attrs);
  221. if (!success)
  222. return Time();
  223. return attrs.ctime;
  224. }
  225. U64 FileNode::getSize()
  226. {
  227. Attributes attrs;
  228. bool success = getAttributes( &attrs );
  229. if ( !success )
  230. return 0;
  231. return attrs.size;
  232. }
  233. U32 FileNode::getChecksum()
  234. {
  235. bool calculateCRC = (mLastChecksum == Torque::Time());
  236. if ( !calculateCRC )
  237. {
  238. Torque::Time modTime = getModifiedTime();
  239. calculateCRC = (modTime > mLastChecksum);
  240. }
  241. if ( calculateCRC )
  242. mChecksum = calculateChecksum();
  243. if ( mChecksum )
  244. mLastChecksum = Time::getCurrentTime();
  245. return mChecksum;
  246. }
  247. //-----------------------------------------------------------------------------
  248. class FileSystemRedirect: public FileSystem
  249. {
  250. friend class FileSystemRedirectChangeNotifier;
  251. public:
  252. FileSystemRedirect(MountSystem* mfs,const Path& path);
  253. String getTypeStr() const { return "Redirect"; }
  254. FileNodeRef resolve(const Path& path);
  255. FileNodeRef create(const Path& path,FileNode::Mode);
  256. bool remove(const Path& path);
  257. bool rename(const Path& a,const Path& b);
  258. Path mapTo(const Path& path);
  259. Path mapFrom(const Path& path);
  260. private:
  261. Path _merge(const Path& path);
  262. Path mPath;
  263. MountSystem *mMFS;
  264. };
  265. class FileSystemRedirectChangeNotifier : public FileSystemChangeNotifier
  266. {
  267. public:
  268. FileSystemRedirectChangeNotifier( FileSystem *fs );
  269. bool addNotification( const Path &path, ChangeDelegate callback );
  270. bool removeNotification( const Path &path, ChangeDelegate callback );
  271. protected:
  272. virtual void internalProcessOnce() {}
  273. virtual bool internalAddNotification( const Path &dir ) { return false; }
  274. virtual bool internalRemoveNotification( const Path &dir ) { return false; }
  275. };
  276. FileSystemRedirectChangeNotifier::FileSystemRedirectChangeNotifier( FileSystem *fs )
  277. : FileSystemChangeNotifier( fs )
  278. {
  279. }
  280. bool FileSystemRedirectChangeNotifier::addNotification( const Path &path, ChangeDelegate callback )
  281. {
  282. FileSystemRedirect *rfs = (FileSystemRedirect*)mFS;
  283. Path redirectPath = rfs->_merge( path );
  284. FileSystemRef fs = rfs->mMFS->getFileSystem( redirectPath );
  285. if ( !fs || !fs->getChangeNotifier() )
  286. return false;
  287. return fs->getChangeNotifier()->addNotification( redirectPath, callback );
  288. }
  289. bool FileSystemRedirectChangeNotifier::removeNotification( const Path &path, ChangeDelegate callback )
  290. {
  291. FileSystemRedirect *rfs = (FileSystemRedirect*)mFS;
  292. Path redirectPath = rfs->_merge( path );
  293. FileSystemRef fs = rfs->mMFS->getFileSystem( redirectPath );
  294. if ( !fs || !fs->getChangeNotifier() )
  295. return false;
  296. return fs->getChangeNotifier()->removeNotification( redirectPath, callback );
  297. }
  298. FileSystemRedirect::FileSystemRedirect(MountSystem* mfs,const Path& path)
  299. {
  300. mMFS = mfs;
  301. mPath.setRoot(path.getRoot());
  302. mPath.setPath(path.getPath());
  303. mChangeNotifier = new FileSystemRedirectChangeNotifier( this );
  304. }
  305. Path FileSystemRedirect::_merge(const Path& path)
  306. {
  307. Path p = mPath;
  308. p.setPath(Path::Join(p.getPath(),'/',Path::CompressPath(path.getPath())));
  309. p.setFileName(path.getFileName());
  310. p.setExtension(path.getExtension());
  311. return p;
  312. }
  313. FileNodeRef FileSystemRedirect::resolve(const Path& path)
  314. {
  315. Path p = _merge(path);
  316. FileSystemRef fs = mMFS->getFileSystem(p);
  317. if (fs != NULL)
  318. return fs->resolve(p);
  319. return NULL;
  320. }
  321. FileNodeRef FileSystemRedirect::create(const Path& path,FileNode::Mode mode)
  322. {
  323. Path p = _merge(path);
  324. FileSystemRef fs = mMFS->getFileSystem(p);
  325. if (fs != NULL)
  326. return fs->create(p,mode);
  327. return NULL;
  328. }
  329. bool FileSystemRedirect::remove(const Path& path)
  330. {
  331. Path p = _merge(path);
  332. FileSystemRef fs = mMFS->getFileSystem(p);
  333. if (fs != NULL)
  334. return fs->remove(p);
  335. return false;
  336. }
  337. bool FileSystemRedirect::rename(const Path& a,const Path& b)
  338. {
  339. Path na = _merge(a);
  340. Path nb = _merge(b);
  341. FileSystemRef fsa = mMFS->getFileSystem(na);
  342. FileSystemRef fsb = mMFS->getFileSystem(nb);
  343. if (fsa.getPointer() == fsb.getPointer())
  344. return fsa->rename(na,nb);
  345. return false;
  346. }
  347. Path FileSystemRedirect::mapTo(const Path& path)
  348. {
  349. Path p = _merge(path);
  350. FileSystemRef fs = mMFS->getFileSystem(p);
  351. if (fs != NULL)
  352. return fs->mapTo(p);
  353. return NULL;
  354. }
  355. Path FileSystemRedirect::mapFrom(const Path& path)
  356. {
  357. Path p = _merge(path);
  358. FileSystemRef fs = mMFS->getFileSystem(p);
  359. if (fs != NULL)
  360. return fs->mapFrom(p);
  361. return NULL;
  362. }
  363. //-----------------------------------------------------------------------------
  364. void MountSystem::_log(const String& msg)
  365. {
  366. String newMsg = "MountSystem: " + msg;
  367. Con::warnf("%s", newMsg.c_str());
  368. }
  369. FileSystemRef MountSystem::_removeMountFromList(String root)
  370. {
  371. for (Vector<MountFS>::iterator itr = mMountList.begin(); itr != mMountList.end(); itr++)
  372. {
  373. if (root.equal( itr->root, String::NoCase ))
  374. {
  375. FileSystemRef fs = itr->fileSystem;
  376. mMountList.erase(itr);
  377. return fs;
  378. }
  379. }
  380. return NULL;
  381. }
  382. FileSystemRef MountSystem::_getFileSystemFromList(const Path& path) const
  383. {
  384. for (Vector<MountFS>::const_iterator itr = mMountList.begin(); itr != mMountList.end(); itr++)
  385. {
  386. if (itr->root.equal( path.getRoot(), String::NoCase ))
  387. return itr->fileSystem;
  388. }
  389. return NULL;
  390. }
  391. Path MountSystem::_normalize(const Path& path)
  392. {
  393. Path po = path;
  394. // Assign to cwd root if none is specified.
  395. if( po.getRoot().isEmpty() )
  396. po.setRoot( mCWD.getRoot() );
  397. // Merge in current working directory if the path is relative to
  398. // the current cwd.
  399. if( po.getRoot().equal( mCWD.getRoot(), String::NoCase ) && po.isRelative() )
  400. {
  401. po.setPath( Path::CompressPath( Path::Join( mCWD.getPath(),'/',po.getPath() ) ) );
  402. }
  403. return po;
  404. }
  405. bool MountSystem::copyFile(const Path& source, const Path& destination, bool noOverwrite)
  406. {
  407. // Exit out early if we're not overriding
  408. if (isFile(destination) && noOverwrite)
  409. {
  410. return true;
  411. }
  412. FileRef sourceFile = openFile(source, FS::File::AccessMode::Read);
  413. const U64 sourceFileSize = sourceFile->getSize();
  414. void* writeBuffer = dMalloc(sourceFileSize);
  415. sourceFile->read(writeBuffer, sourceFileSize);
  416. FileRef destinationFile = openFile(destination, FS::File::AccessMode::Write);
  417. const bool success = destinationFile->write(writeBuffer, sourceFileSize) == sourceFileSize;
  418. dFree(writeBuffer);
  419. return success;
  420. }
  421. FileRef MountSystem::createFile(const Path& path)
  422. {
  423. Path np = _normalize(path);
  424. FileSystemRef fs = _getFileSystemFromList(np);
  425. if (fs && fs->isReadOnly())
  426. {
  427. _log(String::ToString("Cannot create file %s, filesystem is read-only", path.getFullPath().c_str()));
  428. return NULL;
  429. }
  430. if (fs != NULL)
  431. return static_cast<File*>(fs->create(np,FileNode::File).getPointer());
  432. return NULL;
  433. }
  434. DirectoryRef MountSystem::createDirectory(const Path& path, FileSystemRef fs)
  435. {
  436. Path np = _normalize(path);
  437. if (fs.isNull())
  438. fs = _getFileSystemFromList(np);
  439. if (fs && fs->isReadOnly())
  440. {
  441. _log(String::ToString("Cannot create directory %s, filesystem is read-only", path.getFullPath().c_str()));
  442. return NULL;
  443. }
  444. if (fs != NULL)
  445. return static_cast<Directory*>(fs->create(np,FileNode::Directory).getPointer());
  446. return NULL;
  447. }
  448. FileRef MountSystem::openFile(const Path& path,File::AccessMode mode)
  449. {
  450. FileNodeRef node = getFileNode(path);
  451. if (node != NULL)
  452. {
  453. FileRef file = dynamic_cast<File*>(node.getPointer());
  454. if (file != NULL)
  455. {
  456. if (file->open(mode))
  457. return file;
  458. else
  459. return NULL;
  460. }
  461. }
  462. else
  463. {
  464. if (mode != File::Read)
  465. {
  466. FileRef file = createFile(path);
  467. if (file != NULL)
  468. {
  469. file->open(mode);
  470. return file;
  471. }
  472. }
  473. }
  474. return NULL;
  475. }
  476. DirectoryRef MountSystem::openDirectory(const Path& path)
  477. {
  478. FileNodeRef node = getFileNode(path);
  479. if (node != NULL)
  480. {
  481. DirectoryRef dir = dynamic_cast<Directory*>(node.getPointer());
  482. if (dir != NULL)
  483. {
  484. dir->open();
  485. return dir;
  486. }
  487. }
  488. return NULL;
  489. }
  490. bool MountSystem::remove(const Path& path)
  491. {
  492. Path np = _normalize(path);
  493. FileSystemRef fs = _getFileSystemFromList(np);
  494. if (fs && fs->isReadOnly())
  495. {
  496. _log(String::ToString("Cannot remove path %s, filesystem is read-only", path.getFullPath().c_str()));
  497. return false;
  498. }
  499. if (fs != NULL)
  500. return fs->remove(np);
  501. return false;
  502. }
  503. bool MountSystem::rename(const Path& from,const Path& to)
  504. {
  505. // Will only rename files on the same filesystem
  506. Path pa = _normalize(from);
  507. Path pb = _normalize(to);
  508. FileSystemRef fsa = _getFileSystemFromList(pa);
  509. FileSystemRef fsb = _getFileSystemFromList(pb);
  510. if (!fsa || !fsb)
  511. return false;
  512. if (fsa.getPointer() != fsb.getPointer())
  513. {
  514. _log(String::ToString("Cannot rename path %s to a different filesystem", from.getFullPath().c_str()));
  515. return false;
  516. }
  517. if (fsa->isReadOnly() || fsb->isReadOnly())
  518. {
  519. _log(String::ToString("Cannot rename path %s; source or target filesystem is read-only", from.getFullPath().c_str()));
  520. return false;
  521. }
  522. return fsa->rename(pa,pb);
  523. }
  524. bool MountSystem::mount(String root,FileSystemRef fs)
  525. {
  526. MountFS mount;
  527. mount.root = root;
  528. mount.path = "/";
  529. mount.fileSystem = fs;
  530. mMountList.push_back(mount);
  531. return true;
  532. }
  533. bool MountSystem::mount(String root,const Path &path)
  534. {
  535. return mount(root,new FileSystemRedirect(this,_normalize(path)));
  536. }
  537. FileSystemRef MountSystem::unmount(String root)
  538. {
  539. FileSystemRef first = _removeMountFromList(root);
  540. // remove remaining FSes on this root
  541. while (!_removeMountFromList(root).isNull())
  542. ;
  543. return first;
  544. }
  545. bool MountSystem::unmount(FileSystemRef fs)
  546. {
  547. if (fs.isNull())
  548. return false;
  549. // iterate back to front in case FS is in list multiple times.
  550. // also check that fs is not null each time since its a strong ref
  551. // so it could be nulled during removal.
  552. bool unmounted = false;
  553. for (S32 i = mMountList.size() - 1; !fs.isNull() && i >= 0; --i)
  554. {
  555. if (mMountList[i].fileSystem.getPointer() == fs.getPointer())
  556. {
  557. mMountList.erase(i);
  558. unmounted = true;
  559. }
  560. }
  561. return unmounted;
  562. }
  563. bool MountSystem::setCwd(const Path& file)
  564. {
  565. if (file.getPath().isEmpty())
  566. return false;
  567. mCWD.setRoot(file.getRoot());
  568. mCWD.setPath(file.getPath());
  569. return true;
  570. }
  571. const Path& MountSystem::getCwd() const
  572. {
  573. return mCWD;
  574. }
  575. FileSystemRef MountSystem::getFileSystem(const Path& path)
  576. {
  577. return _getFileSystemFromList(_normalize(path));
  578. }
  579. bool MountSystem::getFileAttributes(const Path& path,FileNode::Attributes* attr)
  580. {
  581. FileNodeRef file = getFileNode(path);
  582. if (file != NULL)
  583. {
  584. bool result = file->getAttributes(attr);
  585. return result;
  586. }
  587. return false;
  588. }
  589. FileNodeRef MountSystem::getFileNode(const Path& path)
  590. {
  591. Path np = _normalize(path);
  592. FileSystemRef fs = _getFileSystemFromList(np);
  593. if (fs != NULL)
  594. return fs->resolve(np);
  595. return NULL;
  596. }
  597. bool MountSystem::mapFSPath( const String &inRoot, const Path &inPath, Path &outPath )
  598. {
  599. FileSystemRef fs = _getFileSystemFromList(inRoot);
  600. if ( fs == NULL )
  601. {
  602. outPath = Path();
  603. return false;
  604. }
  605. outPath = fs->mapFrom( inPath );
  606. return outPath.getFullPath() != String();
  607. }
  608. S32 MountSystem::findByPattern( const Path &inBasePath, const String &inFilePattern, bool inRecursive, Vector<String> &outList, bool includeDirs/* =false */, bool multiMatch /* = true */ )
  609. {
  610. if (mFindByPatternOverrideFS.isNull() && !inBasePath.isDirectory() )
  611. return -1;
  612. DirectoryRef dir = NULL;
  613. if (mFindByPatternOverrideFS.isNull())
  614. // open directory using standard mount system search
  615. dir = openDirectory( inBasePath );
  616. else
  617. {
  618. // use specified filesystem to open directory
  619. FileNodeRef fNode = mFindByPatternOverrideFS->resolveLoose(inBasePath);
  620. if (fNode && (dir = dynamic_cast<Directory*>(fNode.getPointer())) != NULL)
  621. dir->open();
  622. }
  623. if ( dir == NULL )
  624. return -1;
  625. if (includeDirs)
  626. {
  627. // prepend cheesy "DIR:" annotation for directories
  628. outList.push_back(String("DIR:") + inBasePath.getPath());
  629. }
  630. FileNode::Attributes attrs;
  631. Vector<String> recurseDirs;
  632. while ( dir->read( &attrs ) )
  633. {
  634. // skip hidden files
  635. if ( attrs.name.c_str()[0] == '.' )
  636. continue;
  637. String name( attrs.name );
  638. if ( (attrs.flags & FileNode::Directory) && inRecursive )
  639. {
  640. name += '/';
  641. String path = Path::Join( inBasePath, '/', name );
  642. recurseDirs.push_back( path );
  643. }
  644. if ( !multiMatch && FindMatch::isMatch( inFilePattern, attrs.name, false ) )
  645. {
  646. String path = Path::Join( inBasePath, '/', name );
  647. outList.push_back( path );
  648. }
  649. if ( multiMatch && FindMatch::isMatchMultipleExprs( inFilePattern, attrs.name, false ) )
  650. {
  651. String path = Path::Join( inBasePath, '/', name );
  652. outList.push_back( path );
  653. }
  654. }
  655. dir->close();
  656. for ( S32 i = 0; i < recurseDirs.size(); i++ )
  657. findByPattern( recurseDirs[i], inFilePattern, true, outList, includeDirs, multiMatch );
  658. return outList.size();
  659. }
  660. bool MountSystem::isFile(const Path& path)
  661. {
  662. FileNode::Attributes attr;
  663. if (getFileAttributes(path,&attr))
  664. return attr.flags & FileNode::File;
  665. return false;
  666. }
  667. bool MountSystem::isDirectory(const Path& path, FileSystemRef fsRef)
  668. {
  669. FileNode::Attributes attr;
  670. if (fsRef.isNull())
  671. {
  672. if (getFileAttributes(path,&attr))
  673. return attr.flags & FileNode::Directory;
  674. return false;
  675. }
  676. else
  677. {
  678. FileNodeRef fnRef = fsRef->resolve(path);
  679. if (fnRef.isNull())
  680. return false;
  681. if (fnRef->getAttributes(&attr))
  682. return attr.flags & FileNode::Directory;
  683. return false;
  684. }
  685. }
  686. bool MountSystem::isReadOnly(const Path& path)
  687. {
  688. // first check to see if filesystem is read only
  689. FileSystemRef fs = getFileSystem(path);
  690. if ( fs.isNull() )
  691. // no filesystem owns this file...oh well, return false
  692. return false;
  693. if (fs->isReadOnly())
  694. return true;
  695. // check the file attributes, note that if the file does not exist,
  696. // this function returns false. that should be ok since we know
  697. // the file system is writable at this point.
  698. FileNode::Attributes attr;
  699. if (getFileAttributes(path,&attr))
  700. return attr.flags & FileNode::ReadOnly;
  701. return false;
  702. }
  703. void MountSystem::startFileChangeNotifications()
  704. {
  705. for ( U32 i = 0; i < mMountList.size(); i++ )
  706. {
  707. FileSystemChangeNotifier *notifier = mMountList[i].fileSystem->getChangeNotifier();
  708. if ( notifier != NULL && !notifier->isNotifying() )
  709. notifier->startNotifier();
  710. }
  711. }
  712. void MountSystem::stopFileChangeNotifications()
  713. {
  714. for ( U32 i = 0; i < mMountList.size(); i++ )
  715. {
  716. FileSystemChangeNotifier *notifier = mMountList[i].fileSystem->getChangeNotifier();
  717. if ( notifier != NULL && notifier->isNotifying() )
  718. notifier->stopNotifier();
  719. }
  720. }
  721. bool MountSystem::createPath(const Path& path)
  722. {
  723. if (path.getPath().isEmpty())
  724. return true;
  725. // See if the pathectory exists
  726. Path dir;
  727. dir.setRoot(path.getRoot());
  728. dir.setPath(path.getPath());
  729. // in a virtual mount system, isDirectory may return true if the directory exists in a read only FS,
  730. // but the directory may not exist on a writeable filesystem that is also mounted.
  731. // So get the target filesystem that will
  732. // be used for the full writable path and and make sure the directory exists on it.
  733. FileSystemRef fsRef = getFileSystem(path);
  734. if (isDirectory(dir,fsRef))
  735. return true;
  736. // Start from the top and work our way down
  737. Path sub;
  738. dir.setPath(path.isAbsolute()? String("/"): String());
  739. for (U32 i = 0; i < path.getDirectoryCount(); i++)
  740. {
  741. sub.setPath(path.getDirectory(i));
  742. dir.appendPath(sub);
  743. if (!isDirectory(dir,fsRef))
  744. {
  745. if (!createDirectory(dir,fsRef))
  746. return false;
  747. }
  748. }
  749. return true;
  750. }
  751. //-----------------------------------------------------------------------------
  752. // Default global mount system
  753. #ifndef TORQUE_DISABLE_VIRTUAL_MOUNT_SYSTEM
  754. // Note that the Platform::FS::MountZips() must be called in platformVolume.cpp for zip support to work.
  755. static VirtualMountSystem sgMountSystem;
  756. #else
  757. static MountSystem sgMountSystem;
  758. #endif
  759. namespace FS
  760. {
  761. FileRef CreateFile(const Path &path)
  762. {
  763. return sgMountSystem.createFile(path);
  764. }
  765. bool CopyFile(const Path& source, const Path& destination, bool noOverwrite)
  766. {
  767. return sgMountSystem.copyFile(source, destination, noOverwrite);
  768. }
  769. DirectoryRef CreateDirectory(const Path &path)
  770. {
  771. return sgMountSystem.createDirectory(path);
  772. }
  773. FileRef OpenFile(const Path &path, File::AccessMode mode)
  774. {
  775. return sgMountSystem.openFile(path,mode);
  776. }
  777. bool ReadFile(const Path &inPath, void *&outData, U32 &outSize, bool inNullTerminate )
  778. {
  779. FileRef fileR = OpenFile( inPath, File::Read );
  780. outData = NULL;
  781. outSize = 0;
  782. // We'll get a NULL file reference if
  783. // the file failed to open.
  784. if ( fileR == NULL )
  785. return false;
  786. outSize = fileR->getSize();
  787. // Its not a failure to read an empty
  788. // file... but we can exit early.
  789. if ( outSize == 0 )
  790. return true;
  791. U32 sizeRead = 0;
  792. if ( inNullTerminate )
  793. {
  794. outData = new char [outSize+1];
  795. if( !outData )
  796. {
  797. // out of memory
  798. return false;
  799. }
  800. sizeRead = fileR->read(outData, outSize);
  801. static_cast<char *>(outData)[outSize] = '\0';
  802. }
  803. else
  804. {
  805. outData = new char [outSize];
  806. if( !outData )
  807. {
  808. // out of memory
  809. return false;
  810. }
  811. sizeRead = fileR->read(outData, outSize);
  812. }
  813. if ( sizeRead != outSize )
  814. {
  815. delete static_cast<char *>(outData);
  816. outData = NULL;
  817. outSize = 0;
  818. return false;
  819. }
  820. return true;
  821. }
  822. DirectoryRef OpenDirectory(const Path &path)
  823. {
  824. return sgMountSystem.openDirectory(path);
  825. }
  826. bool Remove(const Path &path)
  827. {
  828. return sgMountSystem.remove(path);
  829. }
  830. bool Rename(const Path &from, const Path &to)
  831. {
  832. return sgMountSystem.rename(from,to);
  833. }
  834. bool Mount(String root, FileSystemRef fs)
  835. {
  836. return sgMountSystem.mount(root,fs);
  837. }
  838. bool Mount(String root, const Path &path)
  839. {
  840. return sgMountSystem.mount(root,path);
  841. }
  842. FileSystemRef Unmount(String root)
  843. {
  844. return sgMountSystem.unmount(root);
  845. }
  846. bool Unmount(FileSystemRef fs)
  847. {
  848. return sgMountSystem.unmount(fs);
  849. }
  850. bool SetCwd(const Path &file)
  851. {
  852. return sgMountSystem.setCwd(file);
  853. }
  854. const Path& GetCwd()
  855. {
  856. return sgMountSystem.getCwd();
  857. }
  858. FileSystemRef GetFileSystem(const Path &path)
  859. {
  860. return sgMountSystem.getFileSystem(path);
  861. }
  862. bool GetFileAttributes(const Path &path, FileNode::Attributes* attr)
  863. {
  864. return sgMountSystem.getFileAttributes(path,attr);
  865. }
  866. S32 CompareModifiedTimes(const Path& p1, const Path& p2)
  867. {
  868. FileNode::Attributes a1, a2;
  869. if (!Torque::FS::GetFileAttributes(p1, &a1))
  870. return -1;
  871. if (!Torque::FS::GetFileAttributes(p2, &a2))
  872. return -1;
  873. if (a1.mtime < a2.mtime)
  874. return -1;
  875. if (a1.mtime == a2.mtime)
  876. return 0;
  877. return 1;
  878. }
  879. FileNodeRef GetFileNode(const Path &path)
  880. {
  881. return sgMountSystem.getFileNode(path);
  882. }
  883. bool MapFSPath( const String &inRoot, const Path &inPath, Path &outPath )
  884. {
  885. return sgMountSystem.mapFSPath( inRoot, inPath, outPath );
  886. }
  887. bool GetFSPath( const Path &inPath, Path &outPath )
  888. {
  889. FileSystemRef sys = GetFileSystem( inPath );
  890. if ( sys )
  891. {
  892. outPath = sys->mapTo( inPath );
  893. return true;
  894. }
  895. return false;
  896. }
  897. S32 FindByPattern( const Path &inBasePath, const String &inFilePattern, bool inRecursive, Vector<String> &outList, bool multiMatch )
  898. {
  899. return sgMountSystem.findByPattern(inBasePath, inFilePattern, inRecursive, outList, false, multiMatch);
  900. }
  901. bool IsFile(const Path &path)
  902. {
  903. return sgMountSystem.isFile(path);
  904. }
  905. bool IsScriptFile(const char* pFilePath)
  906. {
  907. return (sgMountSystem.isFile(pFilePath)
  908. || sgMountSystem.isFile(pFilePath + String(".dso"))
  909. || sgMountSystem.isFile(pFilePath + String(".mis"))
  910. || sgMountSystem.isFile(pFilePath + String(".mis.dso"))
  911. || sgMountSystem.isFile(pFilePath + String(".gui"))
  912. || sgMountSystem.isFile(pFilePath + String(".gui.dso"))
  913. || sgMountSystem.isFile(pFilePath + String("." TORQUE_SCRIPT_EXTENSION))
  914. || sgMountSystem.isFile(pFilePath + String("." TORQUE_SCRIPT_EXTENSION) + String(".dso")));
  915. }
  916. bool IsDirectory(const Path &path)
  917. {
  918. return sgMountSystem.isDirectory(path);
  919. }
  920. bool IsReadOnly(const Path &path)
  921. {
  922. return sgMountSystem.isReadOnly(path);
  923. }
  924. String MakeUniquePath( const char *path, const char *fileName, const char *ext )
  925. {
  926. Path filePath;
  927. filePath.setPath( path );
  928. filePath.setFileName( fileName );
  929. filePath.setExtension( ext );
  930. // First get an upper bound on the range of filenames to search. This lets us
  931. // quickly skip past a large number of existing filenames.
  932. // Note: upper limit of 2^31 added to handle the degenerate case of a folder
  933. // with files named using the powers of 2, but plenty of space in between!
  934. U32 high = 1;
  935. while ( IsFile( filePath ) && ( high < 0x80000000 ) )
  936. {
  937. high = high * 2;
  938. filePath.setFileName( String::ToString( "%s%d", fileName, high ) );
  939. }
  940. // Now perform binary search for first filename in the range that doesn't exist
  941. // Note that the returned name will not be strictly numerically *first* if the
  942. // existing filenames are non-sequential (eg. 4,6,7), but it will still be unique.
  943. if ( high > 1 )
  944. {
  945. U32 low = high / 2;
  946. while ( high - low > 1 )
  947. {
  948. U32 probe = low + ( high - low ) / 2;
  949. filePath.setFileName( String::ToString( "%s%d", fileName, probe ) );
  950. if ( IsFile( filePath ) )
  951. low = probe;
  952. else
  953. high = probe;
  954. }
  955. // The 'high' index is guaranteed not to exist
  956. filePath.setFileName( String::ToString( "%s%d", fileName, high ) );
  957. }
  958. return filePath.getFullPath();
  959. }
  960. void StartFileChangeNotifications() { sgMountSystem.startFileChangeNotifications(); }
  961. void StopFileChangeNotifications() { sgMountSystem.stopFileChangeNotifications(); }
  962. S32 GetNumMounts() { return sgMountSystem.getNumMounts(); }
  963. String GetMountRoot( S32 index ) { return sgMountSystem.getMountRoot(index); }
  964. String GetMountPath( S32 index ) { return sgMountSystem.getMountPath(index); }
  965. String GetMountType( S32 index ) { return sgMountSystem.getMountType(index); }
  966. bool CreatePath(const Path& path)
  967. {
  968. return sgMountSystem.createPath(path);
  969. }
  970. } // Namespace FS
  971. } // Namespace Torque