The JUCE cross-platform C++ framework, with DISTRHO/KXStudio specific changes
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

570 lines
17KB

  1. /*
  2. ==============================================================================
  3. This file is part of the JUCE library - "Jules' Utility Class Extensions"
  4. Copyright 2004-11 by Raw Material Software Ltd.
  5. ------------------------------------------------------------------------------
  6. JUCE can be redistributed and/or modified under the terms of the GNU General
  7. Public License (Version 2), as published by the Free Software Foundation.
  8. A copy of the license is included in the JUCE distribution, or can be found
  9. online at www.gnu.org/licenses.
  10. JUCE is distributed in the hope that it will be useful, but WITHOUT ANY
  11. WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
  12. A PARTICULAR PURPOSE. See the GNU General Public License for more details.
  13. ------------------------------------------------------------------------------
  14. To release a closed-source product which uses JUCE, commercial licenses are
  15. available: visit www.rawmaterialsoftware.com/juce for more information.
  16. ==============================================================================
  17. */
  18. BEGIN_JUCE_NAMESPACE
  19. //==============================================================================
  20. class ZipFile::ZipEntryInfo
  21. {
  22. public:
  23. ZipFile::ZipEntry entry;
  24. size_t streamOffset;
  25. size_t compressedSize;
  26. bool compressed;
  27. };
  28. //==============================================================================
  29. class ZipFile::ZipInputStream : public InputStream
  30. {
  31. public:
  32. //==============================================================================
  33. ZipInputStream (ZipFile& file_, ZipFile::ZipEntryInfo& zei)
  34. : file (file_),
  35. zipEntryInfo (zei),
  36. pos (0),
  37. headerSize (0),
  38. inputStream (file_.inputStream)
  39. {
  40. if (file_.inputSource != nullptr)
  41. {
  42. inputStream = streamToDelete = file.inputSource->createInputStream();
  43. }
  44. else
  45. {
  46. #if JUCE_DEBUG
  47. file_.numOpenStreams++;
  48. #endif
  49. }
  50. char buffer [30];
  51. if (inputStream != nullptr
  52. && inputStream->setPosition (zei.streamOffset)
  53. && inputStream->read (buffer, 30) == 30
  54. && ByteOrder::littleEndianInt (buffer) == 0x04034b50)
  55. {
  56. headerSize = 30 + ByteOrder::littleEndianShort (buffer + 26)
  57. + ByteOrder::littleEndianShort (buffer + 28);
  58. }
  59. }
  60. ~ZipInputStream()
  61. {
  62. #if JUCE_DEBUG
  63. if (inputStream != nullptr && inputStream == file.inputStream)
  64. file.numOpenStreams--;
  65. #endif
  66. }
  67. int64 getTotalLength()
  68. {
  69. return zipEntryInfo.compressedSize;
  70. }
  71. int read (void* buffer, int howMany)
  72. {
  73. if (headerSize <= 0)
  74. return 0;
  75. howMany = (int) jmin ((int64) howMany, zipEntryInfo.compressedSize - pos);
  76. if (inputStream == nullptr)
  77. return 0;
  78. int num;
  79. if (inputStream == file.inputStream)
  80. {
  81. const ScopedLock sl (file.lock);
  82. inputStream->setPosition (pos + zipEntryInfo.streamOffset + headerSize);
  83. num = inputStream->read (buffer, howMany);
  84. }
  85. else
  86. {
  87. inputStream->setPosition (pos + zipEntryInfo.streamOffset + headerSize);
  88. num = inputStream->read (buffer, howMany);
  89. }
  90. pos += num;
  91. return num;
  92. }
  93. bool isExhausted()
  94. {
  95. return headerSize <= 0 || pos >= zipEntryInfo.compressedSize;
  96. }
  97. int64 getPosition()
  98. {
  99. return pos;
  100. }
  101. bool setPosition (int64 newPos)
  102. {
  103. pos = jlimit ((int64) 0, (int64) zipEntryInfo.compressedSize, newPos);
  104. return true;
  105. }
  106. private:
  107. //==============================================================================
  108. ZipFile& file;
  109. ZipEntryInfo zipEntryInfo;
  110. int64 pos;
  111. int headerSize;
  112. InputStream* inputStream;
  113. ScopedPointer<InputStream> streamToDelete;
  114. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ZipInputStream);
  115. };
  116. //==============================================================================
  117. ZipFile::ZipFile (InputStream* const source_, const bool deleteStreamWhenDestroyed)
  118. : inputStream (source_)
  119. #if JUCE_DEBUG
  120. , numOpenStreams (0)
  121. #endif
  122. {
  123. if (deleteStreamWhenDestroyed)
  124. streamToDelete = inputStream;
  125. init();
  126. }
  127. ZipFile::ZipFile (const File& file)
  128. : inputStream (nullptr)
  129. #if JUCE_DEBUG
  130. , numOpenStreams (0)
  131. #endif
  132. {
  133. inputSource = new FileInputSource (file);
  134. init();
  135. }
  136. ZipFile::ZipFile (InputSource* const inputSource_)
  137. : inputStream (nullptr),
  138. inputSource (inputSource_)
  139. #if JUCE_DEBUG
  140. , numOpenStreams (0)
  141. #endif
  142. {
  143. init();
  144. }
  145. ZipFile::~ZipFile()
  146. {
  147. #if JUCE_DEBUG
  148. entries.clear();
  149. /* If you hit this assertion, it means you've created a stream to read one of the items in the
  150. zipfile, but you've forgotten to delete that stream object before deleting the file..
  151. Streams can't be kept open after the file is deleted because they need to share the input
  152. stream that the file uses to read itself.
  153. */
  154. jassert (numOpenStreams == 0);
  155. #endif
  156. }
  157. //==============================================================================
  158. int ZipFile::getNumEntries() const noexcept
  159. {
  160. return entries.size();
  161. }
  162. const ZipFile::ZipEntry* ZipFile::getEntry (const int index) const noexcept
  163. {
  164. ZipEntryInfo* const zei = entries [index];
  165. return zei != nullptr ? &(zei->entry) : nullptr;
  166. }
  167. int ZipFile::getIndexOfFileName (const String& fileName) const noexcept
  168. {
  169. for (int i = 0; i < entries.size(); ++i)
  170. if (entries.getUnchecked (i)->entry.filename == fileName)
  171. return i;
  172. return -1;
  173. }
  174. const ZipFile::ZipEntry* ZipFile::getEntry (const String& fileName) const noexcept
  175. {
  176. return getEntry (getIndexOfFileName (fileName));
  177. }
  178. InputStream* ZipFile::createStreamForEntry (const int index)
  179. {
  180. ZipEntryInfo* const zei = entries[index];
  181. InputStream* stream = nullptr;
  182. if (zei != nullptr)
  183. {
  184. stream = new ZipInputStream (*this, *zei);
  185. if (zei->compressed)
  186. {
  187. stream = new GZIPDecompressorInputStream (stream, true, true,
  188. zei->entry.uncompressedSize);
  189. // (much faster to unzip in big blocks using a buffer..)
  190. stream = new BufferedInputStream (stream, 32768, true);
  191. }
  192. }
  193. return stream;
  194. }
  195. class ZipFile::ZipFilenameComparator
  196. {
  197. public:
  198. int compareElements (const ZipFile::ZipEntryInfo* first, const ZipFile::ZipEntryInfo* second)
  199. {
  200. return first->entry.filename.compare (second->entry.filename);
  201. }
  202. };
  203. void ZipFile::sortEntriesByFilename()
  204. {
  205. ZipFilenameComparator sorter;
  206. entries.sort (sorter);
  207. }
  208. //==============================================================================
  209. void ZipFile::init()
  210. {
  211. ScopedPointer <InputStream> toDelete;
  212. InputStream* in = inputStream;
  213. if (inputSource != nullptr)
  214. {
  215. in = inputSource->createInputStream();
  216. toDelete = in;
  217. }
  218. if (in != nullptr)
  219. {
  220. int numEntries = 0;
  221. int pos = findEndOfZipEntryTable (*in, numEntries);
  222. if (pos >= 0 && pos < in->getTotalLength())
  223. {
  224. const int size = (int) (in->getTotalLength() - pos);
  225. in->setPosition (pos);
  226. MemoryBlock headerData;
  227. if (in->readIntoMemoryBlock (headerData, size) == size)
  228. {
  229. pos = 0;
  230. for (int i = 0; i < numEntries; ++i)
  231. {
  232. if (pos + 46 > size)
  233. break;
  234. const char* const buffer = static_cast <const char*> (headerData.getData()) + pos;
  235. const int fileNameLen = ByteOrder::littleEndianShort (buffer + 28);
  236. if (pos + 46 + fileNameLen > size)
  237. break;
  238. ZipEntryInfo* const zei = new ZipEntryInfo();
  239. zei->entry.filename = String::fromUTF8 (buffer + 46, fileNameLen);
  240. const int time = ByteOrder::littleEndianShort (buffer + 12);
  241. const int date = ByteOrder::littleEndianShort (buffer + 14);
  242. const int year = 1980 + (date >> 9);
  243. const int month = ((date >> 5) & 15) - 1;
  244. const int day = date & 31;
  245. const int hours = time >> 11;
  246. const int minutes = (time >> 5) & 63;
  247. const int seconds = (time & 31) << 1;
  248. zei->entry.fileTime = Time (year, month, day, hours, minutes, seconds);
  249. zei->compressed = ByteOrder::littleEndianShort (buffer + 10) != 0;
  250. zei->compressedSize = (size_t) ByteOrder::littleEndianInt (buffer + 20);
  251. zei->entry.uncompressedSize = ByteOrder::littleEndianInt (buffer + 24);
  252. zei->streamOffset = ByteOrder::littleEndianInt (buffer + 42);
  253. entries.add (zei);
  254. pos += 46 + fileNameLen
  255. + ByteOrder::littleEndianShort (buffer + 30)
  256. + ByteOrder::littleEndianShort (buffer + 32);
  257. }
  258. }
  259. }
  260. }
  261. }
  262. int ZipFile::findEndOfZipEntryTable (InputStream& input, int& numEntries)
  263. {
  264. BufferedInputStream in (input, 8192);
  265. in.setPosition (in.getTotalLength());
  266. int64 pos = in.getPosition();
  267. const int64 lowestPos = jmax ((int64) 0, pos - 1024);
  268. char buffer [32] = { 0 };
  269. while (pos > lowestPos)
  270. {
  271. in.setPosition (pos - 22);
  272. pos = in.getPosition();
  273. memcpy (buffer + 22, buffer, 4);
  274. if (in.read (buffer, 22) != 22)
  275. return 0;
  276. for (int i = 0; i < 22; ++i)
  277. {
  278. if (ByteOrder::littleEndianInt (buffer + i) == 0x06054b50)
  279. {
  280. in.setPosition (pos + i);
  281. in.read (buffer, 22);
  282. numEntries = ByteOrder::littleEndianShort (buffer + 10);
  283. return (int) ByteOrder::littleEndianInt (buffer + 16);
  284. }
  285. }
  286. }
  287. return 0;
  288. }
  289. bool ZipFile::uncompressTo (const File& targetDirectory,
  290. const bool shouldOverwriteFiles)
  291. {
  292. for (int i = 0; i < entries.size(); ++i)
  293. if (! uncompressEntry (i, targetDirectory, shouldOverwriteFiles))
  294. return false;
  295. return true;
  296. }
  297. bool ZipFile::uncompressEntry (const int index,
  298. const File& targetDirectory,
  299. bool shouldOverwriteFiles)
  300. {
  301. const ZipEntryInfo* zei = entries [index];
  302. if (zei != nullptr)
  303. {
  304. const File targetFile (targetDirectory.getChildFile (zei->entry.filename));
  305. if (zei->entry.filename.endsWithChar ('/'))
  306. {
  307. return targetFile.createDirectory(); // (entry is a directory, not a file)
  308. }
  309. else
  310. {
  311. ScopedPointer<InputStream> in (createStreamForEntry (index));
  312. if (in != nullptr)
  313. {
  314. if (shouldOverwriteFiles && ! targetFile.deleteFile())
  315. return false;
  316. if ((! targetFile.exists()) && targetFile.getParentDirectory().createDirectory())
  317. {
  318. ScopedPointer<FileOutputStream> out (targetFile.createOutputStream());
  319. if (out != nullptr)
  320. {
  321. out->writeFromInputStream (*in, -1);
  322. out = nullptr;
  323. targetFile.setCreationTime (zei->entry.fileTime);
  324. targetFile.setLastModificationTime (zei->entry.fileTime);
  325. targetFile.setLastAccessTime (zei->entry.fileTime);
  326. return true;
  327. }
  328. }
  329. }
  330. }
  331. }
  332. return false;
  333. }
  334. //=============================================================================
  335. extern unsigned long juce_crc32 (unsigned long crc, const unsigned char* buf, unsigned len);
  336. class ZipFile::Builder::Item
  337. {
  338. public:
  339. Item (const File& file_, const int compressionLevel_, const String& storedPathName_)
  340. : file (file_),
  341. storedPathname (storedPathName_.isEmpty() ? file_.getFileName() : storedPathName_),
  342. compressionLevel (compressionLevel_),
  343. compressedSize (0),
  344. headerStart (0)
  345. {
  346. }
  347. bool writeData (OutputStream& target, const int64 overallStartPosition)
  348. {
  349. MemoryOutputStream compressedData;
  350. if (compressionLevel > 0)
  351. {
  352. GZIPCompressorOutputStream compressor (&compressedData, compressionLevel, false,
  353. GZIPCompressorOutputStream::windowBitsRaw);
  354. if (! writeSource (compressor))
  355. return false;
  356. }
  357. else
  358. {
  359. if (! writeSource (compressedData))
  360. return false;
  361. }
  362. compressedSize = (int) compressedData.getDataSize();
  363. headerStart = (int) (target.getPosition() - overallStartPosition);
  364. target.writeInt (0x04034b50);
  365. writeFlagsAndSizes (target);
  366. target << storedPathname
  367. << compressedData;
  368. return true;
  369. }
  370. bool writeDirectoryEntry (OutputStream& target)
  371. {
  372. target.writeInt (0x02014b50);
  373. target.writeShort (20); // version written
  374. writeFlagsAndSizes (target);
  375. target.writeShort (0); // comment length
  376. target.writeShort (0); // start disk num
  377. target.writeShort (0); // internal attributes
  378. target.writeInt (0); // external attributes
  379. target.writeInt (headerStart);
  380. target << storedPathname;
  381. return true;
  382. }
  383. private:
  384. const File file;
  385. String storedPathname;
  386. int compressionLevel, compressedSize, headerStart;
  387. unsigned long checksum;
  388. void writeTimeAndDate (OutputStream& target) const
  389. {
  390. const Time t (file.getLastModificationTime());
  391. target.writeShort ((short) (t.getSeconds() + (t.getMinutes() << 5) + (t.getHours() << 11)));
  392. target.writeShort ((short) (t.getDayOfMonth() + ((t.getMonth() + 1) << 5) + ((t.getYear() - 1980) << 9)));
  393. }
  394. bool writeSource (OutputStream& target)
  395. {
  396. checksum = 0;
  397. ScopedPointer<FileInputStream> input (file.createInputStream());
  398. if (input == nullptr)
  399. return false;
  400. const int bufferSize = 2048;
  401. HeapBlock<unsigned char> buffer (bufferSize);
  402. while (! input->isExhausted())
  403. {
  404. const int bytesRead = input->read (buffer, bufferSize);
  405. if (bytesRead < 0)
  406. return false;
  407. checksum = juce_crc32 (checksum, buffer, (unsigned int) bytesRead);
  408. target.write (buffer, bytesRead);
  409. }
  410. return true;
  411. }
  412. void writeFlagsAndSizes (OutputStream& target) const
  413. {
  414. target.writeShort (10); // version needed
  415. target.writeShort (0); // flags
  416. target.writeShort (compressionLevel > 0 ? (short) 8 : (short) 0);
  417. writeTimeAndDate (target);
  418. target.writeInt ((int) checksum);
  419. target.writeInt (compressedSize);
  420. target.writeInt ((int) file.getSize());
  421. target.writeShort ((short) storedPathname.toUTF8().sizeInBytes() - 1);
  422. target.writeShort (0); // extra field length
  423. }
  424. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (Item);
  425. };
  426. //=============================================================================
  427. ZipFile::Builder::Builder() {}
  428. ZipFile::Builder::~Builder() {}
  429. void ZipFile::Builder::addFile (const File& fileToAdd, const int compressionLevel, const String& storedPathName)
  430. {
  431. items.add (new Item (fileToAdd, compressionLevel, storedPathName));
  432. }
  433. bool ZipFile::Builder::writeToStream (OutputStream& target) const
  434. {
  435. const int64 fileStart = target.getPosition();
  436. int i;
  437. for (i = 0; i < items.size(); ++i)
  438. if (! items.getUnchecked (i)->writeData (target, fileStart))
  439. return false;
  440. const int64 directoryStart = target.getPosition();
  441. for (i = 0; i < items.size(); ++i)
  442. if (! items.getUnchecked (i)->writeDirectoryEntry (target))
  443. return false;
  444. const int64 directoryEnd = target.getPosition();
  445. target.writeInt (0x06054b50);
  446. target.writeShort (0);
  447. target.writeShort (0);
  448. target.writeShort ((short) items.size());
  449. target.writeShort ((short) items.size());
  450. target.writeInt ((int) (directoryEnd - directoryStart));
  451. target.writeInt ((int) (directoryStart - fileStart));
  452. target.writeShort (0);
  453. target.flush();
  454. return true;
  455. }
  456. END_JUCE_NAMESPACE