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.

575 lines
16KB

  1. /*
  2. ==============================================================================
  3. This file is part of the JUCE library.
  4. Copyright (c) 2020 - Raw Material Software Limited
  5. JUCE is an open source library subject to commercial or open-source
  6. licensing.
  7. By using JUCE, you agree to the terms of both the JUCE 6 End-User License
  8. Agreement and JUCE Privacy Policy (both effective as of the 16th June 2020).
  9. End User License Agreement: www.juce.com/juce-6-licence
  10. Privacy Policy: www.juce.com/juce-privacy-policy
  11. Or: You may also use this code under the terms of the GPL v3 (see
  12. www.gnu.org/licenses).
  13. JUCE IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL WARRANTIES, WHETHER
  14. EXPRESSED OR IMPLIED, INCLUDING MERCHANTABILITY AND FITNESS FOR PURPOSE, ARE
  15. DISCLAIMED.
  16. ==============================================================================
  17. */
  18. namespace juce
  19. {
  20. Label::Label (const String& name, const String& labelText)
  21. : Component (name),
  22. textValue (labelText),
  23. lastTextValue (labelText)
  24. {
  25. setColour (TextEditor::textColourId, Colours::black);
  26. setColour (TextEditor::backgroundColourId, Colours::transparentBlack);
  27. setColour (TextEditor::outlineColourId, Colours::transparentBlack);
  28. textValue.addListener (this);
  29. }
  30. Label::~Label()
  31. {
  32. textValue.removeListener (this);
  33. if (ownerComponent != nullptr)
  34. ownerComponent->removeComponentListener (this);
  35. editor.reset();
  36. }
  37. //==============================================================================
  38. void Label::setText (const String& newText, NotificationType notification)
  39. {
  40. hideEditor (true);
  41. if (lastTextValue != newText)
  42. {
  43. lastTextValue = newText;
  44. textValue = newText;
  45. repaint();
  46. textWasChanged();
  47. if (ownerComponent != nullptr)
  48. componentMovedOrResized (*ownerComponent, true, true);
  49. if (notification != dontSendNotification)
  50. callChangeListeners();
  51. }
  52. }
  53. String Label::getText (bool returnActiveEditorContents) const
  54. {
  55. return (returnActiveEditorContents && isBeingEdited())
  56. ? editor->getText()
  57. : textValue.toString();
  58. }
  59. void Label::valueChanged (Value&)
  60. {
  61. if (lastTextValue != textValue.toString())
  62. setText (textValue.toString(), sendNotification);
  63. }
  64. //==============================================================================
  65. void Label::setFont (const Font& newFont)
  66. {
  67. if (font != newFont)
  68. {
  69. font = newFont;
  70. repaint();
  71. }
  72. }
  73. Font Label::getFont() const noexcept
  74. {
  75. return font;
  76. }
  77. void Label::setEditable (bool editOnSingleClick,
  78. bool editOnDoubleClick,
  79. bool lossOfFocusDiscards)
  80. {
  81. editSingleClick = editOnSingleClick;
  82. editDoubleClick = editOnDoubleClick;
  83. lossOfFocusDiscardsChanges = lossOfFocusDiscards;
  84. const auto isKeybordFocusable = (editOnSingleClick || editOnDoubleClick);
  85. setWantsKeyboardFocus (isKeybordFocusable);
  86. setFocusContainerType (isKeybordFocusable ? FocusContainerType::keyboardFocusContainer
  87. : FocusContainerType::none);
  88. invalidateAccessibilityHandler();
  89. }
  90. void Label::setJustificationType (Justification newJustification)
  91. {
  92. if (justification != newJustification)
  93. {
  94. justification = newJustification;
  95. repaint();
  96. }
  97. }
  98. void Label::setBorderSize (BorderSize<int> newBorder)
  99. {
  100. if (border != newBorder)
  101. {
  102. border = newBorder;
  103. repaint();
  104. }
  105. }
  106. //==============================================================================
  107. Component* Label::getAttachedComponent() const
  108. {
  109. return ownerComponent.get();
  110. }
  111. void Label::attachToComponent (Component* owner, bool onLeft)
  112. {
  113. jassert (owner != this); // Not a great idea to try to attach it to itself!
  114. if (ownerComponent != nullptr)
  115. ownerComponent->removeComponentListener (this);
  116. ownerComponent = owner;
  117. leftOfOwnerComp = onLeft;
  118. if (ownerComponent != nullptr)
  119. {
  120. setVisible (ownerComponent->isVisible());
  121. ownerComponent->addComponentListener (this);
  122. componentParentHierarchyChanged (*ownerComponent);
  123. componentMovedOrResized (*ownerComponent, true, true);
  124. }
  125. }
  126. void Label::componentMovedOrResized (Component& component, bool /*wasMoved*/, bool /*wasResized*/)
  127. {
  128. auto& lf = getLookAndFeel();
  129. auto f = lf.getLabelFont (*this);
  130. auto borderSize = lf.getLabelBorderSize (*this);
  131. if (leftOfOwnerComp)
  132. {
  133. auto width = jmin (roundToInt (f.getStringWidthFloat (textValue.toString()) + 0.5f)
  134. + borderSize.getLeftAndRight(),
  135. component.getX());
  136. setBounds (component.getX() - width, component.getY(), width, component.getHeight());
  137. }
  138. else
  139. {
  140. auto height = borderSize.getTopAndBottom() + 6 + roundToInt (f.getHeight() + 0.5f);
  141. setBounds (component.getX(), component.getY() - height, component.getWidth(), height);
  142. }
  143. }
  144. void Label::componentParentHierarchyChanged (Component& component)
  145. {
  146. if (auto* parent = component.getParentComponent())
  147. parent->addChildComponent (this);
  148. }
  149. void Label::componentVisibilityChanged (Component& component)
  150. {
  151. setVisible (component.isVisible());
  152. }
  153. //==============================================================================
  154. void Label::textWasEdited() {}
  155. void Label::textWasChanged() {}
  156. void Label::editorShown (TextEditor* textEditor)
  157. {
  158. Component::BailOutChecker checker (this);
  159. listeners.callChecked (checker, [this, textEditor] (Label::Listener& l) { l.editorShown (this, *textEditor); });
  160. if (checker.shouldBailOut())
  161. return;
  162. if (onEditorShow != nullptr)
  163. onEditorShow();
  164. }
  165. void Label::editorAboutToBeHidden (TextEditor* textEditor)
  166. {
  167. if (auto* peer = getPeer())
  168. peer->dismissPendingTextInput();
  169. Component::BailOutChecker checker (this);
  170. listeners.callChecked (checker, [this, textEditor] (Label::Listener& l) { l.editorHidden (this, *textEditor); });
  171. if (checker.shouldBailOut())
  172. return;
  173. if (onEditorHide != nullptr)
  174. onEditorHide();
  175. }
  176. void Label::showEditor()
  177. {
  178. if (editor == nullptr)
  179. {
  180. editor.reset (createEditorComponent());
  181. editor->setSize (10, 10);
  182. addAndMakeVisible (editor.get());
  183. editor->setText (getText(), false);
  184. editor->setKeyboardType (keyboardType);
  185. editor->addListener (this);
  186. editor->grabKeyboardFocus();
  187. if (editor == nullptr) // may be deleted by a callback
  188. return;
  189. editor->setHighlightedRegion (Range<int> (0, textValue.toString().length()));
  190. resized();
  191. repaint();
  192. editorShown (editor.get());
  193. enterModalState (false);
  194. editor->grabKeyboardFocus();
  195. }
  196. }
  197. bool Label::updateFromTextEditorContents (TextEditor& ed)
  198. {
  199. auto newText = ed.getText();
  200. if (textValue.toString() != newText)
  201. {
  202. lastTextValue = newText;
  203. textValue = newText;
  204. repaint();
  205. textWasChanged();
  206. if (ownerComponent != nullptr)
  207. componentMovedOrResized (*ownerComponent, true, true);
  208. return true;
  209. }
  210. return false;
  211. }
  212. void Label::hideEditor (bool discardCurrentEditorContents)
  213. {
  214. if (editor != nullptr)
  215. {
  216. WeakReference<Component> deletionChecker (this);
  217. std::unique_ptr<TextEditor> outgoingEditor;
  218. std::swap (outgoingEditor, editor);
  219. editorAboutToBeHidden (outgoingEditor.get());
  220. const bool changed = (! discardCurrentEditorContents)
  221. && updateFromTextEditorContents (*outgoingEditor);
  222. outgoingEditor.reset();
  223. if (deletionChecker != nullptr)
  224. repaint();
  225. if (changed)
  226. textWasEdited();
  227. if (deletionChecker != nullptr)
  228. exitModalState (0);
  229. if (changed && deletionChecker != nullptr)
  230. callChangeListeners();
  231. }
  232. }
  233. void Label::inputAttemptWhenModal()
  234. {
  235. if (editor != nullptr)
  236. {
  237. if (lossOfFocusDiscardsChanges)
  238. textEditorEscapeKeyPressed (*editor);
  239. else
  240. textEditorReturnKeyPressed (*editor);
  241. }
  242. }
  243. bool Label::isBeingEdited() const noexcept
  244. {
  245. return editor != nullptr;
  246. }
  247. static void copyColourIfSpecified (Label& l, TextEditor& ed, int colourID, int targetColourID)
  248. {
  249. if (l.isColourSpecified (colourID) || l.getLookAndFeel().isColourSpecified (colourID))
  250. ed.setColour (targetColourID, l.findColour (colourID));
  251. }
  252. TextEditor* Label::createEditorComponent()
  253. {
  254. auto* ed = new TextEditor (getName());
  255. ed->applyFontToAllText (getLookAndFeel().getLabelFont (*this));
  256. copyAllExplicitColoursTo (*ed);
  257. copyColourIfSpecified (*this, *ed, textWhenEditingColourId, TextEditor::textColourId);
  258. copyColourIfSpecified (*this, *ed, backgroundWhenEditingColourId, TextEditor::backgroundColourId);
  259. copyColourIfSpecified (*this, *ed, outlineWhenEditingColourId, TextEditor::focusedOutlineColourId);
  260. return ed;
  261. }
  262. TextEditor* Label::getCurrentTextEditor() const noexcept
  263. {
  264. return editor.get();
  265. }
  266. //==============================================================================
  267. void Label::paint (Graphics& g)
  268. {
  269. getLookAndFeel().drawLabel (g, *this);
  270. }
  271. void Label::mouseUp (const MouseEvent& e)
  272. {
  273. if (editSingleClick
  274. && isEnabled()
  275. && contains (e.getPosition())
  276. && ! (e.mouseWasDraggedSinceMouseDown() || e.mods.isPopupMenu()))
  277. {
  278. showEditor();
  279. }
  280. }
  281. void Label::mouseDoubleClick (const MouseEvent& e)
  282. {
  283. if (editDoubleClick
  284. && isEnabled()
  285. && ! e.mods.isPopupMenu())
  286. {
  287. showEditor();
  288. }
  289. }
  290. void Label::resized()
  291. {
  292. if (editor != nullptr)
  293. editor->setBounds (getLocalBounds());
  294. }
  295. void Label::focusGained (FocusChangeType cause)
  296. {
  297. if (editSingleClick
  298. && isEnabled()
  299. && (cause == focusChangedByTabKey
  300. || (cause == focusChangedDirectly && ! isCurrentlyModal())))
  301. {
  302. showEditor();
  303. }
  304. }
  305. void Label::enablementChanged()
  306. {
  307. repaint();
  308. }
  309. void Label::colourChanged()
  310. {
  311. repaint();
  312. }
  313. void Label::setMinimumHorizontalScale (const float newScale)
  314. {
  315. if (minimumHorizontalScale != newScale)
  316. {
  317. minimumHorizontalScale = newScale;
  318. repaint();
  319. }
  320. }
  321. //==============================================================================
  322. // We'll use a custom focus traverser here to make sure focus goes from the
  323. // text editor to another component rather than back to the label itself.
  324. class LabelKeyboardFocusTraverser : public KeyboardFocusTraverser
  325. {
  326. public:
  327. explicit LabelKeyboardFocusTraverser (Label& l) : owner (l) {}
  328. Component* getDefaultComponent (Component* parent) override
  329. {
  330. auto getContainer = [&]
  331. {
  332. if (owner.getCurrentTextEditor() != nullptr && parent == &owner)
  333. return owner.findKeyboardFocusContainer();
  334. return parent;
  335. };
  336. if (auto* container = getContainer())
  337. KeyboardFocusTraverser::getDefaultComponent (container);
  338. return nullptr;
  339. }
  340. Component* getNextComponent (Component* c) override { return KeyboardFocusTraverser::getNextComponent (getComp (c)); }
  341. Component* getPreviousComponent (Component* c) override { return KeyboardFocusTraverser::getPreviousComponent (getComp (c)); }
  342. private:
  343. Component* getComp (Component* current) const
  344. {
  345. if (auto* ed = owner.getCurrentTextEditor())
  346. if (current == ed)
  347. return current->getParentComponent();
  348. return current;
  349. }
  350. Label& owner;
  351. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (LabelKeyboardFocusTraverser)
  352. };
  353. std::unique_ptr<ComponentTraverser> Label::createKeyboardFocusTraverser()
  354. {
  355. return std::make_unique<LabelKeyboardFocusTraverser> (*this);
  356. }
  357. //==============================================================================
  358. void Label::addListener (Label::Listener* l) { listeners.add (l); }
  359. void Label::removeListener (Label::Listener* l) { listeners.remove (l); }
  360. void Label::callChangeListeners()
  361. {
  362. Component::BailOutChecker checker (this);
  363. listeners.callChecked (checker, [this] (Listener& l) { l.labelTextChanged (this); });
  364. if (checker.shouldBailOut())
  365. return;
  366. if (onTextChange != nullptr)
  367. onTextChange();
  368. }
  369. //==============================================================================
  370. void Label::textEditorTextChanged (TextEditor& ed)
  371. {
  372. if (editor != nullptr)
  373. {
  374. jassert (&ed == editor.get());
  375. if (! (hasKeyboardFocus (true) || isCurrentlyBlockedByAnotherModalComponent()))
  376. {
  377. if (lossOfFocusDiscardsChanges)
  378. textEditorEscapeKeyPressed (ed);
  379. else
  380. textEditorReturnKeyPressed (ed);
  381. }
  382. }
  383. }
  384. void Label::textEditorReturnKeyPressed (TextEditor& ed)
  385. {
  386. if (editor != nullptr)
  387. {
  388. jassert (&ed == editor.get());
  389. WeakReference<Component> deletionChecker (this);
  390. bool changed = updateFromTextEditorContents (ed);
  391. hideEditor (true);
  392. if (changed && deletionChecker != nullptr)
  393. {
  394. textWasEdited();
  395. if (deletionChecker != nullptr)
  396. callChangeListeners();
  397. }
  398. }
  399. }
  400. void Label::textEditorEscapeKeyPressed (TextEditor& ed)
  401. {
  402. if (editor != nullptr)
  403. {
  404. jassert (&ed == editor.get());
  405. ignoreUnused (ed);
  406. editor->setText (textValue.toString(), false);
  407. hideEditor (true);
  408. }
  409. }
  410. void Label::textEditorFocusLost (TextEditor& ed)
  411. {
  412. textEditorTextChanged (ed);
  413. }
  414. //==============================================================================
  415. class LabelAccessibilityHandler : public AccessibilityHandler
  416. {
  417. public:
  418. explicit LabelAccessibilityHandler (Label& labelToWrap)
  419. : AccessibilityHandler (labelToWrap,
  420. AccessibilityRole::staticText,
  421. getAccessibilityActions (labelToWrap),
  422. { std::make_unique<LabelValueInterface> (labelToWrap) }),
  423. label (labelToWrap)
  424. {
  425. }
  426. String getTitle() const override
  427. {
  428. return label.getText();
  429. }
  430. private:
  431. class LabelValueInterface : public AccessibilityTextValueInterface
  432. {
  433. public:
  434. explicit LabelValueInterface (Label& labelToWrap)
  435. : label (labelToWrap)
  436. {
  437. }
  438. bool isReadOnly() const override { return true; }
  439. String getCurrentValueAsString() const override { return label.getText(); }
  440. void setValueAsString (const String&) override {}
  441. private:
  442. Label& label;
  443. };
  444. static AccessibilityActions getAccessibilityActions (Label& label)
  445. {
  446. if (label.isEditable())
  447. return AccessibilityActions().addAction (AccessibilityActionType::press, [&label] { label.showEditor(); });
  448. return {};
  449. }
  450. Label& label;
  451. //==============================================================================
  452. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (LabelAccessibilityHandler)
  453. };
  454. std::unique_ptr<AccessibilityHandler> Label::createAccessibilityHandler()
  455. {
  456. return std::make_unique<LabelAccessibilityHandler> (*this);
  457. }
  458. } // namespace juce