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.

645 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 = nullptr;
  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 firstItemIdOffset)
  76. {
  77. for (int i = 0; i < itemsToAdd.size(); ++i)
  78. currentMenu.addItem (i + firstItemIdOffset, itemsToAdd[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. ScopedPointer<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. label = newLabel;
  336. }
  337. addAndMakeVisible (label);
  338. EditableState newEditableState = (label->isEditable() ? labelIsEditable : labelIsNotEditable);
  339. if (newEditableState != labelEditableState)
  340. {
  341. labelEditableState = newEditableState;
  342. setWantsKeyboardFocus (labelEditableState == labelIsNotEditable);
  343. }
  344. label->addListener (this);
  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. void ComboBox::labelTextChanged (Label*)
  387. {
  388. triggerAsyncUpdate();
  389. }
  390. //==============================================================================
  391. void ComboBox::showPopupIfNotActive()
  392. {
  393. if (! menuActive)
  394. {
  395. menuActive = true;
  396. SafePointer<ComboBox> safePointer (this);
  397. // as this method was triggered by a mouse event, the same mouse event may have
  398. // exited the modal state of other popups currently on the screen. By calling
  399. // showPopup asynchronously, we are giving the other popups a chance to properly
  400. // close themselves
  401. MessageManager::callAsync([safePointer] () mutable { if (safePointer != nullptr) safePointer->showPopup(); });
  402. }
  403. }
  404. void ComboBox::hidePopup()
  405. {
  406. if (menuActive)
  407. {
  408. menuActive = false;
  409. PopupMenu::dismissAllActiveMenus();
  410. repaint();
  411. }
  412. }
  413. static void comboBoxPopupMenuFinishedCallback (int result, ComboBox* combo)
  414. {
  415. if (combo != nullptr)
  416. {
  417. combo->hidePopup();
  418. if (result != 0)
  419. combo->setSelectedId (result);
  420. }
  421. }
  422. void ComboBox::showPopup()
  423. {
  424. PopupMenu noChoicesMenu;
  425. const bool hasItems = (currentMenu.getNumItems() > 0);
  426. if (hasItems)
  427. {
  428. auto selectedId = getSelectedId();
  429. for (PopupMenu::MenuItemIterator iterator (currentMenu, true); iterator.next();)
  430. {
  431. auto& item = iterator.getItem();
  432. if (item.itemID != 0)
  433. item.isTicked = (item.itemID == selectedId);
  434. }
  435. }
  436. else
  437. {
  438. noChoicesMenu.addItem (1, noChoicesMessage, false, false);
  439. }
  440. auto& menuToShow = (hasItems ? currentMenu : noChoicesMenu);
  441. menuToShow.setLookAndFeel (&getLookAndFeel());
  442. menuToShow.showMenuAsync (PopupMenu::Options().withTargetComponent (this)
  443. .withItemThatMustBeVisible (getSelectedId())
  444. .withMinimumWidth (getWidth())
  445. .withMaximumNumColumns (1)
  446. .withStandardItemHeight (label->getHeight()),
  447. ModalCallbackFunction::forComponent (comboBoxPopupMenuFinishedCallback, this));
  448. }
  449. //==============================================================================
  450. void ComboBox::mouseDown (const MouseEvent& e)
  451. {
  452. beginDragAutoRepeat (300);
  453. isButtonDown = isEnabled() && ! e.mods.isPopupMenu();
  454. if (isButtonDown && (e.eventComponent == this || ! label->isEditable()))
  455. showPopupIfNotActive();
  456. }
  457. void ComboBox::mouseDrag (const MouseEvent& e)
  458. {
  459. beginDragAutoRepeat (50);
  460. if (isButtonDown && e.mouseWasDraggedSinceMouseDown())
  461. showPopupIfNotActive();
  462. }
  463. void ComboBox::mouseUp (const MouseEvent& e2)
  464. {
  465. if (isButtonDown)
  466. {
  467. isButtonDown = false;
  468. repaint();
  469. auto e = e2.getEventRelativeTo (this);
  470. if (reallyContains (e.getPosition(), true)
  471. && (e2.eventComponent == this || ! label->isEditable()))
  472. {
  473. showPopupIfNotActive();
  474. }
  475. }
  476. }
  477. void ComboBox::mouseWheelMove (const MouseEvent& e, const MouseWheelDetails& wheel)
  478. {
  479. if (! menuActive && scrollWheelEnabled && e.eventComponent == this && wheel.deltaY != 0.0f)
  480. {
  481. auto oldPos = (int) mouseWheelAccumulator;
  482. mouseWheelAccumulator += wheel.deltaY * 5.0f;
  483. if (auto delta = oldPos - (int) mouseWheelAccumulator)
  484. nudgeSelectedItem (delta);
  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 (ComboBoxListener* listener) { listeners.add (listener); }
  497. void ComboBox::removeListener (ComboBoxListener* listener) { listeners.remove (listener); }
  498. void ComboBox::handleAsyncUpdate()
  499. {
  500. Component::BailOutChecker checker (this);
  501. listeners.callChecked (checker, &ComboBox::Listener::comboBoxChanged, this);
  502. }
  503. void ComboBox::sendChange (const NotificationType notification)
  504. {
  505. if (notification != dontSendNotification)
  506. triggerAsyncUpdate();
  507. if (notification == sendNotificationSync)
  508. handleUpdateNowIfNeeded();
  509. }
  510. // Old deprecated methods - remove eventually...
  511. void ComboBox::clear (const bool dontSendChange) { clear (dontSendChange ? dontSendNotification : sendNotification); }
  512. void ComboBox::setSelectedItemIndex (const int index, const bool dontSendChange) { setSelectedItemIndex (index, dontSendChange ? dontSendNotification : sendNotification); }
  513. void ComboBox::setSelectedId (const int newItemId, const bool dontSendChange) { setSelectedId (newItemId, dontSendChange ? dontSendNotification : sendNotification); }
  514. void ComboBox::setText (const String& newText, const bool dontSendChange) { setText (newText, dontSendChange ? dontSendNotification : sendNotification); }
  515. } // namespace juce