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.

1231 lines
38KB

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