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.

425 lines
12KB

  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. //==============================================================================
  19. String createAlphaNumericUID()
  20. {
  21. String uid;
  22. const char chars[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
  23. Random r;
  24. uid << chars [r.nextInt (52)]; // make sure the first character is always a letter
  25. for (int i = 5; --i >= 0;)
  26. {
  27. r.setSeedRandomly();
  28. uid << chars [r.nextInt (62)];
  29. }
  30. return uid;
  31. }
  32. String hexString8Digits (int value)
  33. {
  34. return String::toHexString (value).paddedLeft ('0', 8);
  35. }
  36. String createGUID (const String& seed)
  37. {
  38. const String hex (MD5 ((seed + "_guidsalt").toUTF8()).toHexString().toUpperCase());
  39. return "{" + hex.substring (0, 8)
  40. + "-" + hex.substring (8, 12)
  41. + "-" + hex.substring (12, 16)
  42. + "-" + hex.substring (16, 20)
  43. + "-" + hex.substring (20, 32)
  44. + "}";
  45. }
  46. String escapeSpaces (const String& s)
  47. {
  48. return s.replace (" ", "\\ ");
  49. }
  50. String addQuotesIfContainsSpaces (const String& text)
  51. {
  52. return (text.containsChar (' ') && ! text.isQuotedString()) ? text.quoted() : text;
  53. }
  54. void setValueIfVoid (Value value, const var& defaultValue)
  55. {
  56. if (value.getValue().isVoid())
  57. value = defaultValue;
  58. }
  59. //==============================================================================
  60. StringPairArray parsePreprocessorDefs (const String& text)
  61. {
  62. StringPairArray result;
  63. String::CharPointerType s (text.getCharPointer());
  64. while (! s.isEmpty())
  65. {
  66. String token, value;
  67. s = s.findEndOfWhitespace();
  68. while ((! s.isEmpty()) && *s != '=' && ! s.isWhitespace())
  69. token << s.getAndAdvance();
  70. s = s.findEndOfWhitespace();
  71. if (*s == '=')
  72. {
  73. ++s;
  74. s = s.findEndOfWhitespace();
  75. while ((! s.isEmpty()) && ! s.isWhitespace())
  76. {
  77. if (*s == ',')
  78. {
  79. ++s;
  80. break;
  81. }
  82. if (*s == '\\' && (s[1] == ' ' || s[1] == ','))
  83. ++s;
  84. value << s.getAndAdvance();
  85. }
  86. }
  87. if (token.isNotEmpty())
  88. result.set (token, value);
  89. }
  90. return result;
  91. }
  92. StringPairArray mergePreprocessorDefs (StringPairArray inheritedDefs, const StringPairArray& overridingDefs)
  93. {
  94. for (int i = 0; i < overridingDefs.size(); ++i)
  95. inheritedDefs.set (overridingDefs.getAllKeys()[i], overridingDefs.getAllValues()[i]);
  96. return inheritedDefs;
  97. }
  98. String createGCCPreprocessorFlags (const StringPairArray& defs)
  99. {
  100. String s;
  101. for (int i = 0; i < defs.size(); ++i)
  102. {
  103. String def (defs.getAllKeys()[i]);
  104. const String value (defs.getAllValues()[i]);
  105. if (value.isNotEmpty())
  106. def << "=" << value;
  107. if (! def.endsWithChar ('"'))
  108. def = def.quoted();
  109. s += " -D " + def;
  110. }
  111. return s;
  112. }
  113. String replacePreprocessorDefs (const StringPairArray& definitions, String sourceString)
  114. {
  115. for (int i = 0; i < definitions.size(); ++i)
  116. {
  117. const String key (definitions.getAllKeys()[i]);
  118. const String value (definitions.getAllValues()[i]);
  119. sourceString = sourceString.replace ("${" + key + "}", value);
  120. }
  121. return sourceString;
  122. }
  123. StringArray getSearchPathsFromString (const String& searchPath)
  124. {
  125. StringArray s;
  126. s.addTokens (searchPath, ";\r\n", String::empty);
  127. s.trim();
  128. s.removeEmptyStrings();
  129. s.removeDuplicates (false);
  130. return s;
  131. }
  132. void addPlistDictionaryKey (XmlElement* xml, const String& key, const String& value)
  133. {
  134. forEachXmlChildElementWithTagName (*xml, e, "key")
  135. {
  136. if (e->getAllSubText().trim().equalsIgnoreCase (key))
  137. {
  138. if (e->getNextElement() != nullptr && e->getNextElement()->hasTagName ("key"))
  139. {
  140. // try to fix broken plist format..
  141. xml->removeChildElement (e, true);
  142. break;
  143. }
  144. else
  145. {
  146. return; // (value already exists)
  147. }
  148. }
  149. }
  150. xml->createNewChildElement ("key") ->addTextElement (key);
  151. xml->createNewChildElement ("string")->addTextElement (value);
  152. }
  153. void addPlistDictionaryKeyBool (XmlElement* xml, const String& key, const bool value)
  154. {
  155. xml->createNewChildElement ("key")->addTextElement (key);
  156. xml->createNewChildElement (value ? "true" : "false");
  157. }
  158. void addPlistDictionaryKeyInt (XmlElement* xml, const String& key, int value)
  159. {
  160. xml->createNewChildElement ("key")->addTextElement (key);
  161. xml->createNewChildElement ("integer")->addTextElement (String (value));
  162. }
  163. //==============================================================================
  164. void autoScrollForMouseEvent (const MouseEvent& e, bool scrollX, bool scrollY)
  165. {
  166. if (Viewport* const viewport = e.eventComponent->findParentComponentOfClass<Viewport>())
  167. {
  168. const MouseEvent e2 (e.getEventRelativeTo (viewport));
  169. viewport->autoScroll (scrollX ? e2.x : 20, scrollY ? e2.y : 20, 8, 16);
  170. }
  171. }
  172. //==============================================================================
  173. int indexOfLineStartingWith (const StringArray& lines, const String& text, int index)
  174. {
  175. const int len = text.length();
  176. for (const String* i = lines.begin() + index, * const e = lines.end(); i < e; ++i)
  177. {
  178. if (CharacterFunctions::compareUpTo (i->getCharPointer().findEndOfWhitespace(),
  179. text.getCharPointer(), len) == 0)
  180. return index;
  181. ++index;
  182. }
  183. return -1;
  184. }
  185. //==============================================================================
  186. RolloverHelpComp::RolloverHelpComp()
  187. : lastComp (nullptr)
  188. {
  189. setInterceptsMouseClicks (false, false);
  190. startTimer (150);
  191. }
  192. void RolloverHelpComp::paint (Graphics& g)
  193. {
  194. AttributedString s;
  195. s.setJustification (Justification::centredLeft);
  196. s.append (lastTip, Font (14.0f), findColour (mainBackgroundColourId).contrasting (0.7f));
  197. TextLayout tl;
  198. tl.createLayoutWithBalancedLineLengths (s, getWidth() - 10.0f);
  199. if (tl.getNumLines() > 3)
  200. tl.createLayout (s, getWidth() - 10.0f);
  201. tl.draw (g, getLocalBounds().toFloat());
  202. }
  203. void RolloverHelpComp::timerCallback()
  204. {
  205. Component* newComp = Desktop::getInstance().getMainMouseSource().getComponentUnderMouse();
  206. if (newComp != nullptr
  207. && (newComp->getTopLevelComponent() != getTopLevelComponent()
  208. || newComp->isCurrentlyBlockedByAnotherModalComponent()))
  209. newComp = nullptr;
  210. if (newComp != lastComp)
  211. {
  212. lastComp = newComp;
  213. String newTip (findTip (newComp));
  214. if (newTip != lastTip)
  215. {
  216. lastTip = newTip;
  217. repaint();
  218. }
  219. }
  220. }
  221. String RolloverHelpComp::findTip (Component* c)
  222. {
  223. while (c != nullptr)
  224. {
  225. if (TooltipClient* const tc = dynamic_cast <TooltipClient*> (c))
  226. {
  227. const String tip (tc->getTooltip());
  228. if (tip.isNotEmpty())
  229. return tip;
  230. }
  231. c = c->getParentComponent();
  232. }
  233. return String::empty;
  234. }
  235. //==============================================================================
  236. class UTF8Component : public Component,
  237. private TextEditorListener
  238. {
  239. public:
  240. UTF8Component()
  241. : desc (String::empty,
  242. "Type any string into the box, and it'll be shown below as a portable UTF-8 literal, "
  243. "ready to cut-and-paste into your source-code...")
  244. {
  245. desc.setJustificationType (Justification::centred);
  246. desc.setColour (Label::textColourId, Colours::white);
  247. addAndMakeVisible (&desc);
  248. const Colour bkgd (Colours::white.withAlpha (0.6f));
  249. userText.setMultiLine (true, true);
  250. userText.setReturnKeyStartsNewLine (true);
  251. userText.setColour (TextEditor::backgroundColourId, bkgd);
  252. addAndMakeVisible (&userText);
  253. userText.addListener (this);
  254. resultText.setMultiLine (true, true);
  255. resultText.setColour (TextEditor::backgroundColourId, bkgd);
  256. resultText.setReadOnly (true);
  257. resultText.setSelectAllWhenFocused (true);
  258. addAndMakeVisible (&resultText);
  259. userText.setText (getLastText());
  260. }
  261. void textEditorTextChanged (TextEditor&)
  262. {
  263. update();
  264. }
  265. void textEditorEscapeKeyPressed (TextEditor&)
  266. {
  267. getTopLevelComponent()->exitModalState (0);
  268. }
  269. void update()
  270. {
  271. getLastText() = userText.getText();
  272. resultText.setText (CodeHelpers::stringLiteral (getLastText(), 100), false);
  273. }
  274. void resized()
  275. {
  276. desc.setBounds (8, 8, getWidth() - 16, 44);
  277. userText.setBounds (desc.getX(), desc.getBottom() + 8, getWidth() - 16, getHeight() / 2 - desc.getBottom() - 8);
  278. resultText.setBounds (desc.getX(), userText.getBottom() + 4, getWidth() - 16, getHeight() - userText.getBottom() - 12);
  279. }
  280. private:
  281. Label desc;
  282. TextEditor userText, resultText;
  283. String& getLastText()
  284. {
  285. static String t;
  286. return t;
  287. }
  288. };
  289. void showUTF8ToolWindow (ScopedPointer<Component>& ownerPointer)
  290. {
  291. if (ownerPointer != nullptr)
  292. {
  293. ownerPointer->toFront (true);
  294. }
  295. else
  296. {
  297. new FloatingToolWindow ("UTF-8 String Literal Converter",
  298. "utf8WindowPos",
  299. new UTF8Component(), ownerPointer,
  300. 400, 300,
  301. 300, 300, 1000, 1000);
  302. }
  303. }
  304. //==============================================================================
  305. bool cancelAnyModalComponents()
  306. {
  307. ModalComponentManager& mm = *ModalComponentManager::getInstance();
  308. const int numModal = mm.getNumModalComponents();
  309. for (int i = numModal; --i >= 0;)
  310. if (Component* c = mm.getModalComponent(i))
  311. c->exitModalState (0);
  312. return numModal > 0;
  313. }
  314. class AsyncCommandRetrier : public Timer
  315. {
  316. public:
  317. AsyncCommandRetrier (const ApplicationCommandTarget::InvocationInfo& inf)
  318. : info (inf)
  319. {
  320. info.originatingComponent = nullptr;
  321. startTimer (500);
  322. }
  323. void timerCallback() override
  324. {
  325. stopTimer();
  326. commandManager->invoke (info, true);
  327. delete this;
  328. }
  329. ApplicationCommandTarget::InvocationInfo info;
  330. JUCE_DECLARE_NON_COPYABLE (AsyncCommandRetrier)
  331. };
  332. bool reinvokeCommandAfterCancellingModalComps (const ApplicationCommandTarget::InvocationInfo& info)
  333. {
  334. if (cancelAnyModalComponents())
  335. {
  336. new AsyncCommandRetrier (info);
  337. return true;
  338. }
  339. return false;
  340. }