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.

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