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.

555 lines
16KB

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