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.

2118 lines
63KB

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