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.

1162 lines
37KB

  1. /*
  2. ==============================================================================
  3. This file is part of the JUCE library.
  4. Copyright (c) 2020 - Raw Material Software Limited
  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 6 End-User License
  8. Agreement and JUCE Privacy Policy (both effective as of the 16th June 2020).
  9. End User License Agreement: www.juce.com/juce-6-licence
  10. Privacy Policy: www.juce.com/juce-privacy-policy
  11. Or: You may also use this code under the terms of the GPL v3 (see
  12. www.gnu.org/licenses).
  13. JUCE IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL WARRANTIES, WHETHER
  14. EXPRESSED OR IMPLIED, INCLUDING MERCHANTABILITY AND FITNESS FOR PURPOSE, ARE
  15. DISCLAIMED.
  16. ==============================================================================
  17. */
  18. namespace juce
  19. {
  20. template<typename RowComponentType>
  21. static AccessibilityActions getListRowAccessibilityActions (RowComponentType& rowComponent)
  22. {
  23. auto onFocus = [&rowComponent]
  24. {
  25. rowComponent.owner.scrollToEnsureRowIsOnscreen (rowComponent.row);
  26. rowComponent.owner.selectRow (rowComponent.row);
  27. };
  28. auto onPress = [&rowComponent, onFocus]
  29. {
  30. onFocus();
  31. rowComponent.owner.keyPressed (KeyPress (KeyPress::returnKey));
  32. };
  33. auto onToggle = [&rowComponent]
  34. {
  35. rowComponent.owner.flipRowSelection (rowComponent.row);
  36. };
  37. return AccessibilityActions().addAction (AccessibilityActionType::focus, std::move (onFocus))
  38. .addAction (AccessibilityActionType::press, std::move (onPress))
  39. .addAction (AccessibilityActionType::toggle, std::move (onToggle));
  40. }
  41. class ListBox::RowComponent : public Component,
  42. public TooltipClient
  43. {
  44. public:
  45. RowComponent (ListBox& lb) : owner (lb) {}
  46. void paint (Graphics& g) override
  47. {
  48. if (auto* m = owner.getModel())
  49. m->paintListBoxItem (row, g, getWidth(), getHeight(), isSelected);
  50. }
  51. void update (const int newRow, const bool nowSelected)
  52. {
  53. const auto rowHasChanged = (row != newRow);
  54. const auto selectionHasChanged = (isSelected != nowSelected);
  55. if (rowHasChanged || selectionHasChanged)
  56. {
  57. repaint();
  58. if (rowHasChanged)
  59. row = newRow;
  60. if (selectionHasChanged)
  61. isSelected = nowSelected;
  62. }
  63. if (auto* m = owner.getModel())
  64. {
  65. setMouseCursor (m->getMouseCursorForRow (row));
  66. customComponent.reset (m->refreshComponentForRow (newRow, nowSelected, customComponent.release()));
  67. if (customComponent != nullptr)
  68. {
  69. addAndMakeVisible (customComponent.get());
  70. customComponent->setBounds (getLocalBounds());
  71. if (customComponent->getAccessibilityHandler() != nullptr)
  72. invalidateAccessibilityHandler();
  73. }
  74. }
  75. if (selectionHasChanged)
  76. if (auto* handler = getAccessibilityHandler())
  77. isSelected ? handler->grabFocus() : handler->giveAwayFocus();
  78. }
  79. void performSelection (const MouseEvent& e, bool isMouseUp)
  80. {
  81. owner.selectRowsBasedOnModifierKeys (row, e.mods, isMouseUp);
  82. if (auto* m = owner.getModel())
  83. m->listBoxItemClicked (row, e);
  84. }
  85. bool isInDragToScrollViewport() const noexcept
  86. {
  87. if (auto* vp = owner.getViewport())
  88. return vp->isScrollOnDragEnabled() && (vp->canScrollVertically() || vp->canScrollHorizontally());
  89. return false;
  90. }
  91. void mouseDown (const MouseEvent& e) override
  92. {
  93. isDragging = false;
  94. isDraggingToScroll = false;
  95. selectRowOnMouseUp = false;
  96. if (isEnabled())
  97. {
  98. if (owner.selectOnMouseDown && ! (isSelected || isInDragToScrollViewport()))
  99. performSelection (e, false);
  100. else
  101. selectRowOnMouseUp = true;
  102. }
  103. }
  104. void mouseUp (const MouseEvent& e) override
  105. {
  106. if (isEnabled() && selectRowOnMouseUp && ! (isDragging || isDraggingToScroll))
  107. performSelection (e, true);
  108. }
  109. void mouseDoubleClick (const MouseEvent& e) override
  110. {
  111. if (isEnabled())
  112. if (auto* m = owner.getModel())
  113. m->listBoxItemDoubleClicked (row, e);
  114. }
  115. void mouseDrag (const MouseEvent& e) override
  116. {
  117. if (auto* m = owner.getModel())
  118. {
  119. if (isEnabled() && e.mouseWasDraggedSinceMouseDown() && ! isDragging)
  120. {
  121. SparseSet<int> rowsToDrag;
  122. if (owner.selectOnMouseDown || owner.isRowSelected (row))
  123. rowsToDrag = owner.getSelectedRows();
  124. else
  125. rowsToDrag.addRange (Range<int>::withStartAndLength (row, 1));
  126. if (rowsToDrag.size() > 0)
  127. {
  128. auto dragDescription = m->getDragSourceDescription (rowsToDrag);
  129. if (! (dragDescription.isVoid() || (dragDescription.isString() && dragDescription.toString().isEmpty())))
  130. {
  131. isDragging = true;
  132. owner.startDragAndDrop (e, rowsToDrag, dragDescription, true);
  133. }
  134. }
  135. }
  136. }
  137. if (! isDraggingToScroll)
  138. if (auto* vp = owner.getViewport())
  139. isDraggingToScroll = vp->isCurrentlyScrollingOnDrag();
  140. }
  141. void resized() override
  142. {
  143. if (customComponent != nullptr)
  144. customComponent->setBounds (getLocalBounds());
  145. }
  146. String getTooltip() override
  147. {
  148. if (auto* m = owner.getModel())
  149. return m->getTooltipForRow (row);
  150. return {};
  151. }
  152. //==============================================================================
  153. class RowAccessibilityHandler : public AccessibilityHandler
  154. {
  155. public:
  156. explicit RowAccessibilityHandler (RowComponent& rowComponentToWrap)
  157. : AccessibilityHandler (rowComponentToWrap,
  158. AccessibilityRole::listItem,
  159. getListRowAccessibilityActions (rowComponentToWrap),
  160. { std::make_unique<RowCellInterface> (*this) }),
  161. rowComponent (rowComponentToWrap)
  162. {
  163. }
  164. String getTitle() const override
  165. {
  166. if (auto* m = rowComponent.owner.getModel())
  167. return m->getNameForRow (rowComponent.row);
  168. return {};
  169. }
  170. AccessibleState getCurrentState() const override
  171. {
  172. if (auto* m = rowComponent.owner.getModel())
  173. if (rowComponent.row >= m->getNumRows())
  174. return AccessibleState().withIgnored();
  175. auto state = AccessibilityHandler::getCurrentState().withAccessibleOffscreen();
  176. if (rowComponent.owner.multipleSelection)
  177. state = state.withMultiSelectable();
  178. else
  179. state = state.withSelectable();
  180. if (rowComponent.isSelected)
  181. state = state.withSelected();
  182. return state;
  183. }
  184. private:
  185. class RowCellInterface : public AccessibilityCellInterface
  186. {
  187. public:
  188. explicit RowCellInterface (RowAccessibilityHandler& h) : handler (h) {}
  189. int getColumnIndex() const override { return 0; }
  190. int getColumnSpan() const override { return 1; }
  191. int getRowIndex() const override { return handler.rowComponent.row; }
  192. int getRowSpan() const override { return 1; }
  193. int getDisclosureLevel() const override { return 0; }
  194. const AccessibilityHandler* getTableHandler() const override
  195. {
  196. return handler.rowComponent.owner.getAccessibilityHandler();
  197. }
  198. private:
  199. RowAccessibilityHandler& handler;
  200. };
  201. RowComponent& rowComponent;
  202. };
  203. std::unique_ptr<AccessibilityHandler> createAccessibilityHandler() override
  204. {
  205. if (customComponent != nullptr && customComponent->getAccessibilityHandler() != nullptr)
  206. return nullptr;
  207. return std::make_unique<RowAccessibilityHandler> (*this);
  208. }
  209. //==============================================================================
  210. ListBox& owner;
  211. std::unique_ptr<Component> customComponent;
  212. int row = -1;
  213. bool isSelected = false, isDragging = false, isDraggingToScroll = false, selectRowOnMouseUp = false;
  214. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (RowComponent)
  215. };
  216. //==============================================================================
  217. class ListBox::ListViewport : public Viewport
  218. {
  219. public:
  220. ListViewport (ListBox& lb) : owner (lb)
  221. {
  222. setWantsKeyboardFocus (false);
  223. setAccessible (false);
  224. auto content = std::make_unique<Component>();
  225. content->setWantsKeyboardFocus (false);
  226. content->setAccessible (false);
  227. setViewedComponent (content.release());
  228. }
  229. RowComponent* getComponentForRow (const int row) const noexcept
  230. {
  231. return rows [row % jmax (1, rows.size())];
  232. }
  233. RowComponent* getComponentForRowIfOnscreen (const int row) const noexcept
  234. {
  235. return (row >= firstIndex && row < firstIndex + rows.size())
  236. ? getComponentForRow (row) : nullptr;
  237. }
  238. int getRowNumberOfComponent (Component* const rowComponent) const noexcept
  239. {
  240. const int index = getViewedComponent()->getIndexOfChildComponent (rowComponent);
  241. const int num = rows.size();
  242. for (int i = num; --i >= 0;)
  243. if (((firstIndex + i) % jmax (1, num)) == index)
  244. return firstIndex + i;
  245. return -1;
  246. }
  247. void visibleAreaChanged (const Rectangle<int>&) override
  248. {
  249. updateVisibleArea (true);
  250. if (auto* m = owner.getModel())
  251. m->listWasScrolled();
  252. if (auto* handler = owner.getAccessibilityHandler())
  253. handler->notifyAccessibilityEvent (AccessibilityEvent::structureChanged);
  254. }
  255. void updateVisibleArea (const bool makeSureItUpdatesContent)
  256. {
  257. hasUpdated = false;
  258. auto& content = *getViewedComponent();
  259. auto newX = content.getX();
  260. auto newY = content.getY();
  261. auto newW = jmax (owner.minimumRowWidth, getMaximumVisibleWidth());
  262. auto newH = owner.totalItems * owner.getRowHeight();
  263. if (newY + newH < getMaximumVisibleHeight() && newH > getMaximumVisibleHeight())
  264. newY = getMaximumVisibleHeight() - newH;
  265. content.setBounds (newX, newY, newW, newH);
  266. if (makeSureItUpdatesContent && ! hasUpdated)
  267. updateContents();
  268. }
  269. void updateContents()
  270. {
  271. hasUpdated = true;
  272. auto rowH = owner.getRowHeight();
  273. auto& content = *getViewedComponent();
  274. if (rowH > 0)
  275. {
  276. auto y = getViewPositionY();
  277. auto w = content.getWidth();
  278. const int numNeeded = 4 + getMaximumVisibleHeight() / rowH;
  279. rows.removeRange (numNeeded, rows.size());
  280. while (numNeeded > rows.size())
  281. {
  282. auto* newRow = rows.add (new RowComponent (owner));
  283. content.addAndMakeVisible (newRow);
  284. }
  285. firstIndex = y / rowH;
  286. firstWholeIndex = (y + rowH - 1) / rowH;
  287. lastWholeIndex = (y + getMaximumVisibleHeight() - 1) / rowH;
  288. auto startIndex = jmax (0, firstIndex - 1);
  289. for (int i = 0; i < numNeeded; ++i)
  290. {
  291. const int row = i + startIndex;
  292. if (auto* rowComp = getComponentForRow (row))
  293. {
  294. rowComp->setBounds (0, row * rowH, w, rowH);
  295. rowComp->update (row, owner.isRowSelected (row));
  296. }
  297. }
  298. }
  299. if (owner.headerComponent != nullptr)
  300. owner.headerComponent->setBounds (owner.outlineThickness + content.getX(),
  301. owner.outlineThickness,
  302. jmax (owner.getWidth() - owner.outlineThickness * 2,
  303. content.getWidth()),
  304. owner.headerComponent->getHeight());
  305. }
  306. void selectRow (const int row, const int rowH, const bool dontScroll,
  307. const int lastSelectedRow, const int totalRows, const bool isMouseClick)
  308. {
  309. hasUpdated = false;
  310. if (row < firstWholeIndex && ! dontScroll)
  311. {
  312. setViewPosition (getViewPositionX(), row * rowH);
  313. }
  314. else if (row >= lastWholeIndex && ! dontScroll)
  315. {
  316. const int rowsOnScreen = lastWholeIndex - firstWholeIndex;
  317. if (row >= lastSelectedRow + rowsOnScreen
  318. && rowsOnScreen < totalRows - 1
  319. && ! isMouseClick)
  320. {
  321. setViewPosition (getViewPositionX(),
  322. jlimit (0, jmax (0, totalRows - rowsOnScreen), row) * rowH);
  323. }
  324. else
  325. {
  326. setViewPosition (getViewPositionX(),
  327. jmax (0, (row + 1) * rowH - getMaximumVisibleHeight()));
  328. }
  329. }
  330. if (! hasUpdated)
  331. updateContents();
  332. }
  333. void scrollToEnsureRowIsOnscreen (const int row, const int rowH)
  334. {
  335. if (row < firstWholeIndex)
  336. {
  337. setViewPosition (getViewPositionX(), row * rowH);
  338. }
  339. else if (row >= lastWholeIndex)
  340. {
  341. setViewPosition (getViewPositionX(),
  342. jmax (0, (row + 1) * rowH - getMaximumVisibleHeight()));
  343. }
  344. }
  345. void paint (Graphics& g) override
  346. {
  347. if (isOpaque())
  348. g.fillAll (owner.findColour (ListBox::backgroundColourId));
  349. }
  350. bool keyPressed (const KeyPress& key) override
  351. {
  352. if (Viewport::respondsToKey (key))
  353. {
  354. const int allowableMods = owner.multipleSelection ? ModifierKeys::shiftModifier : 0;
  355. if ((key.getModifiers().getRawFlags() & ~allowableMods) == 0)
  356. {
  357. // we want to avoid these keypresses going to the viewport, and instead allow
  358. // them to pass up to our listbox..
  359. return false;
  360. }
  361. }
  362. return Viewport::keyPressed (key);
  363. }
  364. private:
  365. ListBox& owner;
  366. OwnedArray<RowComponent> rows;
  367. int firstIndex = 0, firstWholeIndex = 0, lastWholeIndex = 0;
  368. bool hasUpdated = false;
  369. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ListViewport)
  370. };
  371. //==============================================================================
  372. struct ListBoxMouseMoveSelector : public MouseListener
  373. {
  374. ListBoxMouseMoveSelector (ListBox& lb) : owner (lb)
  375. {
  376. owner.addMouseListener (this, true);
  377. }
  378. ~ListBoxMouseMoveSelector() override
  379. {
  380. owner.removeMouseListener (this);
  381. }
  382. void mouseMove (const MouseEvent& e) override
  383. {
  384. auto pos = e.getEventRelativeTo (&owner).position.toInt();
  385. owner.selectRow (owner.getRowContainingPosition (pos.x, pos.y), true);
  386. }
  387. void mouseExit (const MouseEvent& e) override
  388. {
  389. mouseMove (e);
  390. }
  391. ListBox& owner;
  392. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ListBoxMouseMoveSelector)
  393. };
  394. //==============================================================================
  395. ListBox::ListBox (const String& name, ListBoxModel* const m)
  396. : Component (name), model (m)
  397. {
  398. viewport.reset (new ListViewport (*this));
  399. addAndMakeVisible (viewport.get());
  400. setWantsKeyboardFocus (true);
  401. setFocusContainerType (FocusContainerType::focusContainer);
  402. colourChanged();
  403. }
  404. ListBox::~ListBox()
  405. {
  406. headerComponent.reset();
  407. viewport.reset();
  408. }
  409. void ListBox::setModel (ListBoxModel* const newModel)
  410. {
  411. if (model != newModel)
  412. {
  413. model = newModel;
  414. repaint();
  415. updateContent();
  416. }
  417. }
  418. void ListBox::setMultipleSelectionEnabled (bool b) noexcept { multipleSelection = b; }
  419. void ListBox::setClickingTogglesRowSelection (bool b) noexcept { alwaysFlipSelection = b; }
  420. void ListBox::setRowSelectedOnMouseDown (bool b) noexcept { selectOnMouseDown = b; }
  421. void ListBox::setMouseMoveSelectsRows (bool b)
  422. {
  423. if (b)
  424. {
  425. if (mouseMoveSelector == nullptr)
  426. mouseMoveSelector.reset (new ListBoxMouseMoveSelector (*this));
  427. }
  428. else
  429. {
  430. mouseMoveSelector.reset();
  431. }
  432. }
  433. //==============================================================================
  434. void ListBox::paint (Graphics& g)
  435. {
  436. if (! hasDoneInitialUpdate)
  437. updateContent();
  438. g.fillAll (findColour (backgroundColourId));
  439. }
  440. void ListBox::paintOverChildren (Graphics& g)
  441. {
  442. if (outlineThickness > 0)
  443. {
  444. g.setColour (findColour (outlineColourId));
  445. g.drawRect (getLocalBounds(), outlineThickness);
  446. }
  447. }
  448. void ListBox::resized()
  449. {
  450. viewport->setBoundsInset (BorderSize<int> (outlineThickness + (headerComponent != nullptr ? headerComponent->getHeight() : 0),
  451. outlineThickness, outlineThickness, outlineThickness));
  452. viewport->setSingleStepSizes (20, getRowHeight());
  453. viewport->updateVisibleArea (false);
  454. }
  455. void ListBox::visibilityChanged()
  456. {
  457. viewport->updateVisibleArea (true);
  458. }
  459. Viewport* ListBox::getViewport() const noexcept
  460. {
  461. return viewport.get();
  462. }
  463. //==============================================================================
  464. void ListBox::updateContent()
  465. {
  466. hasDoneInitialUpdate = true;
  467. totalItems = (model != nullptr) ? model->getNumRows() : 0;
  468. bool selectionChanged = false;
  469. if (selected.size() > 0 && selected [selected.size() - 1] >= totalItems)
  470. {
  471. selected.removeRange ({ totalItems, std::numeric_limits<int>::max() });
  472. lastRowSelected = getSelectedRow (0);
  473. selectionChanged = true;
  474. }
  475. viewport->updateVisibleArea (isVisible());
  476. viewport->resized();
  477. if (selectionChanged)
  478. {
  479. if (model != nullptr)
  480. model->selectedRowsChanged (lastRowSelected);
  481. if (auto* handler = getAccessibilityHandler())
  482. handler->notifyAccessibilityEvent (AccessibilityEvent::rowSelectionChanged);
  483. }
  484. }
  485. //==============================================================================
  486. void ListBox::selectRow (int row, bool dontScroll, bool deselectOthersFirst)
  487. {
  488. selectRowInternal (row, dontScroll, deselectOthersFirst, false);
  489. }
  490. void ListBox::selectRowInternal (const int row,
  491. bool dontScroll,
  492. bool deselectOthersFirst,
  493. bool isMouseClick)
  494. {
  495. if (! multipleSelection)
  496. deselectOthersFirst = true;
  497. if ((! isRowSelected (row))
  498. || (deselectOthersFirst && getNumSelectedRows() > 1))
  499. {
  500. if (isPositiveAndBelow (row, totalItems))
  501. {
  502. if (deselectOthersFirst)
  503. selected.clear();
  504. selected.addRange ({ row, row + 1 });
  505. if (getHeight() == 0 || getWidth() == 0)
  506. dontScroll = true;
  507. viewport->selectRow (row, getRowHeight(), dontScroll,
  508. lastRowSelected, totalItems, isMouseClick);
  509. lastRowSelected = row;
  510. model->selectedRowsChanged (row);
  511. if (auto* handler = getAccessibilityHandler())
  512. handler->notifyAccessibilityEvent (AccessibilityEvent::rowSelectionChanged);
  513. }
  514. else
  515. {
  516. if (deselectOthersFirst)
  517. deselectAllRows();
  518. }
  519. }
  520. }
  521. void ListBox::deselectRow (const int row)
  522. {
  523. if (selected.contains (row))
  524. {
  525. selected.removeRange ({ row, row + 1 });
  526. if (row == lastRowSelected)
  527. lastRowSelected = getSelectedRow (0);
  528. viewport->updateContents();
  529. model->selectedRowsChanged (lastRowSelected);
  530. if (auto* handler = getAccessibilityHandler())
  531. handler->notifyAccessibilityEvent (AccessibilityEvent::rowSelectionChanged);
  532. }
  533. }
  534. void ListBox::setSelectedRows (const SparseSet<int>& setOfRowsToBeSelected,
  535. const NotificationType sendNotificationEventToModel)
  536. {
  537. selected = setOfRowsToBeSelected;
  538. selected.removeRange ({ totalItems, std::numeric_limits<int>::max() });
  539. if (! isRowSelected (lastRowSelected))
  540. lastRowSelected = getSelectedRow (0);
  541. viewport->updateContents();
  542. if (model != nullptr && sendNotificationEventToModel == sendNotification)
  543. model->selectedRowsChanged (lastRowSelected);
  544. if (auto* handler = getAccessibilityHandler())
  545. handler->notifyAccessibilityEvent (AccessibilityEvent::rowSelectionChanged);
  546. }
  547. SparseSet<int> ListBox::getSelectedRows() const
  548. {
  549. return selected;
  550. }
  551. void ListBox::selectRangeOfRows (int firstRow, int lastRow, bool dontScrollToShowThisRange)
  552. {
  553. if (multipleSelection && (firstRow != lastRow))
  554. {
  555. const int numRows = totalItems - 1;
  556. firstRow = jlimit (0, jmax (0, numRows), firstRow);
  557. lastRow = jlimit (0, jmax (0, numRows), lastRow);
  558. selected.addRange ({ jmin (firstRow, lastRow),
  559. jmax (firstRow, lastRow) + 1 });
  560. selected.removeRange ({ lastRow, lastRow + 1 });
  561. }
  562. selectRowInternal (lastRow, dontScrollToShowThisRange, false, true);
  563. }
  564. void ListBox::flipRowSelection (const int row)
  565. {
  566. if (isRowSelected (row))
  567. deselectRow (row);
  568. else
  569. selectRowInternal (row, false, false, true);
  570. }
  571. void ListBox::deselectAllRows()
  572. {
  573. if (! selected.isEmpty())
  574. {
  575. selected.clear();
  576. lastRowSelected = -1;
  577. viewport->updateContents();
  578. if (model != nullptr)
  579. model->selectedRowsChanged (lastRowSelected);
  580. if (auto* handler = getAccessibilityHandler())
  581. handler->notifyAccessibilityEvent (AccessibilityEvent::rowSelectionChanged);
  582. }
  583. }
  584. void ListBox::selectRowsBasedOnModifierKeys (const int row,
  585. ModifierKeys mods,
  586. const bool isMouseUpEvent)
  587. {
  588. if (multipleSelection && (mods.isCommandDown() || alwaysFlipSelection))
  589. {
  590. flipRowSelection (row);
  591. }
  592. else if (multipleSelection && mods.isShiftDown() && lastRowSelected >= 0)
  593. {
  594. selectRangeOfRows (lastRowSelected, row);
  595. }
  596. else if ((! mods.isPopupMenu()) || ! isRowSelected (row))
  597. {
  598. selectRowInternal (row, false, ! (multipleSelection && (! isMouseUpEvent) && isRowSelected (row)), true);
  599. }
  600. }
  601. int ListBox::getNumSelectedRows() const
  602. {
  603. return selected.size();
  604. }
  605. int ListBox::getSelectedRow (const int index) const
  606. {
  607. return (isPositiveAndBelow (index, selected.size()))
  608. ? selected [index] : -1;
  609. }
  610. bool ListBox::isRowSelected (const int row) const
  611. {
  612. return selected.contains (row);
  613. }
  614. int ListBox::getLastRowSelected() const
  615. {
  616. return isRowSelected (lastRowSelected) ? lastRowSelected : -1;
  617. }
  618. //==============================================================================
  619. int ListBox::getRowContainingPosition (const int x, const int y) const noexcept
  620. {
  621. if (isPositiveAndBelow (x, getWidth()))
  622. {
  623. const int row = (viewport->getViewPositionY() + y - viewport->getY()) / rowHeight;
  624. if (isPositiveAndBelow (row, totalItems))
  625. return row;
  626. }
  627. return -1;
  628. }
  629. int ListBox::getInsertionIndexForPosition (const int x, const int y) const noexcept
  630. {
  631. if (isPositiveAndBelow (x, getWidth()))
  632. return jlimit (0, totalItems, (viewport->getViewPositionY() + y + rowHeight / 2 - viewport->getY()) / rowHeight);
  633. return -1;
  634. }
  635. Component* ListBox::getComponentForRowNumber (const int row) const noexcept
  636. {
  637. if (auto* listRowComp = viewport->getComponentForRowIfOnscreen (row))
  638. return listRowComp->customComponent.get();
  639. return nullptr;
  640. }
  641. int ListBox::getRowNumberOfComponent (Component* const rowComponent) const noexcept
  642. {
  643. return viewport->getRowNumberOfComponent (rowComponent);
  644. }
  645. Rectangle<int> ListBox::getRowPosition (int rowNumber, bool relativeToComponentTopLeft) const noexcept
  646. {
  647. auto y = viewport->getY() + rowHeight * rowNumber;
  648. if (relativeToComponentTopLeft)
  649. y -= viewport->getViewPositionY();
  650. return { viewport->getX(), y,
  651. viewport->getViewedComponent()->getWidth(), rowHeight };
  652. }
  653. void ListBox::setVerticalPosition (const double proportion)
  654. {
  655. auto offscreen = viewport->getViewedComponent()->getHeight() - viewport->getHeight();
  656. viewport->setViewPosition (viewport->getViewPositionX(),
  657. jmax (0, roundToInt (proportion * offscreen)));
  658. }
  659. double ListBox::getVerticalPosition() const
  660. {
  661. auto offscreen = viewport->getViewedComponent()->getHeight() - viewport->getHeight();
  662. return offscreen > 0 ? viewport->getViewPositionY() / (double) offscreen
  663. : 0;
  664. }
  665. int ListBox::getVisibleRowWidth() const noexcept
  666. {
  667. return viewport->getViewWidth();
  668. }
  669. void ListBox::scrollToEnsureRowIsOnscreen (const int row)
  670. {
  671. viewport->scrollToEnsureRowIsOnscreen (row, getRowHeight());
  672. }
  673. //==============================================================================
  674. bool ListBox::keyPressed (const KeyPress& key)
  675. {
  676. const int numVisibleRows = viewport->getHeight() / getRowHeight();
  677. const bool multiple = multipleSelection
  678. && lastRowSelected >= 0
  679. && key.getModifiers().isShiftDown();
  680. if (key.isKeyCode (KeyPress::upKey))
  681. {
  682. if (multiple)
  683. selectRangeOfRows (lastRowSelected, lastRowSelected - 1);
  684. else
  685. selectRow (jmax (0, lastRowSelected - 1));
  686. }
  687. else if (key.isKeyCode (KeyPress::downKey))
  688. {
  689. if (multiple)
  690. selectRangeOfRows (lastRowSelected, lastRowSelected + 1);
  691. else
  692. selectRow (jmin (totalItems - 1, jmax (0, lastRowSelected + 1)));
  693. }
  694. else if (key.isKeyCode (KeyPress::pageUpKey))
  695. {
  696. if (multiple)
  697. selectRangeOfRows (lastRowSelected, lastRowSelected - numVisibleRows);
  698. else
  699. selectRow (jmax (0, jmax (0, lastRowSelected) - numVisibleRows));
  700. }
  701. else if (key.isKeyCode (KeyPress::pageDownKey))
  702. {
  703. if (multiple)
  704. selectRangeOfRows (lastRowSelected, lastRowSelected + numVisibleRows);
  705. else
  706. selectRow (jmin (totalItems - 1, jmax (0, lastRowSelected) + numVisibleRows));
  707. }
  708. else if (key.isKeyCode (KeyPress::homeKey))
  709. {
  710. if (multiple)
  711. selectRangeOfRows (lastRowSelected, 0);
  712. else
  713. selectRow (0);
  714. }
  715. else if (key.isKeyCode (KeyPress::endKey))
  716. {
  717. if (multiple)
  718. selectRangeOfRows (lastRowSelected, totalItems - 1);
  719. else
  720. selectRow (totalItems - 1);
  721. }
  722. else if (key.isKeyCode (KeyPress::returnKey) && isRowSelected (lastRowSelected))
  723. {
  724. if (model != nullptr)
  725. model->returnKeyPressed (lastRowSelected);
  726. }
  727. else if ((key.isKeyCode (KeyPress::deleteKey) || key.isKeyCode (KeyPress::backspaceKey))
  728. && isRowSelected (lastRowSelected))
  729. {
  730. if (model != nullptr)
  731. model->deleteKeyPressed (lastRowSelected);
  732. }
  733. else if (multipleSelection && key == KeyPress ('a', ModifierKeys::commandModifier, 0))
  734. {
  735. selectRangeOfRows (0, std::numeric_limits<int>::max());
  736. }
  737. else
  738. {
  739. return false;
  740. }
  741. return true;
  742. }
  743. bool ListBox::keyStateChanged (const bool isKeyDown)
  744. {
  745. return isKeyDown
  746. && (KeyPress::isKeyCurrentlyDown (KeyPress::upKey)
  747. || KeyPress::isKeyCurrentlyDown (KeyPress::pageUpKey)
  748. || KeyPress::isKeyCurrentlyDown (KeyPress::downKey)
  749. || KeyPress::isKeyCurrentlyDown (KeyPress::pageDownKey)
  750. || KeyPress::isKeyCurrentlyDown (KeyPress::homeKey)
  751. || KeyPress::isKeyCurrentlyDown (KeyPress::endKey)
  752. || KeyPress::isKeyCurrentlyDown (KeyPress::returnKey));
  753. }
  754. void ListBox::mouseWheelMove (const MouseEvent& e, const MouseWheelDetails& wheel)
  755. {
  756. bool eventWasUsed = false;
  757. if (wheel.deltaX != 0.0f && getHorizontalScrollBar().isVisible())
  758. {
  759. eventWasUsed = true;
  760. getHorizontalScrollBar().mouseWheelMove (e, wheel);
  761. }
  762. if (wheel.deltaY != 0.0f && getVerticalScrollBar().isVisible())
  763. {
  764. eventWasUsed = true;
  765. getVerticalScrollBar().mouseWheelMove (e, wheel);
  766. }
  767. if (! eventWasUsed)
  768. Component::mouseWheelMove (e, wheel);
  769. }
  770. void ListBox::mouseUp (const MouseEvent& e)
  771. {
  772. if (e.mouseWasClicked() && model != nullptr)
  773. model->backgroundClicked (e);
  774. }
  775. //==============================================================================
  776. void ListBox::setRowHeight (const int newHeight)
  777. {
  778. rowHeight = jmax (1, newHeight);
  779. viewport->setSingleStepSizes (20, rowHeight);
  780. updateContent();
  781. }
  782. int ListBox::getNumRowsOnScreen() const noexcept
  783. {
  784. return viewport->getMaximumVisibleHeight() / rowHeight;
  785. }
  786. void ListBox::setMinimumContentWidth (const int newMinimumWidth)
  787. {
  788. minimumRowWidth = newMinimumWidth;
  789. updateContent();
  790. }
  791. int ListBox::getVisibleContentWidth() const noexcept { return viewport->getMaximumVisibleWidth(); }
  792. ScrollBar& ListBox::getVerticalScrollBar() const noexcept { return viewport->getVerticalScrollBar(); }
  793. ScrollBar& ListBox::getHorizontalScrollBar() const noexcept { return viewport->getHorizontalScrollBar(); }
  794. void ListBox::colourChanged()
  795. {
  796. setOpaque (findColour (backgroundColourId).isOpaque());
  797. viewport->setOpaque (isOpaque());
  798. repaint();
  799. }
  800. void ListBox::parentHierarchyChanged()
  801. {
  802. colourChanged();
  803. }
  804. void ListBox::setOutlineThickness (int newThickness)
  805. {
  806. outlineThickness = newThickness;
  807. resized();
  808. }
  809. void ListBox::setHeaderComponent (std::unique_ptr<Component> newHeaderComponent)
  810. {
  811. headerComponent = std::move (newHeaderComponent);
  812. addAndMakeVisible (headerComponent.get());
  813. ListBox::resized();
  814. }
  815. void ListBox::repaintRow (const int rowNumber) noexcept
  816. {
  817. repaint (getRowPosition (rowNumber, true));
  818. }
  819. Image ListBox::createSnapshotOfRows (const SparseSet<int>& rows, int& imageX, int& imageY)
  820. {
  821. Rectangle<int> imageArea;
  822. auto firstRow = getRowContainingPosition (0, viewport->getY());
  823. for (int i = getNumRowsOnScreen() + 2; --i >= 0;)
  824. {
  825. if (rows.contains (firstRow + i))
  826. {
  827. if (auto* rowComp = viewport->getComponentForRowIfOnscreen (firstRow + i))
  828. {
  829. auto pos = getLocalPoint (rowComp, Point<int>());
  830. imageArea = imageArea.getUnion ({ pos.x, pos.y, rowComp->getWidth(), rowComp->getHeight() });
  831. }
  832. }
  833. }
  834. imageArea = imageArea.getIntersection (getLocalBounds());
  835. imageX = imageArea.getX();
  836. imageY = imageArea.getY();
  837. auto listScale = Component::getApproximateScaleFactorForComponent (this);
  838. Image snapshot (Image::ARGB,
  839. roundToInt ((float) imageArea.getWidth() * listScale),
  840. roundToInt ((float) imageArea.getHeight() * listScale),
  841. true);
  842. for (int i = getNumRowsOnScreen() + 2; --i >= 0;)
  843. {
  844. if (rows.contains (firstRow + i))
  845. {
  846. if (auto* rowComp = viewport->getComponentForRowIfOnscreen (firstRow + i))
  847. {
  848. Graphics g (snapshot);
  849. g.setOrigin (getLocalPoint (rowComp, Point<int>()) - imageArea.getPosition());
  850. auto rowScale = Component::getApproximateScaleFactorForComponent (rowComp);
  851. if (g.reduceClipRegion (rowComp->getLocalBounds() * rowScale))
  852. {
  853. g.beginTransparencyLayer (0.6f);
  854. g.addTransform (AffineTransform::scale (rowScale));
  855. rowComp->paintEntireComponent (g, false);
  856. g.endTransparencyLayer();
  857. }
  858. }
  859. }
  860. }
  861. return snapshot;
  862. }
  863. void ListBox::startDragAndDrop (const MouseEvent& e, const SparseSet<int>& rowsToDrag, const var& dragDescription, bool allowDraggingToOtherWindows)
  864. {
  865. if (auto* dragContainer = DragAndDropContainer::findParentDragContainerFor (this))
  866. {
  867. int x, y;
  868. auto dragImage = createSnapshotOfRows (rowsToDrag, x, y);
  869. auto p = Point<int> (x, y) - e.getEventRelativeTo (this).position.toInt();
  870. dragContainer->startDragging (dragDescription, this, dragImage, allowDraggingToOtherWindows, &p, &e.source);
  871. }
  872. else
  873. {
  874. // to be able to do a drag-and-drop operation, the listbox needs to
  875. // be inside a component which is also a DragAndDropContainer.
  876. jassertfalse;
  877. }
  878. }
  879. std::unique_ptr<AccessibilityHandler> ListBox::createAccessibilityHandler()
  880. {
  881. class TableInterface : public AccessibilityTableInterface
  882. {
  883. public:
  884. explicit TableInterface (ListBox& listBoxToWrap)
  885. : listBox (listBoxToWrap)
  886. {
  887. }
  888. int getNumRows() const override
  889. {
  890. if (listBox.model != nullptr)
  891. return getHeaderHandler() != nullptr ? listBox.model->getNumRows() + 1
  892. : listBox.model->getNumRows();
  893. return 0;
  894. }
  895. int getNumColumns() const override
  896. {
  897. return 1;
  898. }
  899. const AccessibilityHandler* getCellHandler (int row, int) const override
  900. {
  901. if (auto* headerHandler = getHeaderHandler())
  902. {
  903. if (row == 0)
  904. return headerHandler;
  905. --row;
  906. }
  907. if (auto* rowComponent = listBox.viewport->getComponentForRow (row))
  908. return rowComponent->getAccessibilityHandler();
  909. return nullptr;
  910. }
  911. private:
  912. const AccessibilityHandler* getHeaderHandler() const
  913. {
  914. if (listBox.headerComponent != nullptr)
  915. return listBox.headerComponent->getAccessibilityHandler();
  916. return nullptr;
  917. }
  918. ListBox& listBox;
  919. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (TableInterface)
  920. };
  921. return std::make_unique<AccessibilityHandler> (*this,
  922. AccessibilityRole::list,
  923. AccessibilityActions{},
  924. AccessibilityHandler::Interfaces { std::make_unique<TableInterface> (*this) });
  925. }
  926. //==============================================================================
  927. Component* ListBoxModel::refreshComponentForRow (int, bool, Component* existingComponentToUpdate)
  928. {
  929. ignoreUnused (existingComponentToUpdate);
  930. jassert (existingComponentToUpdate == nullptr); // indicates a failure in the code that recycles the components
  931. return nullptr;
  932. }
  933. String ListBoxModel::getNameForRow (int rowNumber) { return "Row " + String (rowNumber + 1); }
  934. void ListBoxModel::listBoxItemClicked (int, const MouseEvent&) {}
  935. void ListBoxModel::listBoxItemDoubleClicked (int, const MouseEvent&) {}
  936. void ListBoxModel::backgroundClicked (const MouseEvent&) {}
  937. void ListBoxModel::selectedRowsChanged (int) {}
  938. void ListBoxModel::deleteKeyPressed (int) {}
  939. void ListBoxModel::returnKeyPressed (int) {}
  940. void ListBoxModel::listWasScrolled() {}
  941. var ListBoxModel::getDragSourceDescription (const SparseSet<int>&) { return {}; }
  942. String ListBoxModel::getTooltipForRow (int) { return {}; }
  943. MouseCursor ListBoxModel::getMouseCursorForRow (int) { return MouseCursor::NormalCursor; }
  944. } // namespace juce