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.

529 lines
15KB

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