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.

491 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. static Image createTexturisedBackgroundTile()
  155. {
  156. const Colour bkg (LookAndFeel::getDefaultLookAndFeel().findColour (mainBackgroundColourId));
  157. const int64 hash = bkg.getARGB() + 0x3474572a;
  158. Image tile (ImageCache::getFromHashCode (hash));
  159. if (tile.isNull())
  160. {
  161. const Image original (ImageCache::getFromMemory (BinaryData::brushed_aluminium_png,
  162. BinaryData::brushed_aluminium_pngSize));
  163. tile = Image (Image::RGB, original.getWidth(), original.getHeight(), false);
  164. for (int y = 0; y < tile.getHeight(); ++y)
  165. {
  166. for (int x = 0; x < tile.getWidth(); ++x)
  167. {
  168. const float b = original.getPixelAt (x, y).getBrightness();
  169. tile.setPixelAt (x, y, bkg.withMultipliedBrightness (b + 0.4f));
  170. }
  171. }
  172. ImageCache::addImageToCache (tile, hash);
  173. }
  174. return tile;
  175. }
  176. void drawTexturedBackground (Graphics& g)
  177. {
  178. g.setTiledImageFill (createTexturisedBackgroundTile(), 0, 0, 1.0f);
  179. g.fillAll();
  180. }
  181. //==============================================================================
  182. int indexOfLineStartingWith (const StringArray& lines, const String& text, int startIndex)
  183. {
  184. startIndex = jmax (0, startIndex);
  185. while (startIndex < lines.size())
  186. {
  187. if (lines[startIndex].trimStart().startsWithIgnoreCase (text))
  188. return startIndex;
  189. ++startIndex;
  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. TooltipClient* const tc = dynamic_cast <TooltipClient*> (c);
  234. if (tc != nullptr)
  235. {
  236. const String tip (tc->getTooltip());
  237. if (tip.isNotEmpty())
  238. return tip;
  239. }
  240. c = c->getParentComponent();
  241. }
  242. return String::empty;
  243. }
  244. //==============================================================================
  245. FloatingLabelComponent::FloatingLabelComponent()
  246. : font (10.0f)
  247. {
  248. setInterceptsMouseClicks (false, false);
  249. }
  250. void FloatingLabelComponent::remove()
  251. {
  252. if (getParentComponent() != nullptr)
  253. getParentComponent()->removeChildComponent (this);
  254. }
  255. void FloatingLabelComponent::update (Component* parent, const String& text, const Colour& textColour, int x, int y, bool toRight, bool below)
  256. {
  257. colour = textColour;
  258. Rectangle<int> r;
  259. if (text != getName())
  260. {
  261. setName (text);
  262. glyphs.clear();
  263. glyphs.addJustifiedText (font, text, 0, 0, 200.0f, Justification::left);
  264. glyphs.justifyGlyphs (0, std::numeric_limits<int>::max(), 0, 0, 1000, 1000, Justification::topLeft);
  265. r = glyphs.getBoundingBox (0, std::numeric_limits<int>::max(), false)
  266. .getSmallestIntegerContainer().expanded (1, 1);
  267. }
  268. else
  269. {
  270. r = getLocalBounds();
  271. }
  272. r.setPosition (x + (toRight ? 3 : -(r.getWidth() + 3)), y + (below ? 2 : -(r.getHeight() + 2)));
  273. setBounds (r);
  274. parent->addAndMakeVisible (this);
  275. }
  276. void FloatingLabelComponent::paint (Graphics& g)
  277. {
  278. g.setFont (font);
  279. g.setColour (Colours::white.withAlpha (0.5f));
  280. g.fillRoundedRectangle (0, 0, (float) getWidth(), (float) getHeight(), 3);
  281. g.setColour (colour);
  282. glyphs.draw (g, AffineTransform::translation (1.0f, 1.0f));
  283. }
  284. //==============================================================================
  285. class UTF8Component : public Component,
  286. private TextEditorListener
  287. {
  288. public:
  289. UTF8Component()
  290. : desc (String::empty,
  291. "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...")
  292. {
  293. desc.setJustificationType (Justification::centred);
  294. desc.setColour (Label::textColourId, Colours::white);
  295. addAndMakeVisible (&desc);
  296. const Colour bkgd (Colours::white.withAlpha (0.6f));
  297. userText.setMultiLine (true, true);
  298. userText.setReturnKeyStartsNewLine (true);
  299. userText.setColour (TextEditor::backgroundColourId, bkgd);
  300. addAndMakeVisible (&userText);
  301. userText.addListener (this);
  302. resultText.setMultiLine (true, true);
  303. resultText.setColour (TextEditor::backgroundColourId, bkgd);
  304. resultText.setReadOnly (true);
  305. resultText.setSelectAllWhenFocused (true);
  306. addAndMakeVisible (&resultText);
  307. userText.setText (getLastText());
  308. }
  309. void textEditorTextChanged (TextEditor&)
  310. {
  311. update();
  312. }
  313. void textEditorEscapeKeyPressed (TextEditor&)
  314. {
  315. getTopLevelComponent()->exitModalState (0);
  316. }
  317. void update()
  318. {
  319. getLastText() = userText.getText();
  320. resultText.setText (CodeHelpers::stringLiteral (getLastText()), false);
  321. }
  322. void resized()
  323. {
  324. desc.setBounds (8, 8, getWidth() - 16, 44);
  325. userText.setBounds (desc.getX(), desc.getBottom() + 8, getWidth() - 16, getHeight() / 2 - desc.getBottom() - 8);
  326. resultText.setBounds (desc.getX(), userText.getBottom() + 4, getWidth() - 16, getHeight() - userText.getBottom() - 12);
  327. }
  328. private:
  329. Label desc;
  330. TextEditor userText, resultText;
  331. String& getLastText()
  332. {
  333. static String t;
  334. return t;
  335. }
  336. };
  337. void showUTF8ToolWindow (ScopedPointer<Component>& ownerPointer)
  338. {
  339. if (ownerPointer != nullptr)
  340. {
  341. ownerPointer->toFront (true);
  342. }
  343. else
  344. {
  345. new FloatingToolWindow ("UTF-8 String Literal Converter",
  346. "utf8WindowPos",
  347. new UTF8Component(), ownerPointer,
  348. 400, 300,
  349. 300, 300, 1000, 1000);
  350. }
  351. }
  352. bool cancelAnyModalComponents()
  353. {
  354. const int numModal = ModalComponentManager::getInstance()->getNumModalComponents();
  355. for (int i = numModal; --i >= 0;)
  356. if (ModalComponentManager::getInstance()->getModalComponent(i) != nullptr)
  357. ModalComponentManager::getInstance()->getModalComponent(i)->exitModalState (0);
  358. return numModal > 0;
  359. }
  360. //==============================================================================
  361. class AsyncCommandRetrier : public Timer
  362. {
  363. public:
  364. AsyncCommandRetrier (const ApplicationCommandTarget::InvocationInfo& info_)
  365. : info (info_)
  366. {
  367. info.originatingComponent = nullptr;
  368. startTimer (500);
  369. }
  370. void timerCallback()
  371. {
  372. stopTimer();
  373. commandManager->invoke (info, true);
  374. delete this;
  375. }
  376. ApplicationCommandTarget::InvocationInfo info;
  377. JUCE_DECLARE_NON_COPYABLE (AsyncCommandRetrier);
  378. };
  379. bool reinvokeCommandAfterCancellingModalComps (const ApplicationCommandTarget::InvocationInfo& info)
  380. {
  381. if (cancelAnyModalComponents())
  382. {
  383. new AsyncCommandRetrier (info);
  384. return true;
  385. }
  386. return false;
  387. }