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.

667 lines
23KB

  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_Application.h"
  19. #include "jucer_AppearanceSettings.h"
  20. namespace AppearanceColours
  21. {
  22. struct ColourInfo
  23. {
  24. const char* name;
  25. uint32 colourID;
  26. bool mustBeOpaque;
  27. bool applyToEditorOnly;
  28. };
  29. static const ColourInfo colours[] =
  30. {
  31. { "Main Window Bkgd", mainBackgroundColourId, true, false },
  32. { "Treeview Highlight", treeviewHighlightColourId, false, false },
  33. { "Code Background", CodeEditorComponent::backgroundColourId, true, false },
  34. { "Line Number Bkgd", CodeEditorComponent::lineNumberBackgroundId, false, false },
  35. { "Line Numbers", CodeEditorComponent::lineNumberTextId, false, false },
  36. { "Plain Text", CodeEditorComponent::defaultTextColourId, false, false },
  37. { "Selected Text Bkgd", CodeEditorComponent::highlightColourId, false, false },
  38. { "Caret", CaretComponent::caretColourId, false, true }
  39. };
  40. }
  41. //==============================================================================
  42. AppearanceSettings::AppearanceSettings()
  43. : settings ("COLOUR_SCHEME")
  44. {
  45. IntrojucerLookAndFeel lf;
  46. for (int i = 0; i < sizeof (AppearanceColours::colours) / sizeof (AppearanceColours::colours[0]); ++i)
  47. getColourValue (AppearanceColours::colours[i].name) = lf.findColour (AppearanceColours::colours[i].colourID).toString();
  48. CodeDocument doc;
  49. CPlusPlusCodeTokeniser tokeniser;
  50. CodeEditorComponent editor (doc, &tokeniser);
  51. const CodeEditorComponent::ColourScheme cs (editor.getColourScheme());
  52. for (int i = cs.types.size(); --i >= 0;)
  53. {
  54. CodeEditorComponent::ColourScheme::TokenType& t = cs.types.getReference(i);
  55. getColourValue (t.name) = t.colour.toString();
  56. }
  57. getCodeFontValue() = getDefaultCodeFont().toString();
  58. settings.addListener (this);
  59. }
  60. File AppearanceSettings::getSchemesFolder()
  61. {
  62. File f (getAppProperties().getFile().getSiblingFile ("Schemes"));
  63. f.createDirectory();
  64. return f;
  65. }
  66. void AppearanceSettings::writeDefaultSchemeFile (const String& xmlString, const String& name)
  67. {
  68. const File file (getSchemesFolder().getChildFile (name).withFileExtension (getSchemeFileSuffix()));
  69. if (! file.exists())
  70. {
  71. AppearanceSettings settings;
  72. ScopedPointer<XmlElement> xml (XmlDocument::parse (xmlString));
  73. if (xml != nullptr)
  74. settings.readFromXML (*xml);
  75. settings.writeToFile (file);
  76. }
  77. }
  78. void AppearanceSettings::refreshPresetSchemeList()
  79. {
  80. writeDefaultSchemeFile (String::empty, "Default (Light)");
  81. writeDefaultSchemeFile (BinaryData::dark_scheme_xml, "Default (Dark)");
  82. Array<File> newSchemes;
  83. getSchemesFolder().findChildFiles (newSchemes, File::findFiles, false, String ("*") + getSchemeFileSuffix());
  84. if (newSchemes != presetSchemeFiles)
  85. {
  86. presetSchemeFiles.swapWithArray (newSchemes);
  87. commandManager->commandStatusChanged();
  88. }
  89. }
  90. StringArray AppearanceSettings::getPresetSchemes()
  91. {
  92. StringArray s;
  93. for (int i = 0; i < presetSchemeFiles.size(); ++i)
  94. s.add (presetSchemeFiles.getReference(i).getFileNameWithoutExtension());
  95. return s;
  96. }
  97. void AppearanceSettings::selectPresetScheme (int index)
  98. {
  99. readFromFile (presetSchemeFiles [index]);
  100. }
  101. bool AppearanceSettings::readFromXML (const XmlElement& xml)
  102. {
  103. if (xml.hasTagName (settings.getType().toString()))
  104. {
  105. const ValueTree newSettings (ValueTree::fromXml (xml));
  106. // we'll manually copy across the new properties to the existing tree so that
  107. // any open editors will be kept up to date..
  108. settings.copyPropertiesFrom (newSettings, nullptr);
  109. for (int i = settings.getNumChildren(); --i >= 0;)
  110. {
  111. ValueTree c (settings.getChild (i));
  112. const ValueTree newValue (newSettings.getChildWithProperty (Ids::name, c.getProperty (Ids::name)));
  113. if (newValue.isValid())
  114. c.copyPropertiesFrom (newValue, nullptr);
  115. }
  116. return true;
  117. }
  118. return false;
  119. }
  120. bool AppearanceSettings::readFromFile (const File& file)
  121. {
  122. const ScopedPointer<XmlElement> xml (XmlDocument::parse (file));
  123. return xml != nullptr && readFromXML (*xml);
  124. }
  125. bool AppearanceSettings::writeToFile (const File& file) const
  126. {
  127. const ScopedPointer<XmlElement> xml (settings.createXml());
  128. return xml != nullptr && xml->writeToFile (file, String::empty);
  129. }
  130. Font AppearanceSettings::getDefaultCodeFont()
  131. {
  132. return Font (Font::getDefaultMonospacedFontName(), Font::getDefaultStyle(), 13.0f);
  133. }
  134. StringArray AppearanceSettings::getColourNames() const
  135. {
  136. StringArray s;
  137. for (int i = 0; i < settings.getNumChildren(); ++i)
  138. {
  139. const ValueTree c (settings.getChild(i));
  140. if (c.hasType ("COLOUR"))
  141. s.add (c [Ids::name]);
  142. }
  143. return s;
  144. }
  145. void AppearanceSettings::updateColourScheme()
  146. {
  147. applyToLookAndFeel (LookAndFeel::getDefaultLookAndFeel());
  148. JucerApplication::getApp().mainWindowList.sendLookAndFeelChange();
  149. }
  150. void AppearanceSettings::applyToLookAndFeel (LookAndFeel& lf) const
  151. {
  152. for (int i = 0; i < sizeof (AppearanceColours::colours) / sizeof (AppearanceColours::colours[0]); ++i)
  153. {
  154. Colour col;
  155. if (getColour (AppearanceColours::colours[i].name, col))
  156. {
  157. if (AppearanceColours::colours[i].mustBeOpaque)
  158. col = Colours::white.overlaidWith (col);
  159. if (! AppearanceColours::colours[i].applyToEditorOnly)
  160. lf.setColour (AppearanceColours::colours[i].colourID, col);
  161. }
  162. }
  163. lf.setColour (ScrollBar::thumbColourId,
  164. getScrollbarColourForBackground (lf.findColour (mainBackgroundColourId)));
  165. }
  166. void AppearanceSettings::applyToCodeEditor (CodeEditorComponent& editor) const
  167. {
  168. CodeEditorComponent::ColourScheme cs (editor.getColourScheme());
  169. for (int i = cs.types.size(); --i >= 0;)
  170. {
  171. CodeEditorComponent::ColourScheme::TokenType& t = cs.types.getReference(i);
  172. getColour (t.name, t.colour);
  173. }
  174. editor.setColourScheme (cs);
  175. editor.setFont (getCodeFont());
  176. for (int i = 0; i < sizeof (AppearanceColours::colours) / sizeof (AppearanceColours::colours[0]); ++i)
  177. {
  178. if (AppearanceColours::colours[i].applyToEditorOnly)
  179. {
  180. Colour col;
  181. if (getColour (AppearanceColours::colours[i].name, col))
  182. editor.setColour (AppearanceColours::colours[i].colourID, col);
  183. }
  184. }
  185. editor.setColour (ScrollBar::thumbColourId,
  186. getScrollbarColourForBackground (editor.findColour (CodeEditorComponent::backgroundColourId)));
  187. }
  188. Font AppearanceSettings::getCodeFont() const
  189. {
  190. const String fontString (settings [Ids::font].toString());
  191. if (fontString.isEmpty())
  192. return getDefaultCodeFont();
  193. return Font::fromString (fontString);
  194. }
  195. Value AppearanceSettings::getCodeFontValue()
  196. {
  197. return settings.getPropertyAsValue (Ids::font, nullptr);
  198. }
  199. Value AppearanceSettings::getColourValue (const String& colourName)
  200. {
  201. ValueTree c (settings.getChildWithProperty (Ids::name, colourName));
  202. if (! c.isValid())
  203. {
  204. c = ValueTree ("COLOUR");
  205. c.setProperty (Ids::name, colourName, nullptr);
  206. settings.addChild (c, -1, nullptr);
  207. }
  208. return c.getPropertyAsValue (Ids::colour, nullptr);
  209. }
  210. bool AppearanceSettings::getColour (const String& name, Colour& result) const
  211. {
  212. const ValueTree colour (settings.getChildWithProperty (Ids::name, name));
  213. if (colour.isValid())
  214. {
  215. result = Colour::fromString (colour [Ids::colour].toString());
  216. return true;
  217. }
  218. return false;
  219. }
  220. Colour AppearanceSettings::getScrollbarColourForBackground (const Colour& background)
  221. {
  222. return background.contrasting().withAlpha (0.13f);
  223. }
  224. //==============================================================================
  225. struct AppearanceEditor
  226. {
  227. class Window : public DialogWindow
  228. {
  229. public:
  230. Window() : DialogWindow ("Appearance Settings", Colours::darkgrey, true, true)
  231. {
  232. setUsingNativeTitleBar (true);
  233. if (getAppSettings().monospacedFontNames.size() == 0)
  234. setContentOwned (new FontScanPanel(), false);
  235. else
  236. setContentOwned (new EditorPanel(), false);
  237. setResizable (true, true);
  238. const int width = 350;
  239. setResizeLimits (width, 200, width, 1000);
  240. String windowState (getAppProperties().getValue (getWindowPosName()));
  241. if (windowState.isNotEmpty())
  242. restoreWindowStateFromString (windowState);
  243. else
  244. centreAroundComponent (Component::getCurrentlyFocusedComponent(), width, 500);
  245. setVisible (true);
  246. }
  247. ~Window()
  248. {
  249. getAppProperties().setValue (getWindowPosName(), getWindowStateAsString());
  250. }
  251. void closeButtonPressed()
  252. {
  253. JucerApplication::getApp().appearanceEditorWindow = nullptr;
  254. }
  255. private:
  256. static const char* getWindowPosName() { return "colourSchemeEditorPos"; }
  257. JUCE_DECLARE_NON_COPYABLE (Window);
  258. };
  259. //==============================================================================
  260. class FontScanPanel : public Component,
  261. private Timer
  262. {
  263. public:
  264. FontScanPanel()
  265. {
  266. fontsToScan = Font::findAllTypefaceNames();
  267. startTimer (1);
  268. }
  269. void paint (Graphics& g)
  270. {
  271. g.fillAll (Colours::darkgrey);
  272. g.setFont (14.0f);
  273. g.setColour (Colours::white);
  274. g.drawFittedText ("Scanning for fonts..", getLocalBounds(), Justification::centred, 2);
  275. const int size = 30;
  276. getLookAndFeel().drawSpinningWaitAnimation (g, Colours::white, (getWidth() - size) / 2, getHeight() / 2 - 50, size, size);
  277. }
  278. void timerCallback()
  279. {
  280. repaint();
  281. if (fontsToScan.size() == 0)
  282. {
  283. getAppSettings().monospacedFontNames = fontsFound;
  284. Window* w = findParentComponentOfClass<Window>();
  285. if (w != nullptr)
  286. w->setContentOwned (new EditorPanel(), false);
  287. }
  288. else
  289. {
  290. if (isMonospacedTypeface (fontsToScan[0]))
  291. fontsFound.add (fontsToScan[0]);
  292. fontsToScan.remove (0);
  293. }
  294. }
  295. // A rather hacky trick to select only the fixed-pitch fonts..
  296. // This is unfortunately a bit slow, but will work on all platforms.
  297. static bool isMonospacedTypeface (const String& name)
  298. {
  299. const Font font (name, 20.0f, Font::plain);
  300. const int width = font.getStringWidth ("....");
  301. return width == font.getStringWidth ("WWWW")
  302. && width == font.getStringWidth ("0000")
  303. && width == font.getStringWidth ("1111")
  304. && width == font.getStringWidth ("iiii");
  305. }
  306. StringArray fontsToScan, fontsFound;
  307. };
  308. //==============================================================================
  309. class EditorPanel : public Component,
  310. private Button::Listener
  311. {
  312. public:
  313. EditorPanel()
  314. : loadButton ("Load Scheme..."),
  315. saveButton ("Save Scheme...")
  316. {
  317. rebuildProperties();
  318. addAndMakeVisible (&panel);
  319. loadButton.setColour (TextButton::buttonColourId, Colours::darkgrey.withAlpha (0.5f));
  320. saveButton.setColour (TextButton::buttonColourId, Colours::darkgrey.withAlpha (0.5f));
  321. loadButton.setColour (TextButton::textColourOffId, Colours::white);
  322. saveButton.setColour (TextButton::textColourOffId, Colours::white);
  323. addAndMakeVisible (&loadButton);
  324. addAndMakeVisible (&saveButton);
  325. loadButton.addListener (this);
  326. saveButton.addListener (this);
  327. }
  328. void rebuildProperties()
  329. {
  330. AppearanceSettings& scheme = getAppSettings().appearance;
  331. Array <PropertyComponent*> props;
  332. Value fontValue (scheme.getCodeFontValue());
  333. props.add (FontNameValueSource::createProperty ("Code Editor Font", fontValue));
  334. props.add (FontSizeValueSource::createProperty ("Font Size", fontValue));
  335. const StringArray colourNames (scheme.getColourNames());
  336. for (int i = 0; i < colourNames.size(); ++i)
  337. props.add (new ColourPropertyComponent (nullptr, colourNames[i],
  338. scheme.getColourValue (colourNames[i]),
  339. Colours::white, false));
  340. panel.clear();
  341. panel.addProperties (props);
  342. }
  343. void resized()
  344. {
  345. Rectangle<int> r (getLocalBounds());
  346. panel.setBounds (r.removeFromTop (getHeight() - 28).reduced (4, 2));
  347. loadButton.setBounds (r.removeFromLeft (getWidth() / 2).reduced (10, 4));
  348. saveButton.setBounds (r.reduced (10, 3));
  349. }
  350. private:
  351. PropertyPanel panel;
  352. TextButton loadButton, saveButton;
  353. void buttonClicked (Button* b)
  354. {
  355. if (b == &loadButton)
  356. loadScheme();
  357. else
  358. saveScheme();
  359. }
  360. void saveScheme()
  361. {
  362. FileChooser fc ("Select a file in which to save this colour-scheme...",
  363. getAppSettings().appearance.getSchemesFolder()
  364. .getNonexistentChildFile ("Scheme", AppearanceSettings::getSchemeFileSuffix()),
  365. AppearanceSettings::getSchemeFileWildCard());
  366. if (fc.browseForFileToSave (true))
  367. {
  368. File file (fc.getResult().withFileExtension (AppearanceSettings::getSchemeFileSuffix()));
  369. getAppSettings().appearance.writeToFile (file);
  370. getAppSettings().appearance.refreshPresetSchemeList();
  371. }
  372. }
  373. void loadScheme()
  374. {
  375. FileChooser fc ("Please select a colour-scheme file to load...",
  376. getAppSettings().appearance.getSchemesFolder(),
  377. AppearanceSettings::getSchemeFileWildCard());
  378. if (fc.browseForFileToOpen())
  379. {
  380. if (getAppSettings().appearance.readFromFile (fc.getResult()))
  381. rebuildProperties();
  382. }
  383. }
  384. JUCE_DECLARE_NON_COPYABLE (EditorPanel);
  385. };
  386. //==============================================================================
  387. class FontNameValueSource : public ValueSourceFilter
  388. {
  389. public:
  390. FontNameValueSource (const Value& source) : ValueSourceFilter (source) {}
  391. var getValue() const
  392. {
  393. return Font::fromString (sourceValue.toString()).getTypefaceName();
  394. }
  395. void setValue (const var& newValue)
  396. {
  397. Font font (Font::fromString (sourceValue.toString()));
  398. font.setTypefaceName (newValue.toString().isEmpty() ? Font::getDefaultMonospacedFontName()
  399. : newValue.toString());
  400. sourceValue = font.toString();
  401. }
  402. static ChoicePropertyComponent* createProperty (const String& title, const Value& value)
  403. {
  404. StringArray fontNames = getAppSettings().monospacedFontNames;
  405. Array<var> values;
  406. values.add (Font::getDefaultMonospacedFontName());
  407. values.add (var());
  408. for (int i = 0; i < fontNames.size(); ++i)
  409. values.add (fontNames[i]);
  410. StringArray names;
  411. names.add ("<Default Monospaced>");
  412. names.add (String::empty);
  413. names.addArray (getAppSettings().monospacedFontNames);
  414. return new ChoicePropertyComponent (Value (new FontNameValueSource (value)),
  415. title, names, values);
  416. }
  417. };
  418. //==============================================================================
  419. class FontSizeValueSource : public ValueSourceFilter
  420. {
  421. public:
  422. FontSizeValueSource (const Value& source) : ValueSourceFilter (source) {}
  423. var getValue() const
  424. {
  425. return Font::fromString (sourceValue.toString()).getHeight();
  426. }
  427. void setValue (const var& newValue)
  428. {
  429. sourceValue = Font::fromString (sourceValue.toString()).withHeight (newValue).toString();
  430. }
  431. static PropertyComponent* createProperty (const String& title, const Value& value)
  432. {
  433. return new SliderPropertyComponent (Value (new FontSizeValueSource (value)),
  434. title, 5.0, 40.0, 0.1, 0.5);
  435. }
  436. };
  437. };
  438. Component* AppearanceSettings::createEditorWindow()
  439. {
  440. return new AppearanceEditor::Window();
  441. }
  442. //==============================================================================
  443. IntrojucerLookAndFeel::IntrojucerLookAndFeel()
  444. {
  445. setColour (mainBackgroundColourId, Colour::greyLevel (0.8f));
  446. setColour (treeviewHighlightColourId, Colour (0x401111ee));
  447. }
  448. Rectangle<int> IntrojucerLookAndFeel::getPropertyComponentContentPosition (PropertyComponent& component)
  449. {
  450. if (component.findParentComponentOfClass<AppearanceEditor::EditorPanel>() != nullptr)
  451. return component.getLocalBounds().reduced (1, 1).removeFromRight (component.getWidth() / 2);
  452. return LookAndFeel::getPropertyComponentContentPosition (component);
  453. }
  454. int IntrojucerLookAndFeel::getTabButtonOverlap (int tabDepth) { return -1; }
  455. int IntrojucerLookAndFeel::getTabButtonSpaceAroundImage() { return 1; }
  456. int IntrojucerLookAndFeel::getTabButtonBestWidth (TabBarButton& button, int tabDepth) { return 120; }
  457. void IntrojucerLookAndFeel::createTabTextLayout (const TabBarButton& button, const Rectangle<int>& textArea, GlyphArrangement& textLayout)
  458. {
  459. Font font (textArea.getHeight() * 0.5f);
  460. font.setUnderline (button.hasKeyboardFocus (false));
  461. textLayout.addFittedText (font, button.getButtonText().trim(),
  462. (float) textArea.getX(), (float) textArea.getY(), (float) textArea.getWidth(), (float) textArea.getHeight(),
  463. Justification::centred, 1);
  464. }
  465. Colour IntrojucerLookAndFeel::getTabBackgroundColour (TabBarButton& button)
  466. {
  467. const Colour normalBkg (button.getTabBackgroundColour());
  468. Colour bkg (normalBkg.contrasting (0.15f));
  469. if (button.isFrontTab())
  470. bkg = bkg.overlaidWith (Colours::yellow.withAlpha (0.5f));
  471. return bkg;
  472. }
  473. void IntrojucerLookAndFeel::drawTabButton (TabBarButton& button, Graphics& g, bool isMouseOver, bool isMouseDown)
  474. {
  475. const Rectangle<int> activeArea (button.getActiveArea());
  476. const Colour bkg (getTabBackgroundColour (button));
  477. g.setGradientFill (ColourGradient (bkg.brighter (0.1f), 0, (float) activeArea.getY(),
  478. bkg.darker (0.1f), 0, (float) activeArea.getBottom(), false));
  479. g.fillRect (activeArea);
  480. g.setColour (button.getTabBackgroundColour().darker (0.3f));
  481. g.drawRect (activeArea);
  482. GlyphArrangement textLayout;
  483. createTabTextLayout (button, button.getTextArea(), textLayout);
  484. const float alpha = button.isEnabled() ? ((isMouseOver || isMouseDown) ? 1.0f : 0.8f) : 0.3f;
  485. g.setColour (bkg.contrasting().withMultipliedAlpha (alpha));
  486. textLayout.draw (g);
  487. }
  488. Rectangle<int> IntrojucerLookAndFeel::getTabButtonExtraComponentBounds (const TabBarButton& button, Rectangle<int>& textArea, Component& comp)
  489. {
  490. GlyphArrangement textLayout;
  491. createTabTextLayout (button, textArea, textLayout);
  492. const int textWidth = (int) textLayout.getBoundingBox (0, -1, false).getWidth();
  493. const int extraSpace = jmax (0, textArea.getWidth() - (textWidth + comp.getWidth())) / 2;
  494. textArea.removeFromRight (extraSpace);
  495. textArea.removeFromLeft (extraSpace);
  496. return textArea.removeFromRight (comp.getWidth());
  497. }
  498. void IntrojucerLookAndFeel::drawStretchableLayoutResizerBar (Graphics& g, int /*w*/, int /*h*/, bool /*isVerticalBar*/, bool isMouseOver, bool isMouseDragging)
  499. {
  500. if (isMouseOver || isMouseDragging)
  501. g.fillAll (Colours::yellow.withAlpha (0.4f));
  502. }
  503. void IntrojucerLookAndFeel::drawScrollbar (Graphics& g, ScrollBar& scrollbar, int x, int y, int width, int height,
  504. bool isScrollbarVertical, int thumbStartPosition, int thumbSize,
  505. bool isMouseOver, bool isMouseDown)
  506. {
  507. Path thumbPath;
  508. if (thumbSize > 0)
  509. {
  510. const float thumbIndent = (isScrollbarVertical ? width : height) * 0.25f;
  511. const float thumbIndentx2 = thumbIndent * 2.0f;
  512. if (isScrollbarVertical)
  513. thumbPath.addRoundedRectangle (x + thumbIndent, thumbStartPosition + thumbIndent,
  514. width - thumbIndentx2, thumbSize - thumbIndentx2, (width - thumbIndentx2) * 0.5f);
  515. else
  516. thumbPath.addRoundedRectangle (thumbStartPosition + thumbIndent, y + thumbIndent,
  517. thumbSize - thumbIndentx2, height - thumbIndentx2, (height - thumbIndentx2) * 0.5f);
  518. }
  519. Colour thumbCol (scrollbar.findColour (ScrollBar::thumbColourId, true));
  520. if (isMouseOver || isMouseDown)
  521. thumbCol = thumbCol.withMultipliedAlpha (2.0f);
  522. g.setColour (thumbCol);
  523. g.fillPath (thumbPath);
  524. g.setColour (thumbCol.contrasting ((isMouseOver || isMouseDown) ? 0.2f : 0.1f));
  525. g.strokePath (thumbPath, PathStrokeType (1.0f));
  526. }