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.

541 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. return getCleanedStringArray (s);
  129. }
  130. StringArray getCommaOrWhitespaceSeparatedItems (const String& sourceString)
  131. {
  132. StringArray s;
  133. s.addTokens (sourceString, ", \t\r\n", StringRef());
  134. return getCleanedStringArray (s);
  135. }
  136. StringArray getCleanedStringArray (StringArray s)
  137. {
  138. s.trim();
  139. s.removeEmptyStrings();
  140. s.removeDuplicates (false);
  141. return s;
  142. }
  143. void addPlistDictionaryKey (XmlElement* xml, const String& key, const String& value)
  144. {
  145. forEachXmlChildElementWithTagName (*xml, e, "key")
  146. {
  147. if (e->getAllSubText().trim().equalsIgnoreCase (key))
  148. {
  149. if (e->getNextElement() != nullptr && e->getNextElement()->hasTagName ("key"))
  150. {
  151. // try to fix broken plist format..
  152. xml->removeChildElement (e, true);
  153. break;
  154. }
  155. return; // (value already exists)
  156. }
  157. }
  158. xml->createNewChildElement ("key")->addTextElement (key);
  159. xml->createNewChildElement ("string")->addTextElement (value);
  160. }
  161. void addPlistDictionaryKeyBool (XmlElement* xml, const String& key, const bool value)
  162. {
  163. xml->createNewChildElement ("key")->addTextElement (key);
  164. xml->createNewChildElement (value ? "true" : "false");
  165. }
  166. void addPlistDictionaryKeyInt (XmlElement* xml, const String& key, int value)
  167. {
  168. xml->createNewChildElement ("key")->addTextElement (key);
  169. xml->createNewChildElement ("integer")->addTextElement (String (value));
  170. }
  171. //==============================================================================
  172. void autoScrollForMouseEvent (const MouseEvent& e, bool scrollX, bool scrollY)
  173. {
  174. if (Viewport* const viewport = e.eventComponent->findParentComponentOfClass<Viewport>())
  175. {
  176. const MouseEvent e2 (e.getEventRelativeTo (viewport));
  177. viewport->autoScroll (scrollX ? e2.x : 20, scrollY ? e2.y : 20, 8, 16);
  178. }
  179. }
  180. //==============================================================================
  181. int indexOfLineStartingWith (const StringArray& lines, const String& text, int index)
  182. {
  183. const int len = text.length();
  184. for (const String* i = lines.begin() + index, * const e = lines.end(); i < e; ++i)
  185. {
  186. if (CharacterFunctions::compareUpTo (i->getCharPointer().findEndOfWhitespace(),
  187. text.getCharPointer(), len) == 0)
  188. return index;
  189. ++index;
  190. }
  191. return -1;
  192. }
  193. //==============================================================================
  194. RolloverHelpComp::RolloverHelpComp()
  195. : lastComp (nullptr)
  196. {
  197. setInterceptsMouseClicks (false, false);
  198. startTimer (150);
  199. }
  200. void RolloverHelpComp::paint (Graphics& g)
  201. {
  202. AttributedString s;
  203. s.setJustification (Justification::centredLeft);
  204. s.append (lastTip, Font (14.0f), findColour (mainBackgroundColourId).contrasting (0.7f));
  205. TextLayout tl;
  206. tl.createLayoutWithBalancedLineLengths (s, getWidth() - 10.0f);
  207. if (tl.getNumLines() > 3)
  208. tl.createLayout (s, getWidth() - 10.0f);
  209. tl.draw (g, getLocalBounds().toFloat());
  210. }
  211. void RolloverHelpComp::timerCallback()
  212. {
  213. Component* newComp = Desktop::getInstance().getMainMouseSource().getComponentUnderMouse();
  214. if (newComp != nullptr
  215. && (newComp->getTopLevelComponent() != getTopLevelComponent()
  216. || newComp->isCurrentlyBlockedByAnotherModalComponent()))
  217. newComp = nullptr;
  218. if (newComp != lastComp)
  219. {
  220. lastComp = newComp;
  221. String newTip (findTip (newComp));
  222. if (newTip != lastTip)
  223. {
  224. lastTip = newTip;
  225. repaint();
  226. }
  227. }
  228. }
  229. String RolloverHelpComp::findTip (Component* c)
  230. {
  231. while (c != nullptr)
  232. {
  233. if (TooltipClient* const tc = dynamic_cast <TooltipClient*> (c))
  234. {
  235. const String tip (tc->getTooltip());
  236. if (tip.isNotEmpty())
  237. return tip;
  238. }
  239. c = c->getParentComponent();
  240. }
  241. return String::empty;
  242. }
  243. //==============================================================================
  244. class UTF8Component : public Component,
  245. private TextEditorListener
  246. {
  247. public:
  248. UTF8Component()
  249. : desc (String::empty,
  250. "Type any string into the box, and it'll be shown below as a portable UTF-8 literal, "
  251. "ready to cut-and-paste into your source-code...")
  252. {
  253. desc.setJustificationType (Justification::centred);
  254. desc.setColour (Label::textColourId, Colours::white);
  255. addAndMakeVisible (desc);
  256. const Colour bkgd (Colours::white.withAlpha (0.6f));
  257. userText.setMultiLine (true, true);
  258. userText.setReturnKeyStartsNewLine (true);
  259. userText.setColour (TextEditor::backgroundColourId, bkgd);
  260. addAndMakeVisible (userText);
  261. userText.addListener (this);
  262. resultText.setFont (getAppSettings().appearance.getCodeFont().withHeight (13.0f));
  263. resultText.setMultiLine (true, true);
  264. resultText.setColour (TextEditor::backgroundColourId, bkgd);
  265. resultText.setReadOnly (true);
  266. resultText.setSelectAllWhenFocused (true);
  267. addAndMakeVisible (resultText);
  268. userText.setText (getLastText());
  269. }
  270. void textEditorTextChanged (TextEditor&)
  271. {
  272. update();
  273. }
  274. void textEditorEscapeKeyPressed (TextEditor&)
  275. {
  276. getTopLevelComponent()->exitModalState (0);
  277. }
  278. void update()
  279. {
  280. getLastText() = userText.getText();
  281. resultText.setText (CodeHelpers::stringLiteral (getLastText(), 100), false);
  282. }
  283. void resized()
  284. {
  285. Rectangle<int> r (getLocalBounds().reduced (8));
  286. desc.setBounds (r.removeFromTop (44));
  287. r.removeFromTop (8);
  288. userText.setBounds (r.removeFromTop (r.getHeight() / 2));
  289. r.removeFromTop (8);
  290. resultText.setBounds (r);
  291. }
  292. private:
  293. Label desc;
  294. TextEditor userText, resultText;
  295. String& getLastText()
  296. {
  297. static String t;
  298. return t;
  299. }
  300. };
  301. void showUTF8ToolWindow (ScopedPointer<Component>& ownerPointer)
  302. {
  303. if (ownerPointer != nullptr)
  304. {
  305. ownerPointer->toFront (true);
  306. }
  307. else
  308. {
  309. new FloatingToolWindow ("UTF-8 String Literal Converter",
  310. "utf8WindowPos",
  311. new UTF8Component(), ownerPointer,
  312. 500, 500,
  313. 300, 300, 1000, 1000);
  314. }
  315. }
  316. //==============================================================================
  317. class SVGPathDataComponent : public Component,
  318. private TextEditorListener
  319. {
  320. public:
  321. SVGPathDataComponent()
  322. : desc (String::empty,
  323. "Paste an SVG path string into the top box, and it'll be converted to some C++ "
  324. "code that will load it as a Path object..")
  325. {
  326. desc.setJustificationType (Justification::centred);
  327. desc.setColour (Label::textColourId, Colours::white);
  328. addAndMakeVisible (desc);
  329. const Colour bkgd (Colours::white.withAlpha (0.6f));
  330. userText.setFont (getAppSettings().appearance.getCodeFont().withHeight (13.0f));
  331. userText.setMultiLine (true, true);
  332. userText.setReturnKeyStartsNewLine (true);
  333. userText.setColour (TextEditor::backgroundColourId, bkgd);
  334. addAndMakeVisible (userText);
  335. userText.addListener (this);
  336. resultText.setFont (getAppSettings().appearance.getCodeFont().withHeight (13.0f));
  337. resultText.setMultiLine (true, true);
  338. resultText.setColour (TextEditor::backgroundColourId, bkgd);
  339. resultText.setReadOnly (true);
  340. resultText.setSelectAllWhenFocused (true);
  341. addAndMakeVisible (resultText);
  342. userText.setText (getLastText());
  343. }
  344. void textEditorTextChanged (TextEditor&)
  345. {
  346. update();
  347. }
  348. void textEditorEscapeKeyPressed (TextEditor&)
  349. {
  350. getTopLevelComponent()->exitModalState (0);
  351. }
  352. void update()
  353. {
  354. getLastText() = userText.getText();
  355. path = Drawable::parseSVGPath (getLastText().trim().unquoted().trim());
  356. String result = "No path generated.. Not a valid SVG path string?";
  357. if (! path.isEmpty())
  358. {
  359. MemoryOutputStream data;
  360. path.writePathToStream (data);
  361. MemoryOutputStream out;
  362. out << "static const unsigned char pathData[] = ";
  363. CodeHelpers::writeDataAsCppLiteral (data.getMemoryBlock(), out, false, true);
  364. out << newLine
  365. << newLine
  366. << "Path path;" << newLine
  367. << "path.loadPathFromData (pathData, sizeof (pathData));" << newLine;
  368. result = out.toString();
  369. }
  370. resultText.setText (result, false);
  371. repaint (previewPathArea);
  372. }
  373. void resized()
  374. {
  375. Rectangle<int> r (getLocalBounds().reduced (8));
  376. desc.setBounds (r.removeFromTop (44));
  377. r.removeFromTop (8);
  378. userText.setBounds (r.removeFromTop (r.getHeight() / 2));
  379. r.removeFromTop (8);
  380. previewPathArea = r.removeFromRight (r.getHeight());
  381. resultText.setBounds (r);
  382. }
  383. void paint (Graphics& g)
  384. {
  385. g.setColour (Colours::white);
  386. g.fillPath (path, path.getTransformToScaleToFit (previewPathArea.reduced (4).toFloat(), true));
  387. }
  388. private:
  389. Label desc;
  390. TextEditor userText, resultText;
  391. Rectangle<int> previewPathArea;
  392. Path path;
  393. String& getLastText()
  394. {
  395. static String t;
  396. return t;
  397. }
  398. };
  399. void showSVGPathDataToolWindow (ScopedPointer<Component>& ownerPointer)
  400. {
  401. if (ownerPointer != nullptr)
  402. ownerPointer->toFront (true);
  403. else
  404. new FloatingToolWindow ("SVG Path Converter",
  405. "svgPathWindowPos",
  406. new SVGPathDataComponent(), ownerPointer,
  407. 500, 500,
  408. 300, 300, 1000, 1000);
  409. }
  410. //==============================================================================
  411. class AsyncCommandRetrier : public Timer
  412. {
  413. public:
  414. AsyncCommandRetrier (const ApplicationCommandTarget::InvocationInfo& inf)
  415. : info (inf)
  416. {
  417. info.originatingComponent = nullptr;
  418. startTimer (500);
  419. }
  420. void timerCallback() override
  421. {
  422. stopTimer();
  423. IntrojucerApp::getCommandManager().invoke (info, true);
  424. delete this;
  425. }
  426. ApplicationCommandTarget::InvocationInfo info;
  427. JUCE_DECLARE_NON_COPYABLE (AsyncCommandRetrier)
  428. };
  429. bool reinvokeCommandAfterCancellingModalComps (const ApplicationCommandTarget::InvocationInfo& info)
  430. {
  431. if (ModalComponentManager::getInstance()->cancelAllModalComponents())
  432. {
  433. new AsyncCommandRetrier (info);
  434. return true;
  435. }
  436. return false;
  437. }