Audio plugin host https://kx.studio/carla
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.

juce_Label.cpp 16KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589
  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. 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. {
  301. showEditor();
  302. }
  303. }
  304. void Label::enablementChanged()
  305. {
  306. repaint();
  307. }
  308. void Label::colourChanged()
  309. {
  310. repaint();
  311. }
  312. void Label::setMinimumHorizontalScale (const float newScale)
  313. {
  314. if (minimumHorizontalScale != newScale)
  315. {
  316. minimumHorizontalScale = newScale;
  317. repaint();
  318. }
  319. }
  320. //==============================================================================
  321. // We'll use a custom focus traverser here to make sure focus goes from the
  322. // text editor to another component rather than back to the label itself.
  323. class LabelKeyboardFocusTraverser : public KeyboardFocusTraverser
  324. {
  325. public:
  326. explicit LabelKeyboardFocusTraverser (Label& l) : owner (l) {}
  327. Component* getDefaultComponent (Component* parent) override
  328. {
  329. if (auto* container = getKeyboardFocusContainer (parent))
  330. return KeyboardFocusTraverser::getDefaultComponent (container);
  331. return nullptr;
  332. }
  333. Component* getNextComponent (Component* c) override { return KeyboardFocusTraverser::getNextComponent (getComp (c)); }
  334. Component* getPreviousComponent (Component* c) override { return KeyboardFocusTraverser::getPreviousComponent (getComp (c)); }
  335. std::vector<Component*> getAllComponents (Component* parent) override
  336. {
  337. if (auto* container = getKeyboardFocusContainer (parent))
  338. return KeyboardFocusTraverser::getAllComponents (container);
  339. return {};
  340. }
  341. private:
  342. Component* getComp (Component* current) const
  343. {
  344. if (auto* ed = owner.getCurrentTextEditor())
  345. if (current == ed)
  346. return current->getParentComponent();
  347. return current;
  348. }
  349. Component* getKeyboardFocusContainer (Component* parent) const
  350. {
  351. if (owner.getCurrentTextEditor() != nullptr && parent == &owner)
  352. return owner.findKeyboardFocusContainer();
  353. return parent;
  354. }
  355. Label& owner;
  356. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (LabelKeyboardFocusTraverser)
  357. };
  358. std::unique_ptr<ComponentTraverser> Label::createKeyboardFocusTraverser()
  359. {
  360. return std::make_unique<LabelKeyboardFocusTraverser> (*this);
  361. }
  362. //==============================================================================
  363. void Label::addListener (Label::Listener* l) { listeners.add (l); }
  364. void Label::removeListener (Label::Listener* l) { listeners.remove (l); }
  365. void Label::callChangeListeners()
  366. {
  367. Component::BailOutChecker checker (this);
  368. listeners.callChecked (checker, [this] (Listener& l) { l.labelTextChanged (this); });
  369. if (checker.shouldBailOut())
  370. return;
  371. if (onTextChange != nullptr)
  372. onTextChange();
  373. }
  374. //==============================================================================
  375. void Label::textEditorTextChanged (TextEditor& ed)
  376. {
  377. if (editor != nullptr)
  378. {
  379. jassert (&ed == editor.get());
  380. if (! (hasKeyboardFocus (true) || isCurrentlyBlockedByAnotherModalComponent()))
  381. {
  382. if (lossOfFocusDiscardsChanges)
  383. textEditorEscapeKeyPressed (ed);
  384. else
  385. textEditorReturnKeyPressed (ed);
  386. }
  387. }
  388. }
  389. void Label::textEditorReturnKeyPressed (TextEditor& ed)
  390. {
  391. if (editor != nullptr)
  392. {
  393. jassert (&ed == editor.get());
  394. WeakReference<Component> deletionChecker (this);
  395. bool changed = updateFromTextEditorContents (ed);
  396. hideEditor (true);
  397. if (changed && deletionChecker != nullptr)
  398. {
  399. textWasEdited();
  400. if (deletionChecker != nullptr)
  401. callChangeListeners();
  402. }
  403. }
  404. }
  405. void Label::textEditorEscapeKeyPressed (TextEditor& ed)
  406. {
  407. if (editor != nullptr)
  408. {
  409. jassertquiet (&ed == editor.get());
  410. editor->setText (textValue.toString(), false);
  411. hideEditor (true);
  412. }
  413. }
  414. void Label::textEditorFocusLost (TextEditor& ed)
  415. {
  416. textEditorTextChanged (ed);
  417. }
  418. //==============================================================================
  419. class LabelAccessibilityHandler : public AccessibilityHandler
  420. {
  421. public:
  422. explicit LabelAccessibilityHandler (Label& labelToWrap)
  423. : AccessibilityHandler (labelToWrap,
  424. labelToWrap.isEditable() ? AccessibilityRole::editableText : AccessibilityRole::label,
  425. getAccessibilityActions (labelToWrap),
  426. { std::make_unique<LabelValueInterface> (labelToWrap) }),
  427. label (labelToWrap)
  428. {
  429. }
  430. String getTitle() const override { return label.getText(); }
  431. String getHelp() const override { return label.getTooltip(); }
  432. AccessibleState getCurrentState() const override
  433. {
  434. if (label.isBeingEdited())
  435. return {}; // allow focus to pass through to the TextEditor
  436. return AccessibilityHandler::getCurrentState();
  437. }
  438. private:
  439. class LabelValueInterface : public AccessibilityTextValueInterface
  440. {
  441. public:
  442. explicit LabelValueInterface (Label& labelToWrap)
  443. : label (labelToWrap)
  444. {
  445. }
  446. bool isReadOnly() const override { return true; }
  447. String getCurrentValueAsString() const override { return label.getText(); }
  448. void setValueAsString (const String&) override {}
  449. private:
  450. Label& label;
  451. //==============================================================================
  452. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (LabelValueInterface)
  453. };
  454. static AccessibilityActions getAccessibilityActions (Label& label)
  455. {
  456. if (label.isEditable())
  457. return AccessibilityActions().addAction (AccessibilityActionType::press, [&label] { label.showEditor(); });
  458. return {};
  459. }
  460. Label& label;
  461. //==============================================================================
  462. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (LabelAccessibilityHandler)
  463. };
  464. std::unique_ptr<AccessibilityHandler> Label::createAccessibilityHandler()
  465. {
  466. return std::make_unique<LabelAccessibilityHandler> (*this);
  467. }
  468. } // namespace juce