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.

574 lines
17KB

  1. /*
  2. ==============================================================================
  3. This file is part of the JUCE library.
  4. Copyright (c) 2015 - ROLI Ltd.
  5. Permission is granted to use this software under the terms of either:
  6. a) the GPL v2 (or any later version)
  7. b) the Affero GPL v3
  8. Details of these licenses can be found at: www.gnu.org/licenses
  9. JUCE is distributed in the hope that it will be useful, but WITHOUT ANY
  10. WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
  11. A PARTICULAR PURPOSE. See the GNU General Public License for more details.
  12. ------------------------------------------------------------------------------
  13. To release a closed-source product which uses JUCE, commercial licenses are
  14. available: visit www.juce.com for more information.
  15. ==============================================================================
  16. */
  17. #include "../jucer_Headers.h"
  18. #include "../Application/jucer_Application.h"
  19. namespace
  20. {
  21. bool keyFoundAndNotSequentialDuplicate (XmlElement* xml, const String& key)
  22. {
  23. forEachXmlChildElementWithTagName (*xml, element, "key")
  24. {
  25. if (element->getAllSubText().trim().equalsIgnoreCase (key))
  26. {
  27. if (element->getNextElement() != nullptr && element->getNextElement()->hasTagName ("key"))
  28. {
  29. // found broken plist format (sequential duplicate), fix by removing
  30. xml->removeChildElement (element, true);
  31. return false;
  32. }
  33. // key found (not sequential duplicate)
  34. return true;
  35. }
  36. }
  37. // key not found
  38. return false;
  39. }
  40. }
  41. //==============================================================================
  42. String createAlphaNumericUID()
  43. {
  44. String uid;
  45. const char chars[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
  46. Random r;
  47. uid << chars [r.nextInt (52)]; // make sure the first character is always a letter
  48. for (int i = 5; --i >= 0;)
  49. {
  50. r.setSeedRandomly();
  51. uid << chars [r.nextInt (62)];
  52. }
  53. return uid;
  54. }
  55. String hexString8Digits (int value)
  56. {
  57. return String::toHexString (value).paddedLeft ('0', 8);
  58. }
  59. String createGUID (const String& seed)
  60. {
  61. const String hex (MD5 ((seed + "_guidsalt").toUTF8()).toHexString().toUpperCase());
  62. return "{" + hex.substring (0, 8)
  63. + "-" + hex.substring (8, 12)
  64. + "-" + hex.substring (12, 16)
  65. + "-" + hex.substring (16, 20)
  66. + "-" + hex.substring (20, 32)
  67. + "}";
  68. }
  69. String escapeSpaces (const String& s)
  70. {
  71. return s.replace (" ", "\\ ");
  72. }
  73. String addQuotesIfContainsSpaces (const String& text)
  74. {
  75. return (text.containsChar (' ') && ! text.isQuotedString()) ? text.quoted() : text;
  76. }
  77. void setValueIfVoid (Value value, const var& defaultValue)
  78. {
  79. if (value.getValue().isVoid())
  80. value = defaultValue;
  81. }
  82. //==============================================================================
  83. StringPairArray parsePreprocessorDefs (const String& text)
  84. {
  85. StringPairArray result;
  86. String::CharPointerType s (text.getCharPointer());
  87. while (! s.isEmpty())
  88. {
  89. String token, value;
  90. s = s.findEndOfWhitespace();
  91. while ((! s.isEmpty()) && *s != '=' && ! s.isWhitespace())
  92. token << s.getAndAdvance();
  93. s = s.findEndOfWhitespace();
  94. if (*s == '=')
  95. {
  96. ++s;
  97. s = s.findEndOfWhitespace();
  98. while ((! s.isEmpty()) && ! s.isWhitespace())
  99. {
  100. if (*s == ',')
  101. {
  102. ++s;
  103. break;
  104. }
  105. if (*s == '\\' && (s[1] == ' ' || s[1] == ','))
  106. ++s;
  107. value << s.getAndAdvance();
  108. }
  109. }
  110. if (token.isNotEmpty())
  111. result.set (token, value);
  112. }
  113. return result;
  114. }
  115. StringPairArray mergePreprocessorDefs (StringPairArray inheritedDefs, const StringPairArray& overridingDefs)
  116. {
  117. for (int i = 0; i < overridingDefs.size(); ++i)
  118. inheritedDefs.set (overridingDefs.getAllKeys()[i], overridingDefs.getAllValues()[i]);
  119. return inheritedDefs;
  120. }
  121. String createGCCPreprocessorFlags (const StringPairArray& defs)
  122. {
  123. String s;
  124. for (int i = 0; i < defs.size(); ++i)
  125. {
  126. String def (defs.getAllKeys()[i]);
  127. const String value (defs.getAllValues()[i]);
  128. if (value.isNotEmpty())
  129. def << "=" << value;
  130. if (! def.endsWithChar ('"'))
  131. def = def.quoted();
  132. s += " -D " + def;
  133. }
  134. return s;
  135. }
  136. String replacePreprocessorDefs (const StringPairArray& definitions, String sourceString)
  137. {
  138. for (int i = 0; i < definitions.size(); ++i)
  139. {
  140. const String key (definitions.getAllKeys()[i]);
  141. const String value (definitions.getAllValues()[i]);
  142. sourceString = sourceString.replace ("${" + key + "}", value);
  143. }
  144. return sourceString;
  145. }
  146. StringArray getSearchPathsFromString (const String& searchPath)
  147. {
  148. StringArray s;
  149. s.addTokens (searchPath, ";\r\n", StringRef());
  150. return getCleanedStringArray (s);
  151. }
  152. StringArray getCommaOrWhitespaceSeparatedItems (const String& sourceString)
  153. {
  154. StringArray s;
  155. s.addTokens (sourceString, ", \t\r\n", StringRef());
  156. return getCleanedStringArray (s);
  157. }
  158. StringArray getCleanedStringArray (StringArray s)
  159. {
  160. s.trim();
  161. s.removeEmptyStrings();
  162. s.removeDuplicates (false);
  163. return s;
  164. }
  165. void addPlistDictionaryKey (XmlElement* xml, const String& key, const String& value)
  166. {
  167. if (keyFoundAndNotSequentialDuplicate (xml, key))
  168. return;
  169. xml->createNewChildElement ("key")->addTextElement (key);
  170. xml->createNewChildElement ("string")->addTextElement (value);
  171. }
  172. void addPlistDictionaryKeyBool (XmlElement* xml, const String& key, const bool value)
  173. {
  174. if (keyFoundAndNotSequentialDuplicate (xml, key))
  175. return;
  176. xml->createNewChildElement ("key")->addTextElement (key);
  177. xml->createNewChildElement (value ? "true" : "false");
  178. }
  179. void addPlistDictionaryKeyInt (XmlElement* xml, const String& key, int value)
  180. {
  181. if (keyFoundAndNotSequentialDuplicate (xml, key))
  182. return;
  183. xml->createNewChildElement ("key")->addTextElement (key);
  184. xml->createNewChildElement ("integer")->addTextElement (String (value));
  185. }
  186. //==============================================================================
  187. void autoScrollForMouseEvent (const MouseEvent& e, bool scrollX, bool scrollY)
  188. {
  189. if (Viewport* const viewport = e.eventComponent->findParentComponentOfClass<Viewport>())
  190. {
  191. const MouseEvent e2 (e.getEventRelativeTo (viewport));
  192. viewport->autoScroll (scrollX ? e2.x : 20, scrollY ? e2.y : 20, 8, 16);
  193. }
  194. }
  195. //==============================================================================
  196. int indexOfLineStartingWith (const StringArray& lines, const String& text, int index)
  197. {
  198. const int len = text.length();
  199. for (const String* i = lines.begin() + index, * const e = lines.end(); i < e; ++i)
  200. {
  201. if (CharacterFunctions::compareUpTo (i->getCharPointer().findEndOfWhitespace(),
  202. text.getCharPointer(), len) == 0)
  203. return index;
  204. ++index;
  205. }
  206. return -1;
  207. }
  208. //==============================================================================
  209. bool fileNeedsCppSyntaxHighlighting (const File& file)
  210. {
  211. if (file.hasFileExtension (sourceOrHeaderFileExtensions))
  212. return true;
  213. // This is a bit of a bodge to deal with libc++ headers with no extension..
  214. char fileStart[64] = { 0 };
  215. FileInputStream fin (file);
  216. fin.read (fileStart, sizeof (fileStart) - 4);
  217. return String (fileStart).trimStart().startsWith ("// -*- C++ -*-");
  218. }
  219. //==============================================================================
  220. RolloverHelpComp::RolloverHelpComp()
  221. : lastComp (nullptr)
  222. {
  223. setInterceptsMouseClicks (false, false);
  224. startTimer (150);
  225. }
  226. void RolloverHelpComp::paint (Graphics& g)
  227. {
  228. AttributedString s;
  229. s.setJustification (Justification::centredLeft);
  230. s.append (lastTip, Font (14.0f), findColour (mainBackgroundColourId).contrasting (0.7f));
  231. TextLayout tl;
  232. tl.createLayoutWithBalancedLineLengths (s, getWidth() - 10.0f);
  233. if (tl.getNumLines() > 3)
  234. tl.createLayout (s, getWidth() - 10.0f);
  235. tl.draw (g, getLocalBounds().toFloat());
  236. }
  237. void RolloverHelpComp::timerCallback()
  238. {
  239. Component* newComp = Desktop::getInstance().getMainMouseSource().getComponentUnderMouse();
  240. if (newComp != nullptr
  241. && (newComp->getTopLevelComponent() != getTopLevelComponent()
  242. || newComp->isCurrentlyBlockedByAnotherModalComponent()))
  243. newComp = nullptr;
  244. if (newComp != lastComp)
  245. {
  246. lastComp = newComp;
  247. String newTip (findTip (newComp));
  248. if (newTip != lastTip)
  249. {
  250. lastTip = newTip;
  251. repaint();
  252. }
  253. }
  254. }
  255. String RolloverHelpComp::findTip (Component* c)
  256. {
  257. while (c != nullptr)
  258. {
  259. if (TooltipClient* const tc = dynamic_cast <TooltipClient*> (c))
  260. {
  261. const String tip (tc->getTooltip());
  262. if (tip.isNotEmpty())
  263. return tip;
  264. }
  265. c = c->getParentComponent();
  266. }
  267. return String::empty;
  268. }
  269. //==============================================================================
  270. class UTF8Component : public Component,
  271. private TextEditorListener
  272. {
  273. public:
  274. UTF8Component()
  275. : desc (String::empty,
  276. "Type any string into the box, and it'll be shown below as a portable UTF-8 literal, "
  277. "ready to cut-and-paste into your source-code...")
  278. {
  279. desc.setJustificationType (Justification::centred);
  280. desc.setColour (Label::textColourId, Colours::white);
  281. addAndMakeVisible (desc);
  282. const Colour bkgd (Colours::white.withAlpha (0.6f));
  283. userText.setMultiLine (true, true);
  284. userText.setReturnKeyStartsNewLine (true);
  285. userText.setColour (TextEditor::backgroundColourId, bkgd);
  286. addAndMakeVisible (userText);
  287. userText.addListener (this);
  288. resultText.setFont (getAppSettings().appearance.getCodeFont().withHeight (13.0f));
  289. resultText.setMultiLine (true, true);
  290. resultText.setColour (TextEditor::backgroundColourId, bkgd);
  291. resultText.setReadOnly (true);
  292. resultText.setSelectAllWhenFocused (true);
  293. addAndMakeVisible (resultText);
  294. userText.setText (getLastText());
  295. }
  296. void textEditorTextChanged (TextEditor&)
  297. {
  298. update();
  299. }
  300. void textEditorEscapeKeyPressed (TextEditor&)
  301. {
  302. getTopLevelComponent()->exitModalState (0);
  303. }
  304. void update()
  305. {
  306. getLastText() = userText.getText();
  307. resultText.setText (CodeHelpers::stringLiteral (getLastText(), 100), false);
  308. }
  309. void resized()
  310. {
  311. Rectangle<int> r (getLocalBounds().reduced (8));
  312. desc.setBounds (r.removeFromTop (44));
  313. r.removeFromTop (8);
  314. userText.setBounds (r.removeFromTop (r.getHeight() / 2));
  315. r.removeFromTop (8);
  316. resultText.setBounds (r);
  317. }
  318. private:
  319. Label desc;
  320. TextEditor userText, resultText;
  321. String& getLastText()
  322. {
  323. static String t;
  324. return t;
  325. }
  326. };
  327. void showUTF8ToolWindow (ScopedPointer<Component>& ownerPointer)
  328. {
  329. if (ownerPointer != nullptr)
  330. {
  331. ownerPointer->toFront (true);
  332. }
  333. else
  334. {
  335. new FloatingToolWindow ("UTF-8 String Literal Converter",
  336. "utf8WindowPos",
  337. new UTF8Component(), ownerPointer,
  338. 500, 500,
  339. 300, 300, 1000, 1000);
  340. }
  341. }
  342. //==============================================================================
  343. class SVGPathDataComponent : public Component,
  344. private TextEditorListener
  345. {
  346. public:
  347. SVGPathDataComponent()
  348. : desc (String::empty,
  349. "Paste an SVG path string into the top box, and it'll be converted to some C++ "
  350. "code that will load it as a Path object..")
  351. {
  352. desc.setJustificationType (Justification::centred);
  353. desc.setColour (Label::textColourId, Colours::white);
  354. addAndMakeVisible (desc);
  355. const Colour bkgd (Colours::white.withAlpha (0.6f));
  356. userText.setFont (getAppSettings().appearance.getCodeFont().withHeight (13.0f));
  357. userText.setMultiLine (true, true);
  358. userText.setReturnKeyStartsNewLine (true);
  359. userText.setColour (TextEditor::backgroundColourId, bkgd);
  360. addAndMakeVisible (userText);
  361. userText.addListener (this);
  362. resultText.setFont (getAppSettings().appearance.getCodeFont().withHeight (13.0f));
  363. resultText.setMultiLine (true, true);
  364. resultText.setColour (TextEditor::backgroundColourId, bkgd);
  365. resultText.setReadOnly (true);
  366. resultText.setSelectAllWhenFocused (true);
  367. addAndMakeVisible (resultText);
  368. userText.setText (getLastText());
  369. }
  370. void textEditorTextChanged (TextEditor&)
  371. {
  372. update();
  373. }
  374. void textEditorEscapeKeyPressed (TextEditor&)
  375. {
  376. getTopLevelComponent()->exitModalState (0);
  377. }
  378. void update()
  379. {
  380. getLastText() = userText.getText();
  381. path = Drawable::parseSVGPath (getLastText().trim().unquoted().trim());
  382. String result = "No path generated.. Not a valid SVG path string?";
  383. if (! path.isEmpty())
  384. {
  385. MemoryOutputStream data;
  386. path.writePathToStream (data);
  387. MemoryOutputStream out;
  388. out << "static const unsigned char pathData[] = ";
  389. CodeHelpers::writeDataAsCppLiteral (data.getMemoryBlock(), out, false, true);
  390. out << newLine
  391. << newLine
  392. << "Path path;" << newLine
  393. << "path.loadPathFromData (pathData, sizeof (pathData));" << newLine;
  394. result = out.toString();
  395. }
  396. resultText.setText (result, false);
  397. repaint (previewPathArea);
  398. }
  399. void resized()
  400. {
  401. Rectangle<int> r (getLocalBounds().reduced (8));
  402. desc.setBounds (r.removeFromTop (44));
  403. r.removeFromTop (8);
  404. userText.setBounds (r.removeFromTop (r.getHeight() / 2));
  405. r.removeFromTop (8);
  406. previewPathArea = r.removeFromRight (r.getHeight());
  407. resultText.setBounds (r);
  408. }
  409. void paint (Graphics& g)
  410. {
  411. g.setColour (Colours::white);
  412. g.fillPath (path, path.getTransformToScaleToFit (previewPathArea.reduced (4).toFloat(), true));
  413. }
  414. private:
  415. Label desc;
  416. TextEditor userText, resultText;
  417. Rectangle<int> previewPathArea;
  418. Path path;
  419. String& getLastText()
  420. {
  421. static String t;
  422. return t;
  423. }
  424. };
  425. void showSVGPathDataToolWindow (ScopedPointer<Component>& ownerPointer)
  426. {
  427. if (ownerPointer != nullptr)
  428. ownerPointer->toFront (true);
  429. else
  430. new FloatingToolWindow ("SVG Path Converter",
  431. "svgPathWindowPos",
  432. new SVGPathDataComponent(), ownerPointer,
  433. 500, 500,
  434. 300, 300, 1000, 1000);
  435. }
  436. //==============================================================================
  437. class AsyncCommandRetrier : public Timer
  438. {
  439. public:
  440. AsyncCommandRetrier (const ApplicationCommandTarget::InvocationInfo& inf)
  441. : info (inf)
  442. {
  443. info.originatingComponent = nullptr;
  444. startTimer (500);
  445. }
  446. void timerCallback() override
  447. {
  448. stopTimer();
  449. IntrojucerApp::getCommandManager().invoke (info, true);
  450. delete this;
  451. }
  452. ApplicationCommandTarget::InvocationInfo info;
  453. JUCE_DECLARE_NON_COPYABLE (AsyncCommandRetrier)
  454. };
  455. bool reinvokeCommandAfterCancellingModalComps (const ApplicationCommandTarget::InvocationInfo& info)
  456. {
  457. if (ModalComponentManager::getInstance()->cancelAllModalComponents())
  458. {
  459. new AsyncCommandRetrier (info);
  460. return true;
  461. }
  462. return false;
  463. }