Audio plugin host https://kx.studio/carla
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.

1889 lines
53KB

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