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.

483 lines
13KB

  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. #include "../../Application/jucer_Headers.h"
  20. #ifdef BUILDING_JUCE_COMPILEENGINE
  21. const char* getPreferredLineFeed() { return "\r\n"; }
  22. #endif
  23. //==============================================================================
  24. String joinLinesIntoSourceFile (StringArray& lines)
  25. {
  26. while (lines.size() > 10 && lines [lines.size() - 1].isEmpty())
  27. lines.remove (lines.size() - 1);
  28. return lines.joinIntoString (getPreferredLineFeed()) + getPreferredLineFeed();
  29. }
  30. String replaceLineFeeds (const String& content, const String& lineFeed)
  31. {
  32. StringArray lines;
  33. lines.addLines (content);
  34. return lines.joinIntoString (lineFeed);
  35. }
  36. String getLineFeedForFile (const String& fileContent)
  37. {
  38. auto t = fileContent.getCharPointer();
  39. while (! t.isEmpty())
  40. {
  41. switch (t.getAndAdvance())
  42. {
  43. case 0: break;
  44. case '\n': return "\n";
  45. case '\r': if (*t == '\n') return "\r\n";
  46. default: continue;
  47. }
  48. }
  49. return {};
  50. }
  51. String trimCommentCharsFromStartOfLine (const String& line)
  52. {
  53. return line.trimStart().trimCharactersAtStart ("*/").trimStart();
  54. }
  55. String createAlphaNumericUID()
  56. {
  57. String uid;
  58. const char chars[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
  59. Random r;
  60. uid << chars[r.nextInt (52)]; // make sure the first character is always a letter
  61. for (int i = 5; --i >= 0;)
  62. {
  63. r.setSeedRandomly();
  64. uid << chars [r.nextInt (62)];
  65. }
  66. return uid;
  67. }
  68. String hexString8Digits (int value)
  69. {
  70. return String::toHexString (value).paddedLeft ('0', 8);
  71. }
  72. String createGUID (const String& seed)
  73. {
  74. auto hex = MD5 ((seed + "_guidsalt").toUTF8()).toHexString().toUpperCase();
  75. return "{" + hex.substring (0, 8)
  76. + "-" + hex.substring (8, 12)
  77. + "-" + hex.substring (12, 16)
  78. + "-" + hex.substring (16, 20)
  79. + "-" + hex.substring (20, 32)
  80. + "}";
  81. }
  82. String escapeSpaces (const String& s)
  83. {
  84. return s.replace (" ", "\\ ");
  85. }
  86. String addQuotesIfContainsSpaces (const String& text)
  87. {
  88. return (text.containsChar (' ') && ! text.isQuotedString()) ? text.quoted() : text;
  89. }
  90. void setValueIfVoid (Value value, const var& defaultValue)
  91. {
  92. if (value.getValue().isVoid())
  93. value = defaultValue;
  94. }
  95. //==============================================================================
  96. StringPairArray parsePreprocessorDefs (const String& text)
  97. {
  98. StringPairArray result;
  99. auto s = text.getCharPointer();
  100. while (! s.isEmpty())
  101. {
  102. String token, value;
  103. s = s.findEndOfWhitespace();
  104. while ((! s.isEmpty()) && *s != '=' && ! s.isWhitespace())
  105. token << s.getAndAdvance();
  106. s = s.findEndOfWhitespace();
  107. if (*s == '=')
  108. {
  109. ++s;
  110. while ((! s.isEmpty()) && *s == ' ')
  111. ++s;
  112. while ((! s.isEmpty()) && ! s.isWhitespace())
  113. {
  114. if (*s == ',')
  115. {
  116. ++s;
  117. break;
  118. }
  119. if (*s == '\\' && (s[1] == ' ' || s[1] == ','))
  120. ++s;
  121. value << s.getAndAdvance();
  122. }
  123. }
  124. if (token.isNotEmpty())
  125. result.set (token, value);
  126. }
  127. return result;
  128. }
  129. StringPairArray mergePreprocessorDefs (StringPairArray inheritedDefs, const StringPairArray& overridingDefs)
  130. {
  131. for (int i = 0; i < overridingDefs.size(); ++i)
  132. inheritedDefs.set (overridingDefs.getAllKeys()[i], overridingDefs.getAllValues()[i]);
  133. return inheritedDefs;
  134. }
  135. String createGCCPreprocessorFlags (const StringPairArray& defs)
  136. {
  137. String s;
  138. for (int i = 0; i < defs.size(); ++i)
  139. {
  140. auto def = defs.getAllKeys()[i];
  141. auto value = defs.getAllValues()[i];
  142. if (value.isNotEmpty())
  143. def << "=" << value;
  144. s += " -D" + def;
  145. }
  146. return s;
  147. }
  148. String replacePreprocessorDefs (const StringPairArray& definitions, String sourceString)
  149. {
  150. for (int i = 0; i < definitions.size(); ++i)
  151. {
  152. const String key (definitions.getAllKeys()[i]);
  153. const String value (definitions.getAllValues()[i]);
  154. sourceString = sourceString.replace ("${" + key + "}", value);
  155. }
  156. return sourceString;
  157. }
  158. StringArray getSearchPathsFromString (const String& searchPath)
  159. {
  160. StringArray s;
  161. s.addTokens (searchPath, ";\r\n", StringRef());
  162. return getCleanedStringArray (s);
  163. }
  164. StringArray getCommaOrWhitespaceSeparatedItems (const String& sourceString)
  165. {
  166. StringArray s;
  167. s.addTokens (sourceString, ", \t\r\n", StringRef());
  168. return getCleanedStringArray (s);
  169. }
  170. StringArray getCleanedStringArray (StringArray s)
  171. {
  172. s.trim();
  173. s.removeEmptyStrings();
  174. return s;
  175. }
  176. //==============================================================================
  177. static bool keyFoundAndNotSequentialDuplicate (XmlElement* xml, const String& key)
  178. {
  179. forEachXmlChildElementWithTagName (*xml, element, "key")
  180. {
  181. if (element->getAllSubText().trim().equalsIgnoreCase (key))
  182. {
  183. if (element->getNextElement() != nullptr && element->getNextElement()->hasTagName ("key"))
  184. {
  185. // found broken plist format (sequential duplicate), fix by removing
  186. xml->removeChildElement (element, true);
  187. return false;
  188. }
  189. // key found (not sequential duplicate)
  190. return true;
  191. }
  192. }
  193. // key not found
  194. return false;
  195. }
  196. static bool addKeyIfNotFound (XmlElement* xml, const String& key)
  197. {
  198. if (! keyFoundAndNotSequentialDuplicate (xml, key))
  199. {
  200. xml->createNewChildElement ("key")->addTextElement (key);
  201. return true;
  202. }
  203. return false;
  204. }
  205. void addPlistDictionaryKey (XmlElement* xml, const String& key, const String& value)
  206. {
  207. if (addKeyIfNotFound (xml, key))
  208. xml->createNewChildElement ("string")->addTextElement (value);
  209. }
  210. void addPlistDictionaryKeyBool (XmlElement* xml, const String& key, const bool value)
  211. {
  212. if (addKeyIfNotFound (xml, key))
  213. xml->createNewChildElement (value ? "true" : "false");
  214. }
  215. void addPlistDictionaryKeyInt (XmlElement* xml, const String& key, int value)
  216. {
  217. if (addKeyIfNotFound (xml, key))
  218. xml->createNewChildElement ("integer")->addTextElement (String (value));
  219. }
  220. //==============================================================================
  221. void autoScrollForMouseEvent (const MouseEvent& e, bool scrollX, bool scrollY)
  222. {
  223. if (Viewport* const viewport = e.eventComponent->findParentComponentOfClass<Viewport>())
  224. {
  225. const MouseEvent e2 (e.getEventRelativeTo (viewport));
  226. viewport->autoScroll (scrollX ? e2.x : 20, scrollY ? e2.y : 20, 8, 16);
  227. }
  228. }
  229. //==============================================================================
  230. int indexOfLineStartingWith (const StringArray& lines, const String& text, int index)
  231. {
  232. const int len = text.length();
  233. for (const String* i = lines.begin() + index, * const e = lines.end(); i < e; ++i)
  234. {
  235. if (CharacterFunctions::compareUpTo (i->getCharPointer().findEndOfWhitespace(),
  236. text.getCharPointer(), len) == 0)
  237. return index;
  238. ++index;
  239. }
  240. return -1;
  241. }
  242. //==============================================================================
  243. bool fileNeedsCppSyntaxHighlighting (const File& file)
  244. {
  245. if (file.hasFileExtension (sourceOrHeaderFileExtensions))
  246. return true;
  247. // This is a bit of a bodge to deal with libc++ headers with no extension..
  248. char fileStart[128] = { 0 };
  249. FileInputStream fin (file);
  250. fin.read (fileStart, sizeof (fileStart) - 4);
  251. return CharPointer_UTF8::isValidString (fileStart, sizeof (fileStart))
  252. && String (fileStart).trimStart().startsWith ("// -*- C++ -*-");
  253. }
  254. //==============================================================================
  255. StringArray getJUCEModules() noexcept
  256. {
  257. static StringArray juceModuleIds =
  258. {
  259. "juce_analytics",
  260. "juce_audio_basics",
  261. "juce_audio_devices",
  262. "juce_audio_formats",
  263. "juce_audio_plugin_client",
  264. "juce_audio_processors",
  265. "juce_audio_utils",
  266. "juce_blocks_basics",
  267. "juce_box2d",
  268. "juce_core",
  269. "juce_cryptography",
  270. "juce_data_structures",
  271. "juce_dsp",
  272. "juce_events",
  273. "juce_graphics",
  274. "juce_gui_basics",
  275. "juce_gui_extra",
  276. "juce_opengl",
  277. "juce_osc",
  278. "juce_product_unlocking",
  279. "juce_video"
  280. };
  281. return juceModuleIds;
  282. }
  283. bool isJUCEModule (const String& moduleID) noexcept
  284. {
  285. return getJUCEModules().contains (moduleID);
  286. }
  287. StringArray getModulesRequiredForConsole() noexcept
  288. {
  289. return { "juce_core",
  290. "juce_data_structures",
  291. "juce_events"
  292. };
  293. }
  294. StringArray getModulesRequiredForComponent() noexcept
  295. {
  296. return { "juce_core",
  297. "juce_data_structures",
  298. "juce_events",
  299. "juce_graphics",
  300. "juce_gui_basics"
  301. };
  302. }
  303. StringArray getModulesRequiredForAudioProcessor() noexcept
  304. {
  305. return { "juce_audio_basics",
  306. "juce_audio_devices",
  307. "juce_audio_formats",
  308. "juce_audio_plugin_client",
  309. "juce_audio_processors",
  310. "juce_audio_utils",
  311. "juce_core",
  312. "juce_data_structures",
  313. "juce_events",
  314. "juce_graphics",
  315. "juce_gui_basics",
  316. "juce_gui_extra"
  317. };
  318. }
  319. bool isPIPFile (const File& file) noexcept
  320. {
  321. for (auto line : StringArray::fromLines (file.loadFileAsString()))
  322. {
  323. auto trimmedLine = trimCommentCharsFromStartOfLine (line);
  324. if (trimmedLine.startsWith ("BEGIN_JUCE_PIP_METADATA"))
  325. return true;
  326. }
  327. return false;
  328. }
  329. bool isValidJUCEExamplesDirectory (const File& directory) noexcept
  330. {
  331. if (! directory.exists() || ! directory.isDirectory() || ! directory.containsSubDirectories())
  332. return false;
  333. return directory.getChildFile ("Assets").getChildFile ("juce_icon.png").existsAsFile();
  334. }
  335. //==============================================================================
  336. static var parseJUCEHeaderMetadata (const StringArray& lines)
  337. {
  338. auto* o = new DynamicObject();
  339. var result (o);
  340. for (auto& line : lines)
  341. {
  342. auto trimmedLine = trimCommentCharsFromStartOfLine (line);
  343. auto colon = trimmedLine.indexOfChar (':');
  344. if (colon >= 0)
  345. {
  346. auto key = trimmedLine.substring (0, colon).trim();
  347. auto value = trimmedLine.substring (colon + 1).trim();
  348. o->setProperty (key, value);
  349. }
  350. }
  351. return result;
  352. }
  353. static String parseMetadataItem (const StringArray& lines, int& index)
  354. {
  355. String result = lines[index++];
  356. while (index < lines.size())
  357. {
  358. auto continuationLine = trimCommentCharsFromStartOfLine (lines[index]);
  359. if (continuationLine.isEmpty() || continuationLine.indexOfChar (':') != -1
  360. || continuationLine.startsWith ("END_JUCE_"))
  361. break;
  362. result += " " + continuationLine;
  363. ++index;
  364. }
  365. return result;
  366. }
  367. var parseJUCEHeaderMetadata (const File& file)
  368. {
  369. StringArray lines;
  370. file.readLines (lines);
  371. for (int i = 0; i < lines.size(); ++i)
  372. {
  373. auto trimmedLine = trimCommentCharsFromStartOfLine (lines[i]);
  374. if (trimmedLine.startsWith ("BEGIN_JUCE_"))
  375. {
  376. StringArray desc;
  377. auto j = i + 1;
  378. while (j < lines.size())
  379. {
  380. if (trimCommentCharsFromStartOfLine (lines[j]).startsWith ("END_JUCE_"))
  381. return parseJUCEHeaderMetadata (desc);
  382. desc.add (parseMetadataItem (lines, j));
  383. }
  384. }
  385. }
  386. return {};
  387. }