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.

644 lines
17KB

  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() && 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. }
  391. }
  392. void ComboBox::hidePopup()
  393. {
  394. if (menuActive)
  395. {
  396. menuActive = false;
  397. PopupMenu::dismissAllActiveMenus();
  398. repaint();
  399. }
  400. }
  401. static void comboBoxPopupMenuFinishedCallback (int result, ComboBox* combo)
  402. {
  403. if (combo != nullptr)
  404. {
  405. combo->hidePopup();
  406. if (result != 0)
  407. combo->setSelectedId (result);
  408. }
  409. }
  410. void ComboBox::showPopup()
  411. {
  412. if (! menuActive)
  413. menuActive = true;
  414. auto menu = currentMenu;
  415. if (menu.getNumItems() > 0)
  416. {
  417. auto selectedId = getSelectedId();
  418. for (PopupMenu::MenuItemIterator iterator (menu, true); iterator.next();)
  419. {
  420. auto& item = iterator.getItem();
  421. if (item.itemID != 0)
  422. item.isTicked = (item.itemID == selectedId);
  423. }
  424. }
  425. else
  426. {
  427. menu.addItem (1, noChoicesMessage, false, false);
  428. }
  429. auto& lf = getLookAndFeel();
  430. menu.setLookAndFeel (&lf);
  431. menu.showMenuAsync (lf.getOptionsForComboBoxPopupMenu (*this, *label),
  432. ModalCallbackFunction::forComponent (comboBoxPopupMenuFinishedCallback, this));
  433. }
  434. //==============================================================================
  435. void ComboBox::mouseDown (const MouseEvent& e)
  436. {
  437. beginDragAutoRepeat (300);
  438. isButtonDown = isEnabled() && ! e.mods.isPopupMenu();
  439. if (isButtonDown && (e.eventComponent == this || ! label->isEditable()))
  440. showPopupIfNotActive();
  441. }
  442. void ComboBox::mouseDrag (const MouseEvent& e)
  443. {
  444. beginDragAutoRepeat (50);
  445. if (isButtonDown && e.mouseWasDraggedSinceMouseDown())
  446. showPopupIfNotActive();
  447. }
  448. void ComboBox::mouseUp (const MouseEvent& e2)
  449. {
  450. if (isButtonDown)
  451. {
  452. isButtonDown = false;
  453. repaint();
  454. auto e = e2.getEventRelativeTo (this);
  455. if (reallyContains (e.getPosition(), true)
  456. && (e2.eventComponent == this || ! label->isEditable()))
  457. {
  458. showPopupIfNotActive();
  459. }
  460. }
  461. }
  462. void ComboBox::mouseWheelMove (const MouseEvent& e, const MouseWheelDetails& wheel)
  463. {
  464. if (! menuActive && scrollWheelEnabled && e.eventComponent == this && wheel.deltaY != 0.0f)
  465. {
  466. mouseWheelAccumulator += wheel.deltaY * 5.0f;
  467. while (mouseWheelAccumulator > 1.0f)
  468. {
  469. mouseWheelAccumulator -= 1.0f;
  470. nudgeSelectedItem (-1);
  471. }
  472. while (mouseWheelAccumulator < -1.0f)
  473. {
  474. mouseWheelAccumulator += 1.0f;
  475. nudgeSelectedItem (1);
  476. }
  477. }
  478. else
  479. {
  480. Component::mouseWheelMove (e, wheel);
  481. }
  482. }
  483. void ComboBox::setScrollWheelEnabled (bool enabled) noexcept
  484. {
  485. scrollWheelEnabled = enabled;
  486. }
  487. //==============================================================================
  488. void ComboBox::addListener (ComboBox::Listener* l) { listeners.add (l); }
  489. void ComboBox::removeListener (ComboBox::Listener* l) { listeners.remove (l); }
  490. void ComboBox::handleAsyncUpdate()
  491. {
  492. Component::BailOutChecker checker (this);
  493. listeners.callChecked (checker, [this] (Listener& l) { l.comboBoxChanged (this); });
  494. if (checker.shouldBailOut())
  495. return;
  496. if (onChange != nullptr)
  497. onChange();
  498. }
  499. void ComboBox::sendChange (const NotificationType notification)
  500. {
  501. if (notification != dontSendNotification)
  502. triggerAsyncUpdate();
  503. if (notification == sendNotificationSync)
  504. handleUpdateNowIfNeeded();
  505. }
  506. // Old deprecated methods - remove eventually...
  507. void ComboBox::clear (const bool dontSendChange) { clear (dontSendChange ? dontSendNotification : sendNotification); }
  508. void ComboBox::setSelectedItemIndex (const int index, const bool dontSendChange) { setSelectedItemIndex (index, dontSendChange ? dontSendNotification : sendNotification); }
  509. void ComboBox::setSelectedId (const int newItemId, const bool dontSendChange) { setSelectedId (newItemId, dontSendChange ? dontSendNotification : sendNotification); }
  510. void ComboBox::setText (const String& newText, const bool dontSendChange) { setText (newText, dontSendChange ? dontSendNotification : sendNotification); }
  511. } // namespace juce