juce_ComboBox.cpp 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646
  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. noChoicesMessage (TRANS("(no choices)"))
  24. {
  25. setRepaintsOnMouseActivity (true);
  26. lookAndFeelChanged();
  27. currentId.addListener (this);
  28. }
  29. ComboBox::~ComboBox()
  30. {
  31. currentId.removeListener (this);
  32. hidePopup();
  33. label.reset();
  34. }
  35. //==============================================================================
  36. void ComboBox::setEditableText (const bool isEditable)
  37. {
  38. if (label->isEditableOnSingleClick() != isEditable || label->isEditableOnDoubleClick() != isEditable)
  39. {
  40. label->setEditable (isEditable, isEditable, false);
  41. labelEditableState = (isEditable ? labelIsEditable : labelIsNotEditable);
  42. setWantsKeyboardFocus (labelEditableState == labelIsNotEditable);
  43. resized();
  44. }
  45. }
  46. bool ComboBox::isTextEditable() const noexcept
  47. {
  48. return label->isEditable();
  49. }
  50. void ComboBox::setJustificationType (Justification justification)
  51. {
  52. label->setJustificationType (justification);
  53. }
  54. Justification ComboBox::getJustificationType() const noexcept
  55. {
  56. return label->getJustificationType();
  57. }
  58. void ComboBox::setTooltip (const String& newTooltip)
  59. {
  60. SettableTooltipClient::setTooltip (newTooltip);
  61. label->setTooltip (newTooltip);
  62. }
  63. //==============================================================================
  64. void ComboBox::addItem (const String& newItemText, int newItemId)
  65. {
  66. // you can't add empty strings to the list..
  67. jassert (newItemText.isNotEmpty());
  68. // IDs must be non-zero, as zero is used to indicate a lack of selection.
  69. jassert (newItemId != 0);
  70. // you shouldn't use duplicate item IDs!
  71. jassert (getItemForId (newItemId) == nullptr);
  72. if (newItemText.isNotEmpty() && newItemId != 0)
  73. currentMenu.addItem (newItemId, newItemText, true, false);
  74. }
  75. void ComboBox::addItemList (const StringArray& itemsToAdd, int firstItemID)
  76. {
  77. for (auto& i : itemsToAdd)
  78. currentMenu.addItem (firstItemID++, i);
  79. }
  80. void ComboBox::addSeparator()
  81. {
  82. currentMenu.addSeparator();
  83. }
  84. void ComboBox::addSectionHeading (const String& headingName)
  85. {
  86. // you can't add empty strings to the list..
  87. jassert (headingName.isNotEmpty());
  88. if (headingName.isNotEmpty())
  89. currentMenu.addSectionHeader (headingName);
  90. }
  91. void ComboBox::setItemEnabled (int itemId, bool shouldBeEnabled)
  92. {
  93. if (auto* item = getItemForId (itemId))
  94. item->isEnabled = shouldBeEnabled;
  95. }
  96. bool ComboBox::isItemEnabled (int itemId) const noexcept
  97. {
  98. if (auto* item = getItemForId (itemId))
  99. return item->isEnabled;
  100. return false;
  101. }
  102. void ComboBox::changeItemText (int itemId, const String& newText)
  103. {
  104. if (auto* item = getItemForId (itemId))
  105. item->text = newText;
  106. else
  107. jassertfalse;
  108. }
  109. void ComboBox::clear (const NotificationType notification)
  110. {
  111. currentMenu.clear();
  112. if (! label->isEditable())
  113. setSelectedItemIndex (-1, notification);
  114. }
  115. //==============================================================================
  116. PopupMenu::Item* ComboBox::getItemForId (int itemId) const noexcept
  117. {
  118. if (itemId != 0)
  119. {
  120. for (PopupMenu::MenuItemIterator iterator (currentMenu, true); iterator.next();)
  121. {
  122. auto& item = iterator.getItem();
  123. if (item.itemID == itemId)
  124. return &item;
  125. }
  126. }
  127. return nullptr;
  128. }
  129. PopupMenu::Item* ComboBox::getItemForIndex (const int index) const noexcept
  130. {
  131. int n = 0;
  132. for (PopupMenu::MenuItemIterator iterator (currentMenu, true); iterator.next();)
  133. {
  134. auto& item = iterator.getItem();
  135. if (item.itemID != 0)
  136. if (n++ == index)
  137. return &item;
  138. }
  139. return nullptr;
  140. }
  141. int ComboBox::getNumItems() const noexcept
  142. {
  143. int n = 0;
  144. for (PopupMenu::MenuItemIterator iterator (currentMenu, true); iterator.next();)
  145. {
  146. auto& item = iterator.getItem();
  147. if (item.itemID != 0)
  148. n++;
  149. }
  150. return n;
  151. }
  152. String ComboBox::getItemText (const int index) const
  153. {
  154. if (auto* item = getItemForIndex (index))
  155. return item->text;
  156. return {};
  157. }
  158. int ComboBox::getItemId (const int index) const noexcept
  159. {
  160. if (auto* item = getItemForIndex (index))
  161. return item->itemID;
  162. return 0;
  163. }
  164. int ComboBox::indexOfItemId (const int itemId) const noexcept
  165. {
  166. if (itemId != 0)
  167. {
  168. int n = 0;
  169. for (PopupMenu::MenuItemIterator iterator (currentMenu, true); iterator.next();)
  170. {
  171. auto& item = iterator.getItem();
  172. if (item.itemID == itemId)
  173. return n;
  174. else if (item.itemID != 0)
  175. n++;
  176. }
  177. }
  178. return -1;
  179. }
  180. //==============================================================================
  181. int ComboBox::getSelectedItemIndex() const
  182. {
  183. auto index = indexOfItemId (currentId.getValue());
  184. if (getText() != getItemText (index))
  185. index = -1;
  186. return index;
  187. }
  188. void ComboBox::setSelectedItemIndex (const int index, const NotificationType notification)
  189. {
  190. setSelectedId (getItemId (index), notification);
  191. }
  192. int ComboBox::getSelectedId() const noexcept
  193. {
  194. if (auto* item = getItemForId (currentId.getValue()))
  195. if (getText() == item->text)
  196. return item->itemID;
  197. return 0;
  198. }
  199. void ComboBox::setSelectedId (const int newItemId, const NotificationType notification)
  200. {
  201. auto* item = getItemForId (newItemId);
  202. auto newItemText = item != nullptr ? item->text : String();
  203. if (lastCurrentId != newItemId || label->getText() != newItemText)
  204. {
  205. label->setText (newItemText, dontSendNotification);
  206. lastCurrentId = newItemId;
  207. currentId = newItemId;
  208. repaint(); // for the benefit of the 'none selected' text
  209. sendChange (notification);
  210. }
  211. }
  212. bool ComboBox::selectIfEnabled (const int index)
  213. {
  214. if (auto* item = getItemForIndex (index))
  215. {
  216. if (item->isEnabled)
  217. {
  218. setSelectedItemIndex (index);
  219. return true;
  220. }
  221. }
  222. return false;
  223. }
  224. bool ComboBox::nudgeSelectedItem (int delta)
  225. {
  226. for (int i = getSelectedItemIndex() + delta; isPositiveAndBelow (i, getNumItems()); i += delta)
  227. if (selectIfEnabled (i))
  228. return true;
  229. return false;
  230. }
  231. void ComboBox::valueChanged (Value&)
  232. {
  233. if (lastCurrentId != (int) currentId.getValue())
  234. setSelectedId (currentId.getValue());
  235. }
  236. //==============================================================================
  237. String ComboBox::getText() const
  238. {
  239. return label->getText();
  240. }
  241. void ComboBox::setText (const String& newText, const NotificationType notification)
  242. {
  243. for (PopupMenu::MenuItemIterator iterator (currentMenu, true); iterator.next();)
  244. {
  245. auto& item = iterator.getItem();
  246. if (item.itemID != 0
  247. && item.text == newText)
  248. {
  249. setSelectedId (item.itemID, notification);
  250. return;
  251. }
  252. }
  253. lastCurrentId = 0;
  254. currentId = 0;
  255. repaint();
  256. if (label->getText() != newText)
  257. {
  258. label->setText (newText, dontSendNotification);
  259. sendChange (notification);
  260. }
  261. }
  262. void ComboBox::showEditor()
  263. {
  264. jassert (isTextEditable()); // you probably shouldn't do this to a non-editable combo box?
  265. label->showEditor();
  266. }
  267. //==============================================================================
  268. void ComboBox::setTextWhenNothingSelected (const String& newMessage)
  269. {
  270. if (textWhenNothingSelected != newMessage)
  271. {
  272. textWhenNothingSelected = newMessage;
  273. repaint();
  274. }
  275. }
  276. String ComboBox::getTextWhenNothingSelected() const
  277. {
  278. return textWhenNothingSelected;
  279. }
  280. void ComboBox::setTextWhenNoChoicesAvailable (const String& newMessage)
  281. {
  282. noChoicesMessage = newMessage;
  283. }
  284. String ComboBox::getTextWhenNoChoicesAvailable() const
  285. {
  286. return noChoicesMessage;
  287. }
  288. //==============================================================================
  289. void ComboBox::paint (Graphics& g)
  290. {
  291. getLookAndFeel().drawComboBox (g, getWidth(), getHeight(), isButtonDown,
  292. label->getRight(), 0, getWidth() - label->getRight(), getHeight(),
  293. *this);
  294. if (textWhenNothingSelected.isNotEmpty() && label->getText().isEmpty() && ! label->isBeingEdited())
  295. getLookAndFeel().drawComboBoxTextWhenNothingSelected (g, *this, *label);
  296. }
  297. void ComboBox::resized()
  298. {
  299. if (getHeight() > 0 && getWidth() > 0)
  300. getLookAndFeel().positionComboBoxText (*this, *label);
  301. }
  302. void ComboBox::enablementChanged()
  303. {
  304. repaint();
  305. }
  306. void ComboBox::colourChanged()
  307. {
  308. lookAndFeelChanged();
  309. }
  310. void ComboBox::parentHierarchyChanged()
  311. {
  312. lookAndFeelChanged();
  313. }
  314. void ComboBox::lookAndFeelChanged()
  315. {
  316. repaint();
  317. {
  318. std::unique_ptr<Label> newLabel (getLookAndFeel().createComboBoxTextBox (*this));
  319. jassert (newLabel != nullptr);
  320. if (label != nullptr)
  321. {
  322. newLabel->setEditable (label->isEditable());
  323. newLabel->setJustificationType (label->getJustificationType());
  324. newLabel->setTooltip (label->getTooltip());
  325. newLabel->setText (label->getText(), dontSendNotification);
  326. }
  327. std::swap (label, newLabel);
  328. }
  329. addAndMakeVisible (label.get());
  330. EditableState newEditableState = (label->isEditable() ? labelIsEditable : labelIsNotEditable);
  331. if (newEditableState != labelEditableState)
  332. {
  333. labelEditableState = newEditableState;
  334. setWantsKeyboardFocus (labelEditableState == labelIsNotEditable);
  335. }
  336. label->onTextChange = [this] { triggerAsyncUpdate(); };
  337. label->addMouseListener (this, false);
  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. } // namespace juce