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.

575 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[128] = { 0 };
  215. FileInputStream fin (file);
  216. fin.read (fileStart, sizeof (fileStart) - 4);
  217. return CharPointer_UTF8::isValidString (fileStart, sizeof (fileStart))
  218. && String (fileStart).trimStart().startsWith ("// -*- C++ -*-");
  219. }
  220. //==============================================================================
  221. RolloverHelpComp::RolloverHelpComp()
  222. : lastComp (nullptr)
  223. {
  224. setInterceptsMouseClicks (false, false);
  225. startTimer (150);
  226. }
  227. void RolloverHelpComp::paint (Graphics& g)
  228. {
  229. AttributedString s;
  230. s.setJustification (Justification::centredLeft);
  231. s.append (lastTip, Font (14.0f), findColour (mainBackgroundColourId).contrasting (0.7f));
  232. TextLayout tl;
  233. tl.createLayoutWithBalancedLineLengths (s, getWidth() - 10.0f);
  234. if (tl.getNumLines() > 3)
  235. tl.createLayout (s, getWidth() - 10.0f);
  236. tl.draw (g, getLocalBounds().toFloat());
  237. }
  238. void RolloverHelpComp::timerCallback()
  239. {
  240. Component* newComp = Desktop::getInstance().getMainMouseSource().getComponentUnderMouse();
  241. if (newComp != nullptr
  242. && (newComp->getTopLevelComponent() != getTopLevelComponent()
  243. || newComp->isCurrentlyBlockedByAnotherModalComponent()))
  244. newComp = nullptr;
  245. if (newComp != lastComp)
  246. {
  247. lastComp = newComp;
  248. String newTip (findTip (newComp));
  249. if (newTip != lastTip)
  250. {
  251. lastTip = newTip;
  252. repaint();
  253. }
  254. }
  255. }
  256. String RolloverHelpComp::findTip (Component* c)
  257. {
  258. while (c != nullptr)
  259. {
  260. if (TooltipClient* const tc = dynamic_cast<TooltipClient*> (c))
  261. {
  262. const String tip (tc->getTooltip());
  263. if (tip.isNotEmpty())
  264. return tip;
  265. }
  266. c = c->getParentComponent();
  267. }
  268. return String::empty;
  269. }
  270. //==============================================================================
  271. class UTF8Component : public Component,
  272. private TextEditorListener
  273. {
  274. public:
  275. UTF8Component()
  276. : desc (String::empty,
  277. "Type any string into the box, and it'll be shown below as a portable UTF-8 literal, "
  278. "ready to cut-and-paste into your source-code...")
  279. {
  280. desc.setJustificationType (Justification::centred);
  281. desc.setColour (Label::textColourId, Colours::white);
  282. addAndMakeVisible (desc);
  283. const Colour bkgd (Colours::white.withAlpha (0.6f));
  284. userText.setMultiLine (true, true);
  285. userText.setReturnKeyStartsNewLine (true);
  286. userText.setColour (TextEditor::backgroundColourId, bkgd);
  287. addAndMakeVisible (userText);
  288. userText.addListener (this);
  289. resultText.setFont (getAppSettings().appearance.getCodeFont().withHeight (13.0f));
  290. resultText.setMultiLine (true, true);
  291. resultText.setColour (TextEditor::backgroundColourId, bkgd);
  292. resultText.setReadOnly (true);
  293. resultText.setSelectAllWhenFocused (true);
  294. addAndMakeVisible (resultText);
  295. userText.setText (getLastText());
  296. }
  297. void textEditorTextChanged (TextEditor&)
  298. {
  299. update();
  300. }
  301. void textEditorEscapeKeyPressed (TextEditor&)
  302. {
  303. getTopLevelComponent()->exitModalState (0);
  304. }
  305. void update()
  306. {
  307. getLastText() = userText.getText();
  308. resultText.setText (CodeHelpers::stringLiteral (getLastText(), 100), false);
  309. }
  310. void resized()
  311. {
  312. Rectangle<int> r (getLocalBounds().reduced (8));
  313. desc.setBounds (r.removeFromTop (44));
  314. r.removeFromTop (8);
  315. userText.setBounds (r.removeFromTop (r.getHeight() / 2));
  316. r.removeFromTop (8);
  317. resultText.setBounds (r);
  318. }
  319. private:
  320. Label desc;
  321. TextEditor userText, resultText;
  322. String& getLastText()
  323. {
  324. static String t;
  325. return t;
  326. }
  327. };
  328. void showUTF8ToolWindow (ScopedPointer<Component>& ownerPointer)
  329. {
  330. if (ownerPointer != nullptr)
  331. {
  332. ownerPointer->toFront (true);
  333. }
  334. else
  335. {
  336. new FloatingToolWindow ("UTF-8 String Literal Converter",
  337. "utf8WindowPos",
  338. new UTF8Component(), ownerPointer,
  339. 500, 500,
  340. 300, 300, 1000, 1000);
  341. }
  342. }
  343. //==============================================================================
  344. class SVGPathDataComponent : public Component,
  345. private TextEditorListener
  346. {
  347. public:
  348. SVGPathDataComponent()
  349. : desc (String::empty,
  350. "Paste an SVG path string into the top box, and it'll be converted to some C++ "
  351. "code that will load it as a Path object..")
  352. {
  353. desc.setJustificationType (Justification::centred);
  354. desc.setColour (Label::textColourId, Colours::white);
  355. addAndMakeVisible (desc);
  356. const Colour bkgd (Colours::white.withAlpha (0.6f));
  357. userText.setFont (getAppSettings().appearance.getCodeFont().withHeight (13.0f));
  358. userText.setMultiLine (true, true);
  359. userText.setReturnKeyStartsNewLine (true);
  360. userText.setColour (TextEditor::backgroundColourId, bkgd);
  361. addAndMakeVisible (userText);
  362. userText.addListener (this);
  363. resultText.setFont (getAppSettings().appearance.getCodeFont().withHeight (13.0f));
  364. resultText.setMultiLine (true, true);
  365. resultText.setColour (TextEditor::backgroundColourId, bkgd);
  366. resultText.setReadOnly (true);
  367. resultText.setSelectAllWhenFocused (true);
  368. addAndMakeVisible (resultText);
  369. userText.setText (getLastText());
  370. }
  371. void textEditorTextChanged (TextEditor&)
  372. {
  373. update();
  374. }
  375. void textEditorEscapeKeyPressed (TextEditor&)
  376. {
  377. getTopLevelComponent()->exitModalState (0);
  378. }
  379. void update()
  380. {
  381. getLastText() = userText.getText();
  382. path = Drawable::parseSVGPath (getLastText().trim().unquoted().trim());
  383. String result = "No path generated.. Not a valid SVG path string?";
  384. if (! path.isEmpty())
  385. {
  386. MemoryOutputStream data;
  387. path.writePathToStream (data);
  388. MemoryOutputStream out;
  389. out << "static const unsigned char pathData[] = ";
  390. CodeHelpers::writeDataAsCppLiteral (data.getMemoryBlock(), out, false, true);
  391. out << newLine
  392. << newLine
  393. << "Path path;" << newLine
  394. << "path.loadPathFromData (pathData, sizeof (pathData));" << newLine;
  395. result = out.toString();
  396. }
  397. resultText.setText (result, false);
  398. repaint (previewPathArea);
  399. }
  400. void resized()
  401. {
  402. Rectangle<int> r (getLocalBounds().reduced (8));
  403. desc.setBounds (r.removeFromTop (44));
  404. r.removeFromTop (8);
  405. userText.setBounds (r.removeFromTop (r.getHeight() / 2));
  406. r.removeFromTop (8);
  407. previewPathArea = r.removeFromRight (r.getHeight());
  408. resultText.setBounds (r);
  409. }
  410. void paint (Graphics& g)
  411. {
  412. g.setColour (Colours::white);
  413. g.fillPath (path, path.getTransformToScaleToFit (previewPathArea.reduced (4).toFloat(), true));
  414. }
  415. private:
  416. Label desc;
  417. TextEditor userText, resultText;
  418. Rectangle<int> previewPathArea;
  419. Path path;
  420. String& getLastText()
  421. {
  422. static String t;
  423. return t;
  424. }
  425. };
  426. void showSVGPathDataToolWindow (ScopedPointer<Component>& ownerPointer)
  427. {
  428. if (ownerPointer != nullptr)
  429. ownerPointer->toFront (true);
  430. else
  431. new FloatingToolWindow ("SVG Path Converter",
  432. "svgPathWindowPos",
  433. new SVGPathDataComponent(), ownerPointer,
  434. 500, 500,
  435. 300, 300, 1000, 1000);
  436. }
  437. //==============================================================================
  438. class AsyncCommandRetrier : public Timer
  439. {
  440. public:
  441. AsyncCommandRetrier (const ApplicationCommandTarget::InvocationInfo& inf)
  442. : info (inf)
  443. {
  444. info.originatingComponent = nullptr;
  445. startTimer (500);
  446. }
  447. void timerCallback() override
  448. {
  449. stopTimer();
  450. IntrojucerApp::getCommandManager().invoke (info, true);
  451. delete this;
  452. }
  453. ApplicationCommandTarget::InvocationInfo info;
  454. JUCE_DECLARE_NON_COPYABLE (AsyncCommandRetrier)
  455. };
  456. bool reinvokeCommandAfterCancellingModalComps (const ApplicationCommandTarget::InvocationInfo& info)
  457. {
  458. if (ModalComponentManager::getInstance()->cancelAllModalComponents())
  459. {
  460. new AsyncCommandRetrier (info);
  461. return true;
  462. }
  463. return false;
  464. }