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.

490 lines
14KB

  1. /*
  2. ==============================================================================
  3. This file is part of the JUCE library - "Jules' Utility Class Extensions"
  4. Copyright 2004-11 by Raw Material Software Ltd.
  5. ------------------------------------------------------------------------------
  6. JUCE can be redistributed and/or modified under the terms of the GNU General
  7. Public License (Version 2), as published by the Free Software Foundation.
  8. A copy of the license is included in the JUCE distribution, or can be found
  9. online at www.gnu.org/licenses.
  10. JUCE is distributed in the hope that it will be useful, but WITHOUT ANY
  11. WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
  12. A PARTICULAR PURPOSE. See the GNU General Public License for more details.
  13. ------------------------------------------------------------------------------
  14. To release a closed-source product which uses JUCE, commercial licenses are
  15. available: visit www.rawmaterialsoftware.com/juce for more information.
  16. ==============================================================================
  17. */
  18. #include "../jucer_Headers.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", String::empty);
  128. s.trim();
  129. s.removeEmptyStrings();
  130. s.removeDuplicates (false);
  131. return s;
  132. }
  133. //==============================================================================
  134. void autoScrollForMouseEvent (const MouseEvent& e, bool scrollX, bool scrollY)
  135. {
  136. Viewport* const viewport = e.eventComponent->findParentComponentOfClass<Viewport>();
  137. if (viewport != nullptr)
  138. {
  139. const MouseEvent e2 (e.getEventRelativeTo (viewport));
  140. viewport->autoScroll (scrollX ? e2.x : 20, scrollY ? e2.y : 20, 8, 16);
  141. }
  142. }
  143. void drawComponentPlaceholder (Graphics& g, int w, int h, const String& text)
  144. {
  145. g.fillAll (Colours::white.withAlpha (0.4f));
  146. g.setColour (Colours::grey);
  147. g.drawRect (0, 0, w, h);
  148. g.drawLine (0.5f, 0.5f, w - 0.5f, h - 0.5f);
  149. g.drawLine (0.5f, h - 0.5f, w - 0.5f, 0.5f);
  150. g.setColour (Colours::black);
  151. g.setFont (11.0f);
  152. g.drawFittedText (text, 2, 2, w - 4, h - 4, Justification::centredTop, 2);
  153. }
  154. void drawRecessedShadows (Graphics& g, int w, int h, int shadowSize)
  155. {
  156. ColourGradient cg (Colours::black.withAlpha (0.15f), 0, 0,
  157. Colours::transparentBlack, 0, (float) shadowSize, false);
  158. cg.addColour (0.4, Colours::black.withAlpha (0.07f));
  159. cg.addColour (0.6, Colours::black.withAlpha (0.02f));
  160. g.setGradientFill (cg);
  161. g.fillRect (0, 0, w, shadowSize);
  162. cg.point1.setXY (0.0f, (float) h);
  163. cg.point2.setXY (0.0f, (float) h - shadowSize);
  164. g.setGradientFill (cg);
  165. g.fillRect (0, h - shadowSize, w, shadowSize);
  166. cg.point1.setXY (0.0f, 0.0f);
  167. cg.point2.setXY ((float) shadowSize, 0.0f);
  168. g.setGradientFill (cg);
  169. g.fillRect (0, 0, shadowSize, h);
  170. cg.point1.setXY ((float) w, 0.0f);
  171. cg.point2.setXY ((float) w - shadowSize, 0.0f);
  172. g.setGradientFill (cg);
  173. g.fillRect (w - shadowSize, 0, shadowSize, h);
  174. }
  175. //==============================================================================
  176. int indexOfLineStartingWith (const StringArray& lines, const String& text, int startIndex)
  177. {
  178. startIndex = jmax (0, startIndex);
  179. while (startIndex < lines.size())
  180. {
  181. if (lines[startIndex].trimStart().startsWithIgnoreCase (text))
  182. return startIndex;
  183. ++startIndex;
  184. }
  185. return -1;
  186. }
  187. //==============================================================================
  188. RolloverHelpComp::RolloverHelpComp()
  189. : lastComp (nullptr)
  190. {
  191. setInterceptsMouseClicks (false, false);
  192. startTimer (150);
  193. }
  194. void RolloverHelpComp::paint (Graphics& g)
  195. {
  196. AttributedString s;
  197. s.setJustification (Justification::centredLeft);
  198. s.append (lastTip, Font (14.0f), Colour::greyLevel (0.15f));
  199. TextLayout tl;
  200. tl.createLayoutWithBalancedLineLengths (s, getWidth() - 10.0f);
  201. if (tl.getNumLines() > 3)
  202. tl.createLayout (s, getWidth() - 10.0f);
  203. tl.draw (g, getLocalBounds().toFloat());
  204. }
  205. void RolloverHelpComp::timerCallback()
  206. {
  207. Component* newComp = Desktop::getInstance().getMainMouseSource().getComponentUnderMouse();
  208. if (newComp != nullptr
  209. && (newComp->getTopLevelComponent() != getTopLevelComponent()
  210. || newComp->isCurrentlyBlockedByAnotherModalComponent()))
  211. newComp = nullptr;
  212. if (newComp != lastComp)
  213. {
  214. lastComp = newComp;
  215. String newTip (findTip (newComp));
  216. if (newTip != lastTip)
  217. {
  218. lastTip = newTip;
  219. repaint();
  220. }
  221. }
  222. }
  223. String RolloverHelpComp::findTip (Component* c)
  224. {
  225. while (c != nullptr)
  226. {
  227. TooltipClient* const tc = dynamic_cast <TooltipClient*> (c);
  228. if (tc != nullptr)
  229. {
  230. const String tip (tc->getTooltip());
  231. if (tip.isNotEmpty())
  232. return tip;
  233. }
  234. c = c->getParentComponent();
  235. }
  236. return String::empty;
  237. }
  238. //==============================================================================
  239. FloatingLabelComponent::FloatingLabelComponent()
  240. : font (10.0f)
  241. {
  242. setInterceptsMouseClicks (false, false);
  243. }
  244. void FloatingLabelComponent::remove()
  245. {
  246. if (getParentComponent() != nullptr)
  247. getParentComponent()->removeChildComponent (this);
  248. }
  249. void FloatingLabelComponent::update (Component* parent, const String& text, const Colour& textColour, int x, int y, bool toRight, bool below)
  250. {
  251. colour = textColour;
  252. Rectangle<int> r;
  253. if (text != getName())
  254. {
  255. setName (text);
  256. glyphs.clear();
  257. glyphs.addJustifiedText (font, text, 0, 0, 200.0f, Justification::left);
  258. glyphs.justifyGlyphs (0, std::numeric_limits<int>::max(), 0, 0, 1000, 1000, Justification::topLeft);
  259. r = glyphs.getBoundingBox (0, std::numeric_limits<int>::max(), false)
  260. .getSmallestIntegerContainer().expanded (1, 1);
  261. }
  262. else
  263. {
  264. r = getLocalBounds();
  265. }
  266. r.setPosition (x + (toRight ? 3 : -(r.getWidth() + 3)), y + (below ? 2 : -(r.getHeight() + 2)));
  267. setBounds (r);
  268. parent->addAndMakeVisible (this);
  269. }
  270. void FloatingLabelComponent::paint (Graphics& g)
  271. {
  272. g.setFont (font);
  273. g.setColour (Colours::white.withAlpha (0.5f));
  274. g.fillRoundedRectangle (0, 0, (float) getWidth(), (float) getHeight(), 3);
  275. g.setColour (colour);
  276. glyphs.draw (g, AffineTransform::translation (1.0f, 1.0f));
  277. }
  278. //==============================================================================
  279. class UTF8Component : public Component,
  280. private TextEditorListener
  281. {
  282. public:
  283. UTF8Component()
  284. : desc (String::empty,
  285. "Type any string into the box, and it'll be shown below as a portable UTF-8 literal, ready to cut-and-paste into your source-code...")
  286. {
  287. setSize (400, 300);
  288. desc.setBounds ("8, 8, parent.width - 8, 55");
  289. desc.setJustificationType (Justification::centred);
  290. addAndMakeVisible (&desc);
  291. userText.setMultiLine (true, true);
  292. userText.setBounds ("8, 60, parent.width - 8, parent.height / 2 - 4");
  293. addAndMakeVisible (&userText);
  294. userText.addListener (this);
  295. resultText.setMultiLine (true, true);
  296. resultText.setReadOnly (true);
  297. resultText.setBounds ("8, parent.height / 2 + 4, parent.width - 8, parent.height - 8");
  298. addAndMakeVisible (&resultText);
  299. userText.setText (getLastText());
  300. }
  301. void textEditorTextChanged (TextEditor&)
  302. {
  303. update();
  304. }
  305. void textEditorEscapeKeyPressed (TextEditor&)
  306. {
  307. getTopLevelComponent()->exitModalState (0);
  308. }
  309. void update()
  310. {
  311. getLastText() = userText.getText();
  312. resultText.setText (CodeHelpers::stringLiteral (getLastText()), false);
  313. }
  314. private:
  315. Label desc;
  316. TextEditor userText, resultText;
  317. String& getLastText()
  318. {
  319. static String t;
  320. return t;
  321. }
  322. };
  323. void showUTF8ToolWindow()
  324. {
  325. UTF8Component comp;
  326. DialogWindow::showModalDialog ("UTF-8 String Literal Converter", &comp,
  327. nullptr, Colours::white, true, true);
  328. }
  329. bool cancelAnyModalComponents()
  330. {
  331. const int numModal = ModalComponentManager::getInstance()->getNumModalComponents();
  332. for (int i = numModal; --i >= 0;)
  333. if (ModalComponentManager::getInstance()->getModalComponent(i) != nullptr)
  334. ModalComponentManager::getInstance()->getModalComponent(i)->exitModalState (0);
  335. return numModal > 0;
  336. }
  337. //==============================================================================
  338. class AsyncCommandRetrier : public Timer
  339. {
  340. public:
  341. AsyncCommandRetrier (const ApplicationCommandTarget::InvocationInfo& info_)
  342. : info (info_)
  343. {
  344. info.originatingComponent = nullptr;
  345. startTimer (500);
  346. }
  347. void timerCallback()
  348. {
  349. stopTimer();
  350. commandManager->invoke (info, true);
  351. delete this;
  352. }
  353. ApplicationCommandTarget::InvocationInfo info;
  354. JUCE_DECLARE_NON_COPYABLE (AsyncCommandRetrier);
  355. };
  356. bool reinvokeCommandAfterCancellingModalComps (const ApplicationCommandTarget::InvocationInfo& info)
  357. {
  358. if (cancelAnyModalComponents())
  359. {
  360. new AsyncCommandRetrier (info);
  361. return true;
  362. }
  363. return false;
  364. }
  365. //==============================================================================
  366. class CallOutBoxCallback : public ModalComponentManager::Callback
  367. {
  368. public:
  369. CallOutBoxCallback (Component& attachTo, Component* content_)
  370. : content (content_),
  371. callout (*content_, attachTo, attachTo.getTopLevelComponent())
  372. {
  373. callout.setVisible (true);
  374. callout.enterModalState (true, this);
  375. }
  376. void modalStateFinished (int) {}
  377. private:
  378. ScopedPointer<Component> content;
  379. CallOutBox callout;
  380. JUCE_DECLARE_NON_COPYABLE (CallOutBoxCallback);
  381. };
  382. void launchAsyncCallOutBox (Component& attachTo, Component* content)
  383. {
  384. new CallOutBoxCallback (attachTo, content);
  385. }