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.

2070 lines
62KB

  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. static int getItemDepth (const TreeViewItem* item)
  21. {
  22. if (item == nullptr || item->getOwnerView() == nullptr)
  23. return 0;
  24. auto depth = item->getOwnerView()->isRootItemVisible() ? 0 : -1;
  25. for (auto* parent = item->getParentItem(); parent != nullptr; parent = parent->getParentItem())
  26. ++depth;
  27. return depth;
  28. }
  29. //==============================================================================
  30. class TreeView::ItemComponent : public Component
  31. {
  32. public:
  33. explicit ItemComponent (TreeViewItem& itemToRepresent)
  34. : item (itemToRepresent),
  35. customComponent (item.createItemComponent())
  36. {
  37. if (hasCustomComponent())
  38. addAndMakeVisible (*customComponent);
  39. }
  40. void paint (Graphics& g) override
  41. {
  42. item.draw (g, getWidth(), mouseIsOverButton);
  43. }
  44. void resized() override
  45. {
  46. if (hasCustomComponent())
  47. {
  48. auto itemPosition = item.getItemPosition (false);
  49. customComponent->setBounds (getLocalBounds().withX (itemPosition.getX())
  50. .withWidth (itemPosition.getWidth()));
  51. }
  52. }
  53. std::unique_ptr<AccessibilityHandler> createAccessibilityHandler() override
  54. {
  55. if (hasCustomComponent() && customComponent->getAccessibilityHandler() != nullptr)
  56. return nullptr;
  57. return std::make_unique<ItemAccessibilityHandler> (*this);
  58. }
  59. void setMouseIsOverButton (bool isOver) { mouseIsOverButton = isOver; }
  60. TreeViewItem& getRepresentedItem() const noexcept { return item; }
  61. private:
  62. //==============================================================================
  63. class ItemAccessibilityHandler : public AccessibilityHandler
  64. {
  65. public:
  66. explicit ItemAccessibilityHandler (ItemComponent& comp)
  67. : AccessibilityHandler (comp,
  68. AccessibilityRole::treeItem,
  69. getAccessibilityActions (comp),
  70. { std::make_unique<ItemCellInterface> (comp) }),
  71. itemComponent (comp)
  72. {
  73. }
  74. String getTitle() const override
  75. {
  76. return itemComponent.getRepresentedItem().getAccessibilityName();
  77. }
  78. AccessibleState getCurrentState() const override
  79. {
  80. auto& treeItem = itemComponent.getRepresentedItem();
  81. auto state = AccessibilityHandler::getCurrentState().withAccessibleOffscreen();
  82. if (auto* tree = treeItem.getOwnerView())
  83. {
  84. if (tree->isMultiSelectEnabled())
  85. state = state.withMultiSelectable();
  86. else
  87. state = state.withSelectable();
  88. }
  89. if (treeItem.mightContainSubItems())
  90. state = state.withExpandable();
  91. if (treeItem.isOpen())
  92. state = state.withExpanded();
  93. else
  94. state = state.withCollapsed();
  95. if (treeItem.isSelected())
  96. state = state.withSelected();
  97. return state;
  98. }
  99. class ItemCellInterface : public AccessibilityCellInterface
  100. {
  101. public:
  102. explicit ItemCellInterface (ItemComponent& c) : itemComponent (c) {}
  103. int getColumnIndex() const override { return 0; }
  104. int getColumnSpan() const override { return 1; }
  105. int getRowIndex() const override
  106. {
  107. return itemComponent.getRepresentedItem().getRowNumberInTree();
  108. }
  109. int getRowSpan() const override
  110. {
  111. return 1;
  112. }
  113. int getDisclosureLevel() const override
  114. {
  115. return getItemDepth (&itemComponent.getRepresentedItem());
  116. }
  117. const AccessibilityHandler* getTableHandler() const override
  118. {
  119. if (auto* tree = itemComponent.getRepresentedItem().getOwnerView())
  120. return tree->getAccessibilityHandler();
  121. return nullptr;
  122. }
  123. private:
  124. ItemComponent& itemComponent;
  125. };
  126. private:
  127. static AccessibilityActions getAccessibilityActions (ItemComponent& itemComponent)
  128. {
  129. auto onFocus = [&itemComponent]
  130. {
  131. auto& treeItem = itemComponent.getRepresentedItem();
  132. if (auto* tree = treeItem.getOwnerView())
  133. tree->scrollToKeepItemVisible (&treeItem);
  134. };
  135. auto onPress = [&itemComponent]
  136. {
  137. itemComponent.getRepresentedItem().itemClicked (generateMouseEvent (itemComponent, { ModifierKeys::leftButtonModifier }));
  138. };
  139. auto onShowMenu = [&itemComponent]
  140. {
  141. itemComponent.getRepresentedItem().itemClicked (generateMouseEvent (itemComponent, { ModifierKeys::popupMenuClickModifier }));
  142. };
  143. auto onToggle = [&itemComponent, onFocus]
  144. {
  145. if (auto* handler = itemComponent.getAccessibilityHandler())
  146. {
  147. auto isSelected = handler->getCurrentState().isSelected();
  148. if (! isSelected)
  149. onFocus();
  150. itemComponent.getRepresentedItem().setSelected (! isSelected, true);
  151. }
  152. };
  153. auto actions = AccessibilityActions().addAction (AccessibilityActionType::focus, std::move (onFocus))
  154. .addAction (AccessibilityActionType::press, std::move (onPress))
  155. .addAction (AccessibilityActionType::showMenu, std::move (onShowMenu))
  156. .addAction (AccessibilityActionType::toggle, std::move (onToggle));
  157. return actions;
  158. }
  159. ItemComponent& itemComponent;
  160. static MouseEvent generateMouseEvent (ItemComponent& itemComp, ModifierKeys mods)
  161. {
  162. auto topLeft = itemComp.getRepresentedItem().getItemPosition (false).toFloat().getTopLeft();
  163. return { Desktop::getInstance().getMainMouseSource(), topLeft, mods,
  164. MouseInputSource::invalidPressure, MouseInputSource::invalidOrientation, MouseInputSource::invalidRotation,
  165. MouseInputSource::invalidTiltX, MouseInputSource::invalidTiltY,
  166. &itemComp, &itemComp, Time::getCurrentTime(), topLeft, Time::getCurrentTime(), 0, false };
  167. }
  168. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ItemAccessibilityHandler)
  169. };
  170. //==============================================================================
  171. bool hasCustomComponent() const noexcept { return customComponent.get() != nullptr; }
  172. TreeViewItem& item;
  173. std::unique_ptr<Component> customComponent;
  174. bool mouseIsOverButton = false;
  175. //==============================================================================
  176. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ItemComponent)
  177. };
  178. //==============================================================================
  179. class TreeView::ContentComponent : public Component,
  180. public TooltipClient,
  181. public AsyncUpdater
  182. {
  183. public:
  184. ContentComponent (TreeView& tree) : owner (tree)
  185. {
  186. setAccessible (false);
  187. }
  188. //==============================================================================
  189. void resized() override
  190. {
  191. triggerAsyncUpdate();
  192. }
  193. String getTooltip() override
  194. {
  195. if (auto* itemComponent = getItemComponentAt (getMouseXYRelative()))
  196. return itemComponent->getRepresentedItem().getTooltip();
  197. return owner.getTooltip();
  198. }
  199. void mouseDown (const MouseEvent& e) override { mouseDownInternal (e.getEventRelativeTo (this)); }
  200. void mouseUp (const MouseEvent& e) override { mouseUpInternal (e.getEventRelativeTo (this)); }
  201. void mouseDoubleClick (const MouseEvent& e) override { mouseDoubleClickInternal (e.getEventRelativeTo (this));}
  202. void mouseDrag (const MouseEvent& e) override { mouseDragInternal (e.getEventRelativeTo (this));}
  203. void mouseMove (const MouseEvent& e) override { mouseMoveInternal (e.getEventRelativeTo (this)); }
  204. void mouseExit (const MouseEvent& e) override { mouseExitInternal (e.getEventRelativeTo (this)); }
  205. //==============================================================================
  206. ItemComponent* getItemComponentAt (Point<int> p)
  207. {
  208. auto iter = std::find_if (itemComponents.cbegin(), itemComponents.cend(),
  209. [p] (const std::unique_ptr<ItemComponent>& c) { return c->getBounds().contains (p); });
  210. if (iter != itemComponents.cend())
  211. return iter->get();
  212. return nullptr;
  213. }
  214. ItemComponent* getComponentForItem (const TreeViewItem* item) const
  215. {
  216. if (item != nullptr)
  217. {
  218. auto iter = std::find_if (itemComponents.cbegin(), itemComponents.cend(),
  219. [item] (const std::unique_ptr<ItemComponent>& c)
  220. {
  221. return &c->getRepresentedItem() == item;
  222. });
  223. if (iter != itemComponents.cend())
  224. return iter->get();
  225. }
  226. return nullptr;
  227. }
  228. void updateComponents()
  229. {
  230. std::vector<ItemComponent*> componentsToKeep;
  231. for (auto* treeItem : getAllVisibleItems())
  232. {
  233. if (auto* itemComp = getComponentForItem (treeItem))
  234. {
  235. componentsToKeep.push_back (itemComp);
  236. }
  237. else
  238. {
  239. auto newComp = std::make_unique<ItemComponent> (*treeItem);
  240. addAndMakeVisible (*newComp);
  241. newComp->addMouseListener (this, true);
  242. componentsToKeep.push_back (newComp.get());
  243. itemComponents.push_back (std::move (newComp));
  244. }
  245. }
  246. for (int i = (int) itemComponents.size(); --i >= 0;)
  247. {
  248. auto& comp = itemComponents[(size_t) i];
  249. if (std::find (componentsToKeep.cbegin(), componentsToKeep.cend(), comp.get())
  250. != componentsToKeep.cend())
  251. {
  252. auto& treeItem = comp->getRepresentedItem();
  253. comp->setBounds ({ 0, treeItem.y, getWidth(), treeItem.itemHeight });
  254. }
  255. else
  256. {
  257. if (isMouseDraggingInChildComp (*comp))
  258. comp->setSize (0, 0);
  259. else
  260. itemComponents.erase (itemComponents.begin() + i);
  261. }
  262. }
  263. }
  264. private:
  265. //==============================================================================
  266. void mouseDownInternal (const MouseEvent& e)
  267. {
  268. updateItemUnderMouse (e);
  269. isDragging = false;
  270. needSelectionOnMouseUp = false;
  271. if (! isEnabled())
  272. return;
  273. if (auto* itemComponent = getItemComponentAt (e.getPosition()))
  274. {
  275. auto& item = itemComponent->getRepresentedItem();
  276. auto pos = item.getItemPosition (false);
  277. // (if the open/close buttons are hidden, we'll treat clicks to the left of the item
  278. // as selection clicks)
  279. if (e.x < pos.getX() && owner.openCloseButtonsVisible)
  280. {
  281. // (clicks to the left of an open/close button are ignored)
  282. if (e.x >= pos.getX() - owner.getIndentSize())
  283. item.setOpen (! item.isOpen());
  284. }
  285. else
  286. {
  287. // mouse-down inside the body of the item..
  288. if (! owner.isMultiSelectEnabled())
  289. item.setSelected (true, true);
  290. else if (item.isSelected())
  291. needSelectionOnMouseUp = ! e.mods.isPopupMenu();
  292. else
  293. selectBasedOnModifiers (item, e.mods);
  294. if (e.x >= pos.getX())
  295. item.itemClicked (e.withNewPosition (e.position - pos.getPosition().toFloat()));
  296. }
  297. }
  298. }
  299. void mouseUpInternal (const MouseEvent& e)
  300. {
  301. updateItemUnderMouse (e);
  302. if (isEnabled() && needSelectionOnMouseUp && e.mouseWasClicked())
  303. if (auto* itemComponent = getItemComponentAt (e.getPosition()))
  304. selectBasedOnModifiers (itemComponent->getRepresentedItem(), e.mods);
  305. }
  306. void mouseDoubleClickInternal (const MouseEvent& e)
  307. {
  308. if (isEnabled() && e.getNumberOfClicks() != 3) // ignore triple clicks
  309. {
  310. if (auto* itemComponent = getItemComponentAt (e.getPosition()))
  311. {
  312. auto& item = itemComponent->getRepresentedItem();
  313. auto pos = item.getItemPosition (false);
  314. if (e.x >= pos.getX() || ! owner.openCloseButtonsVisible)
  315. item.itemDoubleClicked (e.withNewPosition (e.position - pos.getPosition().toFloat()));
  316. }
  317. }
  318. }
  319. void mouseDragInternal (const MouseEvent& e)
  320. {
  321. if (isEnabled()
  322. && ! (isDragging || e.mouseWasClicked()
  323. || e.getDistanceFromDragStart() < 5
  324. || e.mods.isPopupMenu()))
  325. {
  326. isDragging = true;
  327. if (auto* itemComponent = getItemComponentAt (e.getMouseDownPosition()))
  328. {
  329. auto& item = itemComponent->getRepresentedItem();
  330. auto pos = item.getItemPosition (false);
  331. if (e.getMouseDownX() >= pos.getX())
  332. {
  333. auto dragDescription = item.getDragSourceDescription();
  334. if (! (dragDescription.isVoid() || (dragDescription.isString() && dragDescription.toString().isEmpty())))
  335. {
  336. if (auto* dragContainer = DragAndDropContainer::findParentDragContainerFor (this))
  337. {
  338. pos.setSize (pos.getWidth(), item.itemHeight);
  339. auto dragImage = Component::createComponentSnapshot (pos,
  340. true,
  341. Component::getApproximateScaleFactorForComponent (itemComponent));
  342. dragImage.multiplyAllAlphas (0.6f);
  343. auto imageOffset = pos.getPosition() - e.getPosition();
  344. dragContainer->startDragging (dragDescription, &owner, dragImage, true, &imageOffset, &e.source);
  345. }
  346. else
  347. {
  348. // to be able to do a drag-and-drop operation, the treeview needs to
  349. // be inside a component which is also a DragAndDropContainer.
  350. jassertfalse;
  351. }
  352. }
  353. }
  354. }
  355. }
  356. }
  357. void mouseMoveInternal (const MouseEvent& e) { updateItemUnderMouse (e); }
  358. void mouseExitInternal (const MouseEvent& e) { updateItemUnderMouse (e); }
  359. bool isMouseDraggingInChildComp (const Component& comp) const
  360. {
  361. for (auto& ms : Desktop::getInstance().getMouseSources())
  362. if (ms.isDragging())
  363. if (auto* underMouse = ms.getComponentUnderMouse())
  364. return (&comp == underMouse || comp.isParentOf (underMouse));
  365. return false;
  366. }
  367. void updateItemUnderMouse (const MouseEvent& e)
  368. {
  369. ItemComponent* newItem = nullptr;
  370. if (owner.openCloseButtonsVisible)
  371. {
  372. if (auto* itemComponent = getItemComponentAt (e.getPosition()))
  373. {
  374. auto& item = itemComponent->getRepresentedItem();
  375. auto pos = item.getItemPosition (false);
  376. if (e.x < pos.getX()
  377. && e.x >= pos.getX() - owner.getIndentSize()
  378. && item.mightContainSubItems())
  379. {
  380. newItem = itemComponent;
  381. }
  382. }
  383. }
  384. if (itemUnderMouse != newItem)
  385. {
  386. auto updateItem = [] (ItemComponent* itemComp, bool isMouseOverButton)
  387. {
  388. if (itemComp != nullptr)
  389. {
  390. itemComp->setMouseIsOverButton (isMouseOverButton);
  391. itemComp->repaint();
  392. }
  393. };
  394. updateItem (itemUnderMouse, false);
  395. updateItem (newItem, true);
  396. itemUnderMouse = newItem;
  397. }
  398. }
  399. void handleAsyncUpdate() override
  400. {
  401. owner.updateVisibleItems();
  402. }
  403. //==============================================================================
  404. void selectBasedOnModifiers (TreeViewItem& item, const ModifierKeys modifiers)
  405. {
  406. TreeViewItem* firstSelected = nullptr;
  407. if (modifiers.isShiftDown() && ((firstSelected = owner.getSelectedItem (0)) != nullptr))
  408. {
  409. auto* lastSelected = owner.getSelectedItem (owner.getNumSelectedItems() - 1);
  410. jassert (lastSelected != nullptr);
  411. auto rowStart = firstSelected->getRowNumberInTree();
  412. auto rowEnd = lastSelected->getRowNumberInTree();
  413. if (rowStart > rowEnd)
  414. std::swap (rowStart, rowEnd);
  415. auto ourRow = item.getRowNumberInTree();
  416. auto otherEnd = ourRow < rowEnd ? rowStart : rowEnd;
  417. if (ourRow > otherEnd)
  418. std::swap (ourRow, otherEnd);
  419. for (int i = ourRow; i <= otherEnd; ++i)
  420. owner.getItemOnRow (i)->setSelected (true, false);
  421. }
  422. else
  423. {
  424. const auto cmd = modifiers.isCommandDown();
  425. item.setSelected ((! cmd) || ! item.isSelected(), ! cmd);
  426. }
  427. }
  428. static TreeViewItem* getNextVisibleItem (TreeViewItem* item, bool forwards)
  429. {
  430. if (item == nullptr || item->ownerView == nullptr)
  431. return nullptr;
  432. auto* nextItem = item->ownerView->getItemOnRow (item->getRowNumberInTree() + (forwards ? 1 : -1));
  433. return nextItem == item->ownerView->rootItem && ! item->ownerView->rootItemVisible ? nullptr
  434. : nextItem;
  435. }
  436. std::vector<TreeViewItem*> getAllVisibleItems() const
  437. {
  438. if (owner.rootItem == nullptr)
  439. return {};
  440. const auto visibleTop = -getY();
  441. const auto visibleBottom = visibleTop + getParentHeight();
  442. std::vector<TreeViewItem*> visibleItems;
  443. auto* item = [&]
  444. {
  445. auto* i = owner.rootItemVisible ? owner.rootItem
  446. : owner.rootItem->subItems.getFirst();
  447. while (i != nullptr && i->y < visibleTop)
  448. i = getNextVisibleItem (i, true);
  449. return i;
  450. }();
  451. auto addOffscreenItemBuffer = [&visibleItems] (TreeViewItem* i, int num, bool forwards)
  452. {
  453. while (--num >= 0)
  454. {
  455. i = getNextVisibleItem (i, forwards);
  456. if (i == nullptr)
  457. return;
  458. visibleItems.push_back (i);
  459. }
  460. };
  461. addOffscreenItemBuffer (item, 2, false);
  462. while (item != nullptr && item->y < visibleBottom)
  463. {
  464. visibleItems.push_back (item);
  465. item = getNextVisibleItem (item, true);
  466. }
  467. if (item != nullptr)
  468. visibleItems.push_back (item);
  469. addOffscreenItemBuffer (item, 2, true);
  470. return visibleItems;
  471. }
  472. //==============================================================================
  473. TreeView& owner;
  474. std::vector<std::unique_ptr<ItemComponent>> itemComponents;
  475. ItemComponent* itemUnderMouse = nullptr;
  476. bool isDragging = false, needSelectionOnMouseUp = false;
  477. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ContentComponent)
  478. };
  479. //==============================================================================
  480. class TreeView::TreeViewport : public Viewport
  481. {
  482. public:
  483. TreeViewport() = default;
  484. void updateComponents (bool triggerResize)
  485. {
  486. if (auto* tvc = getContentComp())
  487. {
  488. if (triggerResize)
  489. tvc->resized();
  490. else
  491. tvc->updateComponents();
  492. }
  493. repaint();
  494. }
  495. void visibleAreaChanged (const Rectangle<int>& newVisibleArea) override
  496. {
  497. const auto hasScrolledSideways = (newVisibleArea.getX() != lastX);
  498. lastX = newVisibleArea.getX();
  499. updateComponents (hasScrolledSideways);
  500. if (auto* tree = getParentComponent())
  501. if (auto* handler = tree->getAccessibilityHandler())
  502. handler->notifyAccessibilityEvent (AccessibilityEvent::structureChanged);
  503. }
  504. ContentComponent* getContentComp() const noexcept
  505. {
  506. return static_cast<ContentComponent*> (getViewedComponent());
  507. }
  508. bool keyPressed (const KeyPress& key) override
  509. {
  510. if (auto* tree = getParentComponent())
  511. if (tree->keyPressed (key))
  512. return true;
  513. return Viewport::keyPressed (key);
  514. }
  515. private:
  516. int lastX = -1;
  517. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (TreeViewport)
  518. };
  519. //==============================================================================
  520. TreeView::TreeView (const String& name) : Component (name)
  521. {
  522. viewport = std::make_unique<TreeViewport>();
  523. viewport->setAccessible (false);
  524. addAndMakeVisible (viewport.get());
  525. viewport->setViewedComponent (new ContentComponent (*this));
  526. setWantsKeyboardFocus (true);
  527. setFocusContainerType (FocusContainerType::focusContainer);
  528. }
  529. TreeView::~TreeView()
  530. {
  531. if (rootItem != nullptr)
  532. rootItem->setOwnerView (nullptr);
  533. }
  534. void TreeView::setRootItem (TreeViewItem* const newRootItem)
  535. {
  536. if (rootItem != newRootItem)
  537. {
  538. if (newRootItem != nullptr)
  539. {
  540. // can't use a tree item in more than one tree at once..
  541. jassert (newRootItem->ownerView == nullptr);
  542. if (newRootItem->ownerView != nullptr)
  543. newRootItem->ownerView->setRootItem (nullptr);
  544. }
  545. if (rootItem != nullptr)
  546. rootItem->setOwnerView (nullptr);
  547. rootItem = newRootItem;
  548. if (newRootItem != nullptr)
  549. newRootItem->setOwnerView (this);
  550. if (rootItem != nullptr && (defaultOpenness || ! rootItemVisible))
  551. {
  552. rootItem->setOpen (false); // force a re-open
  553. rootItem->setOpen (true);
  554. }
  555. updateVisibleItems();
  556. }
  557. }
  558. void TreeView::deleteRootItem()
  559. {
  560. const std::unique_ptr<TreeViewItem> deleter (rootItem);
  561. setRootItem (nullptr);
  562. }
  563. void TreeView::setRootItemVisible (const bool shouldBeVisible)
  564. {
  565. rootItemVisible = shouldBeVisible;
  566. if (rootItem != nullptr && (defaultOpenness || ! rootItemVisible))
  567. {
  568. rootItem->setOpen (false); // force a re-open
  569. rootItem->setOpen (true);
  570. }
  571. updateVisibleItems();
  572. }
  573. void TreeView::colourChanged()
  574. {
  575. setOpaque (findColour (backgroundColourId).isOpaque());
  576. repaint();
  577. }
  578. void TreeView::setIndentSize (const int newIndentSize)
  579. {
  580. if (indentSize != newIndentSize)
  581. {
  582. indentSize = newIndentSize;
  583. resized();
  584. }
  585. }
  586. int TreeView::getIndentSize() noexcept
  587. {
  588. return indentSize >= 0 ? indentSize
  589. : getLookAndFeel().getTreeViewIndentSize (*this);
  590. }
  591. void TreeView::setDefaultOpenness (const bool isOpenByDefault)
  592. {
  593. if (defaultOpenness != isOpenByDefault)
  594. {
  595. defaultOpenness = isOpenByDefault;
  596. updateVisibleItems();
  597. }
  598. }
  599. void TreeView::setMultiSelectEnabled (const bool canMultiSelect)
  600. {
  601. multiSelectEnabled = canMultiSelect;
  602. }
  603. void TreeView::setOpenCloseButtonsVisible (const bool shouldBeVisible)
  604. {
  605. if (openCloseButtonsVisible != shouldBeVisible)
  606. {
  607. openCloseButtonsVisible = shouldBeVisible;
  608. updateVisibleItems();
  609. }
  610. }
  611. Viewport* TreeView::getViewport() const noexcept
  612. {
  613. return viewport.get();
  614. }
  615. //==============================================================================
  616. void TreeView::clearSelectedItems()
  617. {
  618. if (rootItem != nullptr)
  619. rootItem->deselectAllRecursively (nullptr);
  620. }
  621. int TreeView::getNumSelectedItems (int maximumDepthToSearchTo) const noexcept
  622. {
  623. return rootItem != nullptr ? rootItem->countSelectedItemsRecursively (maximumDepthToSearchTo) : 0;
  624. }
  625. TreeViewItem* TreeView::getSelectedItem (const int index) const noexcept
  626. {
  627. return rootItem != nullptr ? rootItem->getSelectedItemWithIndex (index) : nullptr;
  628. }
  629. int TreeView::getNumRowsInTree() const
  630. {
  631. return rootItem != nullptr ? (rootItem->getNumRows() - (rootItemVisible ? 0 : 1)) : 0;
  632. }
  633. TreeViewItem* TreeView::getItemOnRow (int index) const
  634. {
  635. if (! rootItemVisible)
  636. ++index;
  637. if (rootItem != nullptr && index >= 0)
  638. return rootItem->getItemOnRow (index);
  639. return nullptr;
  640. }
  641. TreeViewItem* TreeView::getItemAt (int y) const noexcept
  642. {
  643. if (auto* itemComponent = viewport->getContentComp()->getItemComponentAt (Point<int> (0, y)))
  644. return &itemComponent->getRepresentedItem();
  645. return nullptr;
  646. }
  647. TreeViewItem* TreeView::findItemFromIdentifierString (const String& identifierString) const
  648. {
  649. if (rootItem == nullptr)
  650. return nullptr;
  651. return rootItem->findItemFromIdentifierString (identifierString);
  652. }
  653. Component* TreeView::getItemComponent (const TreeViewItem* item) const
  654. {
  655. return viewport->getContentComp()->getComponentForItem (item);
  656. }
  657. //==============================================================================
  658. static void addAllSelectedItemIds (TreeViewItem* item, XmlElement& parent)
  659. {
  660. if (item->isSelected())
  661. parent.createNewChildElement ("SELECTED")->setAttribute ("id", item->getItemIdentifierString());
  662. auto numSubItems = item->getNumSubItems();
  663. for (int i = 0; i < numSubItems; ++i)
  664. addAllSelectedItemIds (item->getSubItem (i), parent);
  665. }
  666. std::unique_ptr<XmlElement> TreeView::getOpennessState (bool alsoIncludeScrollPosition) const
  667. {
  668. if (rootItem != nullptr)
  669. {
  670. if (auto rootOpenness = rootItem->getOpennessState (false))
  671. {
  672. if (alsoIncludeScrollPosition)
  673. rootOpenness->setAttribute ("scrollPos", viewport->getViewPositionY());
  674. addAllSelectedItemIds (rootItem, *rootOpenness);
  675. return rootOpenness;
  676. }
  677. }
  678. return {};
  679. }
  680. void TreeView::restoreOpennessState (const XmlElement& newState, bool restoreStoredSelection)
  681. {
  682. if (rootItem != nullptr)
  683. {
  684. rootItem->restoreOpennessState (newState);
  685. if (newState.hasAttribute ("scrollPos"))
  686. viewport->setViewPosition (viewport->getViewPositionX(),
  687. newState.getIntAttribute ("scrollPos"));
  688. if (restoreStoredSelection)
  689. {
  690. clearSelectedItems();
  691. for (auto* e : newState.getChildWithTagNameIterator ("SELECTED"))
  692. if (auto* item = rootItem->findItemFromIdentifierString (e->getStringAttribute ("id")))
  693. item->setSelected (true, false);
  694. }
  695. updateVisibleItems();
  696. }
  697. }
  698. //==============================================================================
  699. void TreeView::paint (Graphics& g)
  700. {
  701. g.fillAll (findColour (backgroundColourId));
  702. }
  703. void TreeView::resized()
  704. {
  705. viewport->setBounds (getLocalBounds());
  706. updateVisibleItems();
  707. }
  708. void TreeView::enablementChanged()
  709. {
  710. repaint();
  711. }
  712. void TreeView::moveSelectedRow (int delta)
  713. {
  714. auto numRowsInTree = getNumRowsInTree();
  715. if (numRowsInTree > 0)
  716. {
  717. int rowSelected = 0;
  718. if (auto* firstSelected = getSelectedItem (0))
  719. rowSelected = firstSelected->getRowNumberInTree();
  720. rowSelected = jlimit (0, numRowsInTree - 1, rowSelected + delta);
  721. for (;;)
  722. {
  723. if (auto* item = getItemOnRow (rowSelected))
  724. {
  725. if (! item->canBeSelected())
  726. {
  727. // if the row we want to highlight doesn't allow it, try skipping
  728. // to the next item..
  729. auto nextRowToTry = jlimit (0, numRowsInTree - 1, rowSelected + (delta < 0 ? -1 : 1));
  730. if (rowSelected != nextRowToTry)
  731. {
  732. rowSelected = nextRowToTry;
  733. continue;
  734. }
  735. break;
  736. }
  737. item->setSelected (true, true);
  738. scrollToKeepItemVisible (item);
  739. }
  740. break;
  741. }
  742. }
  743. }
  744. void TreeView::scrollToKeepItemVisible (TreeViewItem* item)
  745. {
  746. if (item != nullptr && item->ownerView == this)
  747. {
  748. updateVisibleItems();
  749. item = item->getDeepestOpenParentItem();
  750. auto y = item->y;
  751. auto viewTop = viewport->getViewPositionY();
  752. if (y < viewTop)
  753. {
  754. viewport->setViewPosition (viewport->getViewPositionX(), y);
  755. }
  756. else if (y + item->itemHeight > viewTop + viewport->getViewHeight())
  757. {
  758. viewport->setViewPosition (viewport->getViewPositionX(),
  759. (y + item->itemHeight) - viewport->getViewHeight());
  760. }
  761. }
  762. }
  763. bool TreeView::toggleOpenSelectedItem()
  764. {
  765. if (auto* firstSelected = getSelectedItem (0))
  766. {
  767. if (firstSelected->mightContainSubItems())
  768. {
  769. firstSelected->setOpen (! firstSelected->isOpen());
  770. return true;
  771. }
  772. }
  773. return false;
  774. }
  775. void TreeView::moveOutOfSelectedItem()
  776. {
  777. if (auto* firstSelected = getSelectedItem (0))
  778. {
  779. if (firstSelected->isOpen())
  780. {
  781. firstSelected->setOpen (false);
  782. }
  783. else
  784. {
  785. auto* parent = firstSelected->parentItem;
  786. if ((! rootItemVisible) && parent == rootItem)
  787. parent = nullptr;
  788. if (parent != nullptr)
  789. {
  790. parent->setSelected (true, true);
  791. scrollToKeepItemVisible (parent);
  792. }
  793. }
  794. }
  795. }
  796. void TreeView::moveIntoSelectedItem()
  797. {
  798. if (auto* firstSelected = getSelectedItem (0))
  799. {
  800. if (firstSelected->isOpen() || ! firstSelected->mightContainSubItems())
  801. moveSelectedRow (1);
  802. else
  803. firstSelected->setOpen (true);
  804. }
  805. }
  806. void TreeView::moveByPages (int numPages)
  807. {
  808. if (auto* currentItem = getSelectedItem (0))
  809. {
  810. auto pos = currentItem->getItemPosition (false);
  811. auto targetY = pos.getY() + numPages * (getHeight() - pos.getHeight());
  812. auto currentRow = currentItem->getRowNumberInTree();
  813. for (;;)
  814. {
  815. moveSelectedRow (numPages);
  816. currentItem = getSelectedItem (0);
  817. if (currentItem == nullptr)
  818. break;
  819. auto y = currentItem->getItemPosition (false).getY();
  820. if ((numPages < 0 && y <= targetY) || (numPages > 0 && y >= targetY))
  821. break;
  822. auto newRow = currentItem->getRowNumberInTree();
  823. if (newRow == currentRow)
  824. break;
  825. currentRow = newRow;
  826. }
  827. }
  828. }
  829. bool TreeView::keyPressed (const KeyPress& key)
  830. {
  831. if (rootItem != nullptr)
  832. {
  833. if (key == KeyPress::upKey) { moveSelectedRow (-1); return true; }
  834. if (key == KeyPress::downKey) { moveSelectedRow (1); return true; }
  835. if (key == KeyPress::homeKey) { moveSelectedRow (-0x3fffffff); return true; }
  836. if (key == KeyPress::endKey) { moveSelectedRow (0x3fffffff); return true; }
  837. if (key == KeyPress::pageUpKey) { moveByPages (-1); return true; }
  838. if (key == KeyPress::pageDownKey) { moveByPages (1); return true; }
  839. if (key == KeyPress::returnKey) { return toggleOpenSelectedItem(); }
  840. if (key == KeyPress::leftKey) { moveOutOfSelectedItem(); return true; }
  841. if (key == KeyPress::rightKey) { moveIntoSelectedItem(); return true; }
  842. }
  843. return false;
  844. }
  845. void TreeView::updateVisibleItems()
  846. {
  847. if (rootItem != nullptr)
  848. {
  849. rootItem->updatePositions (rootItemVisible ? 0 : -rootItem->itemHeight);
  850. viewport->getViewedComponent()
  851. ->setSize (jmax (viewport->getMaximumVisibleWidth(), rootItem->totalWidth + 50),
  852. rootItem->totalHeight - (rootItemVisible ? 0 : rootItem->itemHeight));
  853. }
  854. else
  855. {
  856. viewport->getViewedComponent()->setSize (0, 0);
  857. }
  858. viewport->updateComponents (false);
  859. }
  860. //==============================================================================
  861. struct TreeView::InsertPoint
  862. {
  863. InsertPoint (TreeView& view, const StringArray& files,
  864. const DragAndDropTarget::SourceDetails& dragSourceDetails)
  865. : pos (dragSourceDetails.localPosition),
  866. item (view.getItemAt (dragSourceDetails.localPosition.y))
  867. {
  868. if (item != nullptr)
  869. {
  870. auto itemPos = item->getItemPosition (true);
  871. insertIndex = item->getIndexInParent();
  872. auto oldY = pos.y;
  873. pos.y = itemPos.getY();
  874. if (item->getNumSubItems() == 0 || ! item->isOpen())
  875. {
  876. if (files.size() > 0 ? item->isInterestedInFileDrag (files)
  877. : item->isInterestedInDragSource (dragSourceDetails))
  878. {
  879. // Check if we're trying to drag into an empty group item..
  880. if (oldY > itemPos.getY() + itemPos.getHeight() / 4
  881. && oldY < itemPos.getBottom() - itemPos.getHeight() / 4)
  882. {
  883. insertIndex = 0;
  884. pos.x = itemPos.getX() + view.getIndentSize();
  885. pos.y = itemPos.getBottom();
  886. return;
  887. }
  888. }
  889. }
  890. if (oldY > itemPos.getCentreY())
  891. {
  892. pos.y += item->getItemHeight();
  893. while (item->isLastOfSiblings() && item->getParentItem() != nullptr
  894. && item->getParentItem()->getParentItem() != nullptr)
  895. {
  896. if (pos.x > itemPos.getX())
  897. break;
  898. item = item->getParentItem();
  899. itemPos = item->getItemPosition (true);
  900. insertIndex = item->getIndexInParent();
  901. }
  902. ++insertIndex;
  903. }
  904. pos.x = itemPos.getX();
  905. item = item->getParentItem();
  906. }
  907. else if (auto* root = view.getRootItem())
  908. {
  909. // If they're dragging beyond the bottom of the list, then insert at the end of the root item..
  910. item = root;
  911. insertIndex = root->getNumSubItems();
  912. pos = root->getItemPosition (true).getBottomLeft();
  913. pos.x += view.getIndentSize();
  914. }
  915. }
  916. Point<int> pos;
  917. TreeViewItem* item;
  918. int insertIndex = 0;
  919. };
  920. //==============================================================================
  921. class TreeView::InsertPointHighlight : public Component
  922. {
  923. public:
  924. InsertPointHighlight()
  925. {
  926. setSize (100, 12);
  927. setAlwaysOnTop (true);
  928. setInterceptsMouseClicks (false, false);
  929. }
  930. void setTargetPosition (const InsertPoint& insertPos, const int width) noexcept
  931. {
  932. lastItem = insertPos.item;
  933. lastIndex = insertPos.insertIndex;
  934. auto offset = getHeight() / 2;
  935. setBounds (insertPos.pos.x - offset, insertPos.pos.y - offset,
  936. width - (insertPos.pos.x - offset), getHeight());
  937. }
  938. void paint (Graphics& g) override
  939. {
  940. Path p;
  941. auto h = (float) getHeight();
  942. p.addEllipse (2.0f, 2.0f, h - 4.0f, h - 4.0f);
  943. p.startNewSubPath (h - 2.0f, h / 2.0f);
  944. p.lineTo ((float) getWidth(), h / 2.0f);
  945. g.setColour (findColour (TreeView::dragAndDropIndicatorColourId, true));
  946. g.strokePath (p, PathStrokeType (2.0f));
  947. }
  948. TreeViewItem* lastItem = nullptr;
  949. int lastIndex = 0;
  950. private:
  951. JUCE_DECLARE_NON_COPYABLE (InsertPointHighlight)
  952. };
  953. //==============================================================================
  954. class TreeView::TargetGroupHighlight : public Component
  955. {
  956. public:
  957. TargetGroupHighlight()
  958. {
  959. setAlwaysOnTop (true);
  960. setInterceptsMouseClicks (false, false);
  961. }
  962. void setTargetPosition (TreeViewItem* const item) noexcept
  963. {
  964. setBounds (item->getItemPosition (true)
  965. .withHeight (item->getItemHeight()));
  966. }
  967. void paint (Graphics& g) override
  968. {
  969. g.setColour (findColour (TreeView::dragAndDropIndicatorColourId, true));
  970. g.drawRoundedRectangle (1.0f, 1.0f, (float) getWidth() - 2.0f, (float) getHeight() - 2.0f, 3.0f, 2.0f);
  971. }
  972. private:
  973. JUCE_DECLARE_NON_COPYABLE (TargetGroupHighlight)
  974. };
  975. //==============================================================================
  976. void TreeView::showDragHighlight (const InsertPoint& insertPos) noexcept
  977. {
  978. beginDragAutoRepeat (100);
  979. if (dragInsertPointHighlight == nullptr)
  980. {
  981. dragInsertPointHighlight = std::make_unique<InsertPointHighlight>();
  982. dragTargetGroupHighlight = std::make_unique<TargetGroupHighlight>();
  983. addAndMakeVisible (dragInsertPointHighlight.get());
  984. addAndMakeVisible (dragTargetGroupHighlight.get());
  985. }
  986. dragInsertPointHighlight->setTargetPosition (insertPos, viewport->getViewWidth());
  987. dragTargetGroupHighlight->setTargetPosition (insertPos.item);
  988. }
  989. void TreeView::hideDragHighlight() noexcept
  990. {
  991. dragInsertPointHighlight = nullptr;
  992. dragTargetGroupHighlight = nullptr;
  993. }
  994. void TreeView::handleDrag (const StringArray& files, const SourceDetails& dragSourceDetails)
  995. {
  996. const auto scrolled = viewport->autoScroll (dragSourceDetails.localPosition.x,
  997. dragSourceDetails.localPosition.y, 20, 10);
  998. InsertPoint insertPos (*this, files, dragSourceDetails);
  999. if (insertPos.item != nullptr)
  1000. {
  1001. if (scrolled || dragInsertPointHighlight == nullptr
  1002. || dragInsertPointHighlight->lastItem != insertPos.item
  1003. || dragInsertPointHighlight->lastIndex != insertPos.insertIndex)
  1004. {
  1005. if (files.size() > 0 ? insertPos.item->isInterestedInFileDrag (files)
  1006. : insertPos.item->isInterestedInDragSource (dragSourceDetails))
  1007. showDragHighlight (insertPos);
  1008. else
  1009. hideDragHighlight();
  1010. }
  1011. }
  1012. else
  1013. {
  1014. hideDragHighlight();
  1015. }
  1016. }
  1017. void TreeView::handleDrop (const StringArray& files, const SourceDetails& dragSourceDetails)
  1018. {
  1019. hideDragHighlight();
  1020. InsertPoint insertPos (*this, files, dragSourceDetails);
  1021. if (insertPos.item == nullptr)
  1022. insertPos.item = rootItem;
  1023. if (insertPos.item != nullptr)
  1024. {
  1025. if (files.size() > 0)
  1026. {
  1027. if (insertPos.item->isInterestedInFileDrag (files))
  1028. insertPos.item->filesDropped (files, insertPos.insertIndex);
  1029. }
  1030. else
  1031. {
  1032. if (insertPos.item->isInterestedInDragSource (dragSourceDetails))
  1033. insertPos.item->itemDropped (dragSourceDetails, insertPos.insertIndex);
  1034. }
  1035. }
  1036. }
  1037. //==============================================================================
  1038. bool TreeView::isInterestedInFileDrag (const StringArray&)
  1039. {
  1040. return true;
  1041. }
  1042. void TreeView::fileDragEnter (const StringArray& files, int x, int y)
  1043. {
  1044. fileDragMove (files, x, y);
  1045. }
  1046. void TreeView::fileDragMove (const StringArray& files, int x, int y)
  1047. {
  1048. handleDrag (files, SourceDetails (var(), this, { x, y }));
  1049. }
  1050. void TreeView::fileDragExit (const StringArray&)
  1051. {
  1052. hideDragHighlight();
  1053. }
  1054. void TreeView::filesDropped (const StringArray& files, int x, int y)
  1055. {
  1056. handleDrop (files, SourceDetails (var(), this, { x, y }));
  1057. }
  1058. bool TreeView::isInterestedInDragSource (const SourceDetails& /*dragSourceDetails*/)
  1059. {
  1060. return true;
  1061. }
  1062. void TreeView::itemDragEnter (const SourceDetails& dragSourceDetails)
  1063. {
  1064. itemDragMove (dragSourceDetails);
  1065. }
  1066. void TreeView::itemDragMove (const SourceDetails& dragSourceDetails)
  1067. {
  1068. handleDrag (StringArray(), dragSourceDetails);
  1069. }
  1070. void TreeView::itemDragExit (const SourceDetails& /*dragSourceDetails*/)
  1071. {
  1072. hideDragHighlight();
  1073. }
  1074. void TreeView::itemDropped (const SourceDetails& dragSourceDetails)
  1075. {
  1076. handleDrop (StringArray(), dragSourceDetails);
  1077. }
  1078. //==============================================================================
  1079. std::unique_ptr<AccessibilityHandler> TreeView::createAccessibilityHandler()
  1080. {
  1081. class TableInterface : public AccessibilityTableInterface
  1082. {
  1083. public:
  1084. explicit TableInterface (TreeView& treeViewToWrap) : treeView (treeViewToWrap) {}
  1085. int getNumRows() const override { return treeView.getNumRowsInTree(); }
  1086. int getNumColumns() const override { return 1; }
  1087. const AccessibilityHandler* getCellHandler (int row, int) const override
  1088. {
  1089. if (auto* itemComp = treeView.getItemComponent (treeView.getItemOnRow (row)))
  1090. return itemComp->getAccessibilityHandler();
  1091. return nullptr;
  1092. }
  1093. private:
  1094. TreeView& treeView;
  1095. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (TableInterface)
  1096. };
  1097. return std::make_unique<AccessibilityHandler> (*this,
  1098. AccessibilityRole::tree,
  1099. AccessibilityActions{},
  1100. AccessibilityHandler::Interfaces { std::make_unique<TableInterface> (*this) });
  1101. }
  1102. //==============================================================================
  1103. TreeViewItem::TreeViewItem()
  1104. {
  1105. static int nextUID = 0;
  1106. uid = nextUID++;
  1107. }
  1108. String TreeViewItem::getUniqueName() const
  1109. {
  1110. return {};
  1111. }
  1112. void TreeViewItem::itemOpennessChanged (bool)
  1113. {
  1114. }
  1115. int TreeViewItem::getNumSubItems() const noexcept
  1116. {
  1117. return subItems.size();
  1118. }
  1119. TreeViewItem* TreeViewItem::getSubItem (const int index) const noexcept
  1120. {
  1121. return subItems[index];
  1122. }
  1123. void TreeViewItem::clearSubItems()
  1124. {
  1125. if (ownerView != nullptr)
  1126. {
  1127. if (! subItems.isEmpty())
  1128. {
  1129. removeAllSubItemsFromList();
  1130. treeHasChanged();
  1131. }
  1132. }
  1133. else
  1134. {
  1135. removeAllSubItemsFromList();
  1136. }
  1137. }
  1138. void TreeViewItem::removeAllSubItemsFromList()
  1139. {
  1140. for (int i = subItems.size(); --i >= 0;)
  1141. removeSubItemFromList (i, true);
  1142. }
  1143. void TreeViewItem::addSubItem (TreeViewItem* const newItem, const int insertPosition)
  1144. {
  1145. if (newItem != nullptr)
  1146. {
  1147. newItem->parentItem = nullptr;
  1148. newItem->setOwnerView (ownerView);
  1149. newItem->y = 0;
  1150. newItem->itemHeight = newItem->getItemHeight();
  1151. newItem->totalHeight = 0;
  1152. newItem->itemWidth = newItem->getItemWidth();
  1153. newItem->totalWidth = 0;
  1154. newItem->parentItem = this;
  1155. if (ownerView != nullptr)
  1156. {
  1157. subItems.insert (insertPosition, newItem);
  1158. treeHasChanged();
  1159. if (newItem->isOpen())
  1160. newItem->itemOpennessChanged (true);
  1161. }
  1162. else
  1163. {
  1164. subItems.insert (insertPosition, newItem);
  1165. if (newItem->isOpen())
  1166. newItem->itemOpennessChanged (true);
  1167. }
  1168. }
  1169. }
  1170. void TreeViewItem::removeSubItem (int index, bool deleteItem)
  1171. {
  1172. if (ownerView != nullptr)
  1173. {
  1174. if (removeSubItemFromList (index, deleteItem))
  1175. treeHasChanged();
  1176. }
  1177. else
  1178. {
  1179. removeSubItemFromList (index, deleteItem);
  1180. }
  1181. }
  1182. bool TreeViewItem::removeSubItemFromList (int index, bool deleteItem)
  1183. {
  1184. if (auto* child = subItems[index])
  1185. {
  1186. child->parentItem = nullptr;
  1187. subItems.remove (index, deleteItem);
  1188. return true;
  1189. }
  1190. return false;
  1191. }
  1192. TreeViewItem::Openness TreeViewItem::getOpenness() const noexcept
  1193. {
  1194. return openness;
  1195. }
  1196. void TreeViewItem::setOpenness (Openness newOpenness)
  1197. {
  1198. auto wasOpen = isOpen();
  1199. openness = newOpenness;
  1200. auto isNowOpen = isOpen();
  1201. if (isNowOpen != wasOpen)
  1202. {
  1203. treeHasChanged();
  1204. itemOpennessChanged (isNowOpen);
  1205. }
  1206. }
  1207. bool TreeViewItem::isOpen() const noexcept
  1208. {
  1209. if (openness == Openness::opennessDefault)
  1210. return ownerView != nullptr && ownerView->defaultOpenness;
  1211. return openness == Openness::opennessOpen;
  1212. }
  1213. void TreeViewItem::setOpen (const bool shouldBeOpen)
  1214. {
  1215. if (isOpen() != shouldBeOpen)
  1216. setOpenness (shouldBeOpen ? Openness::opennessOpen
  1217. : Openness::opennessClosed);
  1218. }
  1219. bool TreeViewItem::isFullyOpen() const noexcept
  1220. {
  1221. if (! isOpen())
  1222. return false;
  1223. for (auto* i : subItems)
  1224. if (! i->isFullyOpen())
  1225. return false;
  1226. return true;
  1227. }
  1228. void TreeViewItem::restoreToDefaultOpenness()
  1229. {
  1230. setOpenness (Openness::opennessDefault);
  1231. }
  1232. bool TreeViewItem::isSelected() const noexcept
  1233. {
  1234. return selected;
  1235. }
  1236. void TreeViewItem::deselectAllRecursively (TreeViewItem* itemToIgnore)
  1237. {
  1238. if (this != itemToIgnore)
  1239. setSelected (false, false);
  1240. for (auto* i : subItems)
  1241. i->deselectAllRecursively (itemToIgnore);
  1242. }
  1243. void TreeViewItem::setSelected (const bool shouldBeSelected,
  1244. const bool deselectOtherItemsFirst,
  1245. const NotificationType notify)
  1246. {
  1247. if (shouldBeSelected && ! canBeSelected())
  1248. return;
  1249. if (deselectOtherItemsFirst)
  1250. getTopLevelItem()->deselectAllRecursively (this);
  1251. if (shouldBeSelected != selected)
  1252. {
  1253. selected = shouldBeSelected;
  1254. if (ownerView != nullptr)
  1255. {
  1256. ownerView->repaint();
  1257. if (selected)
  1258. {
  1259. if (auto* itemComponent = ownerView->getItemComponent (this))
  1260. if (auto* itemHandler = itemComponent->getAccessibilityHandler())
  1261. itemHandler->grabFocus();
  1262. }
  1263. if (auto* handler = ownerView->getAccessibilityHandler())
  1264. handler->notifyAccessibilityEvent (AccessibilityEvent::rowSelectionChanged);
  1265. }
  1266. if (notify != dontSendNotification)
  1267. itemSelectionChanged (shouldBeSelected);
  1268. }
  1269. }
  1270. void TreeViewItem::paintItem (Graphics&, int, int)
  1271. {
  1272. }
  1273. void TreeViewItem::paintOpenCloseButton (Graphics& g, const Rectangle<float>& area, Colour backgroundColour, bool isMouseOver)
  1274. {
  1275. getOwnerView()->getLookAndFeel()
  1276. .drawTreeviewPlusMinusBox (g, area, backgroundColour, isOpen(), isMouseOver);
  1277. }
  1278. void TreeViewItem::paintHorizontalConnectingLine (Graphics& g, const Line<float>& line)
  1279. {
  1280. g.setColour (ownerView->findColour (TreeView::linesColourId));
  1281. g.drawLine (line);
  1282. }
  1283. void TreeViewItem::paintVerticalConnectingLine (Graphics& g, const Line<float>& line)
  1284. {
  1285. g.setColour (ownerView->findColour (TreeView::linesColourId));
  1286. g.drawLine (line);
  1287. }
  1288. void TreeViewItem::itemClicked (const MouseEvent&)
  1289. {
  1290. }
  1291. void TreeViewItem::itemDoubleClicked (const MouseEvent&)
  1292. {
  1293. if (mightContainSubItems())
  1294. setOpen (! isOpen());
  1295. }
  1296. void TreeViewItem::itemSelectionChanged (bool)
  1297. {
  1298. }
  1299. String TreeViewItem::getTooltip()
  1300. {
  1301. return {};
  1302. }
  1303. String TreeViewItem::getAccessibilityName()
  1304. {
  1305. auto tooltipString = getTooltip();
  1306. return tooltipString.isNotEmpty()
  1307. ? tooltipString
  1308. : "Level " + String (getItemDepth (this)) + " row " + String (getIndexInParent());
  1309. }
  1310. void TreeViewItem::ownerViewChanged (TreeView*)
  1311. {
  1312. }
  1313. var TreeViewItem::getDragSourceDescription()
  1314. {
  1315. return {};
  1316. }
  1317. bool TreeViewItem::isInterestedInFileDrag (const StringArray&)
  1318. {
  1319. return false;
  1320. }
  1321. void TreeViewItem::filesDropped (const StringArray& /*files*/, int /*insertIndex*/)
  1322. {
  1323. }
  1324. bool TreeViewItem::isInterestedInDragSource (const DragAndDropTarget::SourceDetails& /*dragSourceDetails*/)
  1325. {
  1326. return false;
  1327. }
  1328. void TreeViewItem::itemDropped (const DragAndDropTarget::SourceDetails& /*dragSourceDetails*/, int /*insertIndex*/)
  1329. {
  1330. }
  1331. Rectangle<int> TreeViewItem::getItemPosition (const bool relativeToTreeViewTopLeft) const noexcept
  1332. {
  1333. auto indentX = getIndentX();
  1334. auto width = itemWidth;
  1335. if (ownerView != nullptr && width < 0)
  1336. width = ownerView->viewport->getViewWidth() - indentX;
  1337. Rectangle<int> r (indentX, y, jmax (0, width), totalHeight);
  1338. if (relativeToTreeViewTopLeft && ownerView != nullptr)
  1339. r -= ownerView->viewport->getViewPosition();
  1340. return r;
  1341. }
  1342. void TreeViewItem::treeHasChanged() const noexcept
  1343. {
  1344. if (ownerView != nullptr)
  1345. ownerView->updateVisibleItems();
  1346. }
  1347. void TreeViewItem::repaintItem() const
  1348. {
  1349. if (ownerView != nullptr && areAllParentsOpen())
  1350. if (auto* component = ownerView->getItemComponent (this))
  1351. component->repaint();
  1352. }
  1353. bool TreeViewItem::areAllParentsOpen() const noexcept
  1354. {
  1355. return parentItem == nullptr
  1356. || (parentItem->isOpen() && parentItem->areAllParentsOpen());
  1357. }
  1358. void TreeViewItem::updatePositions (int newY)
  1359. {
  1360. y = newY;
  1361. itemHeight = getItemHeight();
  1362. totalHeight = itemHeight;
  1363. itemWidth = getItemWidth();
  1364. totalWidth = jmax (itemWidth, 0) + getIndentX();
  1365. if (isOpen())
  1366. {
  1367. newY += totalHeight;
  1368. for (auto* i : subItems)
  1369. {
  1370. i->updatePositions (newY);
  1371. newY += i->totalHeight;
  1372. totalHeight += i->totalHeight;
  1373. totalWidth = jmax (totalWidth, i->totalWidth);
  1374. }
  1375. }
  1376. }
  1377. TreeViewItem* TreeViewItem::getDeepestOpenParentItem() noexcept
  1378. {
  1379. auto* result = this;
  1380. auto* item = this;
  1381. while (item->parentItem != nullptr)
  1382. {
  1383. item = item->parentItem;
  1384. if (! item->isOpen())
  1385. result = item;
  1386. }
  1387. return result;
  1388. }
  1389. void TreeViewItem::setOwnerView (TreeView* const newOwner) noexcept
  1390. {
  1391. ownerView = newOwner;
  1392. for (auto* i : subItems)
  1393. {
  1394. i->setOwnerView (newOwner);
  1395. i->ownerViewChanged (newOwner);
  1396. }
  1397. }
  1398. int TreeViewItem::getIndentX() const noexcept
  1399. {
  1400. int x = ownerView->rootItemVisible ? 1 : 0;
  1401. if (! ownerView->openCloseButtonsVisible)
  1402. --x;
  1403. for (auto* p = parentItem; p != nullptr; p = p->parentItem)
  1404. ++x;
  1405. return x * ownerView->getIndentSize();
  1406. }
  1407. void TreeViewItem::setDrawsInLeftMargin (bool canDrawInLeftMargin) noexcept
  1408. {
  1409. drawsInLeftMargin = canDrawInLeftMargin;
  1410. }
  1411. void TreeViewItem::setDrawsInRightMargin (bool canDrawInRightMargin) noexcept
  1412. {
  1413. drawsInRightMargin = canDrawInRightMargin;
  1414. }
  1415. bool TreeViewItem::areLinesDrawn() const
  1416. {
  1417. return drawLinesSet ? drawLinesInside
  1418. : (ownerView != nullptr && ownerView->getLookAndFeel().areLinesDrawnForTreeView (*ownerView));
  1419. }
  1420. bool TreeViewItem::isLastOfSiblings() const noexcept
  1421. {
  1422. return parentItem == nullptr
  1423. || parentItem->subItems.getLast() == this;
  1424. }
  1425. int TreeViewItem::getIndexInParent() const noexcept
  1426. {
  1427. return parentItem == nullptr ? 0
  1428. : parentItem->subItems.indexOf (this);
  1429. }
  1430. TreeViewItem* TreeViewItem::getTopLevelItem() noexcept
  1431. {
  1432. return parentItem == nullptr ? this
  1433. : parentItem->getTopLevelItem();
  1434. }
  1435. int TreeViewItem::getNumRows() const noexcept
  1436. {
  1437. int num = 1;
  1438. if (isOpen())
  1439. for (auto* i : subItems)
  1440. num += i->getNumRows();
  1441. return num;
  1442. }
  1443. TreeViewItem* TreeViewItem::getItemOnRow (int index) noexcept
  1444. {
  1445. if (index == 0)
  1446. return this;
  1447. if (index > 0 && isOpen())
  1448. {
  1449. --index;
  1450. for (auto* i : subItems)
  1451. {
  1452. if (index == 0)
  1453. return i;
  1454. auto numRows = i->getNumRows();
  1455. if (numRows > index)
  1456. return i->getItemOnRow (index);
  1457. index -= numRows;
  1458. }
  1459. }
  1460. return nullptr;
  1461. }
  1462. int TreeViewItem::countSelectedItemsRecursively (int depth) const noexcept
  1463. {
  1464. int total = isSelected() ? 1 : 0;
  1465. if (depth != 0)
  1466. for (auto* i : subItems)
  1467. total += i->countSelectedItemsRecursively (depth - 1);
  1468. return total;
  1469. }
  1470. TreeViewItem* TreeViewItem::getSelectedItemWithIndex (int index) noexcept
  1471. {
  1472. if (isSelected())
  1473. {
  1474. if (index == 0)
  1475. return this;
  1476. --index;
  1477. }
  1478. if (index >= 0)
  1479. {
  1480. for (auto* i : subItems)
  1481. {
  1482. if (auto* found = i->getSelectedItemWithIndex (index))
  1483. return found;
  1484. index -= i->countSelectedItemsRecursively (-1);
  1485. }
  1486. }
  1487. return nullptr;
  1488. }
  1489. int TreeViewItem::getRowNumberInTree() const noexcept
  1490. {
  1491. if (parentItem != nullptr && ownerView != nullptr)
  1492. {
  1493. if (! parentItem->isOpen())
  1494. return parentItem->getRowNumberInTree();
  1495. auto n = 1 + parentItem->getRowNumberInTree();
  1496. auto ourIndex = parentItem->subItems.indexOf (this);
  1497. jassert (ourIndex >= 0);
  1498. while (--ourIndex >= 0)
  1499. n += parentItem->subItems [ourIndex]->getNumRows();
  1500. if (parentItem->parentItem == nullptr
  1501. && ! ownerView->rootItemVisible)
  1502. --n;
  1503. return n;
  1504. }
  1505. return 0;
  1506. }
  1507. void TreeViewItem::setLinesDrawnForSubItems (bool drawLines) noexcept
  1508. {
  1509. drawLinesInside = drawLines;
  1510. drawLinesSet = true;
  1511. }
  1512. static String escapeSlashesInTreeViewItemName (const String& s)
  1513. {
  1514. return s.replaceCharacter ('/', '\\');
  1515. }
  1516. String TreeViewItem::getItemIdentifierString() const
  1517. {
  1518. String s;
  1519. if (parentItem != nullptr)
  1520. s = parentItem->getItemIdentifierString();
  1521. return s + "/" + escapeSlashesInTreeViewItemName (getUniqueName());
  1522. }
  1523. TreeViewItem* TreeViewItem::findItemFromIdentifierString (const String& identifierString)
  1524. {
  1525. auto thisId = "/" + escapeSlashesInTreeViewItemName (getUniqueName());
  1526. if (thisId == identifierString)
  1527. return this;
  1528. if (identifierString.startsWith (thisId + "/"))
  1529. {
  1530. auto remainingPath = identifierString.substring (thisId.length());
  1531. const auto wasOpen = isOpen();
  1532. setOpen (true);
  1533. for (auto* i : subItems)
  1534. if (auto* item = i->findItemFromIdentifierString (remainingPath))
  1535. return item;
  1536. setOpen (wasOpen);
  1537. }
  1538. return nullptr;
  1539. }
  1540. void TreeViewItem::restoreOpennessState (const XmlElement& e)
  1541. {
  1542. if (e.hasTagName ("CLOSED"))
  1543. {
  1544. setOpen (false);
  1545. }
  1546. else if (e.hasTagName ("OPEN"))
  1547. {
  1548. setOpen (true);
  1549. Array<TreeViewItem*> items;
  1550. items.addArray (subItems);
  1551. for (auto* n : e.getChildIterator())
  1552. {
  1553. auto id = n->getStringAttribute ("id");
  1554. for (int i = 0; i < items.size(); ++i)
  1555. {
  1556. auto* ti = items.getUnchecked (i);
  1557. if (ti->getUniqueName() == id)
  1558. {
  1559. ti->restoreOpennessState (*n);
  1560. items.remove (i);
  1561. break;
  1562. }
  1563. }
  1564. }
  1565. // for any items that weren't mentioned in the XML, reset them to default:
  1566. for (auto* i : items)
  1567. i->restoreToDefaultOpenness();
  1568. }
  1569. }
  1570. std::unique_ptr<XmlElement> TreeViewItem::getOpennessState() const
  1571. {
  1572. return getOpennessState (true);
  1573. }
  1574. std::unique_ptr<XmlElement> TreeViewItem::getOpennessState (bool canReturnNull) const
  1575. {
  1576. auto name = getUniqueName();
  1577. if (name.isNotEmpty())
  1578. {
  1579. std::unique_ptr<XmlElement> e;
  1580. if (isOpen())
  1581. {
  1582. if (canReturnNull && ownerView != nullptr && ownerView->defaultOpenness && isFullyOpen())
  1583. return nullptr;
  1584. e = std::make_unique<XmlElement> ("OPEN");
  1585. for (int i = subItems.size(); --i >= 0;)
  1586. e->prependChildElement (subItems.getUnchecked (i)->getOpennessState (true).release());
  1587. }
  1588. else
  1589. {
  1590. if (canReturnNull && ownerView != nullptr && ! ownerView->defaultOpenness)
  1591. return nullptr;
  1592. e = std::make_unique<XmlElement> ("CLOSED");
  1593. }
  1594. e->setAttribute ("id", name);
  1595. return e;
  1596. }
  1597. // trying to save the openness for an element that has no name - this won't
  1598. // work because it needs the names to identify what to open.
  1599. jassertfalse;
  1600. return {};
  1601. }
  1602. //==============================================================================
  1603. TreeViewItem::OpennessRestorer::OpennessRestorer (TreeViewItem& item)
  1604. : treeViewItem (item),
  1605. oldOpenness (item.getOpennessState())
  1606. {
  1607. }
  1608. TreeViewItem::OpennessRestorer::~OpennessRestorer()
  1609. {
  1610. if (oldOpenness != nullptr)
  1611. treeViewItem.restoreOpennessState (*oldOpenness);
  1612. }
  1613. void TreeViewItem::draw (Graphics& g, int width, bool isMouseOverButton)
  1614. {
  1615. const auto indent = getIndentX();
  1616. const auto itemW = (itemWidth < 0 || drawsInRightMargin) ? width - indent : itemWidth;
  1617. {
  1618. Graphics::ScopedSaveState ss (g);
  1619. g.setOrigin (indent, 0);
  1620. if (g.reduceClipRegion (drawsInLeftMargin ? -indent : 0, 0,
  1621. drawsInLeftMargin ? itemW + indent : itemW, itemHeight))
  1622. {
  1623. if (isSelected())
  1624. g.fillAll (ownerView->findColour (TreeView::selectedItemBackgroundColourId));
  1625. else
  1626. g.fillAll ((getRowNumberInTree() % 2 == 0) ? ownerView->findColour (TreeView::oddItemsColourId)
  1627. : ownerView->findColour (TreeView::evenItemsColourId));
  1628. paintItem (g, itemWidth < 0 ? width - indent : itemWidth, itemHeight);
  1629. }
  1630. }
  1631. const auto halfH = (float) itemHeight * 0.5f;
  1632. const auto indentWidth = ownerView->getIndentSize();
  1633. const auto depth = getItemDepth (this);
  1634. if (depth >= 0 && ownerView->openCloseButtonsVisible)
  1635. {
  1636. auto x = ((float) depth + 0.5f) * (float) indentWidth;
  1637. const auto parentLinesDrawn = parentItem != nullptr && parentItem->areLinesDrawn();
  1638. if (parentLinesDrawn)
  1639. paintVerticalConnectingLine (g, Line<float> (x, 0, x, isLastOfSiblings() ? halfH : (float) itemHeight));
  1640. if (parentLinesDrawn || (parentItem == nullptr && areLinesDrawn()))
  1641. paintHorizontalConnectingLine (g, Line<float> (x, halfH, x + (float) indentWidth * 0.5f, halfH));
  1642. {
  1643. auto* p = parentItem;
  1644. auto d = depth;
  1645. while (p != nullptr && --d >= 0)
  1646. {
  1647. x -= (float) indentWidth;
  1648. if ((p->parentItem == nullptr || p->parentItem->areLinesDrawn()) && ! p->isLastOfSiblings())
  1649. p->paintVerticalConnectingLine (g, Line<float> (x, 0, x, (float) itemHeight));
  1650. p = p->parentItem;
  1651. }
  1652. }
  1653. if (mightContainSubItems())
  1654. {
  1655. auto backgroundColour = ownerView->findColour (TreeView::backgroundColourId);
  1656. paintOpenCloseButton (g, Rectangle<float> ((float) (depth * indentWidth), 0, (float) indentWidth, (float) itemHeight),
  1657. backgroundColour.isTransparent() ? Colours::white : backgroundColour,
  1658. isMouseOverButton);
  1659. }
  1660. }
  1661. }
  1662. } // namespace juce