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.

370 lines
11KB

  1. /*
  2. ==============================================================================
  3. This file is part of the JUCE library.
  4. Copyright (c) 2017 - ROLI Ltd.
  5. JUCE is an open source library subject to commercial or open-source
  6. licensing.
  7. By using JUCE, you agree to the terms of both the JUCE 5 End-User License
  8. Agreement and JUCE 5 Privacy Policy (both updated and effective as of the
  9. 27th April 2017).
  10. End User License Agreement: www.juce.com/juce-5-licence
  11. Privacy Policy: www.juce.com/juce-5-privacy-policy
  12. Or: You may also use this code under the terms of the GPL v3 (see
  13. www.gnu.org/licenses).
  14. JUCE IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL WARRANTIES, WHETHER
  15. EXPRESSED OR IMPLIED, INCLUDING MERCHANTABILITY AND FITNESS FOR PURPOSE, ARE
  16. DISCLAIMED.
  17. ==============================================================================
  18. */
  19. namespace juce
  20. {
  21. namespace PropertyFileConstants
  22. {
  23. JUCE_CONSTEXPR static const int magicNumber = (int) ByteOrder::makeInt ('P', 'R', 'O', 'P');
  24. JUCE_CONSTEXPR static const int magicNumberCompressed = (int) ByteOrder::makeInt ('C', 'P', 'R', 'P');
  25. JUCE_CONSTEXPR static const char* const fileTag = "PROPERTIES";
  26. JUCE_CONSTEXPR static const char* const valueTag = "VALUE";
  27. JUCE_CONSTEXPR static const char* const nameAttribute = "name";
  28. JUCE_CONSTEXPR static const char* const valueAttribute = "val";
  29. }
  30. //==============================================================================
  31. PropertiesFile::Options::Options()
  32. : commonToAllUsers (false),
  33. ignoreCaseOfKeyNames (false),
  34. doNotSave (false),
  35. millisecondsBeforeSaving (3000),
  36. storageFormat (PropertiesFile::storeAsXML),
  37. processLock (nullptr)
  38. {
  39. }
  40. File PropertiesFile::Options::getDefaultFile() const
  41. {
  42. // mustn't have illegal characters in this name..
  43. jassert (applicationName == File::createLegalFileName (applicationName));
  44. #if JUCE_MAC || JUCE_IOS
  45. File dir (commonToAllUsers ? "/Library/"
  46. : "~/Library/");
  47. if (osxLibrarySubFolder != "Preferences" && ! osxLibrarySubFolder.startsWith ("Application Support"))
  48. {
  49. /* The PropertiesFile class always used to put its settings files in "Library/Preferences", but Apple
  50. have changed their advice, and now stipulate that settings should go in "Library/Application Support".
  51. Because older apps would be broken by a silent change in this class's behaviour, you must now
  52. explicitly set the osxLibrarySubFolder value to indicate which path you want to use.
  53. In newer apps, you should always set this to "Application Support"
  54. or "Application Support/YourSubFolderName".
  55. If your app needs to load settings files that were created by older versions of juce and
  56. you want to maintain backwards-compatibility, then you can set this to "Preferences".
  57. But.. for better Apple-compliance, the recommended approach would be to write some code that
  58. finds your old settings files in ~/Library/Preferences, moves them to ~/Library/Application Support,
  59. and then uses the new path.
  60. */
  61. jassertfalse;
  62. dir = dir.getChildFile ("Application Support");
  63. }
  64. else
  65. {
  66. dir = dir.getChildFile (osxLibrarySubFolder);
  67. }
  68. if (folderName.isNotEmpty())
  69. dir = dir.getChildFile (folderName);
  70. #elif JUCE_LINUX || JUCE_ANDROID
  71. auto dir = File (commonToAllUsers ? "/var" : "~")
  72. .getChildFile (folderName.isNotEmpty() ? folderName
  73. : ("." + applicationName));
  74. #elif JUCE_WINDOWS
  75. auto dir = File::getSpecialLocation (commonToAllUsers ? File::commonApplicationDataDirectory
  76. : File::userApplicationDataDirectory);
  77. if (dir == File())
  78. return {};
  79. dir = dir.getChildFile (folderName.isNotEmpty() ? folderName
  80. : applicationName);
  81. #endif
  82. return (filenameSuffix.startsWithChar (L'.')
  83. ? dir.getChildFile (applicationName).withFileExtension (filenameSuffix)
  84. : dir.getChildFile (applicationName + "." + filenameSuffix));
  85. }
  86. //==============================================================================
  87. PropertiesFile::PropertiesFile (const File& f, const Options& o)
  88. : PropertySet (o.ignoreCaseOfKeyNames),
  89. file (f), options (o)
  90. {
  91. reload();
  92. }
  93. PropertiesFile::PropertiesFile (const Options& o)
  94. : PropertySet (o.ignoreCaseOfKeyNames),
  95. file (o.getDefaultFile()), options (o)
  96. {
  97. reload();
  98. }
  99. bool PropertiesFile::reload()
  100. {
  101. ProcessScopedLock pl (createProcessLock());
  102. if (pl != nullptr && ! pl->isLocked())
  103. return false; // locking failure..
  104. loadedOk = (! file.exists()) || loadAsBinary() || loadAsXml();
  105. return loadedOk;
  106. }
  107. PropertiesFile::~PropertiesFile()
  108. {
  109. saveIfNeeded();
  110. }
  111. InterProcessLock::ScopedLockType* PropertiesFile::createProcessLock() const
  112. {
  113. return options.processLock != nullptr ? new InterProcessLock::ScopedLockType (*options.processLock) : nullptr;
  114. }
  115. bool PropertiesFile::saveIfNeeded()
  116. {
  117. const ScopedLock sl (getLock());
  118. return (! needsWriting) || save();
  119. }
  120. bool PropertiesFile::needsToBeSaved() const
  121. {
  122. const ScopedLock sl (getLock());
  123. return needsWriting;
  124. }
  125. void PropertiesFile::setNeedsToBeSaved (const bool needsToBeSaved_)
  126. {
  127. const ScopedLock sl (getLock());
  128. needsWriting = needsToBeSaved_;
  129. }
  130. bool PropertiesFile::save()
  131. {
  132. const ScopedLock sl (getLock());
  133. stopTimer();
  134. if (options.doNotSave
  135. || file == File()
  136. || file.isDirectory()
  137. || ! file.getParentDirectory().createDirectory())
  138. return false;
  139. if (options.storageFormat == storeAsXML)
  140. return saveAsXml();
  141. return saveAsBinary();
  142. }
  143. bool PropertiesFile::loadAsXml()
  144. {
  145. XmlDocument parser (file);
  146. std::unique_ptr<XmlElement> doc (parser.getDocumentElement (true));
  147. if (doc != nullptr && doc->hasTagName (PropertyFileConstants::fileTag))
  148. {
  149. doc.reset (parser.getDocumentElement());
  150. if (doc != nullptr)
  151. {
  152. forEachXmlChildElementWithTagName (*doc, e, PropertyFileConstants::valueTag)
  153. {
  154. auto name = e->getStringAttribute (PropertyFileConstants::nameAttribute);
  155. if (name.isNotEmpty())
  156. getAllProperties().set (name,
  157. e->getFirstChildElement() != nullptr
  158. ? e->getFirstChildElement()->createDocument ("", true)
  159. : e->getStringAttribute (PropertyFileConstants::valueAttribute));
  160. }
  161. return true;
  162. }
  163. // must be a pretty broken XML file we're trying to parse here,
  164. // or a sign that this object needs an InterProcessLock,
  165. // or just a failure reading the file. This last reason is why
  166. // we don't jassertfalse here.
  167. }
  168. return false;
  169. }
  170. bool PropertiesFile::saveAsXml()
  171. {
  172. XmlElement doc (PropertyFileConstants::fileTag);
  173. auto& props = getAllProperties();
  174. for (int i = 0; i < props.size(); ++i)
  175. {
  176. auto* e = doc.createNewChildElement (PropertyFileConstants::valueTag);
  177. e->setAttribute (PropertyFileConstants::nameAttribute, props.getAllKeys() [i]);
  178. // if the value seems to contain xml, store it as such..
  179. if (auto* childElement = XmlDocument::parse (props.getAllValues() [i]))
  180. e->addChildElement (childElement);
  181. else
  182. e->setAttribute (PropertyFileConstants::valueAttribute, props.getAllValues() [i]);
  183. }
  184. ProcessScopedLock pl (createProcessLock());
  185. if (pl != nullptr && ! pl->isLocked())
  186. return false; // locking failure..
  187. if (doc.writeToFile (file, {}))
  188. {
  189. needsWriting = false;
  190. return true;
  191. }
  192. return false;
  193. }
  194. bool PropertiesFile::loadAsBinary()
  195. {
  196. FileInputStream fileStream (file);
  197. if (fileStream.openedOk())
  198. {
  199. auto magicNumber = fileStream.readInt();
  200. if (magicNumber == PropertyFileConstants::magicNumberCompressed)
  201. {
  202. SubregionStream subStream (&fileStream, 4, -1, false);
  203. GZIPDecompressorInputStream gzip (subStream);
  204. return loadAsBinary (gzip);
  205. }
  206. if (magicNumber == PropertyFileConstants::magicNumber)
  207. return loadAsBinary (fileStream);
  208. }
  209. return false;
  210. }
  211. bool PropertiesFile::loadAsBinary (InputStream& input)
  212. {
  213. BufferedInputStream in (input, 2048);
  214. int numValues = in.readInt();
  215. while (--numValues >= 0 && ! in.isExhausted())
  216. {
  217. auto key = in.readString();
  218. auto value = in.readString();
  219. jassert (key.isNotEmpty());
  220. if (key.isNotEmpty())
  221. getAllProperties().set (key, value);
  222. }
  223. return true;
  224. }
  225. bool PropertiesFile::saveAsBinary()
  226. {
  227. ProcessScopedLock pl (createProcessLock());
  228. if (pl != nullptr && ! pl->isLocked())
  229. return false; // locking failure..
  230. TemporaryFile tempFile (file);
  231. {
  232. FileOutputStream out (tempFile.getFile());
  233. if (! out.openedOk())
  234. return false;
  235. if (options.storageFormat == storeAsCompressedBinary)
  236. {
  237. out.writeInt (PropertyFileConstants::magicNumberCompressed);
  238. out.flush();
  239. GZIPCompressorOutputStream zipped (out, 9);
  240. if (! writeToStream (zipped))
  241. return false;
  242. }
  243. else
  244. {
  245. // have you set up the storage option flags correctly?
  246. jassert (options.storageFormat == storeAsBinary);
  247. out.writeInt (PropertyFileConstants::magicNumber);
  248. if (! writeToStream (out))
  249. return false;
  250. }
  251. }
  252. if (! tempFile.overwriteTargetFileWithTemporary())
  253. return false;
  254. needsWriting = false;
  255. return true;
  256. }
  257. bool PropertiesFile::writeToStream (OutputStream& out)
  258. {
  259. auto& props = getAllProperties();
  260. auto& keys = props.getAllKeys();
  261. auto& values = props.getAllValues();
  262. auto numProperties = props.size();
  263. if (! out.writeInt (numProperties))
  264. return false;
  265. for (int i = 0; i < numProperties; ++i)
  266. {
  267. if (! out.writeString (keys[i])) return false;
  268. if (! out.writeString (values[i])) return false;
  269. }
  270. return true;
  271. }
  272. void PropertiesFile::timerCallback()
  273. {
  274. saveIfNeeded();
  275. }
  276. void PropertiesFile::propertyChanged()
  277. {
  278. sendChangeMessage();
  279. needsWriting = true;
  280. if (options.millisecondsBeforeSaving > 0)
  281. startTimer (options.millisecondsBeforeSaving);
  282. else if (options.millisecondsBeforeSaving == 0)
  283. saveIfNeeded();
  284. }
  285. } // namespace juce