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.

1859 lines
51KB

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