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.

652 lines
18KB

  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 selecion.
  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()
  295. && label->getText().isEmpty()
  296. && ! label->isBeingEdited())
  297. {
  298. g.setColour (findColour (textColourId).withMultipliedAlpha (0.5f));
  299. g.setFont (label->getLookAndFeel().getLabelFont (*label));
  300. g.drawFittedText (textWhenNothingSelected, label->getBounds().reduced (2, 1),
  301. label->getJustificationType(),
  302. jmax (1, (int) (label->getHeight() / label->getFont().getHeight())));
  303. }
  304. }
  305. void ComboBox::resized()
  306. {
  307. if (getHeight() > 0 && getWidth() > 0)
  308. getLookAndFeel().positionComboBoxText (*this, *label);
  309. }
  310. void ComboBox::enablementChanged()
  311. {
  312. repaint();
  313. }
  314. void ComboBox::colourChanged()
  315. {
  316. lookAndFeelChanged();
  317. }
  318. void ComboBox::parentHierarchyChanged()
  319. {
  320. lookAndFeelChanged();
  321. }
  322. void ComboBox::lookAndFeelChanged()
  323. {
  324. repaint();
  325. {
  326. std::unique_ptr<Label> newLabel (getLookAndFeel().createComboBoxTextBox (*this));
  327. jassert (newLabel != nullptr);
  328. if (label != nullptr)
  329. {
  330. newLabel->setEditable (label->isEditable());
  331. newLabel->setJustificationType (label->getJustificationType());
  332. newLabel->setTooltip (label->getTooltip());
  333. newLabel->setText (label->getText(), dontSendNotification);
  334. }
  335. std::swap (label, newLabel);
  336. }
  337. addAndMakeVisible (label.get());
  338. EditableState newEditableState = (label->isEditable() ? labelIsEditable : labelIsNotEditable);
  339. if (newEditableState != labelEditableState)
  340. {
  341. labelEditableState = newEditableState;
  342. setWantsKeyboardFocus (labelEditableState == labelIsNotEditable);
  343. }
  344. label->onTextChange = [this] { triggerAsyncUpdate(); };
  345. label->addMouseListener (this, false);
  346. label->setColour (Label::backgroundColourId, Colours::transparentBlack);
  347. label->setColour (Label::textColourId, findColour (ComboBox::textColourId));
  348. label->setColour (TextEditor::textColourId, findColour (ComboBox::textColourId));
  349. label->setColour (TextEditor::backgroundColourId, Colours::transparentBlack);
  350. label->setColour (TextEditor::highlightColourId, findColour (TextEditor::highlightColourId));
  351. label->setColour (TextEditor::outlineColourId, Colours::transparentBlack);
  352. resized();
  353. }
  354. //==============================================================================
  355. bool ComboBox::keyPressed (const KeyPress& key)
  356. {
  357. if (key == KeyPress::upKey || key == KeyPress::leftKey)
  358. {
  359. nudgeSelectedItem (-1);
  360. return true;
  361. }
  362. if (key == KeyPress::downKey || key == KeyPress::rightKey)
  363. {
  364. nudgeSelectedItem (1);
  365. return true;
  366. }
  367. if (key == KeyPress::returnKey)
  368. {
  369. showPopupIfNotActive();
  370. return true;
  371. }
  372. return false;
  373. }
  374. bool ComboBox::keyStateChanged (const bool isKeyDown)
  375. {
  376. // only forward key events that aren't used by this component
  377. return isKeyDown
  378. && (KeyPress::isKeyCurrentlyDown (KeyPress::upKey)
  379. || KeyPress::isKeyCurrentlyDown (KeyPress::leftKey)
  380. || KeyPress::isKeyCurrentlyDown (KeyPress::downKey)
  381. || KeyPress::isKeyCurrentlyDown (KeyPress::rightKey));
  382. }
  383. //==============================================================================
  384. void ComboBox::focusGained (FocusChangeType) { repaint(); }
  385. void ComboBox::focusLost (FocusChangeType) { repaint(); }
  386. //==============================================================================
  387. void ComboBox::showPopupIfNotActive()
  388. {
  389. if (! menuActive)
  390. {
  391. menuActive = true;
  392. SafePointer<ComboBox> safePointer (this);
  393. // as this method was triggered by a mouse event, the same mouse event may have
  394. // exited the modal state of other popups currently on the screen. By calling
  395. // showPopup asynchronously, we are giving the other popups a chance to properly
  396. // close themselves
  397. MessageManager::callAsync ([safePointer]() mutable { if (safePointer != nullptr) safePointer->showPopup(); });
  398. }
  399. }
  400. void ComboBox::hidePopup()
  401. {
  402. if (menuActive)
  403. {
  404. menuActive = false;
  405. PopupMenu::dismissAllActiveMenus();
  406. repaint();
  407. }
  408. }
  409. static void comboBoxPopupMenuFinishedCallback (int result, ComboBox* combo)
  410. {
  411. if (combo != nullptr)
  412. {
  413. combo->hidePopup();
  414. if (result != 0)
  415. combo->setSelectedId (result);
  416. }
  417. }
  418. void ComboBox::showPopup()
  419. {
  420. if (! menuActive)
  421. menuActive = true;
  422. auto menu = currentMenu;
  423. if (menu.getNumItems() > 0)
  424. {
  425. auto selectedId = getSelectedId();
  426. for (PopupMenu::MenuItemIterator iterator (menu, true); iterator.next();)
  427. {
  428. auto& item = iterator.getItem();
  429. if (item.itemID != 0)
  430. item.isTicked = (item.itemID == selectedId);
  431. }
  432. }
  433. else
  434. {
  435. menu.addItem (1, noChoicesMessage, false, false);
  436. }
  437. auto& lf = getLookAndFeel();
  438. menu.setLookAndFeel (&lf);
  439. menu.showMenuAsync (lf.getOptionsForComboBoxPopupMenu (*this, *label),
  440. ModalCallbackFunction::forComponent (comboBoxPopupMenuFinishedCallback, this));
  441. }
  442. //==============================================================================
  443. void ComboBox::mouseDown (const MouseEvent& e)
  444. {
  445. beginDragAutoRepeat (300);
  446. isButtonDown = isEnabled() && ! e.mods.isPopupMenu();
  447. if (isButtonDown && (e.eventComponent == this || ! label->isEditable()))
  448. showPopupIfNotActive();
  449. }
  450. void ComboBox::mouseDrag (const MouseEvent& e)
  451. {
  452. beginDragAutoRepeat (50);
  453. if (isButtonDown && e.mouseWasDraggedSinceMouseDown())
  454. showPopupIfNotActive();
  455. }
  456. void ComboBox::mouseUp (const MouseEvent& e2)
  457. {
  458. if (isButtonDown)
  459. {
  460. isButtonDown = false;
  461. repaint();
  462. auto e = e2.getEventRelativeTo (this);
  463. if (reallyContains (e.getPosition(), true)
  464. && (e2.eventComponent == this || ! label->isEditable()))
  465. {
  466. showPopupIfNotActive();
  467. }
  468. }
  469. }
  470. void ComboBox::mouseWheelMove (const MouseEvent& e, const MouseWheelDetails& wheel)
  471. {
  472. if (! menuActive && scrollWheelEnabled && e.eventComponent == this && wheel.deltaY != 0.0f)
  473. {
  474. mouseWheelAccumulator += wheel.deltaY * 5.0f;
  475. while (mouseWheelAccumulator > 1.0f)
  476. {
  477. mouseWheelAccumulator -= 1.0f;
  478. nudgeSelectedItem (-1);
  479. }
  480. while (mouseWheelAccumulator < -1.0f)
  481. {
  482. mouseWheelAccumulator += 1.0f;
  483. nudgeSelectedItem (1);
  484. }
  485. }
  486. else
  487. {
  488. Component::mouseWheelMove (e, wheel);
  489. }
  490. }
  491. void ComboBox::setScrollWheelEnabled (bool enabled) noexcept
  492. {
  493. scrollWheelEnabled = enabled;
  494. }
  495. //==============================================================================
  496. void ComboBox::addListener (ComboBox::Listener* l) { listeners.add (l); }
  497. void ComboBox::removeListener (ComboBox::Listener* l) { listeners.remove (l); }
  498. void ComboBox::handleAsyncUpdate()
  499. {
  500. Component::BailOutChecker checker (this);
  501. listeners.callChecked (checker, [this] (Listener& l) { l.comboBoxChanged (this); });
  502. if (checker.shouldBailOut())
  503. return;
  504. if (onChange != nullptr)
  505. onChange();
  506. }
  507. void ComboBox::sendChange (const NotificationType notification)
  508. {
  509. if (notification != dontSendNotification)
  510. triggerAsyncUpdate();
  511. if (notification == sendNotificationSync)
  512. handleUpdateNowIfNeeded();
  513. }
  514. // Old deprecated methods - remove eventually...
  515. void ComboBox::clear (const bool dontSendChange) { clear (dontSendChange ? dontSendNotification : sendNotification); }
  516. void ComboBox::setSelectedItemIndex (const int index, const bool dontSendChange) { setSelectedItemIndex (index, dontSendChange ? dontSendNotification : sendNotification); }
  517. void ComboBox::setSelectedId (const int newItemId, const bool dontSendChange) { setSelectedId (newItemId, dontSendChange ? dontSendNotification : sendNotification); }
  518. void ComboBox::setText (const String& newText, const bool dontSendChange) { setText (newText, dontSendChange ? dontSendNotification : sendNotification); }
  519. } // namespace juce