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.

2037 lines
60KB

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