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.

539 lines
16KB

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