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.

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