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.

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