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.

584 lines
16KB

  1. /*
  2. ==============================================================================
  3. This file is part of the JUCE library.
  4. Copyright (c) 2022 - 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 7 End-User License
  8. Agreement and JUCE Privacy Policy.
  9. End User License Agreement: www.juce.com/juce-7-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. NullCheckedInvocation::invoke (onEditorShow);
  163. }
  164. void Label::editorAboutToBeHidden (TextEditor* textEditor)
  165. {
  166. Component::BailOutChecker checker (this);
  167. listeners.callChecked (checker, [this, textEditor] (Label::Listener& l) { l.editorHidden (this, *textEditor); });
  168. if (checker.shouldBailOut())
  169. return;
  170. NullCheckedInvocation::invoke (onEditorHide);
  171. }
  172. void Label::showEditor()
  173. {
  174. if (editor == nullptr)
  175. {
  176. editor.reset (createEditorComponent());
  177. editor->setSize (10, 10);
  178. addAndMakeVisible (editor.get());
  179. editor->setText (getText(), false);
  180. editor->setKeyboardType (keyboardType);
  181. editor->addListener (this);
  182. editor->grabKeyboardFocus();
  183. if (editor == nullptr) // may be deleted by a callback
  184. return;
  185. editor->setHighlightedRegion (Range<int> (0, textValue.toString().length()));
  186. resized();
  187. repaint();
  188. editorShown (editor.get());
  189. enterModalState (false);
  190. editor->grabKeyboardFocus();
  191. }
  192. }
  193. bool Label::updateFromTextEditorContents (TextEditor& ed)
  194. {
  195. auto newText = ed.getText();
  196. if (textValue.toString() != newText)
  197. {
  198. lastTextValue = newText;
  199. textValue = newText;
  200. repaint();
  201. textWasChanged();
  202. if (ownerComponent != nullptr)
  203. componentMovedOrResized (*ownerComponent, true, true);
  204. return true;
  205. }
  206. return false;
  207. }
  208. void Label::hideEditor (bool discardCurrentEditorContents)
  209. {
  210. if (editor != nullptr)
  211. {
  212. WeakReference<Component> deletionChecker (this);
  213. std::unique_ptr<TextEditor> outgoingEditor;
  214. std::swap (outgoingEditor, editor);
  215. editorAboutToBeHidden (outgoingEditor.get());
  216. const bool changed = (! discardCurrentEditorContents)
  217. && updateFromTextEditorContents (*outgoingEditor);
  218. outgoingEditor.reset();
  219. if (deletionChecker != nullptr)
  220. repaint();
  221. if (changed)
  222. textWasEdited();
  223. if (deletionChecker != nullptr)
  224. exitModalState (0);
  225. if (changed && deletionChecker != nullptr)
  226. callChangeListeners();
  227. }
  228. }
  229. void Label::inputAttemptWhenModal()
  230. {
  231. if (editor != nullptr)
  232. {
  233. if (lossOfFocusDiscardsChanges)
  234. textEditorEscapeKeyPressed (*editor);
  235. else
  236. textEditorReturnKeyPressed (*editor);
  237. }
  238. }
  239. bool Label::isBeingEdited() const noexcept
  240. {
  241. return editor != nullptr;
  242. }
  243. static void copyColourIfSpecified (Label& l, TextEditor& ed, int colourID, int targetColourID)
  244. {
  245. if (l.isColourSpecified (colourID) || l.getLookAndFeel().isColourSpecified (colourID))
  246. ed.setColour (targetColourID, l.findColour (colourID));
  247. }
  248. TextEditor* Label::createEditorComponent()
  249. {
  250. auto* ed = new TextEditor (getName());
  251. ed->applyFontToAllText (getLookAndFeel().getLabelFont (*this));
  252. copyAllExplicitColoursTo (*ed);
  253. copyColourIfSpecified (*this, *ed, textWhenEditingColourId, TextEditor::textColourId);
  254. copyColourIfSpecified (*this, *ed, backgroundWhenEditingColourId, TextEditor::backgroundColourId);
  255. copyColourIfSpecified (*this, *ed, outlineWhenEditingColourId, TextEditor::focusedOutlineColourId);
  256. return ed;
  257. }
  258. TextEditor* Label::getCurrentTextEditor() const noexcept
  259. {
  260. return editor.get();
  261. }
  262. //==============================================================================
  263. void Label::paint (Graphics& g)
  264. {
  265. getLookAndFeel().drawLabel (g, *this);
  266. }
  267. void Label::mouseUp (const MouseEvent& e)
  268. {
  269. if (editSingleClick
  270. && isEnabled()
  271. && contains (e.getPosition())
  272. && ! (e.mouseWasDraggedSinceMouseDown() || e.mods.isPopupMenu()))
  273. {
  274. showEditor();
  275. }
  276. }
  277. void Label::mouseDoubleClick (const MouseEvent& e)
  278. {
  279. if (editDoubleClick
  280. && isEnabled()
  281. && ! e.mods.isPopupMenu())
  282. {
  283. showEditor();
  284. }
  285. }
  286. void Label::resized()
  287. {
  288. if (editor != nullptr)
  289. editor->setBounds (getLocalBounds());
  290. }
  291. void Label::focusGained (FocusChangeType cause)
  292. {
  293. if (editSingleClick
  294. && isEnabled()
  295. && cause == focusChangedByTabKey)
  296. {
  297. showEditor();
  298. }
  299. }
  300. void Label::enablementChanged()
  301. {
  302. repaint();
  303. }
  304. void Label::colourChanged()
  305. {
  306. repaint();
  307. }
  308. void Label::setMinimumHorizontalScale (const float newScale)
  309. {
  310. if (! approximatelyEqual (minimumHorizontalScale, newScale))
  311. {
  312. minimumHorizontalScale = newScale;
  313. repaint();
  314. }
  315. }
  316. //==============================================================================
  317. // We'll use a custom focus traverser here to make sure focus goes from the
  318. // text editor to another component rather than back to the label itself.
  319. class LabelKeyboardFocusTraverser final : public KeyboardFocusTraverser
  320. {
  321. public:
  322. explicit LabelKeyboardFocusTraverser (Label& l) : owner (l) {}
  323. Component* getDefaultComponent (Component* parent) override
  324. {
  325. if (auto* container = getKeyboardFocusContainer (parent))
  326. return KeyboardFocusTraverser::getDefaultComponent (container);
  327. return nullptr;
  328. }
  329. Component* getNextComponent (Component* c) override { return KeyboardFocusTraverser::getNextComponent (getComp (c)); }
  330. Component* getPreviousComponent (Component* c) override { return KeyboardFocusTraverser::getPreviousComponent (getComp (c)); }
  331. std::vector<Component*> getAllComponents (Component* parent) override
  332. {
  333. if (auto* container = getKeyboardFocusContainer (parent))
  334. return KeyboardFocusTraverser::getAllComponents (container);
  335. return {};
  336. }
  337. private:
  338. Component* getComp (Component* current) const
  339. {
  340. if (auto* ed = owner.getCurrentTextEditor())
  341. if (current == ed)
  342. return current->getParentComponent();
  343. return current;
  344. }
  345. Component* getKeyboardFocusContainer (Component* parent) const
  346. {
  347. if (owner.getCurrentTextEditor() != nullptr && parent == &owner)
  348. return owner.findKeyboardFocusContainer();
  349. return parent;
  350. }
  351. Label& owner;
  352. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (LabelKeyboardFocusTraverser)
  353. };
  354. std::unique_ptr<ComponentTraverser> Label::createKeyboardFocusTraverser()
  355. {
  356. return std::make_unique<LabelKeyboardFocusTraverser> (*this);
  357. }
  358. //==============================================================================
  359. void Label::addListener (Label::Listener* l) { listeners.add (l); }
  360. void Label::removeListener (Label::Listener* l) { listeners.remove (l); }
  361. void Label::callChangeListeners()
  362. {
  363. Component::BailOutChecker checker (this);
  364. listeners.callChecked (checker, [this] (Listener& l) { l.labelTextChanged (this); });
  365. if (checker.shouldBailOut())
  366. return;
  367. NullCheckedInvocation::invoke (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 ([[maybe_unused]] TextEditor& ed)
  401. {
  402. if (editor != nullptr)
  403. {
  404. jassert (&ed == editor.get());
  405. editor->setText (textValue.toString(), false);
  406. hideEditor (true);
  407. }
  408. }
  409. void Label::textEditorFocusLost (TextEditor& ed)
  410. {
  411. textEditorTextChanged (ed);
  412. }
  413. //==============================================================================
  414. class LabelAccessibilityHandler final : public AccessibilityHandler
  415. {
  416. public:
  417. explicit LabelAccessibilityHandler (Label& labelToWrap)
  418. : AccessibilityHandler (labelToWrap,
  419. labelToWrap.isEditable() ? AccessibilityRole::editableText : AccessibilityRole::label,
  420. getAccessibilityActions (labelToWrap),
  421. { std::make_unique<LabelValueInterface> (labelToWrap) }),
  422. label (labelToWrap)
  423. {
  424. }
  425. String getTitle() const override { return label.getText(); }
  426. String getHelp() const override { return label.getTooltip(); }
  427. AccessibleState getCurrentState() const override
  428. {
  429. if (label.isBeingEdited())
  430. return {}; // allow focus to pass through to the TextEditor
  431. return AccessibilityHandler::getCurrentState();
  432. }
  433. private:
  434. class LabelValueInterface final : public AccessibilityTextValueInterface
  435. {
  436. public:
  437. explicit LabelValueInterface (Label& labelToWrap)
  438. : label (labelToWrap)
  439. {
  440. }
  441. bool isReadOnly() const override { return true; }
  442. String getCurrentValueAsString() const override { return label.getText(); }
  443. void setValueAsString (const String&) override {}
  444. private:
  445. Label& label;
  446. //==============================================================================
  447. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (LabelValueInterface)
  448. };
  449. static AccessibilityActions getAccessibilityActions (Label& label)
  450. {
  451. if (label.isEditable())
  452. return AccessibilityActions().addAction (AccessibilityActionType::press, [&label] { label.showEditor(); });
  453. return {};
  454. }
  455. Label& label;
  456. //==============================================================================
  457. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (LabelAccessibilityHandler)
  458. };
  459. std::unique_ptr<AccessibilityHandler> Label::createAccessibilityHandler()
  460. {
  461. return std::make_unique<LabelAccessibilityHandler> (*this);
  462. }
  463. } // namespace juce