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.

713 lines
20KB

  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. ComboBox::ComboBox (const String& name)
  21. : Component (name),
  22. noChoicesMessage (TRANS("(no choices)"))
  23. {
  24. setRepaintsOnMouseActivity (true);
  25. lookAndFeelChanged();
  26. currentId.addListener (this);
  27. }
  28. ComboBox::~ComboBox()
  29. {
  30. currentId.removeListener (this);
  31. hidePopup();
  32. label.reset();
  33. }
  34. //==============================================================================
  35. void ComboBox::setEditableText (const bool isEditable)
  36. {
  37. if (label->isEditableOnSingleClick() != isEditable || label->isEditableOnDoubleClick() != isEditable)
  38. {
  39. label->setEditable (isEditable, isEditable, false);
  40. labelEditableState = (isEditable ? labelIsEditable : labelIsNotEditable);
  41. const auto isLabelEditable = (labelEditableState == labelIsEditable);
  42. setWantsKeyboardFocus (! isLabelEditable);
  43. label->setAccessible (isLabelEditable);
  44. resized();
  45. }
  46. }
  47. bool ComboBox::isTextEditable() const noexcept
  48. {
  49. return label->isEditable();
  50. }
  51. void ComboBox::setJustificationType (Justification justification)
  52. {
  53. label->setJustificationType (justification);
  54. }
  55. Justification ComboBox::getJustificationType() const noexcept
  56. {
  57. return label->getJustificationType();
  58. }
  59. void ComboBox::setTooltip (const String& newTooltip)
  60. {
  61. SettableTooltipClient::setTooltip (newTooltip);
  62. label->setTooltip (newTooltip);
  63. }
  64. //==============================================================================
  65. void ComboBox::addItem (const String& newItemText, int newItemId)
  66. {
  67. // you can't add empty strings to the list..
  68. jassert (newItemText.isNotEmpty());
  69. // IDs must be non-zero, as zero is used to indicate a lack of selection.
  70. jassert (newItemId != 0);
  71. // you shouldn't use duplicate item IDs!
  72. jassert (getItemForId (newItemId) == nullptr);
  73. if (newItemText.isNotEmpty() && newItemId != 0)
  74. currentMenu.addItem (newItemId, newItemText, true, false);
  75. }
  76. void ComboBox::addItemList (const StringArray& itemsToAdd, int firstItemID)
  77. {
  78. for (auto& i : itemsToAdd)
  79. currentMenu.addItem (firstItemID++, i);
  80. }
  81. void ComboBox::addSeparator()
  82. {
  83. currentMenu.addSeparator();
  84. }
  85. void ComboBox::addSectionHeading (const String& headingName)
  86. {
  87. // you can't add empty strings to the list..
  88. jassert (headingName.isNotEmpty());
  89. if (headingName.isNotEmpty())
  90. currentMenu.addSectionHeader (headingName);
  91. }
  92. void ComboBox::setItemEnabled (int itemId, bool shouldBeEnabled)
  93. {
  94. if (auto* item = getItemForId (itemId))
  95. item->isEnabled = shouldBeEnabled;
  96. }
  97. bool ComboBox::isItemEnabled (int itemId) const noexcept
  98. {
  99. if (auto* item = getItemForId (itemId))
  100. return item->isEnabled;
  101. return false;
  102. }
  103. void ComboBox::changeItemText (int itemId, const String& newText)
  104. {
  105. if (auto* item = getItemForId (itemId))
  106. item->text = newText;
  107. else
  108. jassertfalse;
  109. }
  110. void ComboBox::clear (const NotificationType notification)
  111. {
  112. currentMenu.clear();
  113. if (! label->isEditable())
  114. setSelectedItemIndex (-1, notification);
  115. }
  116. //==============================================================================
  117. PopupMenu::Item* ComboBox::getItemForId (int itemId) const noexcept
  118. {
  119. if (itemId != 0)
  120. {
  121. for (PopupMenu::MenuItemIterator iterator (currentMenu, true); iterator.next();)
  122. {
  123. auto& item = iterator.getItem();
  124. if (item.itemID == itemId)
  125. return &item;
  126. }
  127. }
  128. return nullptr;
  129. }
  130. PopupMenu::Item* ComboBox::getItemForIndex (const int index) const noexcept
  131. {
  132. int n = 0;
  133. for (PopupMenu::MenuItemIterator iterator (currentMenu, true); iterator.next();)
  134. {
  135. auto& item = iterator.getItem();
  136. if (item.itemID != 0)
  137. if (n++ == index)
  138. return &item;
  139. }
  140. return nullptr;
  141. }
  142. int ComboBox::getNumItems() const noexcept
  143. {
  144. int n = 0;
  145. for (PopupMenu::MenuItemIterator iterator (currentMenu, true); iterator.next();)
  146. {
  147. auto& item = iterator.getItem();
  148. if (item.itemID != 0)
  149. n++;
  150. }
  151. return n;
  152. }
  153. String ComboBox::getItemText (const int index) const
  154. {
  155. if (auto* item = getItemForIndex (index))
  156. return item->text;
  157. return {};
  158. }
  159. int ComboBox::getItemId (const int index) const noexcept
  160. {
  161. if (auto* item = getItemForIndex (index))
  162. return item->itemID;
  163. return 0;
  164. }
  165. int ComboBox::indexOfItemId (const int itemId) const noexcept
  166. {
  167. if (itemId != 0)
  168. {
  169. int n = 0;
  170. for (PopupMenu::MenuItemIterator iterator (currentMenu, true); iterator.next();)
  171. {
  172. auto& item = iterator.getItem();
  173. if (item.itemID == itemId)
  174. return n;
  175. else if (item.itemID != 0)
  176. n++;
  177. }
  178. }
  179. return -1;
  180. }
  181. //==============================================================================
  182. int ComboBox::getSelectedItemIndex() const
  183. {
  184. auto index = indexOfItemId (currentId.getValue());
  185. if (getText() != getItemText (index))
  186. index = -1;
  187. return index;
  188. }
  189. void ComboBox::setSelectedItemIndex (const int index, const NotificationType notification)
  190. {
  191. setSelectedId (getItemId (index), notification);
  192. }
  193. int ComboBox::getSelectedId() const noexcept
  194. {
  195. if (auto* item = getItemForId (currentId.getValue()))
  196. if (getText() == item->text)
  197. return item->itemID;
  198. return 0;
  199. }
  200. void ComboBox::setSelectedId (const int newItemId, const NotificationType notification)
  201. {
  202. auto* item = getItemForId (newItemId);
  203. auto newItemText = item != nullptr ? item->text : String();
  204. if (lastCurrentId != newItemId || label->getText() != newItemText)
  205. {
  206. label->setText (newItemText, dontSendNotification);
  207. lastCurrentId = newItemId;
  208. currentId = newItemId;
  209. repaint(); // for the benefit of the 'none selected' text
  210. sendChange (notification);
  211. }
  212. }
  213. bool ComboBox::selectIfEnabled (const int index)
  214. {
  215. if (auto* item = getItemForIndex (index))
  216. {
  217. if (item->isEnabled)
  218. {
  219. setSelectedItemIndex (index);
  220. return true;
  221. }
  222. }
  223. return false;
  224. }
  225. bool ComboBox::nudgeSelectedItem (int delta)
  226. {
  227. for (int i = getSelectedItemIndex() + delta; isPositiveAndBelow (i, getNumItems()); i += delta)
  228. if (selectIfEnabled (i))
  229. return true;
  230. return false;
  231. }
  232. void ComboBox::valueChanged (Value&)
  233. {
  234. if (lastCurrentId != (int) currentId.getValue())
  235. setSelectedId (currentId.getValue());
  236. }
  237. //==============================================================================
  238. String ComboBox::getText() const
  239. {
  240. return label->getText();
  241. }
  242. void ComboBox::setText (const String& newText, const NotificationType notification)
  243. {
  244. for (PopupMenu::MenuItemIterator iterator (currentMenu, true); iterator.next();)
  245. {
  246. auto& item = iterator.getItem();
  247. if (item.itemID != 0
  248. && item.text == newText)
  249. {
  250. setSelectedId (item.itemID, notification);
  251. return;
  252. }
  253. }
  254. lastCurrentId = 0;
  255. currentId = 0;
  256. repaint();
  257. if (label->getText() != newText)
  258. {
  259. label->setText (newText, dontSendNotification);
  260. sendChange (notification);
  261. }
  262. }
  263. void ComboBox::showEditor()
  264. {
  265. jassert (isTextEditable()); // you probably shouldn't do this to a non-editable combo box?
  266. label->showEditor();
  267. }
  268. //==============================================================================
  269. void ComboBox::setTextWhenNothingSelected (const String& newMessage)
  270. {
  271. if (textWhenNothingSelected != newMessage)
  272. {
  273. textWhenNothingSelected = newMessage;
  274. repaint();
  275. }
  276. }
  277. String ComboBox::getTextWhenNothingSelected() const
  278. {
  279. return textWhenNothingSelected;
  280. }
  281. void ComboBox::setTextWhenNoChoicesAvailable (const String& newMessage)
  282. {
  283. noChoicesMessage = newMessage;
  284. }
  285. String ComboBox::getTextWhenNoChoicesAvailable() const
  286. {
  287. return noChoicesMessage;
  288. }
  289. //==============================================================================
  290. void ComboBox::paint (Graphics& g)
  291. {
  292. getLookAndFeel().drawComboBox (g, getWidth(), getHeight(), isButtonDown,
  293. label->getRight(), 0, getWidth() - label->getRight(), getHeight(),
  294. *this);
  295. if (textWhenNothingSelected.isNotEmpty() && label->getText().isEmpty() && ! label->isBeingEdited())
  296. getLookAndFeel().drawComboBoxTextWhenNothingSelected (g, *this, *label);
  297. }
  298. void ComboBox::resized()
  299. {
  300. if (getHeight() > 0 && getWidth() > 0)
  301. getLookAndFeel().positionComboBoxText (*this, *label);
  302. }
  303. void ComboBox::enablementChanged()
  304. {
  305. if (! isEnabled())
  306. hidePopup();
  307. repaint();
  308. }
  309. void ComboBox::colourChanged()
  310. {
  311. lookAndFeelChanged();
  312. }
  313. void ComboBox::parentHierarchyChanged()
  314. {
  315. lookAndFeelChanged();
  316. }
  317. void ComboBox::lookAndFeelChanged()
  318. {
  319. repaint();
  320. {
  321. std::unique_ptr<Label> newLabel (getLookAndFeel().createComboBoxTextBox (*this));
  322. jassert (newLabel != nullptr);
  323. if (label != nullptr)
  324. {
  325. newLabel->setEditable (label->isEditable());
  326. newLabel->setJustificationType (label->getJustificationType());
  327. newLabel->setTooltip (label->getTooltip());
  328. newLabel->setText (label->getText(), dontSendNotification);
  329. }
  330. std::swap (label, newLabel);
  331. }
  332. addAndMakeVisible (label.get());
  333. EditableState newEditableState = (label->isEditable() ? labelIsEditable : labelIsNotEditable);
  334. if (newEditableState != labelEditableState)
  335. {
  336. labelEditableState = newEditableState;
  337. setWantsKeyboardFocus (labelEditableState == labelIsNotEditable);
  338. }
  339. label->onTextChange = [this] { triggerAsyncUpdate(); };
  340. label->addMouseListener (this, false);
  341. label->setAccessible (labelEditableState == labelIsEditable);
  342. label->setColour (Label::backgroundColourId, Colours::transparentBlack);
  343. label->setColour (Label::textColourId, findColour (ComboBox::textColourId));
  344. label->setColour (TextEditor::textColourId, findColour (ComboBox::textColourId));
  345. label->setColour (TextEditor::backgroundColourId, Colours::transparentBlack);
  346. label->setColour (TextEditor::highlightColourId, findColour (TextEditor::highlightColourId));
  347. label->setColour (TextEditor::outlineColourId, Colours::transparentBlack);
  348. resized();
  349. }
  350. //==============================================================================
  351. bool ComboBox::keyPressed (const KeyPress& key)
  352. {
  353. if (key == KeyPress::upKey || key == KeyPress::leftKey)
  354. {
  355. nudgeSelectedItem (-1);
  356. return true;
  357. }
  358. if (key == KeyPress::downKey || key == KeyPress::rightKey)
  359. {
  360. nudgeSelectedItem (1);
  361. return true;
  362. }
  363. if (key == KeyPress::returnKey)
  364. {
  365. showPopupIfNotActive();
  366. return true;
  367. }
  368. return false;
  369. }
  370. bool ComboBox::keyStateChanged (const bool isKeyDown)
  371. {
  372. // only forward key events that aren't used by this component
  373. return isKeyDown
  374. && (KeyPress::isKeyCurrentlyDown (KeyPress::upKey)
  375. || KeyPress::isKeyCurrentlyDown (KeyPress::leftKey)
  376. || KeyPress::isKeyCurrentlyDown (KeyPress::downKey)
  377. || KeyPress::isKeyCurrentlyDown (KeyPress::rightKey));
  378. }
  379. //==============================================================================
  380. void ComboBox::focusGained (FocusChangeType) { repaint(); }
  381. void ComboBox::focusLost (FocusChangeType) { repaint(); }
  382. //==============================================================================
  383. void ComboBox::showPopupIfNotActive()
  384. {
  385. if (! menuActive)
  386. {
  387. menuActive = true;
  388. // as this method was triggered by a mouse event, the same mouse event may have
  389. // exited the modal state of other popups currently on the screen. By calling
  390. // showPopup asynchronously, we are giving the other popups a chance to properly
  391. // close themselves
  392. MessageManager::callAsync ([safePointer = SafePointer<ComboBox> { this }]() mutable { if (safePointer != nullptr) safePointer->showPopup(); });
  393. repaint();
  394. }
  395. }
  396. void ComboBox::hidePopup()
  397. {
  398. if (menuActive)
  399. {
  400. menuActive = false;
  401. PopupMenu::dismissAllActiveMenus();
  402. repaint();
  403. }
  404. }
  405. static void comboBoxPopupMenuFinishedCallback (int result, ComboBox* combo)
  406. {
  407. if (combo != nullptr)
  408. {
  409. combo->hidePopup();
  410. if (result != 0)
  411. combo->setSelectedId (result);
  412. }
  413. }
  414. void ComboBox::showPopup()
  415. {
  416. if (! menuActive)
  417. menuActive = true;
  418. auto menu = currentMenu;
  419. if (menu.getNumItems() > 0)
  420. {
  421. auto selectedId = getSelectedId();
  422. for (PopupMenu::MenuItemIterator iterator (menu, true); iterator.next();)
  423. {
  424. auto& item = iterator.getItem();
  425. if (item.itemID != 0)
  426. item.isTicked = (item.itemID == selectedId);
  427. }
  428. }
  429. else
  430. {
  431. menu.addItem (1, noChoicesMessage, false, false);
  432. }
  433. auto& lf = getLookAndFeel();
  434. menu.setLookAndFeel (&lf);
  435. menu.showMenuAsync (lf.getOptionsForComboBoxPopupMenu (*this, *label),
  436. ModalCallbackFunction::forComponent (comboBoxPopupMenuFinishedCallback, this));
  437. }
  438. //==============================================================================
  439. void ComboBox::mouseDown (const MouseEvent& e)
  440. {
  441. beginDragAutoRepeat (300);
  442. isButtonDown = isEnabled() && ! e.mods.isPopupMenu();
  443. if (isButtonDown && (e.eventComponent == this || ! label->isEditable()))
  444. showPopupIfNotActive();
  445. }
  446. void ComboBox::mouseDrag (const MouseEvent& e)
  447. {
  448. beginDragAutoRepeat (50);
  449. if (isButtonDown && e.mouseWasDraggedSinceMouseDown())
  450. showPopupIfNotActive();
  451. }
  452. void ComboBox::mouseUp (const MouseEvent& e2)
  453. {
  454. if (isButtonDown)
  455. {
  456. isButtonDown = false;
  457. repaint();
  458. auto e = e2.getEventRelativeTo (this);
  459. if (reallyContains (e.getPosition(), true)
  460. && (e2.eventComponent == this || ! label->isEditable()))
  461. {
  462. showPopupIfNotActive();
  463. }
  464. }
  465. }
  466. void ComboBox::mouseWheelMove (const MouseEvent& e, const MouseWheelDetails& wheel)
  467. {
  468. if (! menuActive && scrollWheelEnabled && e.eventComponent == this && wheel.deltaY != 0.0f)
  469. {
  470. mouseWheelAccumulator += wheel.deltaY * 5.0f;
  471. while (mouseWheelAccumulator > 1.0f)
  472. {
  473. mouseWheelAccumulator -= 1.0f;
  474. nudgeSelectedItem (-1);
  475. }
  476. while (mouseWheelAccumulator < -1.0f)
  477. {
  478. mouseWheelAccumulator += 1.0f;
  479. nudgeSelectedItem (1);
  480. }
  481. }
  482. else
  483. {
  484. Component::mouseWheelMove (e, wheel);
  485. }
  486. }
  487. void ComboBox::setScrollWheelEnabled (bool enabled) noexcept
  488. {
  489. scrollWheelEnabled = enabled;
  490. }
  491. //==============================================================================
  492. void ComboBox::addListener (ComboBox::Listener* l) { listeners.add (l); }
  493. void ComboBox::removeListener (ComboBox::Listener* l) { listeners.remove (l); }
  494. void ComboBox::handleAsyncUpdate()
  495. {
  496. Component::BailOutChecker checker (this);
  497. listeners.callChecked (checker, [this] (Listener& l) { l.comboBoxChanged (this); });
  498. if (checker.shouldBailOut())
  499. return;
  500. if (onChange != nullptr)
  501. onChange();
  502. if (auto* handler = getAccessibilityHandler())
  503. handler->notifyAccessibilityEvent (AccessibilityEvent::valueChanged);
  504. }
  505. void ComboBox::sendChange (const NotificationType notification)
  506. {
  507. if (notification != dontSendNotification)
  508. triggerAsyncUpdate();
  509. if (notification == sendNotificationSync)
  510. handleUpdateNowIfNeeded();
  511. }
  512. // Old deprecated methods - remove eventually...
  513. void ComboBox::clear (const bool dontSendChange) { clear (dontSendChange ? dontSendNotification : sendNotification); }
  514. void ComboBox::setSelectedItemIndex (const int index, const bool dontSendChange) { setSelectedItemIndex (index, dontSendChange ? dontSendNotification : sendNotification); }
  515. void ComboBox::setSelectedId (const int newItemId, const bool dontSendChange) { setSelectedId (newItemId, dontSendChange ? dontSendNotification : sendNotification); }
  516. void ComboBox::setText (const String& newText, const bool dontSendChange) { setText (newText, dontSendChange ? dontSendNotification : sendNotification); }
  517. //==============================================================================
  518. class ComboBoxAccessibilityHandler : public AccessibilityHandler
  519. {
  520. public:
  521. explicit ComboBoxAccessibilityHandler (ComboBox& comboBoxToWrap)
  522. : AccessibilityHandler (comboBoxToWrap,
  523. AccessibilityRole::comboBox,
  524. getAccessibilityActions (comboBoxToWrap),
  525. { std::make_unique<ComboBoxValueInterface> (comboBoxToWrap) }),
  526. comboBox (comboBoxToWrap)
  527. {
  528. }
  529. AccessibleState getCurrentState() const override
  530. {
  531. auto state = AccessibilityHandler::getCurrentState().withExpandable();
  532. return comboBox.isPopupActive() ? state.withExpanded() : state.withCollapsed();
  533. }
  534. String getTitle() const override { return comboBox.getText(); }
  535. String getHelp() const override { return comboBox.getTooltip(); }
  536. private:
  537. class ComboBoxValueInterface : public AccessibilityTextValueInterface
  538. {
  539. public:
  540. explicit ComboBoxValueInterface (ComboBox& comboBoxToWrap)
  541. : comboBox (comboBoxToWrap)
  542. {
  543. }
  544. bool isReadOnly() const override { return true; }
  545. String getCurrentValueAsString() const override { return comboBox.getText(); }
  546. void setValueAsString (const String&) override {}
  547. private:
  548. ComboBox& comboBox;
  549. //==============================================================================
  550. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ComboBoxValueInterface)
  551. };
  552. static AccessibilityActions getAccessibilityActions (ComboBox& comboBox)
  553. {
  554. return AccessibilityActions().addAction (AccessibilityActionType::press, [&comboBox] { comboBox.showPopup(); })
  555. .addAction (AccessibilityActionType::showMenu, [&comboBox] { comboBox.showPopup(); });
  556. }
  557. ComboBox& comboBox;
  558. //==============================================================================
  559. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ComboBoxAccessibilityHandler)
  560. };
  561. std::unique_ptr<AccessibilityHandler> ComboBox::createAccessibilityHandler()
  562. {
  563. return std::make_unique<ComboBoxAccessibilityHandler> (*this);
  564. }
  565. } // namespace juce