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.

477 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. 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. else
  146. {
  147. return; // (value already exists)
  148. }
  149. }
  150. }
  151. xml->createNewChildElement ("key") ->addTextElement (key);
  152. xml->createNewChildElement ("string")->addTextElement (value);
  153. }
  154. void addPlistDictionaryKeyBool (XmlElement* xml, const String& key, const bool value)
  155. {
  156. xml->createNewChildElement ("key")->addTextElement (key);
  157. xml->createNewChildElement (value ? "true" : "false");
  158. }
  159. void addPlistDictionaryKeyInt (XmlElement* xml, const String& key, int value)
  160. {
  161. xml->createNewChildElement ("key")->addTextElement (key);
  162. xml->createNewChildElement ("integer")->addTextElement (String (value));
  163. }
  164. //==============================================================================
  165. void autoScrollForMouseEvent (const MouseEvent& e, bool scrollX, bool scrollY)
  166. {
  167. if (Viewport* const viewport = e.eventComponent->findParentComponentOfClass<Viewport>())
  168. {
  169. const MouseEvent e2 (e.getEventRelativeTo (viewport));
  170. viewport->autoScroll (scrollX ? e2.x : 20, scrollY ? e2.y : 20, 8, 16);
  171. }
  172. }
  173. //==============================================================================
  174. int indexOfLineStartingWith (const StringArray& lines, const String& text, int index)
  175. {
  176. const int len = text.length();
  177. for (const String* i = lines.begin() + index, * const e = lines.end(); i < e; ++i)
  178. {
  179. if (CharacterFunctions::compareUpTo (i->getCharPointer().findEndOfWhitespace(),
  180. text.getCharPointer(), len) == 0)
  181. return index;
  182. ++index;
  183. }
  184. return -1;
  185. }
  186. //==============================================================================
  187. RolloverHelpComp::RolloverHelpComp()
  188. : lastComp (nullptr)
  189. {
  190. setInterceptsMouseClicks (false, false);
  191. startTimer (150);
  192. }
  193. void RolloverHelpComp::paint (Graphics& g)
  194. {
  195. AttributedString s;
  196. s.setJustification (Justification::centredLeft);
  197. s.append (lastTip, Font (14.0f), findColour (mainBackgroundColourId).contrasting (0.7f));
  198. TextLayout tl;
  199. tl.createLayoutWithBalancedLineLengths (s, getWidth() - 10.0f);
  200. if (tl.getNumLines() > 3)
  201. tl.createLayout (s, getWidth() - 10.0f);
  202. tl.draw (g, getLocalBounds().toFloat());
  203. }
  204. void RolloverHelpComp::timerCallback()
  205. {
  206. Component* newComp = Desktop::getInstance().getMainMouseSource().getComponentUnderMouse();
  207. if (newComp != nullptr
  208. && (newComp->getTopLevelComponent() != getTopLevelComponent()
  209. || newComp->isCurrentlyBlockedByAnotherModalComponent()))
  210. newComp = nullptr;
  211. if (newComp != lastComp)
  212. {
  213. lastComp = newComp;
  214. String newTip (findTip (newComp));
  215. if (newTip != lastTip)
  216. {
  217. lastTip = newTip;
  218. repaint();
  219. }
  220. }
  221. }
  222. String RolloverHelpComp::findTip (Component* c)
  223. {
  224. while (c != nullptr)
  225. {
  226. if (TooltipClient* const tc = dynamic_cast <TooltipClient*> (c))
  227. {
  228. const String tip (tc->getTooltip());
  229. if (tip.isNotEmpty())
  230. return tip;
  231. }
  232. c = c->getParentComponent();
  233. }
  234. return String::empty;
  235. }
  236. //==============================================================================
  237. FloatingLabelComponent::FloatingLabelComponent()
  238. : font (10.0f)
  239. {
  240. setInterceptsMouseClicks (false, false);
  241. }
  242. void FloatingLabelComponent::remove()
  243. {
  244. if (Component* p = getParentComponent())
  245. p->removeChildComponent (this);
  246. }
  247. void FloatingLabelComponent::update (Component* parent, const String& text, const Colour& textColour,
  248. int x, int y, bool toRight, bool below)
  249. {
  250. colour = textColour;
  251. Rectangle<int> r;
  252. if (text != getName())
  253. {
  254. setName (text);
  255. glyphs.clear();
  256. glyphs.addJustifiedText (font, text, 0, 0, 200.0f, Justification::left);
  257. glyphs.justifyGlyphs (0, std::numeric_limits<int>::max(), 0, 0, 1000, 1000, Justification::topLeft);
  258. r = glyphs.getBoundingBox (0, std::numeric_limits<int>::max(), false)
  259. .getSmallestIntegerContainer().expanded (1, 1);
  260. }
  261. else
  262. {
  263. r = getLocalBounds();
  264. }
  265. r.setPosition (x + (toRight ? 3 : -(r.getWidth() + 3)), y + (below ? 2 : -(r.getHeight() + 2)));
  266. setBounds (r);
  267. parent->addAndMakeVisible (this);
  268. }
  269. void FloatingLabelComponent::paint (Graphics& g)
  270. {
  271. g.setFont (font);
  272. g.setColour (Colours::white.withAlpha (0.5f));
  273. g.fillRoundedRectangle (0, 0, (float) getWidth(), (float) getHeight(), 3);
  274. g.setColour (colour);
  275. glyphs.draw (g, AffineTransform::translation (1.0f, 1.0f));
  276. }
  277. //==============================================================================
  278. class UTF8Component : public Component,
  279. private TextEditorListener
  280. {
  281. public:
  282. UTF8Component()
  283. : desc (String::empty,
  284. "Type any string into the box, and it'll be shown below as a portable UTF-8 literal, "
  285. "ready to cut-and-paste into your source-code...")
  286. {
  287. desc.setJustificationType (Justification::centred);
  288. desc.setColour (Label::textColourId, Colours::white);
  289. addAndMakeVisible (&desc);
  290. const Colour bkgd (Colours::white.withAlpha (0.6f));
  291. userText.setMultiLine (true, true);
  292. userText.setReturnKeyStartsNewLine (true);
  293. userText.setColour (TextEditor::backgroundColourId, bkgd);
  294. addAndMakeVisible (&userText);
  295. userText.addListener (this);
  296. resultText.setMultiLine (true, true);
  297. resultText.setColour (TextEditor::backgroundColourId, bkgd);
  298. resultText.setReadOnly (true);
  299. resultText.setSelectAllWhenFocused (true);
  300. addAndMakeVisible (&resultText);
  301. userText.setText (getLastText());
  302. }
  303. void textEditorTextChanged (TextEditor&)
  304. {
  305. update();
  306. }
  307. void textEditorEscapeKeyPressed (TextEditor&)
  308. {
  309. getTopLevelComponent()->exitModalState (0);
  310. }
  311. void update()
  312. {
  313. getLastText() = userText.getText();
  314. resultText.setText (CodeHelpers::stringLiteral (getLastText(), 100), false);
  315. }
  316. void resized()
  317. {
  318. desc.setBounds (8, 8, getWidth() - 16, 44);
  319. userText.setBounds (desc.getX(), desc.getBottom() + 8, getWidth() - 16, getHeight() / 2 - desc.getBottom() - 8);
  320. resultText.setBounds (desc.getX(), userText.getBottom() + 4, getWidth() - 16, getHeight() - userText.getBottom() - 12);
  321. }
  322. private:
  323. Label desc;
  324. TextEditor userText, resultText;
  325. String& getLastText()
  326. {
  327. static String t;
  328. return t;
  329. }
  330. };
  331. void showUTF8ToolWindow (ScopedPointer<Component>& ownerPointer)
  332. {
  333. if (ownerPointer != nullptr)
  334. {
  335. ownerPointer->toFront (true);
  336. }
  337. else
  338. {
  339. new FloatingToolWindow ("UTF-8 String Literal Converter",
  340. "utf8WindowPos",
  341. new UTF8Component(), ownerPointer,
  342. 400, 300,
  343. 300, 300, 1000, 1000);
  344. }
  345. }
  346. //==============================================================================
  347. bool cancelAnyModalComponents()
  348. {
  349. ModalComponentManager& mm = *ModalComponentManager::getInstance();
  350. const int numModal = mm.getNumModalComponents();
  351. for (int i = numModal; --i >= 0;)
  352. if (Component* c = mm.getModalComponent(i))
  353. c->exitModalState (0);
  354. return numModal > 0;
  355. }
  356. class AsyncCommandRetrier : public Timer
  357. {
  358. public:
  359. AsyncCommandRetrier (const ApplicationCommandTarget::InvocationInfo& inf)
  360. : info (inf)
  361. {
  362. info.originatingComponent = nullptr;
  363. startTimer (500);
  364. }
  365. void timerCallback()
  366. {
  367. stopTimer();
  368. commandManager->invoke (info, true);
  369. delete this;
  370. }
  371. ApplicationCommandTarget::InvocationInfo info;
  372. JUCE_DECLARE_NON_COPYABLE (AsyncCommandRetrier)
  373. };
  374. bool reinvokeCommandAfterCancellingModalComps (const ApplicationCommandTarget::InvocationInfo& info)
  375. {
  376. if (cancelAnyModalComponents())
  377. {
  378. new AsyncCommandRetrier (info);
  379. return true;
  380. }
  381. return false;
  382. }