File.cpp 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475
  1. //
  2. // Copyright (c) 2008-2014 the Urho3D project.
  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 deal
  6. // in the Software without restriction, including without limitation the rights
  7. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  8. // 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 FROM,
  19. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  20. // THE SOFTWARE.
  21. //
  22. #include "Precompiled.h"
  23. #include "File.h"
  24. #include "FileSystem.h"
  25. #include "Log.h"
  26. #include "MemoryBuffer.h"
  27. #include "PackageFile.h"
  28. #include "Profiler.h"
  29. #include <cstdio>
  30. #include <lz4.h>
  31. #include "DebugNew.h"
  32. namespace Urho3D
  33. {
  34. #ifdef WIN32
  35. static const wchar_t* openMode[] =
  36. {
  37. L"rb",
  38. L"wb",
  39. L"w+b"
  40. };
  41. #else
  42. static const char* openMode[] =
  43. {
  44. "rb",
  45. "wb",
  46. "w+b"
  47. };
  48. #endif
  49. static const unsigned READ_BUFFER_SIZE = 32768;
  50. static const unsigned SKIP_BUFFER_SIZE = 1024;
  51. File::File(Context* context) :
  52. Object(context),
  53. mode_(FILE_READ),
  54. handle_(0),
  55. #ifdef ANDROID
  56. assetHandle_(0),
  57. #endif
  58. readBufferOffset_(0),
  59. readBufferSize_(0),
  60. offset_(0),
  61. checksum_(0),
  62. compressed_(false)
  63. {
  64. }
  65. File::File(Context* context, const String& fileName, FileMode mode) :
  66. Object(context),
  67. mode_(FILE_READ),
  68. handle_(0),
  69. #ifdef ANDROID
  70. assetHandle_(0),
  71. #endif
  72. readBufferOffset_(0),
  73. readBufferSize_(0),
  74. offset_(0),
  75. checksum_(0),
  76. compressed_(false)
  77. {
  78. Open(fileName, mode);
  79. }
  80. File::File(Context* context, PackageFile* package, const String& fileName) :
  81. Object(context),
  82. mode_(FILE_READ),
  83. handle_(0),
  84. #ifdef ANDROID
  85. assetHandle_(0),
  86. #endif
  87. readBufferOffset_(0),
  88. readBufferSize_(0),
  89. offset_(0),
  90. checksum_(0),
  91. compressed_(false)
  92. {
  93. Open(package, fileName);
  94. }
  95. File::~File()
  96. {
  97. Close();
  98. }
  99. bool File::Open(const String& fileName, FileMode mode)
  100. {
  101. Close();
  102. FileSystem* fileSystem = GetSubsystem<FileSystem>();
  103. if (fileSystem && !fileSystem->CheckAccess(GetPath(fileName)))
  104. {
  105. LOGERROR("Access denied to " + fileName);
  106. return false;
  107. }
  108. #ifdef ANDROID
  109. if (fileName.StartsWith("/apk/"))
  110. {
  111. if (mode != FILE_READ)
  112. {
  113. LOGERROR("Only read mode is supported for asset files");
  114. return false;
  115. }
  116. assetHandle_ = SDL_RWFromFile(fileName.Substring(5).CString(), "rb");
  117. if (!assetHandle_)
  118. {
  119. LOGERROR("Could not open asset file " + fileName);
  120. return false;
  121. }
  122. else
  123. {
  124. fileName_ = fileName;
  125. mode_ = mode;
  126. position_ = 0;
  127. offset_ = 0;
  128. checksum_ = 0;
  129. size_ = assetHandle_->hidden.androidio.size;
  130. readBuffer_ = new unsigned char[READ_BUFFER_SIZE];
  131. readBufferOffset_ = 0;
  132. readBufferSize_ = 0;
  133. return true;
  134. }
  135. }
  136. #endif
  137. if (fileName.Empty())
  138. {
  139. LOGERROR("Could not open file with empty name");
  140. return false;
  141. }
  142. #ifdef WIN32
  143. handle_ = _wfopen(GetWideNativePath(fileName).CString(), openMode[mode]);
  144. #else
  145. handle_ = fopen(GetNativePath(fileName).CString(), openMode[mode]);
  146. #endif
  147. if (!handle_)
  148. {
  149. LOGERROR("Could not open file " + fileName);
  150. return false;
  151. }
  152. fileName_ = fileName;
  153. mode_ = mode;
  154. position_ = 0;
  155. offset_ = 0;
  156. checksum_ = 0;
  157. compressed_ = false;
  158. fseek((FILE*)handle_, 0, SEEK_END);
  159. size_ = ftell((FILE*)handle_);
  160. fseek((FILE*)handle_, 0, SEEK_SET);
  161. return true;
  162. }
  163. bool File::Open(PackageFile* package, const String& fileName)
  164. {
  165. Close();
  166. if (!package)
  167. return false;
  168. const PackageEntry* entry = package->GetEntry(fileName);
  169. if (!entry)
  170. return false;
  171. #ifdef WIN32
  172. handle_ = _wfopen(GetWideNativePath(package->GetName()).CString(), L"rb");
  173. #else
  174. handle_ = fopen(GetNativePath(package->GetName()).CString(), "rb");
  175. #endif
  176. if (!handle_)
  177. {
  178. LOGERROR("Could not open package file " + fileName);
  179. return false;
  180. }
  181. fileName_ = fileName;
  182. mode_ = FILE_READ;
  183. offset_ = entry->offset_;
  184. checksum_ = entry->checksum_;
  185. position_ = 0;
  186. size_ = entry->size_;
  187. compressed_ = package->IsCompressed();
  188. fseek((FILE*)handle_, offset_, SEEK_SET);
  189. return true;
  190. }
  191. unsigned File::Read(void* dest, unsigned size)
  192. {
  193. #ifdef ANDROID
  194. if (!handle_ && !assetHandle_)
  195. #else
  196. if (!handle_)
  197. #endif
  198. {
  199. // Do not log the error further here to prevent spamming the stderr stream
  200. return 0;
  201. }
  202. if (mode_ == FILE_WRITE)
  203. {
  204. LOGERROR("File not opened for reading");
  205. return 0;
  206. }
  207. if (size + position_ > size_)
  208. size = size_ - position_;
  209. if (!size)
  210. return 0;
  211. #ifdef ANDROID
  212. if (assetHandle_)
  213. {
  214. unsigned sizeLeft = size;
  215. unsigned char* destPtr = (unsigned char*)dest;
  216. while (sizeLeft)
  217. {
  218. if (readBufferOffset_ >= readBufferSize_)
  219. {
  220. readBufferSize_ = Min((int)size_ - position_, (int)READ_BUFFER_SIZE);
  221. readBufferOffset_ = 0;
  222. SDL_RWread(assetHandle_, readBuffer_.Get(), readBufferSize_, 1);
  223. }
  224. unsigned copySize = Min((int)(readBufferSize_ - readBufferOffset_), (int)sizeLeft);
  225. memcpy(destPtr, readBuffer_.Get() + readBufferOffset_, copySize);
  226. destPtr += copySize;
  227. sizeLeft -= copySize;
  228. readBufferOffset_ += copySize;
  229. position_ += copySize;
  230. }
  231. return size;
  232. }
  233. #endif
  234. if (compressed_)
  235. {
  236. unsigned sizeLeft = size;
  237. unsigned char* destPtr = (unsigned char*)dest;
  238. while (sizeLeft)
  239. {
  240. if (!readBuffer_ || readBufferOffset_ >= readBufferSize_)
  241. {
  242. unsigned char blockHeaderBytes[4];
  243. fread(blockHeaderBytes, sizeof blockHeaderBytes, 1, (FILE*)handle_);
  244. MemoryBuffer blockHeader(&blockHeaderBytes[0], sizeof blockHeaderBytes);
  245. unsigned unpackedSize = blockHeader.ReadUShort();
  246. unsigned packedSize = blockHeader.ReadUShort();
  247. if (!readBuffer_)
  248. {
  249. readBuffer_ = new unsigned char[unpackedSize];
  250. inputBuffer_ = new unsigned char[LZ4_compressBound(unpackedSize)];
  251. }
  252. /// \todo Handle errors
  253. fread(inputBuffer_.Get(), packedSize, 1, (FILE*)handle_);
  254. LZ4_decompress_fast((const char*)inputBuffer_.Get(), (char *)readBuffer_.Get(), unpackedSize);
  255. readBufferSize_ = unpackedSize;
  256. readBufferOffset_ = 0;
  257. }
  258. unsigned copySize = Min((int)(readBufferSize_ - readBufferOffset_), (int)sizeLeft);
  259. memcpy(destPtr, readBuffer_.Get() + readBufferOffset_, copySize);
  260. destPtr += copySize;
  261. sizeLeft -= copySize;
  262. readBufferOffset_ += copySize;
  263. position_ += copySize;
  264. }
  265. return size;
  266. }
  267. size_t ret = fread(dest, size, 1, (FILE*)handle_);
  268. if (ret != 1)
  269. {
  270. // Return to the position where the read began
  271. fseek((FILE*)handle_, position_ + offset_, SEEK_SET);
  272. LOGERROR("Error while reading from file " + GetName());
  273. return 0;
  274. }
  275. position_ += size;
  276. return size;
  277. }
  278. unsigned File::Seek(unsigned position)
  279. {
  280. #ifdef ANDROID
  281. if (!handle_ && !assetHandle_)
  282. #else
  283. if (!handle_)
  284. #endif
  285. {
  286. // Do not log the error further here to prevent spamming the stderr stream
  287. return 0;
  288. }
  289. // Allow sparse seeks if writing
  290. if (mode_ == FILE_READ && position > size_)
  291. position = size_;
  292. #ifdef ANDROID
  293. if (assetHandle_)
  294. {
  295. SDL_RWseek(assetHandle_, position, SEEK_SET);
  296. position_ = position;
  297. readBufferOffset_ = 0;
  298. readBufferSize_ = 0;
  299. return position_;
  300. }
  301. #endif
  302. if (compressed_)
  303. {
  304. // Start over from the beginning
  305. if (position == 0)
  306. {
  307. position_ = 0;
  308. readBufferOffset_ = 0;
  309. readBufferSize_ = 0;
  310. fseek((FILE*)handle_, offset_, SEEK_SET);
  311. }
  312. // Skip bytes
  313. else if (position >= position_)
  314. {
  315. unsigned char skipBuffer[SKIP_BUFFER_SIZE];
  316. while (position > position_)
  317. Read(skipBuffer, Min((int)position - position_, (int)SKIP_BUFFER_SIZE));
  318. }
  319. else
  320. LOGERROR("Seeking backward in a compressed file is not supported");
  321. return position_;
  322. }
  323. fseek((FILE*)handle_, position + offset_, SEEK_SET);
  324. position_ = position;
  325. return position_;
  326. }
  327. unsigned File::Write(const void* data, unsigned size)
  328. {
  329. if (!handle_)
  330. {
  331. // Do not log the error further here to prevent spamming the stderr stream
  332. return 0;
  333. }
  334. if (mode_ == FILE_READ)
  335. {
  336. LOGERROR("File not opened for writing");
  337. return 0;
  338. }
  339. if (!size)
  340. return 0;
  341. if (fwrite(data, size, 1, (FILE*)handle_) != 1)
  342. {
  343. // Return to the position where the write began
  344. fseek((FILE*)handle_, position_ + offset_, SEEK_SET);
  345. LOGERROR("Error while writing to file " + GetName());
  346. return 0;
  347. }
  348. position_ += size;
  349. if (position_ > size_)
  350. size_ = position_;
  351. return size;
  352. }
  353. unsigned File::GetChecksum()
  354. {
  355. if (offset_ || checksum_)
  356. return checksum_;
  357. if (!handle_ || mode_ == FILE_WRITE)
  358. return 0;
  359. PROFILE(CalculateFileChecksum);
  360. unsigned oldPos = position_;
  361. checksum_ = 0;
  362. Seek(0);
  363. while (!IsEof())
  364. {
  365. unsigned char block[1024];
  366. unsigned readBytes = Read(block, 1024);
  367. for (unsigned i = 0; i < readBytes; ++i)
  368. checksum_ = SDBMHash(checksum_, block[i]);
  369. }
  370. Seek(oldPos);
  371. return checksum_;
  372. }
  373. void File::Close()
  374. {
  375. #ifdef ANDROID
  376. if (assetHandle_)
  377. {
  378. SDL_RWclose(assetHandle_);
  379. assetHandle_ = 0;
  380. }
  381. #endif
  382. readBuffer_.Reset();
  383. inputBuffer_.Reset();
  384. if (handle_)
  385. {
  386. fclose((FILE*)handle_);
  387. handle_ = 0;
  388. position_ = 0;
  389. size_ = 0;
  390. offset_ = 0;
  391. checksum_ = 0;
  392. }
  393. }
  394. void File::Flush()
  395. {
  396. if (handle_)
  397. fflush((FILE*)handle_);
  398. }
  399. void File::SetName(const String& name)
  400. {
  401. fileName_ = name;
  402. }
  403. bool File::IsOpen() const
  404. {
  405. #ifdef ANDROID
  406. return handle_ != 0 || assetHandle_ != 0;
  407. #else
  408. return handle_ != 0;
  409. #endif
  410. }
  411. }