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.

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