Audio plugin host https://kx.studio/carla
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.

juce_PropertiesFile.cpp 11KB

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