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_ComboBox.cpp 18KB

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