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.

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