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.

1144 lines
36KB

  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. };
  27. auto onPress = [&rowComponent, onFocus]
  28. {
  29. onFocus();
  30. rowComponent.owner.selectRow (rowComponent.row);
  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 && model != nullptr)
  478. model->selectedRowsChanged (lastRowSelected);
  479. }
  480. //==============================================================================
  481. void ListBox::selectRow (int row, bool dontScroll, bool deselectOthersFirst)
  482. {
  483. selectRowInternal (row, dontScroll, deselectOthersFirst, false);
  484. }
  485. void ListBox::selectRowInternal (const int row,
  486. bool dontScroll,
  487. bool deselectOthersFirst,
  488. bool isMouseClick)
  489. {
  490. if (! multipleSelection)
  491. deselectOthersFirst = true;
  492. if ((! isRowSelected (row))
  493. || (deselectOthersFirst && getNumSelectedRows() > 1))
  494. {
  495. if (isPositiveAndBelow (row, totalItems))
  496. {
  497. if (deselectOthersFirst)
  498. selected.clear();
  499. selected.addRange ({ row, row + 1 });
  500. if (getHeight() == 0 || getWidth() == 0)
  501. dontScroll = true;
  502. viewport->selectRow (row, getRowHeight(), dontScroll,
  503. lastRowSelected, totalItems, isMouseClick);
  504. lastRowSelected = row;
  505. model->selectedRowsChanged (row);
  506. }
  507. else
  508. {
  509. if (deselectOthersFirst)
  510. deselectAllRows();
  511. }
  512. }
  513. }
  514. void ListBox::deselectRow (const int row)
  515. {
  516. if (selected.contains (row))
  517. {
  518. selected.removeRange ({ row, row + 1 });
  519. if (row == lastRowSelected)
  520. lastRowSelected = getSelectedRow (0);
  521. viewport->updateContents();
  522. model->selectedRowsChanged (lastRowSelected);
  523. }
  524. }
  525. void ListBox::setSelectedRows (const SparseSet<int>& setOfRowsToBeSelected,
  526. const NotificationType sendNotificationEventToModel)
  527. {
  528. selected = setOfRowsToBeSelected;
  529. selected.removeRange ({ totalItems, std::numeric_limits<int>::max() });
  530. if (! isRowSelected (lastRowSelected))
  531. lastRowSelected = getSelectedRow (0);
  532. viewport->updateContents();
  533. if (model != nullptr && sendNotificationEventToModel == sendNotification)
  534. model->selectedRowsChanged (lastRowSelected);
  535. }
  536. SparseSet<int> ListBox::getSelectedRows() const
  537. {
  538. return selected;
  539. }
  540. void ListBox::selectRangeOfRows (int firstRow, int lastRow, bool dontScrollToShowThisRange)
  541. {
  542. if (multipleSelection && (firstRow != lastRow))
  543. {
  544. const int numRows = totalItems - 1;
  545. firstRow = jlimit (0, jmax (0, numRows), firstRow);
  546. lastRow = jlimit (0, jmax (0, numRows), lastRow);
  547. selected.addRange ({ jmin (firstRow, lastRow),
  548. jmax (firstRow, lastRow) + 1 });
  549. selected.removeRange ({ lastRow, lastRow + 1 });
  550. }
  551. selectRowInternal (lastRow, dontScrollToShowThisRange, false, true);
  552. }
  553. void ListBox::flipRowSelection (const int row)
  554. {
  555. if (isRowSelected (row))
  556. deselectRow (row);
  557. else
  558. selectRowInternal (row, false, false, true);
  559. }
  560. void ListBox::deselectAllRows()
  561. {
  562. if (! selected.isEmpty())
  563. {
  564. selected.clear();
  565. lastRowSelected = -1;
  566. viewport->updateContents();
  567. if (model != nullptr)
  568. model->selectedRowsChanged (lastRowSelected);
  569. }
  570. }
  571. void ListBox::selectRowsBasedOnModifierKeys (const int row,
  572. ModifierKeys mods,
  573. const bool isMouseUpEvent)
  574. {
  575. if (multipleSelection && (mods.isCommandDown() || alwaysFlipSelection))
  576. {
  577. flipRowSelection (row);
  578. }
  579. else if (multipleSelection && mods.isShiftDown() && lastRowSelected >= 0)
  580. {
  581. selectRangeOfRows (lastRowSelected, row);
  582. }
  583. else if ((! mods.isPopupMenu()) || ! isRowSelected (row))
  584. {
  585. selectRowInternal (row, false, ! (multipleSelection && (! isMouseUpEvent) && isRowSelected (row)), true);
  586. }
  587. }
  588. int ListBox::getNumSelectedRows() const
  589. {
  590. return selected.size();
  591. }
  592. int ListBox::getSelectedRow (const int index) const
  593. {
  594. return (isPositiveAndBelow (index, selected.size()))
  595. ? selected [index] : -1;
  596. }
  597. bool ListBox::isRowSelected (const int row) const
  598. {
  599. return selected.contains (row);
  600. }
  601. int ListBox::getLastRowSelected() const
  602. {
  603. return isRowSelected (lastRowSelected) ? lastRowSelected : -1;
  604. }
  605. //==============================================================================
  606. int ListBox::getRowContainingPosition (const int x, const int y) const noexcept
  607. {
  608. if (isPositiveAndBelow (x, getWidth()))
  609. {
  610. const int row = (viewport->getViewPositionY() + y - viewport->getY()) / rowHeight;
  611. if (isPositiveAndBelow (row, totalItems))
  612. return row;
  613. }
  614. return -1;
  615. }
  616. int ListBox::getInsertionIndexForPosition (const int x, const int y) const noexcept
  617. {
  618. if (isPositiveAndBelow (x, getWidth()))
  619. return jlimit (0, totalItems, (viewport->getViewPositionY() + y + rowHeight / 2 - viewport->getY()) / rowHeight);
  620. return -1;
  621. }
  622. Component* ListBox::getComponentForRowNumber (const int row) const noexcept
  623. {
  624. if (auto* listRowComp = viewport->getComponentForRowIfOnscreen (row))
  625. return listRowComp->customComponent.get();
  626. return nullptr;
  627. }
  628. int ListBox::getRowNumberOfComponent (Component* const rowComponent) const noexcept
  629. {
  630. return viewport->getRowNumberOfComponent (rowComponent);
  631. }
  632. Rectangle<int> ListBox::getRowPosition (int rowNumber, bool relativeToComponentTopLeft) const noexcept
  633. {
  634. auto y = viewport->getY() + rowHeight * rowNumber;
  635. if (relativeToComponentTopLeft)
  636. y -= viewport->getViewPositionY();
  637. return { viewport->getX(), y,
  638. viewport->getViewedComponent()->getWidth(), rowHeight };
  639. }
  640. void ListBox::setVerticalPosition (const double proportion)
  641. {
  642. auto offscreen = viewport->getViewedComponent()->getHeight() - viewport->getHeight();
  643. viewport->setViewPosition (viewport->getViewPositionX(),
  644. jmax (0, roundToInt (proportion * offscreen)));
  645. }
  646. double ListBox::getVerticalPosition() const
  647. {
  648. auto offscreen = viewport->getViewedComponent()->getHeight() - viewport->getHeight();
  649. return offscreen > 0 ? viewport->getViewPositionY() / (double) offscreen
  650. : 0;
  651. }
  652. int ListBox::getVisibleRowWidth() const noexcept
  653. {
  654. return viewport->getViewWidth();
  655. }
  656. void ListBox::scrollToEnsureRowIsOnscreen (const int row)
  657. {
  658. viewport->scrollToEnsureRowIsOnscreen (row, getRowHeight());
  659. }
  660. //==============================================================================
  661. bool ListBox::keyPressed (const KeyPress& key)
  662. {
  663. const int numVisibleRows = viewport->getHeight() / getRowHeight();
  664. const bool multiple = multipleSelection
  665. && lastRowSelected >= 0
  666. && key.getModifiers().isShiftDown();
  667. if (key.isKeyCode (KeyPress::upKey))
  668. {
  669. if (multiple)
  670. selectRangeOfRows (lastRowSelected, lastRowSelected - 1);
  671. else
  672. selectRow (jmax (0, lastRowSelected - 1));
  673. }
  674. else if (key.isKeyCode (KeyPress::downKey))
  675. {
  676. if (multiple)
  677. selectRangeOfRows (lastRowSelected, lastRowSelected + 1);
  678. else
  679. selectRow (jmin (totalItems - 1, jmax (0, lastRowSelected + 1)));
  680. }
  681. else if (key.isKeyCode (KeyPress::pageUpKey))
  682. {
  683. if (multiple)
  684. selectRangeOfRows (lastRowSelected, lastRowSelected - numVisibleRows);
  685. else
  686. selectRow (jmax (0, jmax (0, lastRowSelected) - numVisibleRows));
  687. }
  688. else if (key.isKeyCode (KeyPress::pageDownKey))
  689. {
  690. if (multiple)
  691. selectRangeOfRows (lastRowSelected, lastRowSelected + numVisibleRows);
  692. else
  693. selectRow (jmin (totalItems - 1, jmax (0, lastRowSelected) + numVisibleRows));
  694. }
  695. else if (key.isKeyCode (KeyPress::homeKey))
  696. {
  697. if (multiple)
  698. selectRangeOfRows (lastRowSelected, 0);
  699. else
  700. selectRow (0);
  701. }
  702. else if (key.isKeyCode (KeyPress::endKey))
  703. {
  704. if (multiple)
  705. selectRangeOfRows (lastRowSelected, totalItems - 1);
  706. else
  707. selectRow (totalItems - 1);
  708. }
  709. else if (key.isKeyCode (KeyPress::returnKey) && isRowSelected (lastRowSelected))
  710. {
  711. if (model != nullptr)
  712. model->returnKeyPressed (lastRowSelected);
  713. }
  714. else if ((key.isKeyCode (KeyPress::deleteKey) || key.isKeyCode (KeyPress::backspaceKey))
  715. && isRowSelected (lastRowSelected))
  716. {
  717. if (model != nullptr)
  718. model->deleteKeyPressed (lastRowSelected);
  719. }
  720. else if (multipleSelection && key == KeyPress ('a', ModifierKeys::commandModifier, 0))
  721. {
  722. selectRangeOfRows (0, std::numeric_limits<int>::max());
  723. }
  724. else
  725. {
  726. return false;
  727. }
  728. return true;
  729. }
  730. bool ListBox::keyStateChanged (const bool isKeyDown)
  731. {
  732. return isKeyDown
  733. && (KeyPress::isKeyCurrentlyDown (KeyPress::upKey)
  734. || KeyPress::isKeyCurrentlyDown (KeyPress::pageUpKey)
  735. || KeyPress::isKeyCurrentlyDown (KeyPress::downKey)
  736. || KeyPress::isKeyCurrentlyDown (KeyPress::pageDownKey)
  737. || KeyPress::isKeyCurrentlyDown (KeyPress::homeKey)
  738. || KeyPress::isKeyCurrentlyDown (KeyPress::endKey)
  739. || KeyPress::isKeyCurrentlyDown (KeyPress::returnKey));
  740. }
  741. void ListBox::mouseWheelMove (const MouseEvent& e, const MouseWheelDetails& wheel)
  742. {
  743. bool eventWasUsed = false;
  744. if (wheel.deltaX != 0.0f && getHorizontalScrollBar().isVisible())
  745. {
  746. eventWasUsed = true;
  747. getHorizontalScrollBar().mouseWheelMove (e, wheel);
  748. }
  749. if (wheel.deltaY != 0.0f && getVerticalScrollBar().isVisible())
  750. {
  751. eventWasUsed = true;
  752. getVerticalScrollBar().mouseWheelMove (e, wheel);
  753. }
  754. if (! eventWasUsed)
  755. Component::mouseWheelMove (e, wheel);
  756. }
  757. void ListBox::mouseUp (const MouseEvent& e)
  758. {
  759. if (e.mouseWasClicked() && model != nullptr)
  760. model->backgroundClicked (e);
  761. }
  762. //==============================================================================
  763. void ListBox::setRowHeight (const int newHeight)
  764. {
  765. rowHeight = jmax (1, newHeight);
  766. viewport->setSingleStepSizes (20, rowHeight);
  767. updateContent();
  768. }
  769. int ListBox::getNumRowsOnScreen() const noexcept
  770. {
  771. return viewport->getMaximumVisibleHeight() / rowHeight;
  772. }
  773. void ListBox::setMinimumContentWidth (const int newMinimumWidth)
  774. {
  775. minimumRowWidth = newMinimumWidth;
  776. updateContent();
  777. }
  778. int ListBox::getVisibleContentWidth() const noexcept { return viewport->getMaximumVisibleWidth(); }
  779. ScrollBar& ListBox::getVerticalScrollBar() const noexcept { return viewport->getVerticalScrollBar(); }
  780. ScrollBar& ListBox::getHorizontalScrollBar() const noexcept { return viewport->getHorizontalScrollBar(); }
  781. void ListBox::colourChanged()
  782. {
  783. setOpaque (findColour (backgroundColourId).isOpaque());
  784. viewport->setOpaque (isOpaque());
  785. repaint();
  786. }
  787. void ListBox::parentHierarchyChanged()
  788. {
  789. colourChanged();
  790. }
  791. void ListBox::setOutlineThickness (int newThickness)
  792. {
  793. outlineThickness = newThickness;
  794. resized();
  795. }
  796. void ListBox::setHeaderComponent (std::unique_ptr<Component> newHeaderComponent)
  797. {
  798. headerComponent = std::move (newHeaderComponent);
  799. addAndMakeVisible (headerComponent.get());
  800. ListBox::resized();
  801. }
  802. void ListBox::repaintRow (const int rowNumber) noexcept
  803. {
  804. repaint (getRowPosition (rowNumber, true));
  805. }
  806. Image ListBox::createSnapshotOfRows (const SparseSet<int>& rows, int& imageX, int& imageY)
  807. {
  808. Rectangle<int> imageArea;
  809. auto firstRow = getRowContainingPosition (0, viewport->getY());
  810. for (int i = getNumRowsOnScreen() + 2; --i >= 0;)
  811. {
  812. if (rows.contains (firstRow + i))
  813. {
  814. if (auto* rowComp = viewport->getComponentForRowIfOnscreen (firstRow + i))
  815. {
  816. auto pos = getLocalPoint (rowComp, Point<int>());
  817. imageArea = imageArea.getUnion ({ pos.x, pos.y, rowComp->getWidth(), rowComp->getHeight() });
  818. }
  819. }
  820. }
  821. imageArea = imageArea.getIntersection (getLocalBounds());
  822. imageX = imageArea.getX();
  823. imageY = imageArea.getY();
  824. auto listScale = Component::getApproximateScaleFactorForComponent (this);
  825. Image snapshot (Image::ARGB,
  826. roundToInt ((float) imageArea.getWidth() * listScale),
  827. roundToInt ((float) imageArea.getHeight() * listScale),
  828. true);
  829. for (int i = getNumRowsOnScreen() + 2; --i >= 0;)
  830. {
  831. if (rows.contains (firstRow + i))
  832. {
  833. if (auto* rowComp = viewport->getComponentForRowIfOnscreen (firstRow + i))
  834. {
  835. Graphics g (snapshot);
  836. g.setOrigin (getLocalPoint (rowComp, Point<int>()) - imageArea.getPosition());
  837. auto rowScale = Component::getApproximateScaleFactorForComponent (rowComp);
  838. if (g.reduceClipRegion (rowComp->getLocalBounds() * rowScale))
  839. {
  840. g.beginTransparencyLayer (0.6f);
  841. g.addTransform (AffineTransform::scale (rowScale));
  842. rowComp->paintEntireComponent (g, false);
  843. g.endTransparencyLayer();
  844. }
  845. }
  846. }
  847. }
  848. return snapshot;
  849. }
  850. void ListBox::startDragAndDrop (const MouseEvent& e, const SparseSet<int>& rowsToDrag, const var& dragDescription, bool allowDraggingToOtherWindows)
  851. {
  852. if (auto* dragContainer = DragAndDropContainer::findParentDragContainerFor (this))
  853. {
  854. int x, y;
  855. auto dragImage = createSnapshotOfRows (rowsToDrag, x, y);
  856. auto p = Point<int> (x, y) - e.getEventRelativeTo (this).position.toInt();
  857. dragContainer->startDragging (dragDescription, this, dragImage, allowDraggingToOtherWindows, &p, &e.source);
  858. }
  859. else
  860. {
  861. // to be able to do a drag-and-drop operation, the listbox needs to
  862. // be inside a component which is also a DragAndDropContainer.
  863. jassertfalse;
  864. }
  865. }
  866. std::unique_ptr<AccessibilityHandler> ListBox::createAccessibilityHandler()
  867. {
  868. class TableInterface : public AccessibilityTableInterface
  869. {
  870. public:
  871. explicit TableInterface (ListBox& listBoxToWrap)
  872. : listBox (listBoxToWrap)
  873. {
  874. }
  875. int getNumRows() const override
  876. {
  877. if (listBox.model != nullptr)
  878. return getHeaderHandler() != nullptr ? listBox.model->getNumRows() + 1
  879. : listBox.model->getNumRows();
  880. return 0;
  881. }
  882. int getNumColumns() const override
  883. {
  884. return 1;
  885. }
  886. const AccessibilityHandler* getCellHandler (int row, int) const override
  887. {
  888. if (auto* headerHandler = getHeaderHandler())
  889. {
  890. if (row == 0)
  891. return headerHandler;
  892. --row;
  893. }
  894. if (auto* rowComponent = listBox.viewport->getComponentForRow (row))
  895. return rowComponent->getAccessibilityHandler();
  896. return nullptr;
  897. }
  898. private:
  899. const AccessibilityHandler* getHeaderHandler() const
  900. {
  901. if (listBox.headerComponent != nullptr)
  902. return listBox.headerComponent->getAccessibilityHandler();
  903. return nullptr;
  904. }
  905. ListBox& listBox;
  906. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (TableInterface)
  907. };
  908. return std::make_unique<AccessibilityHandler> (*this,
  909. AccessibilityRole::list,
  910. AccessibilityActions{},
  911. AccessibilityHandler::Interfaces { std::make_unique<TableInterface> (*this) });
  912. }
  913. //==============================================================================
  914. Component* ListBoxModel::refreshComponentForRow (int, bool, Component* existingComponentToUpdate)
  915. {
  916. ignoreUnused (existingComponentToUpdate);
  917. jassert (existingComponentToUpdate == nullptr); // indicates a failure in the code that recycles the components
  918. return nullptr;
  919. }
  920. String ListBoxModel::getNameForRow (int rowNumber) { return "Row " + String (rowNumber + 1); }
  921. void ListBoxModel::listBoxItemClicked (int, const MouseEvent&) {}
  922. void ListBoxModel::listBoxItemDoubleClicked (int, const MouseEvent&) {}
  923. void ListBoxModel::backgroundClicked (const MouseEvent&) {}
  924. void ListBoxModel::selectedRowsChanged (int) {}
  925. void ListBoxModel::deleteKeyPressed (int) {}
  926. void ListBoxModel::returnKeyPressed (int) {}
  927. void ListBoxModel::listWasScrolled() {}
  928. var ListBoxModel::getDragSourceDescription (const SparseSet<int>&) { return {}; }
  929. String ListBoxModel::getTooltipForRow (int) { return {}; }
  930. MouseCursor ListBoxModel::getMouseCursorForRow (int) { return MouseCursor::NormalCursor; }
  931. } // namespace juce