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.

686 lines
19KB

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