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

10 years ago
10 years ago
10 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358
  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 PropertyFileConstants
  20. {
  21. JUCE_CONSTEXPR static const int magicNumber = (int) ByteOrder::littleEndianInt ('P', 'R', 'O', 'P');
  22. JUCE_CONSTEXPR static const int magicNumberCompressed = (int) ByteOrder::littleEndianInt ('C', 'P', 'R', 'P');
  23. JUCE_CONSTEXPR static const char* const fileTag = "PROPERTIES";
  24. JUCE_CONSTEXPR static const char* const valueTag = "VALUE";
  25. JUCE_CONSTEXPR static const char* const nameAttribute = "name";
  26. JUCE_CONSTEXPR static const char* const valueAttribute = "val";
  27. }
  28. //==============================================================================
  29. PropertiesFile::Options::Options()
  30. : commonToAllUsers (false),
  31. ignoreCaseOfKeyNames (false),
  32. doNotSave (false),
  33. millisecondsBeforeSaving (3000),
  34. storageFormat (PropertiesFile::storeAsXML),
  35. processLock (nullptr)
  36. {
  37. }
  38. File PropertiesFile::Options::getDefaultFile() const
  39. {
  40. // mustn't have illegal characters in this name..
  41. jassert (applicationName == File::createLegalFileName (applicationName));
  42. #if JUCE_MAC || JUCE_IOS
  43. File dir (commonToAllUsers ? "/Library/"
  44. : "~/Library/");
  45. if (osxLibrarySubFolder != "Preferences" && ! osxLibrarySubFolder.startsWith ("Application Support"))
  46. {
  47. /* The PropertiesFile class always used to put its settings files in "Library/Preferences", but Apple
  48. have changed their advice, and now stipulate that settings should go in "Library/Application Support".
  49. Because older apps would be broken by a silent change in this class's behaviour, you must now
  50. explicitly set the osxLibrarySubFolder value to indicate which path you want to use.
  51. In newer apps, you should always set this to "Application Support"
  52. or "Application Support/YourSubFolderName".
  53. If your app needs to load settings files that were created by older versions of juce and
  54. you want to maintain backwards-compatibility, then you can set this to "Preferences".
  55. But.. for better Apple-compliance, the recommended approach would be to write some code that
  56. finds your old settings files in ~/Library/Preferences, moves them to ~/Library/Application Support,
  57. and then uses the new path.
  58. */
  59. jassertfalse;
  60. dir = dir.getChildFile ("Application Support");
  61. }
  62. else
  63. {
  64. dir = dir.getChildFile (osxLibrarySubFolder);
  65. }
  66. if (folderName.isNotEmpty())
  67. dir = dir.getChildFile (folderName);
  68. #elif JUCE_LINUX || JUCE_ANDROID
  69. const File dir (File (commonToAllUsers ? "/var" : "~")
  70. .getChildFile (folderName.isNotEmpty() ? folderName
  71. : ("." + applicationName)));
  72. #elif JUCE_WINDOWS
  73. File dir (File::getSpecialLocation (commonToAllUsers ? File::commonApplicationDataDirectory
  74. : File::userApplicationDataDirectory));
  75. if (dir == File())
  76. return {};
  77. dir = dir.getChildFile (folderName.isNotEmpty() ? folderName
  78. : applicationName);
  79. #endif
  80. return (filenameSuffix.startsWithChar (L'.')
  81. ? dir.getChildFile (applicationName).withFileExtension (filenameSuffix)
  82. : dir.getChildFile (applicationName + "." + filenameSuffix));
  83. }
  84. //==============================================================================
  85. PropertiesFile::PropertiesFile (const File& f, const Options& o)
  86. : PropertySet (o.ignoreCaseOfKeyNames),
  87. file (f), options (o),
  88. loadedOk (false), needsWriting (false)
  89. {
  90. reload();
  91. }
  92. PropertiesFile::PropertiesFile (const Options& o)
  93. : PropertySet (o.ignoreCaseOfKeyNames),
  94. file (o.getDefaultFile()), options (o),
  95. loadedOk (false), needsWriting (false)
  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. ScopedPointer<XmlElement> doc (parser.getDocumentElement (true));
  147. if (doc != nullptr && doc->hasTagName (PropertyFileConstants::fileTag))
  148. {
  149. doc = parser.getDocumentElement();
  150. if (doc != nullptr)
  151. {
  152. forEachXmlChildElementWithTagName (*doc, e, PropertyFileConstants::valueTag)
  153. {
  154. const String name (e->getStringAttribute (PropertyFileConstants::nameAttribute));
  155. if (name.isNotEmpty())
  156. {
  157. getAllProperties().set (name,
  158. e->getFirstChildElement() != nullptr
  159. ? e->getFirstChildElement()->createDocument ("", true)
  160. : e->getStringAttribute (PropertyFileConstants::valueAttribute));
  161. }
  162. }
  163. return true;
  164. }
  165. // must be a pretty broken XML file we're trying to parse here,
  166. // or a sign that this object needs an InterProcessLock,
  167. // or just a failure reading the file. This last reason is why
  168. // we don't jassertfalse here.
  169. }
  170. return false;
  171. }
  172. bool PropertiesFile::saveAsXml()
  173. {
  174. XmlElement doc (PropertyFileConstants::fileTag);
  175. const StringPairArray& props = getAllProperties();
  176. for (int i = 0; i < props.size(); ++i)
  177. {
  178. XmlElement* const e = doc.createNewChildElement (PropertyFileConstants::valueTag);
  179. e->setAttribute (PropertyFileConstants::nameAttribute, props.getAllKeys() [i]);
  180. // if the value seems to contain xml, store it as such..
  181. if (XmlElement* const childElement = XmlDocument::parse (props.getAllValues() [i]))
  182. e->addChildElement (childElement);
  183. else
  184. e->setAttribute (PropertyFileConstants::valueAttribute, props.getAllValues() [i]);
  185. }
  186. ProcessScopedLock pl (createProcessLock());
  187. if (pl != nullptr && ! pl->isLocked())
  188. return false; // locking failure..
  189. if (doc.writeToFile (file, String()))
  190. {
  191. needsWriting = false;
  192. return true;
  193. }
  194. return false;
  195. }
  196. bool PropertiesFile::loadAsBinary()
  197. {
  198. FileInputStream fileStream (file);
  199. if (fileStream.openedOk())
  200. {
  201. const int magicNumber = fileStream.readInt();
  202. if (magicNumber == PropertyFileConstants::magicNumberCompressed)
  203. {
  204. SubregionStream subStream (&fileStream, 4, -1, false);
  205. GZIPDecompressorInputStream gzip (subStream);
  206. return loadAsBinary (gzip);
  207. }
  208. if (magicNumber == PropertyFileConstants::magicNumber)
  209. return loadAsBinary (fileStream);
  210. }
  211. return false;
  212. }
  213. bool PropertiesFile::loadAsBinary (InputStream& input)
  214. {
  215. BufferedInputStream in (input, 2048);
  216. int numValues = in.readInt();
  217. while (--numValues >= 0 && ! in.isExhausted())
  218. {
  219. const String key (in.readString());
  220. const String value (in.readString());
  221. jassert (key.isNotEmpty());
  222. if (key.isNotEmpty())
  223. getAllProperties().set (key, value);
  224. }
  225. return true;
  226. }
  227. bool PropertiesFile::saveAsBinary()
  228. {
  229. ProcessScopedLock pl (createProcessLock());
  230. if (pl != nullptr && ! pl->isLocked())
  231. return false; // locking failure..
  232. TemporaryFile tempFile (file);
  233. ScopedPointer<OutputStream> out (tempFile.getFile().createOutputStream());
  234. if (out != nullptr)
  235. {
  236. if (options.storageFormat == storeAsCompressedBinary)
  237. {
  238. out->writeInt (PropertyFileConstants::magicNumberCompressed);
  239. out->flush();
  240. out = new GZIPCompressorOutputStream (out.release(), 9, true);
  241. }
  242. else
  243. {
  244. // have you set up the storage option flags correctly?
  245. jassert (options.storageFormat == storeAsBinary);
  246. out->writeInt (PropertyFileConstants::magicNumber);
  247. }
  248. const StringPairArray& props = getAllProperties();
  249. const int numProperties = props.size();
  250. const StringArray& keys = props.getAllKeys();
  251. const StringArray& values = props.getAllValues();
  252. out->writeInt (numProperties);
  253. for (int i = 0; i < numProperties; ++i)
  254. {
  255. out->writeString (keys[i]);
  256. out->writeString (values[i]);
  257. }
  258. out = nullptr;
  259. if (tempFile.overwriteTargetFileWithTemporary())
  260. {
  261. needsWriting = false;
  262. return true;
  263. }
  264. }
  265. return false;
  266. }
  267. void PropertiesFile::timerCallback()
  268. {
  269. saveIfNeeded();
  270. }
  271. void PropertiesFile::propertyChanged()
  272. {
  273. sendChangeMessage();
  274. needsWriting = true;
  275. if (options.millisecondsBeforeSaving > 0)
  276. startTimer (options.millisecondsBeforeSaving);
  277. else if (options.millisecondsBeforeSaving == 0)
  278. saveIfNeeded();
  279. }