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.

2076 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. if (lastSelected == nullptr)
  411. {
  412. jassertfalse;
  413. return;
  414. }
  415. auto rowStart = firstSelected->getRowNumberInTree();
  416. auto rowEnd = lastSelected->getRowNumberInTree();
  417. if (rowStart > rowEnd)
  418. std::swap (rowStart, rowEnd);
  419. auto ourRow = item.getRowNumberInTree();
  420. auto otherEnd = ourRow < rowEnd ? rowStart : rowEnd;
  421. if (ourRow > otherEnd)
  422. std::swap (ourRow, otherEnd);
  423. for (int i = ourRow; i <= otherEnd; ++i)
  424. owner.getItemOnRow (i)->setSelected (true, false);
  425. }
  426. else
  427. {
  428. const auto cmd = modifiers.isCommandDown();
  429. item.setSelected ((! cmd) || ! item.isSelected(), ! cmd);
  430. }
  431. }
  432. static TreeViewItem* getNextVisibleItem (TreeViewItem* item, bool forwards)
  433. {
  434. if (item == nullptr || item->ownerView == nullptr)
  435. return nullptr;
  436. auto* nextItem = item->ownerView->getItemOnRow (item->getRowNumberInTree() + (forwards ? 1 : -1));
  437. return nextItem == item->ownerView->rootItem && ! item->ownerView->rootItemVisible ? nullptr
  438. : nextItem;
  439. }
  440. std::vector<TreeViewItem*> getAllVisibleItems() const
  441. {
  442. if (owner.rootItem == nullptr)
  443. return {};
  444. const auto visibleTop = -getY();
  445. const auto visibleBottom = visibleTop + getParentHeight();
  446. std::vector<TreeViewItem*> visibleItems;
  447. auto* item = [&]
  448. {
  449. auto* i = owner.rootItemVisible ? owner.rootItem
  450. : owner.rootItem->subItems.getFirst();
  451. while (i != nullptr && i->y < visibleTop)
  452. i = getNextVisibleItem (i, true);
  453. return i;
  454. }();
  455. auto addOffscreenItemBuffer = [&visibleItems] (TreeViewItem* i, int num, bool forwards)
  456. {
  457. while (--num >= 0)
  458. {
  459. i = getNextVisibleItem (i, forwards);
  460. if (i == nullptr)
  461. return;
  462. visibleItems.push_back (i);
  463. }
  464. };
  465. addOffscreenItemBuffer (item, 2, false);
  466. while (item != nullptr && item->y < visibleBottom)
  467. {
  468. visibleItems.push_back (item);
  469. item = getNextVisibleItem (item, true);
  470. }
  471. if (item != nullptr)
  472. visibleItems.push_back (item);
  473. addOffscreenItemBuffer (item, 2, true);
  474. return visibleItems;
  475. }
  476. //==============================================================================
  477. TreeView& owner;
  478. std::vector<std::unique_ptr<ItemComponent>> itemComponents;
  479. ItemComponent* itemUnderMouse = nullptr;
  480. bool isDragging = false, needSelectionOnMouseUp = false;
  481. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ContentComponent)
  482. };
  483. //==============================================================================
  484. class TreeView::TreeViewport : public Viewport
  485. {
  486. public:
  487. TreeViewport() = default;
  488. void updateComponents (bool triggerResize)
  489. {
  490. if (auto* tvc = getContentComp())
  491. {
  492. if (triggerResize)
  493. tvc->resized();
  494. else
  495. tvc->updateComponents();
  496. }
  497. repaint();
  498. }
  499. void visibleAreaChanged (const Rectangle<int>& newVisibleArea) override
  500. {
  501. const auto hasScrolledSideways = (newVisibleArea.getX() != lastX);
  502. lastX = newVisibleArea.getX();
  503. updateComponents (hasScrolledSideways);
  504. if (auto* tree = getParentComponent())
  505. if (auto* handler = tree->getAccessibilityHandler())
  506. handler->notifyAccessibilityEvent (AccessibilityEvent::structureChanged);
  507. }
  508. ContentComponent* getContentComp() const noexcept
  509. {
  510. return static_cast<ContentComponent*> (getViewedComponent());
  511. }
  512. bool keyPressed (const KeyPress& key) override
  513. {
  514. if (auto* tree = getParentComponent())
  515. if (tree->keyPressed (key))
  516. return true;
  517. return Viewport::keyPressed (key);
  518. }
  519. private:
  520. int lastX = -1;
  521. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (TreeViewport)
  522. };
  523. //==============================================================================
  524. TreeView::TreeView (const String& name) : Component (name)
  525. {
  526. viewport = std::make_unique<TreeViewport>();
  527. viewport->setAccessible (false);
  528. addAndMakeVisible (viewport.get());
  529. viewport->setViewedComponent (new ContentComponent (*this));
  530. setWantsKeyboardFocus (true);
  531. setFocusContainerType (FocusContainerType::focusContainer);
  532. }
  533. TreeView::~TreeView()
  534. {
  535. if (rootItem != nullptr)
  536. rootItem->setOwnerView (nullptr);
  537. }
  538. void TreeView::setRootItem (TreeViewItem* const newRootItem)
  539. {
  540. if (rootItem != newRootItem)
  541. {
  542. if (newRootItem != nullptr)
  543. {
  544. // can't use a tree item in more than one tree at once..
  545. jassert (newRootItem->ownerView == nullptr);
  546. if (newRootItem->ownerView != nullptr)
  547. newRootItem->ownerView->setRootItem (nullptr);
  548. }
  549. if (rootItem != nullptr)
  550. rootItem->setOwnerView (nullptr);
  551. rootItem = newRootItem;
  552. if (newRootItem != nullptr)
  553. newRootItem->setOwnerView (this);
  554. if (rootItem != nullptr && (defaultOpenness || ! rootItemVisible))
  555. {
  556. rootItem->setOpen (false); // force a re-open
  557. rootItem->setOpen (true);
  558. }
  559. updateVisibleItems();
  560. }
  561. }
  562. void TreeView::deleteRootItem()
  563. {
  564. const std::unique_ptr<TreeViewItem> deleter (rootItem);
  565. setRootItem (nullptr);
  566. }
  567. void TreeView::setRootItemVisible (const bool shouldBeVisible)
  568. {
  569. rootItemVisible = shouldBeVisible;
  570. if (rootItem != nullptr && (defaultOpenness || ! rootItemVisible))
  571. {
  572. rootItem->setOpen (false); // force a re-open
  573. rootItem->setOpen (true);
  574. }
  575. updateVisibleItems();
  576. }
  577. void TreeView::colourChanged()
  578. {
  579. setOpaque (findColour (backgroundColourId).isOpaque());
  580. repaint();
  581. }
  582. void TreeView::setIndentSize (const int newIndentSize)
  583. {
  584. if (indentSize != newIndentSize)
  585. {
  586. indentSize = newIndentSize;
  587. resized();
  588. }
  589. }
  590. int TreeView::getIndentSize() noexcept
  591. {
  592. return indentSize >= 0 ? indentSize
  593. : getLookAndFeel().getTreeViewIndentSize (*this);
  594. }
  595. void TreeView::setDefaultOpenness (const bool isOpenByDefault)
  596. {
  597. if (defaultOpenness != isOpenByDefault)
  598. {
  599. defaultOpenness = isOpenByDefault;
  600. updateVisibleItems();
  601. }
  602. }
  603. void TreeView::setMultiSelectEnabled (const bool canMultiSelect)
  604. {
  605. multiSelectEnabled = canMultiSelect;
  606. }
  607. void TreeView::setOpenCloseButtonsVisible (const bool shouldBeVisible)
  608. {
  609. if (openCloseButtonsVisible != shouldBeVisible)
  610. {
  611. openCloseButtonsVisible = shouldBeVisible;
  612. updateVisibleItems();
  613. }
  614. }
  615. Viewport* TreeView::getViewport() const noexcept
  616. {
  617. return viewport.get();
  618. }
  619. //==============================================================================
  620. void TreeView::clearSelectedItems()
  621. {
  622. if (rootItem != nullptr)
  623. rootItem->deselectAllRecursively (nullptr);
  624. }
  625. int TreeView::getNumSelectedItems (int maximumDepthToSearchTo) const noexcept
  626. {
  627. return rootItem != nullptr ? rootItem->countSelectedItemsRecursively (maximumDepthToSearchTo) : 0;
  628. }
  629. TreeViewItem* TreeView::getSelectedItem (const int index) const noexcept
  630. {
  631. return rootItem != nullptr ? rootItem->getSelectedItemWithIndex (index) : nullptr;
  632. }
  633. int TreeView::getNumRowsInTree() const
  634. {
  635. return rootItem != nullptr ? (rootItem->getNumRows() - (rootItemVisible ? 0 : 1)) : 0;
  636. }
  637. TreeViewItem* TreeView::getItemOnRow (int index) const
  638. {
  639. if (! rootItemVisible)
  640. ++index;
  641. if (rootItem != nullptr && index >= 0)
  642. return rootItem->getItemOnRow (index);
  643. return nullptr;
  644. }
  645. TreeViewItem* TreeView::getItemAt (int y) const noexcept
  646. {
  647. if (auto* contentComp = viewport->getContentComp())
  648. if (auto* itemComponent = contentComp->getItemComponentAt (contentComp->getLocalPoint (this, Point<int> (0, y))))
  649. return &itemComponent->getRepresentedItem();
  650. return nullptr;
  651. }
  652. TreeViewItem* TreeView::findItemFromIdentifierString (const String& identifierString) const
  653. {
  654. if (rootItem == nullptr)
  655. return nullptr;
  656. return rootItem->findItemFromIdentifierString (identifierString);
  657. }
  658. Component* TreeView::getItemComponent (const TreeViewItem* item) const
  659. {
  660. return viewport->getContentComp()->getComponentForItem (item);
  661. }
  662. //==============================================================================
  663. static void addAllSelectedItemIds (TreeViewItem* item, XmlElement& parent)
  664. {
  665. if (item->isSelected())
  666. parent.createNewChildElement ("SELECTED")->setAttribute ("id", item->getItemIdentifierString());
  667. auto numSubItems = item->getNumSubItems();
  668. for (int i = 0; i < numSubItems; ++i)
  669. addAllSelectedItemIds (item->getSubItem (i), parent);
  670. }
  671. std::unique_ptr<XmlElement> TreeView::getOpennessState (bool alsoIncludeScrollPosition) const
  672. {
  673. if (rootItem != nullptr)
  674. {
  675. if (auto rootOpenness = rootItem->getOpennessState (false))
  676. {
  677. if (alsoIncludeScrollPosition)
  678. rootOpenness->setAttribute ("scrollPos", viewport->getViewPositionY());
  679. addAllSelectedItemIds (rootItem, *rootOpenness);
  680. return rootOpenness;
  681. }
  682. }
  683. return {};
  684. }
  685. void TreeView::restoreOpennessState (const XmlElement& newState, bool restoreStoredSelection)
  686. {
  687. if (rootItem != nullptr)
  688. {
  689. rootItem->restoreOpennessState (newState);
  690. if (newState.hasAttribute ("scrollPos"))
  691. viewport->setViewPosition (viewport->getViewPositionX(),
  692. newState.getIntAttribute ("scrollPos"));
  693. if (restoreStoredSelection)
  694. {
  695. clearSelectedItems();
  696. for (auto* e : newState.getChildWithTagNameIterator ("SELECTED"))
  697. if (auto* item = rootItem->findItemFromIdentifierString (e->getStringAttribute ("id")))
  698. item->setSelected (true, false);
  699. }
  700. updateVisibleItems();
  701. }
  702. }
  703. //==============================================================================
  704. void TreeView::paint (Graphics& g)
  705. {
  706. g.fillAll (findColour (backgroundColourId));
  707. }
  708. void TreeView::resized()
  709. {
  710. viewport->setBounds (getLocalBounds());
  711. updateVisibleItems();
  712. }
  713. void TreeView::enablementChanged()
  714. {
  715. repaint();
  716. }
  717. void TreeView::moveSelectedRow (int delta)
  718. {
  719. auto numRowsInTree = getNumRowsInTree();
  720. if (numRowsInTree > 0)
  721. {
  722. int rowSelected = 0;
  723. if (auto* firstSelected = getSelectedItem (0))
  724. rowSelected = firstSelected->getRowNumberInTree();
  725. rowSelected = jlimit (0, numRowsInTree - 1, rowSelected + delta);
  726. for (;;)
  727. {
  728. if (auto* item = getItemOnRow (rowSelected))
  729. {
  730. if (! item->canBeSelected())
  731. {
  732. // if the row we want to highlight doesn't allow it, try skipping
  733. // to the next item..
  734. auto nextRowToTry = jlimit (0, numRowsInTree - 1, rowSelected + (delta < 0 ? -1 : 1));
  735. if (rowSelected != nextRowToTry)
  736. {
  737. rowSelected = nextRowToTry;
  738. continue;
  739. }
  740. break;
  741. }
  742. item->setSelected (true, true);
  743. scrollToKeepItemVisible (item);
  744. }
  745. break;
  746. }
  747. }
  748. }
  749. void TreeView::scrollToKeepItemVisible (TreeViewItem* item)
  750. {
  751. if (item != nullptr && item->ownerView == this)
  752. {
  753. updateVisibleItems();
  754. item = item->getDeepestOpenParentItem();
  755. auto y = item->y;
  756. auto viewTop = viewport->getViewPositionY();
  757. if (y < viewTop)
  758. {
  759. viewport->setViewPosition (viewport->getViewPositionX(), y);
  760. }
  761. else if (y + item->itemHeight > viewTop + viewport->getViewHeight())
  762. {
  763. viewport->setViewPosition (viewport->getViewPositionX(),
  764. (y + item->itemHeight) - viewport->getViewHeight());
  765. }
  766. }
  767. }
  768. bool TreeView::toggleOpenSelectedItem()
  769. {
  770. if (auto* firstSelected = getSelectedItem (0))
  771. {
  772. if (firstSelected->mightContainSubItems())
  773. {
  774. firstSelected->setOpen (! firstSelected->isOpen());
  775. return true;
  776. }
  777. }
  778. return false;
  779. }
  780. void TreeView::moveOutOfSelectedItem()
  781. {
  782. if (auto* firstSelected = getSelectedItem (0))
  783. {
  784. if (firstSelected->isOpen())
  785. {
  786. firstSelected->setOpen (false);
  787. }
  788. else
  789. {
  790. auto* parent = firstSelected->parentItem;
  791. if ((! rootItemVisible) && parent == rootItem)
  792. parent = nullptr;
  793. if (parent != nullptr)
  794. {
  795. parent->setSelected (true, true);
  796. scrollToKeepItemVisible (parent);
  797. }
  798. }
  799. }
  800. }
  801. void TreeView::moveIntoSelectedItem()
  802. {
  803. if (auto* firstSelected = getSelectedItem (0))
  804. {
  805. if (firstSelected->isOpen() || ! firstSelected->mightContainSubItems())
  806. moveSelectedRow (1);
  807. else
  808. firstSelected->setOpen (true);
  809. }
  810. }
  811. void TreeView::moveByPages (int numPages)
  812. {
  813. if (auto* currentItem = getSelectedItem (0))
  814. {
  815. auto pos = currentItem->getItemPosition (false);
  816. auto targetY = pos.getY() + numPages * (getHeight() - pos.getHeight());
  817. auto currentRow = currentItem->getRowNumberInTree();
  818. for (;;)
  819. {
  820. moveSelectedRow (numPages);
  821. currentItem = getSelectedItem (0);
  822. if (currentItem == nullptr)
  823. break;
  824. auto y = currentItem->getItemPosition (false).getY();
  825. if ((numPages < 0 && y <= targetY) || (numPages > 0 && y >= targetY))
  826. break;
  827. auto newRow = currentItem->getRowNumberInTree();
  828. if (newRow == currentRow)
  829. break;
  830. currentRow = newRow;
  831. }
  832. }
  833. }
  834. bool TreeView::keyPressed (const KeyPress& key)
  835. {
  836. if (rootItem != nullptr)
  837. {
  838. if (key == KeyPress::upKey) { moveSelectedRow (-1); return true; }
  839. if (key == KeyPress::downKey) { moveSelectedRow (1); return true; }
  840. if (key == KeyPress::homeKey) { moveSelectedRow (-0x3fffffff); return true; }
  841. if (key == KeyPress::endKey) { moveSelectedRow (0x3fffffff); return true; }
  842. if (key == KeyPress::pageUpKey) { moveByPages (-1); return true; }
  843. if (key == KeyPress::pageDownKey) { moveByPages (1); return true; }
  844. if (key == KeyPress::returnKey) { return toggleOpenSelectedItem(); }
  845. if (key == KeyPress::leftKey) { moveOutOfSelectedItem(); return true; }
  846. if (key == KeyPress::rightKey) { moveIntoSelectedItem(); return true; }
  847. }
  848. return false;
  849. }
  850. void TreeView::updateVisibleItems()
  851. {
  852. if (rootItem != nullptr)
  853. {
  854. rootItem->updatePositions (rootItemVisible ? 0 : -rootItem->itemHeight);
  855. viewport->getViewedComponent()
  856. ->setSize (jmax (viewport->getMaximumVisibleWidth(), rootItem->totalWidth + 50),
  857. rootItem->totalHeight - (rootItemVisible ? 0 : rootItem->itemHeight));
  858. }
  859. else
  860. {
  861. viewport->getViewedComponent()->setSize (0, 0);
  862. }
  863. viewport->updateComponents (false);
  864. }
  865. //==============================================================================
  866. struct TreeView::InsertPoint
  867. {
  868. InsertPoint (TreeView& view, const StringArray& files,
  869. const DragAndDropTarget::SourceDetails& dragSourceDetails)
  870. : pos (dragSourceDetails.localPosition),
  871. item (view.getItemAt (dragSourceDetails.localPosition.y))
  872. {
  873. if (item != nullptr)
  874. {
  875. auto itemPos = item->getItemPosition (true);
  876. insertIndex = item->getIndexInParent();
  877. auto oldY = pos.y;
  878. pos.y = itemPos.getY();
  879. if (item->getNumSubItems() == 0 || ! item->isOpen())
  880. {
  881. if (files.size() > 0 ? item->isInterestedInFileDrag (files)
  882. : item->isInterestedInDragSource (dragSourceDetails))
  883. {
  884. // Check if we're trying to drag into an empty group item..
  885. if (oldY > itemPos.getY() + itemPos.getHeight() / 4
  886. && oldY < itemPos.getBottom() - itemPos.getHeight() / 4)
  887. {
  888. insertIndex = 0;
  889. pos.x = itemPos.getX() + view.getIndentSize();
  890. pos.y = itemPos.getBottom();
  891. return;
  892. }
  893. }
  894. }
  895. if (oldY > itemPos.getCentreY())
  896. {
  897. pos.y += item->getItemHeight();
  898. while (item->isLastOfSiblings() && item->getParentItem() != nullptr
  899. && item->getParentItem()->getParentItem() != nullptr)
  900. {
  901. if (pos.x > itemPos.getX())
  902. break;
  903. item = item->getParentItem();
  904. itemPos = item->getItemPosition (true);
  905. insertIndex = item->getIndexInParent();
  906. }
  907. ++insertIndex;
  908. }
  909. pos.x = itemPos.getX();
  910. item = item->getParentItem();
  911. }
  912. else if (auto* root = view.getRootItem())
  913. {
  914. // If they're dragging beyond the bottom of the list, then insert at the end of the root item..
  915. item = root;
  916. insertIndex = root->getNumSubItems();
  917. pos = root->getItemPosition (true).getBottomLeft();
  918. pos.x += view.getIndentSize();
  919. }
  920. }
  921. Point<int> pos;
  922. TreeViewItem* item;
  923. int insertIndex = 0;
  924. };
  925. //==============================================================================
  926. class TreeView::InsertPointHighlight : public Component
  927. {
  928. public:
  929. InsertPointHighlight()
  930. {
  931. setSize (100, 12);
  932. setAlwaysOnTop (true);
  933. setInterceptsMouseClicks (false, false);
  934. }
  935. void setTargetPosition (const InsertPoint& insertPos, const int width) noexcept
  936. {
  937. lastItem = insertPos.item;
  938. lastIndex = insertPos.insertIndex;
  939. auto offset = getHeight() / 2;
  940. setBounds (insertPos.pos.x - offset, insertPos.pos.y - offset,
  941. width - (insertPos.pos.x - offset), getHeight());
  942. }
  943. void paint (Graphics& g) override
  944. {
  945. Path p;
  946. auto h = (float) getHeight();
  947. p.addEllipse (2.0f, 2.0f, h - 4.0f, h - 4.0f);
  948. p.startNewSubPath (h - 2.0f, h / 2.0f);
  949. p.lineTo ((float) getWidth(), h / 2.0f);
  950. g.setColour (findColour (TreeView::dragAndDropIndicatorColourId, true));
  951. g.strokePath (p, PathStrokeType (2.0f));
  952. }
  953. TreeViewItem* lastItem = nullptr;
  954. int lastIndex = 0;
  955. private:
  956. JUCE_DECLARE_NON_COPYABLE (InsertPointHighlight)
  957. };
  958. //==============================================================================
  959. class TreeView::TargetGroupHighlight : public Component
  960. {
  961. public:
  962. TargetGroupHighlight()
  963. {
  964. setAlwaysOnTop (true);
  965. setInterceptsMouseClicks (false, false);
  966. }
  967. void setTargetPosition (TreeViewItem* const item) noexcept
  968. {
  969. setBounds (item->getItemPosition (true)
  970. .withHeight (item->getItemHeight()));
  971. }
  972. void paint (Graphics& g) override
  973. {
  974. g.setColour (findColour (TreeView::dragAndDropIndicatorColourId, true));
  975. g.drawRoundedRectangle (1.0f, 1.0f, (float) getWidth() - 2.0f, (float) getHeight() - 2.0f, 3.0f, 2.0f);
  976. }
  977. private:
  978. JUCE_DECLARE_NON_COPYABLE (TargetGroupHighlight)
  979. };
  980. //==============================================================================
  981. void TreeView::showDragHighlight (const InsertPoint& insertPos) noexcept
  982. {
  983. beginDragAutoRepeat (100);
  984. if (dragInsertPointHighlight == nullptr)
  985. {
  986. dragInsertPointHighlight = std::make_unique<InsertPointHighlight>();
  987. dragTargetGroupHighlight = std::make_unique<TargetGroupHighlight>();
  988. addAndMakeVisible (dragInsertPointHighlight.get());
  989. addAndMakeVisible (dragTargetGroupHighlight.get());
  990. }
  991. dragInsertPointHighlight->setTargetPosition (insertPos, viewport->getViewWidth());
  992. dragTargetGroupHighlight->setTargetPosition (insertPos.item);
  993. }
  994. void TreeView::hideDragHighlight() noexcept
  995. {
  996. dragInsertPointHighlight = nullptr;
  997. dragTargetGroupHighlight = nullptr;
  998. }
  999. void TreeView::handleDrag (const StringArray& files, const SourceDetails& dragSourceDetails)
  1000. {
  1001. const auto scrolled = viewport->autoScroll (dragSourceDetails.localPosition.x,
  1002. dragSourceDetails.localPosition.y, 20, 10);
  1003. InsertPoint insertPos (*this, files, dragSourceDetails);
  1004. if (insertPos.item != nullptr)
  1005. {
  1006. if (scrolled || dragInsertPointHighlight == nullptr
  1007. || dragInsertPointHighlight->lastItem != insertPos.item
  1008. || dragInsertPointHighlight->lastIndex != insertPos.insertIndex)
  1009. {
  1010. if (files.size() > 0 ? insertPos.item->isInterestedInFileDrag (files)
  1011. : insertPos.item->isInterestedInDragSource (dragSourceDetails))
  1012. showDragHighlight (insertPos);
  1013. else
  1014. hideDragHighlight();
  1015. }
  1016. }
  1017. else
  1018. {
  1019. hideDragHighlight();
  1020. }
  1021. }
  1022. void TreeView::handleDrop (const StringArray& files, const SourceDetails& dragSourceDetails)
  1023. {
  1024. hideDragHighlight();
  1025. InsertPoint insertPos (*this, files, dragSourceDetails);
  1026. if (insertPos.item == nullptr)
  1027. insertPos.item = rootItem;
  1028. if (insertPos.item != nullptr)
  1029. {
  1030. if (files.size() > 0)
  1031. {
  1032. if (insertPos.item->isInterestedInFileDrag (files))
  1033. insertPos.item->filesDropped (files, insertPos.insertIndex);
  1034. }
  1035. else
  1036. {
  1037. if (insertPos.item->isInterestedInDragSource (dragSourceDetails))
  1038. insertPos.item->itemDropped (dragSourceDetails, insertPos.insertIndex);
  1039. }
  1040. }
  1041. }
  1042. //==============================================================================
  1043. bool TreeView::isInterestedInFileDrag (const StringArray&)
  1044. {
  1045. return true;
  1046. }
  1047. void TreeView::fileDragEnter (const StringArray& files, int x, int y)
  1048. {
  1049. fileDragMove (files, x, y);
  1050. }
  1051. void TreeView::fileDragMove (const StringArray& files, int x, int y)
  1052. {
  1053. handleDrag (files, SourceDetails (var(), this, { x, y }));
  1054. }
  1055. void TreeView::fileDragExit (const StringArray&)
  1056. {
  1057. hideDragHighlight();
  1058. }
  1059. void TreeView::filesDropped (const StringArray& files, int x, int y)
  1060. {
  1061. handleDrop (files, SourceDetails (var(), this, { x, y }));
  1062. }
  1063. bool TreeView::isInterestedInDragSource (const SourceDetails& /*dragSourceDetails*/)
  1064. {
  1065. return true;
  1066. }
  1067. void TreeView::itemDragEnter (const SourceDetails& dragSourceDetails)
  1068. {
  1069. itemDragMove (dragSourceDetails);
  1070. }
  1071. void TreeView::itemDragMove (const SourceDetails& dragSourceDetails)
  1072. {
  1073. handleDrag (StringArray(), dragSourceDetails);
  1074. }
  1075. void TreeView::itemDragExit (const SourceDetails& /*dragSourceDetails*/)
  1076. {
  1077. hideDragHighlight();
  1078. }
  1079. void TreeView::itemDropped (const SourceDetails& dragSourceDetails)
  1080. {
  1081. handleDrop (StringArray(), dragSourceDetails);
  1082. }
  1083. //==============================================================================
  1084. std::unique_ptr<AccessibilityHandler> TreeView::createAccessibilityHandler()
  1085. {
  1086. class TableInterface : public AccessibilityTableInterface
  1087. {
  1088. public:
  1089. explicit TableInterface (TreeView& treeViewToWrap) : treeView (treeViewToWrap) {}
  1090. int getNumRows() const override { return treeView.getNumRowsInTree(); }
  1091. int getNumColumns() const override { return 1; }
  1092. const AccessibilityHandler* getCellHandler (int row, int) const override
  1093. {
  1094. if (auto* itemComp = treeView.getItemComponent (treeView.getItemOnRow (row)))
  1095. return itemComp->getAccessibilityHandler();
  1096. return nullptr;
  1097. }
  1098. private:
  1099. TreeView& treeView;
  1100. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (TableInterface)
  1101. };
  1102. return std::make_unique<AccessibilityHandler> (*this,
  1103. AccessibilityRole::tree,
  1104. AccessibilityActions{},
  1105. AccessibilityHandler::Interfaces { std::make_unique<TableInterface> (*this) });
  1106. }
  1107. //==============================================================================
  1108. TreeViewItem::TreeViewItem()
  1109. {
  1110. static int nextUID = 0;
  1111. uid = nextUID++;
  1112. }
  1113. String TreeViewItem::getUniqueName() const
  1114. {
  1115. return {};
  1116. }
  1117. void TreeViewItem::itemOpennessChanged (bool)
  1118. {
  1119. }
  1120. int TreeViewItem::getNumSubItems() const noexcept
  1121. {
  1122. return subItems.size();
  1123. }
  1124. TreeViewItem* TreeViewItem::getSubItem (const int index) const noexcept
  1125. {
  1126. return subItems[index];
  1127. }
  1128. void TreeViewItem::clearSubItems()
  1129. {
  1130. if (ownerView != nullptr)
  1131. {
  1132. if (! subItems.isEmpty())
  1133. {
  1134. removeAllSubItemsFromList();
  1135. treeHasChanged();
  1136. }
  1137. }
  1138. else
  1139. {
  1140. removeAllSubItemsFromList();
  1141. }
  1142. }
  1143. void TreeViewItem::removeAllSubItemsFromList()
  1144. {
  1145. for (int i = subItems.size(); --i >= 0;)
  1146. removeSubItemFromList (i, true);
  1147. }
  1148. void TreeViewItem::addSubItem (TreeViewItem* const newItem, const int insertPosition)
  1149. {
  1150. if (newItem != nullptr)
  1151. {
  1152. newItem->parentItem = nullptr;
  1153. newItem->setOwnerView (ownerView);
  1154. newItem->y = 0;
  1155. newItem->itemHeight = newItem->getItemHeight();
  1156. newItem->totalHeight = 0;
  1157. newItem->itemWidth = newItem->getItemWidth();
  1158. newItem->totalWidth = 0;
  1159. newItem->parentItem = this;
  1160. if (ownerView != nullptr)
  1161. {
  1162. subItems.insert (insertPosition, newItem);
  1163. treeHasChanged();
  1164. if (newItem->isOpen())
  1165. newItem->itemOpennessChanged (true);
  1166. }
  1167. else
  1168. {
  1169. subItems.insert (insertPosition, newItem);
  1170. if (newItem->isOpen())
  1171. newItem->itemOpennessChanged (true);
  1172. }
  1173. }
  1174. }
  1175. void TreeViewItem::removeSubItem (int index, bool deleteItem)
  1176. {
  1177. if (ownerView != nullptr)
  1178. {
  1179. if (removeSubItemFromList (index, deleteItem))
  1180. treeHasChanged();
  1181. }
  1182. else
  1183. {
  1184. removeSubItemFromList (index, deleteItem);
  1185. }
  1186. }
  1187. bool TreeViewItem::removeSubItemFromList (int index, bool deleteItem)
  1188. {
  1189. if (auto* child = subItems[index])
  1190. {
  1191. child->parentItem = nullptr;
  1192. subItems.remove (index, deleteItem);
  1193. return true;
  1194. }
  1195. return false;
  1196. }
  1197. TreeViewItem::Openness TreeViewItem::getOpenness() const noexcept
  1198. {
  1199. return openness;
  1200. }
  1201. void TreeViewItem::setOpenness (Openness newOpenness)
  1202. {
  1203. auto wasOpen = isOpen();
  1204. openness = newOpenness;
  1205. auto isNowOpen = isOpen();
  1206. if (isNowOpen != wasOpen)
  1207. {
  1208. treeHasChanged();
  1209. itemOpennessChanged (isNowOpen);
  1210. }
  1211. }
  1212. bool TreeViewItem::isOpen() const noexcept
  1213. {
  1214. if (openness == Openness::opennessDefault)
  1215. return ownerView != nullptr && ownerView->defaultOpenness;
  1216. return openness == Openness::opennessOpen;
  1217. }
  1218. void TreeViewItem::setOpen (const bool shouldBeOpen)
  1219. {
  1220. if (isOpen() != shouldBeOpen)
  1221. setOpenness (shouldBeOpen ? Openness::opennessOpen
  1222. : Openness::opennessClosed);
  1223. }
  1224. bool TreeViewItem::isFullyOpen() const noexcept
  1225. {
  1226. if (! isOpen())
  1227. return false;
  1228. for (auto* i : subItems)
  1229. if (! i->isFullyOpen())
  1230. return false;
  1231. return true;
  1232. }
  1233. void TreeViewItem::restoreToDefaultOpenness()
  1234. {
  1235. setOpenness (Openness::opennessDefault);
  1236. }
  1237. bool TreeViewItem::isSelected() const noexcept
  1238. {
  1239. return selected;
  1240. }
  1241. void TreeViewItem::deselectAllRecursively (TreeViewItem* itemToIgnore)
  1242. {
  1243. if (this != itemToIgnore)
  1244. setSelected (false, false);
  1245. for (auto* i : subItems)
  1246. i->deselectAllRecursively (itemToIgnore);
  1247. }
  1248. void TreeViewItem::setSelected (const bool shouldBeSelected,
  1249. const bool deselectOtherItemsFirst,
  1250. const NotificationType notify)
  1251. {
  1252. if (shouldBeSelected && ! canBeSelected())
  1253. return;
  1254. if (deselectOtherItemsFirst)
  1255. getTopLevelItem()->deselectAllRecursively (this);
  1256. if (shouldBeSelected != selected)
  1257. {
  1258. selected = shouldBeSelected;
  1259. if (ownerView != nullptr)
  1260. {
  1261. ownerView->repaint();
  1262. if (selected)
  1263. {
  1264. if (auto* itemComponent = ownerView->getItemComponent (this))
  1265. if (auto* itemHandler = itemComponent->getAccessibilityHandler())
  1266. itemHandler->grabFocus();
  1267. }
  1268. if (auto* handler = ownerView->getAccessibilityHandler())
  1269. handler->notifyAccessibilityEvent (AccessibilityEvent::rowSelectionChanged);
  1270. }
  1271. if (notify != dontSendNotification)
  1272. itemSelectionChanged (shouldBeSelected);
  1273. }
  1274. }
  1275. void TreeViewItem::paintItem (Graphics&, int, int)
  1276. {
  1277. }
  1278. void TreeViewItem::paintOpenCloseButton (Graphics& g, const Rectangle<float>& area, Colour backgroundColour, bool isMouseOver)
  1279. {
  1280. getOwnerView()->getLookAndFeel()
  1281. .drawTreeviewPlusMinusBox (g, area, backgroundColour, isOpen(), isMouseOver);
  1282. }
  1283. void TreeViewItem::paintHorizontalConnectingLine (Graphics& g, const Line<float>& line)
  1284. {
  1285. g.setColour (ownerView->findColour (TreeView::linesColourId));
  1286. g.drawLine (line);
  1287. }
  1288. void TreeViewItem::paintVerticalConnectingLine (Graphics& g, const Line<float>& line)
  1289. {
  1290. g.setColour (ownerView->findColour (TreeView::linesColourId));
  1291. g.drawLine (line);
  1292. }
  1293. void TreeViewItem::itemClicked (const MouseEvent&)
  1294. {
  1295. }
  1296. void TreeViewItem::itemDoubleClicked (const MouseEvent&)
  1297. {
  1298. if (mightContainSubItems())
  1299. setOpen (! isOpen());
  1300. }
  1301. void TreeViewItem::itemSelectionChanged (bool)
  1302. {
  1303. }
  1304. String TreeViewItem::getTooltip()
  1305. {
  1306. return {};
  1307. }
  1308. String TreeViewItem::getAccessibilityName()
  1309. {
  1310. auto tooltipString = getTooltip();
  1311. return tooltipString.isNotEmpty()
  1312. ? tooltipString
  1313. : "Level " + String (getItemDepth (this)) + " row " + String (getIndexInParent());
  1314. }
  1315. void TreeViewItem::ownerViewChanged (TreeView*)
  1316. {
  1317. }
  1318. var TreeViewItem::getDragSourceDescription()
  1319. {
  1320. return {};
  1321. }
  1322. bool TreeViewItem::isInterestedInFileDrag (const StringArray&)
  1323. {
  1324. return false;
  1325. }
  1326. void TreeViewItem::filesDropped (const StringArray& /*files*/, int /*insertIndex*/)
  1327. {
  1328. }
  1329. bool TreeViewItem::isInterestedInDragSource (const DragAndDropTarget::SourceDetails& /*dragSourceDetails*/)
  1330. {
  1331. return false;
  1332. }
  1333. void TreeViewItem::itemDropped (const DragAndDropTarget::SourceDetails& /*dragSourceDetails*/, int /*insertIndex*/)
  1334. {
  1335. }
  1336. Rectangle<int> TreeViewItem::getItemPosition (const bool relativeToTreeViewTopLeft) const noexcept
  1337. {
  1338. auto indentX = getIndentX();
  1339. auto width = itemWidth;
  1340. if (ownerView != nullptr && width < 0)
  1341. width = ownerView->viewport->getViewWidth() - indentX;
  1342. Rectangle<int> r (indentX, y, jmax (0, width), totalHeight);
  1343. if (relativeToTreeViewTopLeft && ownerView != nullptr)
  1344. r -= ownerView->viewport->getViewPosition();
  1345. return r;
  1346. }
  1347. void TreeViewItem::treeHasChanged() const noexcept
  1348. {
  1349. if (ownerView != nullptr)
  1350. ownerView->updateVisibleItems();
  1351. }
  1352. void TreeViewItem::repaintItem() const
  1353. {
  1354. if (ownerView != nullptr && areAllParentsOpen())
  1355. if (auto* component = ownerView->getItemComponent (this))
  1356. component->repaint();
  1357. }
  1358. bool TreeViewItem::areAllParentsOpen() const noexcept
  1359. {
  1360. return parentItem == nullptr
  1361. || (parentItem->isOpen() && parentItem->areAllParentsOpen());
  1362. }
  1363. void TreeViewItem::updatePositions (int newY)
  1364. {
  1365. y = newY;
  1366. itemHeight = getItemHeight();
  1367. totalHeight = itemHeight;
  1368. itemWidth = getItemWidth();
  1369. totalWidth = jmax (itemWidth, 0) + getIndentX();
  1370. if (isOpen())
  1371. {
  1372. newY += totalHeight;
  1373. for (auto* i : subItems)
  1374. {
  1375. i->updatePositions (newY);
  1376. newY += i->totalHeight;
  1377. totalHeight += i->totalHeight;
  1378. totalWidth = jmax (totalWidth, i->totalWidth);
  1379. }
  1380. }
  1381. }
  1382. TreeViewItem* TreeViewItem::getDeepestOpenParentItem() noexcept
  1383. {
  1384. auto* result = this;
  1385. auto* item = this;
  1386. while (item->parentItem != nullptr)
  1387. {
  1388. item = item->parentItem;
  1389. if (! item->isOpen())
  1390. result = item;
  1391. }
  1392. return result;
  1393. }
  1394. void TreeViewItem::setOwnerView (TreeView* const newOwner) noexcept
  1395. {
  1396. ownerView = newOwner;
  1397. for (auto* i : subItems)
  1398. {
  1399. i->setOwnerView (newOwner);
  1400. i->ownerViewChanged (newOwner);
  1401. }
  1402. }
  1403. int TreeViewItem::getIndentX() const noexcept
  1404. {
  1405. int x = ownerView->rootItemVisible ? 1 : 0;
  1406. if (! ownerView->openCloseButtonsVisible)
  1407. --x;
  1408. for (auto* p = parentItem; p != nullptr; p = p->parentItem)
  1409. ++x;
  1410. return x * ownerView->getIndentSize();
  1411. }
  1412. void TreeViewItem::setDrawsInLeftMargin (bool canDrawInLeftMargin) noexcept
  1413. {
  1414. drawsInLeftMargin = canDrawInLeftMargin;
  1415. }
  1416. void TreeViewItem::setDrawsInRightMargin (bool canDrawInRightMargin) noexcept
  1417. {
  1418. drawsInRightMargin = canDrawInRightMargin;
  1419. }
  1420. bool TreeViewItem::areLinesDrawn() const
  1421. {
  1422. return drawLinesSet ? drawLinesInside
  1423. : (ownerView != nullptr && ownerView->getLookAndFeel().areLinesDrawnForTreeView (*ownerView));
  1424. }
  1425. bool TreeViewItem::isLastOfSiblings() const noexcept
  1426. {
  1427. return parentItem == nullptr
  1428. || parentItem->subItems.getLast() == this;
  1429. }
  1430. int TreeViewItem::getIndexInParent() const noexcept
  1431. {
  1432. return parentItem == nullptr ? 0
  1433. : parentItem->subItems.indexOf (this);
  1434. }
  1435. TreeViewItem* TreeViewItem::getTopLevelItem() noexcept
  1436. {
  1437. return parentItem == nullptr ? this
  1438. : parentItem->getTopLevelItem();
  1439. }
  1440. int TreeViewItem::getNumRows() const noexcept
  1441. {
  1442. int num = 1;
  1443. if (isOpen())
  1444. for (auto* i : subItems)
  1445. num += i->getNumRows();
  1446. return num;
  1447. }
  1448. TreeViewItem* TreeViewItem::getItemOnRow (int index) noexcept
  1449. {
  1450. if (index == 0)
  1451. return this;
  1452. if (index > 0 && isOpen())
  1453. {
  1454. --index;
  1455. for (auto* i : subItems)
  1456. {
  1457. if (index == 0)
  1458. return i;
  1459. auto numRows = i->getNumRows();
  1460. if (numRows > index)
  1461. return i->getItemOnRow (index);
  1462. index -= numRows;
  1463. }
  1464. }
  1465. return nullptr;
  1466. }
  1467. int TreeViewItem::countSelectedItemsRecursively (int depth) const noexcept
  1468. {
  1469. int total = isSelected() ? 1 : 0;
  1470. if (depth != 0)
  1471. for (auto* i : subItems)
  1472. total += i->countSelectedItemsRecursively (depth - 1);
  1473. return total;
  1474. }
  1475. TreeViewItem* TreeViewItem::getSelectedItemWithIndex (int index) noexcept
  1476. {
  1477. if (isSelected())
  1478. {
  1479. if (index == 0)
  1480. return this;
  1481. --index;
  1482. }
  1483. if (index >= 0)
  1484. {
  1485. for (auto* i : subItems)
  1486. {
  1487. if (auto* found = i->getSelectedItemWithIndex (index))
  1488. return found;
  1489. index -= i->countSelectedItemsRecursively (-1);
  1490. }
  1491. }
  1492. return nullptr;
  1493. }
  1494. int TreeViewItem::getRowNumberInTree() const noexcept
  1495. {
  1496. if (parentItem != nullptr && ownerView != nullptr)
  1497. {
  1498. if (! parentItem->isOpen())
  1499. return parentItem->getRowNumberInTree();
  1500. auto n = 1 + parentItem->getRowNumberInTree();
  1501. auto ourIndex = parentItem->subItems.indexOf (this);
  1502. jassert (ourIndex >= 0);
  1503. while (--ourIndex >= 0)
  1504. n += parentItem->subItems [ourIndex]->getNumRows();
  1505. if (parentItem->parentItem == nullptr
  1506. && ! ownerView->rootItemVisible)
  1507. --n;
  1508. return n;
  1509. }
  1510. return 0;
  1511. }
  1512. void TreeViewItem::setLinesDrawnForSubItems (bool drawLines) noexcept
  1513. {
  1514. drawLinesInside = drawLines;
  1515. drawLinesSet = true;
  1516. }
  1517. static String escapeSlashesInTreeViewItemName (const String& s)
  1518. {
  1519. return s.replaceCharacter ('/', '\\');
  1520. }
  1521. String TreeViewItem::getItemIdentifierString() const
  1522. {
  1523. String s;
  1524. if (parentItem != nullptr)
  1525. s = parentItem->getItemIdentifierString();
  1526. return s + "/" + escapeSlashesInTreeViewItemName (getUniqueName());
  1527. }
  1528. TreeViewItem* TreeViewItem::findItemFromIdentifierString (const String& identifierString)
  1529. {
  1530. auto thisId = "/" + escapeSlashesInTreeViewItemName (getUniqueName());
  1531. if (thisId == identifierString)
  1532. return this;
  1533. if (identifierString.startsWith (thisId + "/"))
  1534. {
  1535. auto remainingPath = identifierString.substring (thisId.length());
  1536. const auto wasOpen = isOpen();
  1537. setOpen (true);
  1538. for (auto* i : subItems)
  1539. if (auto* item = i->findItemFromIdentifierString (remainingPath))
  1540. return item;
  1541. setOpen (wasOpen);
  1542. }
  1543. return nullptr;
  1544. }
  1545. void TreeViewItem::restoreOpennessState (const XmlElement& e)
  1546. {
  1547. if (e.hasTagName ("CLOSED"))
  1548. {
  1549. setOpen (false);
  1550. }
  1551. else if (e.hasTagName ("OPEN"))
  1552. {
  1553. setOpen (true);
  1554. Array<TreeViewItem*> items;
  1555. items.addArray (subItems);
  1556. for (auto* n : e.getChildIterator())
  1557. {
  1558. auto id = n->getStringAttribute ("id");
  1559. for (int i = 0; i < items.size(); ++i)
  1560. {
  1561. auto* ti = items.getUnchecked (i);
  1562. if (ti->getUniqueName() == id)
  1563. {
  1564. ti->restoreOpennessState (*n);
  1565. items.remove (i);
  1566. break;
  1567. }
  1568. }
  1569. }
  1570. // for any items that weren't mentioned in the XML, reset them to default:
  1571. for (auto* i : items)
  1572. i->restoreToDefaultOpenness();
  1573. }
  1574. }
  1575. std::unique_ptr<XmlElement> TreeViewItem::getOpennessState() const
  1576. {
  1577. return getOpennessState (true);
  1578. }
  1579. std::unique_ptr<XmlElement> TreeViewItem::getOpennessState (bool canReturnNull) const
  1580. {
  1581. auto name = getUniqueName();
  1582. if (name.isNotEmpty())
  1583. {
  1584. std::unique_ptr<XmlElement> e;
  1585. if (isOpen())
  1586. {
  1587. if (canReturnNull && ownerView != nullptr && ownerView->defaultOpenness && isFullyOpen())
  1588. return nullptr;
  1589. e = std::make_unique<XmlElement> ("OPEN");
  1590. for (int i = subItems.size(); --i >= 0;)
  1591. e->prependChildElement (subItems.getUnchecked (i)->getOpennessState (true).release());
  1592. }
  1593. else
  1594. {
  1595. if (canReturnNull && ownerView != nullptr && ! ownerView->defaultOpenness)
  1596. return nullptr;
  1597. e = std::make_unique<XmlElement> ("CLOSED");
  1598. }
  1599. e->setAttribute ("id", name);
  1600. return e;
  1601. }
  1602. // trying to save the openness for an element that has no name - this won't
  1603. // work because it needs the names to identify what to open.
  1604. jassertfalse;
  1605. return {};
  1606. }
  1607. //==============================================================================
  1608. TreeViewItem::OpennessRestorer::OpennessRestorer (TreeViewItem& item)
  1609. : treeViewItem (item),
  1610. oldOpenness (item.getOpennessState())
  1611. {
  1612. }
  1613. TreeViewItem::OpennessRestorer::~OpennessRestorer()
  1614. {
  1615. if (oldOpenness != nullptr)
  1616. treeViewItem.restoreOpennessState (*oldOpenness);
  1617. }
  1618. void TreeViewItem::draw (Graphics& g, int width, bool isMouseOverButton)
  1619. {
  1620. const auto indent = getIndentX();
  1621. const auto itemW = (itemWidth < 0 || drawsInRightMargin) ? width - indent : itemWidth;
  1622. {
  1623. Graphics::ScopedSaveState ss (g);
  1624. g.setOrigin (indent, 0);
  1625. if (g.reduceClipRegion (drawsInLeftMargin ? -indent : 0, 0,
  1626. drawsInLeftMargin ? itemW + indent : itemW, itemHeight))
  1627. {
  1628. if (isSelected())
  1629. g.fillAll (ownerView->findColour (TreeView::selectedItemBackgroundColourId));
  1630. else
  1631. g.fillAll ((getRowNumberInTree() % 2 == 0) ? ownerView->findColour (TreeView::oddItemsColourId)
  1632. : ownerView->findColour (TreeView::evenItemsColourId));
  1633. paintItem (g, itemWidth < 0 ? width - indent : itemWidth, itemHeight);
  1634. }
  1635. }
  1636. const auto halfH = (float) itemHeight * 0.5f;
  1637. const auto indentWidth = ownerView->getIndentSize();
  1638. const auto depth = getItemDepth (this);
  1639. if (depth >= 0 && ownerView->openCloseButtonsVisible)
  1640. {
  1641. auto x = ((float) depth + 0.5f) * (float) indentWidth;
  1642. const auto parentLinesDrawn = parentItem != nullptr && parentItem->areLinesDrawn();
  1643. if (parentLinesDrawn)
  1644. paintVerticalConnectingLine (g, Line<float> (x, 0, x, isLastOfSiblings() ? halfH : (float) itemHeight));
  1645. if (parentLinesDrawn || (parentItem == nullptr && areLinesDrawn()))
  1646. paintHorizontalConnectingLine (g, Line<float> (x, halfH, x + (float) indentWidth * 0.5f, halfH));
  1647. {
  1648. auto* p = parentItem;
  1649. auto d = depth;
  1650. while (p != nullptr && --d >= 0)
  1651. {
  1652. x -= (float) indentWidth;
  1653. if ((p->parentItem == nullptr || p->parentItem->areLinesDrawn()) && ! p->isLastOfSiblings())
  1654. p->paintVerticalConnectingLine (g, Line<float> (x, 0, x, (float) itemHeight));
  1655. p = p->parentItem;
  1656. }
  1657. }
  1658. if (mightContainSubItems())
  1659. {
  1660. auto backgroundColour = ownerView->findColour (TreeView::backgroundColourId);
  1661. paintOpenCloseButton (g, Rectangle<float> ((float) (depth * indentWidth), 0, (float) indentWidth, (float) itemHeight),
  1662. backgroundColour.isTransparent() ? Colours::white : backgroundColour,
  1663. isMouseOverButton);
  1664. }
  1665. }
  1666. }
  1667. } // namespace juce