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.

960 lines
40KB

  1. /*
  2. ==============================================================================
  3. This file is part of the JUCE library.
  4. Copyright (c) 2022 - Raw Material Software Limited
  5. JUCE is an open source library subject to commercial or open-source
  6. licensing.
  7. By using JUCE, you agree to the terms of both the JUCE 7 End-User License
  8. Agreement and JUCE Privacy Policy.
  9. End User License Agreement: www.juce.com/juce-7-licence
  10. Privacy Policy: www.juce.com/juce-privacy-policy
  11. Or: You may also use this code under the terms of the GPL v3 (see
  12. www.gnu.org/licenses).
  13. JUCE IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL WARRANTIES, WHETHER
  14. EXPRESSED OR IMPLIED, INCLUDING MERCHANTABILITY AND FITNESS FOR PURPOSE, ARE
  15. DISCLAIMED.
  16. ==============================================================================
  17. */
  18. namespace juce
  19. {
  20. class TreeView;
  21. //==============================================================================
  22. /**
  23. An item in a TreeView.
  24. A TreeViewItem can either be a leaf-node in the tree, or it can contain its
  25. own sub-items.
  26. To implement an item that contains sub-items, override the itemOpennessChanged()
  27. method so that when it is opened, it adds the new sub-items to itself using the
  28. addSubItem method. Depending on the nature of the item it might choose to only
  29. do this the first time it's opened, or it might want to refresh itself each time.
  30. It also has the option of deleting its sub-items when it is closed, or leaving them
  31. in place.
  32. @tags{GUI}
  33. */
  34. class JUCE_API TreeViewItem
  35. {
  36. public:
  37. //==============================================================================
  38. /** Constructor. */
  39. TreeViewItem();
  40. /** Destructor. */
  41. virtual ~TreeViewItem();
  42. //==============================================================================
  43. /** Returns the number of sub-items that have been added to this item.
  44. Note that this doesn't mean much if the node isn't open.
  45. @see getSubItem, mightContainSubItems, addSubItem
  46. */
  47. int getNumSubItems() const noexcept;
  48. /** Returns one of the item's sub-items.
  49. Remember that the object returned might get deleted at any time when its parent
  50. item is closed or refreshed, depending on the nature of the items you're using.
  51. @see getNumSubItems
  52. */
  53. TreeViewItem* getSubItem (int index) const noexcept;
  54. /** Removes any sub-items. */
  55. void clearSubItems();
  56. /** Adds a sub-item.
  57. @param newItem the object to add to the item's sub-item list. Once added, these can be
  58. found using getSubItem(). When the items are later removed with
  59. removeSubItem() (or when this item is deleted), they will be deleted.
  60. @param insertPosition the index which the new item should have when it's added. If this
  61. value is less than 0, the item will be added to the end of the list.
  62. */
  63. void addSubItem (TreeViewItem* newItem, int insertPosition = -1);
  64. /** Adds a sub-item with a sort-comparator, assuming that the existing items are already sorted.
  65. @param comparator the comparator object for sorting - see sortSubItems() for details about
  66. the methods this class must provide.
  67. @param newItem the object to add to the item's sub-item list. Once added, these can be
  68. found using getSubItem(). When the items are later removed with
  69. removeSubItem() (or when this item is deleted), they will be deleted.
  70. */
  71. template <class ElementComparator>
  72. void addSubItemSorted (ElementComparator& comparator, TreeViewItem* newItem)
  73. {
  74. addSubItem (newItem, findInsertIndexInSortedArray (comparator, subItems.begin(), newItem, 0, subItems.size()));
  75. }
  76. /** Removes one of the sub-items.
  77. @param index the item to remove
  78. @param deleteItem if true, the item that is removed will also be deleted.
  79. */
  80. void removeSubItem (int index, bool deleteItem = true);
  81. /** Sorts the list of sub-items using a standard array comparator.
  82. This will use a comparator object to sort the elements into order. The comparator
  83. object must have a method of the form:
  84. @code
  85. int compareElements (TreeViewItem* first, TreeViewItem* second);
  86. @endcode
  87. ..and this method must return:
  88. - a value of < 0 if the first comes before the second
  89. - a value of 0 if the two objects are equivalent
  90. - a value of > 0 if the second comes before the first
  91. To improve performance, the compareElements() method can be declared as static or const.
  92. */
  93. template <class ElementComparator>
  94. void sortSubItems (ElementComparator& comparator)
  95. {
  96. subItems.sort (comparator);
  97. }
  98. //==============================================================================
  99. /** Returns the TreeView to which this item belongs. */
  100. TreeView* getOwnerView() const noexcept { return ownerView; }
  101. /** Returns the item within which this item is contained. */
  102. TreeViewItem* getParentItem() const noexcept { return parentItem; }
  103. //==============================================================================
  104. /** True if this item is currently open in the TreeView.
  105. @see getOpenness
  106. */
  107. bool isOpen() const noexcept;
  108. /** Opens or closes the item.
  109. When opened or closed, the item's itemOpennessChanged() method will be called,
  110. and a subclass should use this callback to create and add any sub-items that
  111. it needs to.
  112. Note that if this is called when the item is in its default openness state, and
  113. this call would not change whether it's open or closed, then no change will be
  114. stored. If you want to explicitly set the openness state to be non-default then
  115. you should use setOpenness instead.
  116. @see setOpenness, itemOpennessChanged, mightContainSubItems
  117. */
  118. void setOpen (bool shouldBeOpen);
  119. /** An enum of states to describe the explicit or implicit openness of an item. */
  120. enum class Openness
  121. {
  122. opennessDefault,
  123. opennessClosed,
  124. opennessOpen
  125. };
  126. /** Returns the openness state of this item.
  127. @see isOpen
  128. */
  129. Openness getOpenness() const noexcept;
  130. /** Opens or closes the item.
  131. If this causes the value of isOpen() to change, then the item's itemOpennessChanged()
  132. method will be called, and a subclass should use this callback to create and add any
  133. sub-items that it needs to.
  134. @see setOpen
  135. */
  136. void setOpenness (Openness newOpenness);
  137. /** True if this item is currently selected.
  138. Use this when painting the node, to decide whether to draw it as selected or not.
  139. */
  140. bool isSelected() const noexcept;
  141. /** Selects or deselects the item.
  142. If shouldNotify == sendNotification, then a callback will be made
  143. to itemSelectionChanged() if the item's selection has changed.
  144. */
  145. void setSelected (bool shouldBeSelected,
  146. bool deselectOtherItemsFirst,
  147. NotificationType shouldNotify = sendNotification);
  148. /** Returns the rectangle that this item occupies.
  149. If relativeToTreeViewTopLeft is true, the coordinates are relative to the
  150. top-left of the TreeView comp, so this will depend on the scroll-position of
  151. the tree. If false, it is relative to the top-left of the topmost item in the
  152. tree (so this would be unaffected by scrolling the view).
  153. */
  154. Rectangle<int> getItemPosition (bool relativeToTreeViewTopLeft) const noexcept;
  155. /** Sends a signal to the TreeView to make it refresh itself.
  156. Call this if your items have changed and you want the tree to update to reflect this.
  157. */
  158. void treeHasChanged() const noexcept;
  159. /** Sends a repaint message to redraw just this item.
  160. Note that you should only call this if you want to repaint a superficial change. If
  161. you're altering the tree's nodes, you should instead call treeHasChanged().
  162. */
  163. void repaintItem() const;
  164. /** Returns the row number of this item in the tree.
  165. The row number of an item will change according to which items are open.
  166. @see TreeView::getNumRowsInTree(), TreeView::getItemOnRow()
  167. */
  168. int getRowNumberInTree() const noexcept;
  169. /** Returns true if all the item's parent nodes are open.
  170. This is useful to check whether the item might actually be visible or not.
  171. */
  172. bool areAllParentsOpen() const noexcept;
  173. /** Changes whether lines are drawn to connect any sub-items to this item.
  174. By default, line-drawing is turned on according to LookAndFeel::areLinesDrawnForTreeView().
  175. */
  176. void setLinesDrawnForSubItems (bool shouldDrawLines) noexcept;
  177. //==============================================================================
  178. /** Tells the tree whether this item can potentially be opened.
  179. If your item could contain sub-items, this should return true; if it returns
  180. false then the tree will not try to open the item. This determines whether or
  181. not the item will be drawn with a 'plus' button next to it.
  182. */
  183. virtual bool mightContainSubItems() = 0;
  184. /** Returns a string to uniquely identify this item.
  185. If you're planning on using the TreeView::getOpennessState() method, then
  186. these strings will be used to identify which nodes are open. The string
  187. should be unique amongst the item's sibling items, but it's ok for there
  188. to be duplicates at other levels of the tree.
  189. If you're not going to store the state, then it's ok not to bother implementing
  190. this method.
  191. */
  192. virtual String getUniqueName() const;
  193. /** Called when an item is opened or closed.
  194. When setOpen() is called and the item has specified that it might
  195. have sub-items with the mightContainSubItems() method, this method
  196. is called to let the item create or manage its sub-items.
  197. So when this is called with isNowOpen set to true (i.e. when the item is being
  198. opened), a subclass might choose to use clearSubItems() and addSubItem() to
  199. refresh its sub-item list.
  200. When this is called with isNowOpen set to false, the subclass might want
  201. to use clearSubItems() to save on space, or it might choose to leave them,
  202. depending on the nature of the tree.
  203. You could also use this callback as a trigger to start a background process
  204. which asynchronously creates sub-items and adds them, if that's more
  205. appropriate for the task in hand.
  206. @see mightContainSubItems
  207. */
  208. virtual void itemOpennessChanged (bool isNowOpen);
  209. /** Must return the width required by this item.
  210. If your item needs to have a particular width in pixels, return that value; if
  211. you'd rather have it just fill whatever space is available in the TreeView,
  212. return -1.
  213. If all your items return -1, no horizontal scrollbar will be shown, but if any
  214. items have fixed widths and extend beyond the width of the TreeView, a
  215. scrollbar will appear.
  216. Each item can be a different width, but if they change width, you should call
  217. treeHasChanged() to update the tree.
  218. */
  219. virtual int getItemWidth() const { return -1; }
  220. /** Must return the height required by this item.
  221. This is the height in pixels that the item will take up. Items in the tree
  222. can be different heights, but if they change height, you should call
  223. treeHasChanged() to update the tree.
  224. */
  225. virtual int getItemHeight() const { return 20; }
  226. /** You can override this method to return false if you don't want to allow the
  227. user to select this item.
  228. */
  229. virtual bool canBeSelected() const { return true; }
  230. /** Creates a component that will be used to represent this item.
  231. You don't have to implement this method - if it returns nullptr then no component
  232. will be used for the item, and you can just draw it using the paintItem()
  233. callback. But if you do return a component, it will be positioned in the
  234. TreeView so that it can be used to represent this item.
  235. The component returned will be managed by the TreeView and will be deleted
  236. later when it goes off the screen or is no longer needed. Its position and
  237. size will be completely managed by the tree, so don't attempt to move it around.
  238. Something you may want to do with your component is to give it a pointer to
  239. the TreeView that created it. This is perfectly safe, and there's no danger
  240. of it becoming a dangling pointer because the TreeView will always delete
  241. the component before it is itself deleted.
  242. As long as you stick to these rules you can return whatever kind of
  243. component you like. It's most useful if you're doing things like drag-and-drop
  244. of items, or want to use a Label component to edit item names, etc.
  245. */
  246. virtual std::unique_ptr<Component> createItemComponent() { return nullptr; }
  247. //==============================================================================
  248. /** Draws the item's contents.
  249. You can choose to either implement this method and draw each item, or you
  250. can use createItemComponent() to create a component that will represent the
  251. item.
  252. If all you need in your tree is to be able to draw the items and detect when
  253. the user selects or double-clicks one of them, it's probably enough to
  254. use paintItem(), itemClicked() and itemDoubleClicked(). If you need more
  255. complicated interactions, you may need to use createItemComponent() instead.
  256. @param g the graphics context to draw into
  257. @param width the width of the area available for drawing
  258. @param height the height of the area available for drawing
  259. */
  260. virtual void paintItem (Graphics& g, int width, int height);
  261. /** Draws the item's open/close button.
  262. If you don't implement this method, the default behaviour is to call
  263. LookAndFeel::drawTreeviewPlusMinusBox(), but you can override it for custom
  264. effects. You may want to override it and call the base-class implementation
  265. with a different backgroundColour parameter, if your implementation has a
  266. background colour other than the default (white).
  267. */
  268. virtual void paintOpenCloseButton (Graphics&, const Rectangle<float>& area,
  269. Colour backgroundColour, bool isMouseOver);
  270. /** Draws the line that connects this item to the vertical line extending below its parent. */
  271. virtual void paintHorizontalConnectingLine (Graphics&, const Line<float>& line);
  272. /** Draws the line that extends vertically up towards one of its parents, or down to one of its children. */
  273. virtual void paintVerticalConnectingLine (Graphics&, const Line<float>& line);
  274. /** This should return true if you want to use a custom component, and also use
  275. the TreeView's built-in mouse handling support, enabling drag-and-drop,
  276. itemClicked() and itemDoubleClicked(); return false if the component should
  277. consume all mouse clicks.
  278. */
  279. virtual bool customComponentUsesTreeViewMouseHandler() const { return false; }
  280. /** Called when the user clicks on this item.
  281. If you're using createItemComponent() to create a custom component for the
  282. item, the mouse-clicks might not make it through to the TreeView, but this
  283. is how you find out about clicks when just drawing each item individually.
  284. The associated mouse-event details are passed in, so you can find out about
  285. which button, where it was, etc.
  286. @see itemDoubleClicked
  287. */
  288. virtual void itemClicked (const MouseEvent&);
  289. /** Called when the user double-clicks on this item.
  290. If you're using createItemComponent() to create a custom component for the
  291. item, the mouse-clicks might not make it through to the TreeView, but this
  292. is how you find out about clicks when just drawing each item individually.
  293. The associated mouse-event details are passed in, so you can find out about
  294. which button, where it was, etc.
  295. If not overridden, the base class method here will open or close the item as
  296. if the 'plus' button had been clicked.
  297. @see itemClicked
  298. */
  299. virtual void itemDoubleClicked (const MouseEvent&);
  300. /** Called when the item is selected or deselected.
  301. Use this if you want to do something special when the item's selectedness
  302. changes. By default it'll get repainted when this happens.
  303. */
  304. virtual void itemSelectionChanged (bool isNowSelected);
  305. /** Called when the owner view changes */
  306. virtual void ownerViewChanged (TreeView* newOwner);
  307. /** The item can return a tool tip string here if it wants to.
  308. @see TooltipClient
  309. */
  310. virtual String getTooltip();
  311. /** Use this to set the name for this item that will be read out by accessibility
  312. clients.
  313. The default implementation will return the tooltip string from getTooltip()
  314. if it is not empty, otherwise it will return a description of the nested level
  315. and row number of the item.
  316. @see AccessibilityHandler
  317. */
  318. virtual String getAccessibilityName();
  319. //==============================================================================
  320. /** To allow items from your TreeView to be dragged-and-dropped, implement this method.
  321. If this returns a non-null variant then when the user drags an item, the TreeView will
  322. try to find a DragAndDropContainer in its parent hierarchy, and will use it to trigger
  323. a drag-and-drop operation, using this string as the source description, with the TreeView
  324. itself as the source component.
  325. If you need more complex drag-and-drop behaviour, you can use custom components for
  326. the items, and use those to trigger the drag.
  327. To accept drag-and-drop in your tree, see isInterestedInDragSource(),
  328. isInterestedInFileDrag(), etc.
  329. @see DragAndDropContainer::startDragging
  330. */
  331. virtual var getDragSourceDescription();
  332. /** If you want your item to be able to have files drag-and-dropped onto it, implement this
  333. method and return true.
  334. If you return true and allow some files to be dropped, you'll also need to implement the
  335. filesDropped() method to do something with them.
  336. Note that this will be called often, so make your implementation very quick! There's
  337. certainly no time to try opening the files and having a think about what's inside them!
  338. For responding to internal drag-and-drop of other types of object, see isInterestedInDragSource().
  339. @see FileDragAndDropTarget::isInterestedInFileDrag, isInterestedInDragSource
  340. */
  341. virtual bool isInterestedInFileDrag (const StringArray& files);
  342. /** When files are dropped into this item, this callback is invoked.
  343. For this to work, you'll need to have also implemented isInterestedInFileDrag().
  344. The insertIndex value indicates where in the list of sub-items the files were dropped.
  345. If files are dropped onto an area of the tree where there are no visible items, this
  346. method is called on the root item of the tree, with an insert index of 0.
  347. @see FileDragAndDropTarget::filesDropped, isInterestedInFileDrag
  348. */
  349. virtual void filesDropped (const StringArray& files, int insertIndex);
  350. /** If you want your item to act as a DragAndDropTarget, implement this method and return true.
  351. If you implement this method, you'll also need to implement itemDropped() in order to handle
  352. the items when they are dropped.
  353. To respond to drag-and-drop of files from external applications, see isInterestedInFileDrag().
  354. @see DragAndDropTarget::isInterestedInDragSource, itemDropped
  355. */
  356. virtual bool isInterestedInDragSource (const DragAndDropTarget::SourceDetails& dragSourceDetails);
  357. /** When a things are dropped into this item, this callback is invoked.
  358. For this to work, you need to have also implemented isInterestedInDragSource().
  359. The insertIndex value indicates where in the list of sub-items the new items should be placed.
  360. If files are dropped onto an area of the tree where there are no visible items, this
  361. method is called on the root item of the tree, with an insert index of 0.
  362. @see isInterestedInDragSource, DragAndDropTarget::itemDropped
  363. */
  364. virtual void itemDropped (const DragAndDropTarget::SourceDetails& dragSourceDetails, int insertIndex);
  365. //==============================================================================
  366. /** Sets a flag to indicate that the item wants to be allowed
  367. to draw all the way across to the left edge of the TreeView.
  368. By default this is false, which means that when the paintItem()
  369. method is called, its graphics context is clipped to only allow
  370. drawing within the item's rectangle. If this flag is set to true,
  371. then the graphics context isn't clipped on its left side, so it
  372. can draw all the way across to the left margin. Note that the
  373. context will still have its origin in the same place though, so
  374. the coordinates of anything to its left will be negative. It's
  375. mostly useful if you want to draw a wider bar behind the
  376. highlighted item.
  377. */
  378. void setDrawsInLeftMargin (bool canDrawInLeftMargin) noexcept;
  379. /** Sets a flag to indicate that the item wants to be allowed
  380. to draw all the way across to the right edge of the TreeView.
  381. Similar to setDrawsInLeftMargin: when this flag is set to true,
  382. then the graphics context isn't clipped on the right side. Unlike
  383. setDrawsInLeftMargin, you will very rarely need to use this function,
  384. as this method won't clip the right margin unless your TreeViewItem
  385. overrides getItemWidth to return a positive value.
  386. @see setDrawsInLeftMargin, getItemWidth
  387. */
  388. void setDrawsInRightMargin (bool canDrawInRightMargin) noexcept;
  389. //==============================================================================
  390. /** Saves the current state of open/closed nodes so it can be restored later.
  391. This takes a snapshot of which sub-nodes have been explicitly opened or closed,
  392. and records it as XML. To identify node objects it uses the
  393. TreeViewItem::getUniqueName() method to create named paths. This
  394. means that the same state of open/closed nodes can be restored to a
  395. completely different instance of the tree, as long as it contains nodes
  396. whose unique names are the same.
  397. You'd normally want to use TreeView::getOpennessState() rather than call it
  398. for a specific item, but this can be handy if you need to briefly save the state
  399. for a section of the tree.
  400. Note that if all nodes of the tree are in their default state, then this may
  401. return a nullptr.
  402. @see TreeView::getOpennessState, restoreOpennessState
  403. */
  404. std::unique_ptr<XmlElement> getOpennessState() const;
  405. /** Restores the openness of this item and all its sub-items from a saved state.
  406. See TreeView::restoreOpennessState for more details.
  407. You'd normally want to use TreeView::restoreOpennessState() rather than call it
  408. for a specific item, but this can be handy if you need to briefly save the state
  409. for a section of the tree.
  410. @see TreeView::restoreOpennessState, getOpennessState
  411. */
  412. void restoreOpennessState (const XmlElement& xml);
  413. //==============================================================================
  414. /** Returns the index of this item in its parent's sub-items. */
  415. int getIndexInParent() const noexcept;
  416. /** Returns true if this item is the last of its parent's sub-items. */
  417. bool isLastOfSiblings() const noexcept;
  418. /** Creates a string that can be used to uniquely retrieve this item in the tree.
  419. The string that is returned can be passed to TreeView::findItemFromIdentifierString().
  420. The string takes the form of a path, constructed from the getUniqueName() of this
  421. item and all its parents, so these must all be correctly implemented for it to work.
  422. @see TreeView::findItemFromIdentifierString, getUniqueName
  423. */
  424. String getItemIdentifierString() const;
  425. //==============================================================================
  426. /**
  427. This handy class takes a copy of a TreeViewItem's openness when you create it,
  428. and restores that openness state when its destructor is called.
  429. This can very handy when you're refreshing sub-items - e.g.
  430. @code
  431. void MyTreeViewItem::updateChildItems()
  432. {
  433. OpennessRestorer openness (*this); // saves the openness state here..
  434. clearSubItems();
  435. // add a bunch of sub-items here which may or may not be the same as the ones that
  436. // were previously there
  437. addSubItem (...
  438. // ..and at this point, the old openness is restored, so any items that haven't
  439. // changed will have their old openness retained.
  440. }
  441. @endcode
  442. */
  443. class JUCE_API OpennessRestorer
  444. {
  445. public:
  446. OpennessRestorer (TreeViewItem&);
  447. ~OpennessRestorer();
  448. private:
  449. TreeViewItem& treeViewItem;
  450. std::unique_ptr<XmlElement> oldOpenness;
  451. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (OpennessRestorer)
  452. };
  453. private:
  454. //==============================================================================
  455. friend class TreeView;
  456. void updatePositions (int);
  457. int getIndentX() const noexcept;
  458. void setOwnerView (TreeView*) noexcept;
  459. TreeViewItem* getTopLevelItem() noexcept;
  460. TreeViewItem* getDeepestOpenParentItem() noexcept;
  461. int getNumRows() const noexcept;
  462. TreeViewItem* getItemOnRow (int) noexcept;
  463. void deselectAllRecursively (TreeViewItem*);
  464. int countSelectedItemsRecursively (int) const noexcept;
  465. TreeViewItem* getSelectedItemWithIndex (int) noexcept;
  466. TreeViewItem* findItemFromIdentifierString (const String&);
  467. void restoreToDefaultOpenness();
  468. bool isFullyOpen() const noexcept;
  469. std::unique_ptr<XmlElement> getOpennessState (bool) const;
  470. bool removeSubItemFromList (int, bool);
  471. void removeAllSubItemsFromList();
  472. bool areLinesDrawn() const;
  473. void draw (Graphics&, int, bool);
  474. //==============================================================================
  475. TreeView* ownerView = nullptr;
  476. TreeViewItem* parentItem = nullptr;
  477. OwnedArray<TreeViewItem> subItems;
  478. Openness openness = Openness::opennessDefault;
  479. int y = 0, itemHeight = 0, totalHeight = 0, itemWidth = 0, totalWidth = 0, uid = 0;
  480. bool selected = false, redrawNeeded = true, drawLinesInside = false, drawLinesSet = false,
  481. drawsInLeftMargin = false, drawsInRightMargin = false;
  482. //==============================================================================
  483. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (TreeViewItem)
  484. };
  485. //==============================================================================
  486. /**
  487. A tree-view component.
  488. Use one of these to hold and display a structure of TreeViewItem objects.
  489. @tags{GUI}
  490. */
  491. class JUCE_API TreeView : public Component,
  492. public SettableTooltipClient,
  493. public FileDragAndDropTarget,
  494. public DragAndDropTarget
  495. {
  496. public:
  497. //==============================================================================
  498. /** Creates an empty TreeView.
  499. Once you've got a TreeView component, you'll need to give it something to
  500. display, using the setRootItem() method.
  501. */
  502. TreeView (const String& componentName = {});
  503. /** Destructor. */
  504. ~TreeView() override;
  505. //==============================================================================
  506. /** Sets the item that is displayed in the TreeView.
  507. A tree has a single root item which contains as many sub-items as it needs. If
  508. you want the tree to contain a number of root items, you should still use a single
  509. root item above these, but hide it using setRootItemVisible().
  510. You can pass nullptr to this method to clear the tree and remove its current root item.
  511. The object passed in will not be deleted by the TreeView, it's up to the caller
  512. to delete it when no longer needed. BUT make absolutely sure that you don't delete
  513. this item until you've removed it from the tree, either by calling setRootItem (nullptr),
  514. or by deleting the tree first. You can also use deleteRootItem() as a quick way
  515. to delete it.
  516. */
  517. void setRootItem (TreeViewItem* newRootItem);
  518. /** Returns the tree's root item.
  519. This will be the last object passed to setRootItem(), or nullptr if none has been set.
  520. */
  521. TreeViewItem* getRootItem() const noexcept { return rootItem; }
  522. /** This will remove and delete the current root item.
  523. It's a convenient way of deleting the item and calling setRootItem (nullptr).
  524. */
  525. void deleteRootItem();
  526. /** Changes whether the tree's root item is shown or not.
  527. If the root item is hidden, only its sub-items will be shown in the TreeView - this
  528. lets you make the tree look as if it's got many root items. If it's hidden, this call
  529. will also make sure the root item is open (otherwise the TreeView would look empty).
  530. */
  531. void setRootItemVisible (bool shouldBeVisible);
  532. /** Returns true if the root item is visible.
  533. @see setRootItemVisible
  534. */
  535. bool isRootItemVisible() const noexcept { return rootItemVisible; }
  536. /** Sets whether items are open or closed by default.
  537. Normally, items are closed until the user opens them, but you can use this
  538. to make them default to being open until explicitly closed.
  539. @see areItemsOpenByDefault
  540. */
  541. void setDefaultOpenness (bool isOpenByDefault);
  542. /** Returns true if the tree's items default to being open.
  543. @see setDefaultOpenness
  544. */
  545. bool areItemsOpenByDefault() const noexcept { return defaultOpenness; }
  546. /** This sets a flag to indicate that the tree can be used for multi-selection.
  547. You can always select multiple items internally by calling the
  548. TreeViewItem::setSelected() method, but this flag indicates whether the user
  549. is allowed to multi-select by clicking on the tree.
  550. By default it is disabled.
  551. @see isMultiSelectEnabled
  552. */
  553. void setMultiSelectEnabled (bool canMultiSelect);
  554. /** Returns whether multi-select has been enabled for the tree.
  555. @see setMultiSelectEnabled
  556. */
  557. bool isMultiSelectEnabled() const noexcept { return multiSelectEnabled; }
  558. /** Sets a flag to indicate whether to hide the open/close buttons.
  559. @see areOpenCloseButtonsVisible
  560. */
  561. void setOpenCloseButtonsVisible (bool shouldBeVisible);
  562. /** Returns whether open/close buttons are shown.
  563. @see setOpenCloseButtonsVisible
  564. */
  565. bool areOpenCloseButtonsVisible() const noexcept { return openCloseButtonsVisible; }
  566. //==============================================================================
  567. /** Deselects any items that are currently selected. */
  568. void clearSelectedItems();
  569. /** Returns the number of items that are currently selected.
  570. If maximumDepthToSearchTo is >= 0, it lets you specify a maximum depth to which the
  571. tree will be recursed.
  572. @see getSelectedItem, clearSelectedItems
  573. */
  574. int getNumSelectedItems (int maximumDepthToSearchTo = -1) const noexcept;
  575. /** Returns one of the selected items in the tree.
  576. @param index the index, 0 to (getNumSelectedItems() - 1)
  577. */
  578. TreeViewItem* getSelectedItem (int index) const noexcept;
  579. /** Moves the selected row up or down by the specified number of rows. */
  580. void moveSelectedRow (int deltaRows);
  581. //==============================================================================
  582. /** Returns the number of rows the tree is using, depending on which items are open.
  583. @see TreeViewItem::getRowNumberInTree()
  584. */
  585. int getNumRowsInTree() const;
  586. /** Returns the item on a particular row of the tree.
  587. If the index is out of range, this will return nullptr.
  588. @see getNumRowsInTree, TreeViewItem::getRowNumberInTree()
  589. */
  590. TreeViewItem* getItemOnRow (int index) const;
  591. /** Returns the item that contains a given y-position relative to the top
  592. of the TreeView component.
  593. */
  594. TreeViewItem* getItemAt (int yPosition) const noexcept;
  595. /** Tries to scroll the tree so that this item is on-screen somewhere. */
  596. void scrollToKeepItemVisible (TreeViewItem* item);
  597. /** Returns the TreeView's Viewport object. */
  598. Viewport* getViewport() const noexcept;
  599. /** Returns the number of pixels by which each nested level of the tree is indented.
  600. @see setIndentSize
  601. */
  602. int getIndentSize() noexcept;
  603. /** Changes the distance by which each nested level of the tree is indented.
  604. @see getIndentSize
  605. */
  606. void setIndentSize (int newIndentSize);
  607. /** Searches the tree for an item with the specified identifier.
  608. The identifier string must have been created by calling TreeViewItem::getItemIdentifierString().
  609. If no such item exists, this will return false. If the item is found, all of its items
  610. will be automatically opened.
  611. */
  612. TreeViewItem* findItemFromIdentifierString (const String& identifierString) const;
  613. /** Returns the component that currently represents a given TreeViewItem. */
  614. Component* getItemComponent (const TreeViewItem* item) const;
  615. //==============================================================================
  616. /** Saves the current state of open/closed nodes so it can be restored later.
  617. This takes a snapshot of which nodes have been explicitly opened or closed,
  618. and records it as XML. To identify node objects it uses the
  619. TreeViewItem::getUniqueName() method to create named paths. This
  620. means that the same state of open/closed nodes can be restored to a
  621. completely different instance of the tree, as long as it contains nodes
  622. whose unique names are the same.
  623. @param alsoIncludeScrollPosition if this is true, the state will also
  624. include information about where the
  625. tree has been scrolled to vertically,
  626. so this can also be restored
  627. @see restoreOpennessState
  628. */
  629. std::unique_ptr<XmlElement> getOpennessState (bool alsoIncludeScrollPosition) const;
  630. /** Restores a previously saved arrangement of open/closed nodes.
  631. This will try to restore a snapshot of the tree's state that was created by
  632. the getOpennessState() method. If any of the nodes named in the original
  633. XML aren't present in this tree, they will be ignored.
  634. If restoreStoredSelection is true, it will also try to re-select any items that
  635. were selected in the stored state.
  636. @see getOpennessState
  637. */
  638. void restoreOpennessState (const XmlElement& newState, bool restoreStoredSelection);
  639. //==============================================================================
  640. /** A set of colour IDs to use to change the colour of various aspects of the TreeView.
  641. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  642. methods.
  643. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  644. */
  645. enum ColourIds
  646. {
  647. backgroundColourId = 0x1000500, /**< A background colour to fill the component with. */
  648. linesColourId = 0x1000501, /**< The colour to draw the lines with.*/
  649. dragAndDropIndicatorColourId = 0x1000502, /**< The colour to use for the drag-and-drop target position indicator. */
  650. selectedItemBackgroundColourId = 0x1000503, /**< The colour to use to fill the background of any selected items. */
  651. oddItemsColourId = 0x1000504, /**< The colour to use to fill the background of the odd numbered items. */
  652. evenItemsColourId = 0x1000505 /**< The colour to use to fill the background of the even numbered items. */
  653. };
  654. //==============================================================================
  655. /** This abstract base class is implemented by LookAndFeel classes to provide
  656. TreeView drawing functionality.
  657. */
  658. struct JUCE_API LookAndFeelMethods
  659. {
  660. virtual ~LookAndFeelMethods() = default;
  661. virtual void drawTreeviewPlusMinusBox (Graphics&, const Rectangle<float>& area,
  662. Colour backgroundColour, bool isItemOpen, bool isMouseOver) = 0;
  663. virtual bool areLinesDrawnForTreeView (TreeView&) = 0;
  664. virtual int getTreeViewIndentSize (TreeView&) = 0;
  665. };
  666. //==============================================================================
  667. /** @internal */
  668. void paint (Graphics&) override;
  669. /** @internal */
  670. void resized() override;
  671. /** @internal */
  672. bool keyPressed (const KeyPress&) override;
  673. /** @internal */
  674. void colourChanged() override;
  675. /** @internal */
  676. void enablementChanged() override;
  677. /** @internal */
  678. bool isInterestedInFileDrag (const StringArray&) override;
  679. /** @internal */
  680. void fileDragEnter (const StringArray&, int, int) override;
  681. /** @internal */
  682. void fileDragMove (const StringArray&, int, int) override;
  683. /** @internal */
  684. void fileDragExit (const StringArray&) override;
  685. /** @internal */
  686. void filesDropped (const StringArray&, int, int) override;
  687. /** @internal */
  688. bool isInterestedInDragSource (const SourceDetails&) override;
  689. /** @internal */
  690. void itemDragEnter (const SourceDetails&) override;
  691. /** @internal */
  692. void itemDragMove (const SourceDetails&) override;
  693. /** @internal */
  694. void itemDragExit (const SourceDetails&) override;
  695. /** @internal */
  696. void itemDropped (const SourceDetails&) override;
  697. private:
  698. friend class TreeViewItem;
  699. class ItemComponent;
  700. class ContentComponent;
  701. class TreeViewport;
  702. class InsertPointHighlight;
  703. class TargetGroupHighlight;
  704. class TreeAccessibilityHandler;
  705. struct InsertPoint;
  706. std::unique_ptr<AccessibilityHandler> createAccessibilityHandler() override;
  707. void itemsChanged() noexcept;
  708. void updateVisibleItems();
  709. void updateButtonUnderMouse (const MouseEvent&);
  710. void showDragHighlight (const InsertPoint&) noexcept;
  711. void hideDragHighlight() noexcept;
  712. void handleDrag (const StringArray&, const SourceDetails&);
  713. void handleDrop (const StringArray&, const SourceDetails&);
  714. bool toggleOpenSelectedItem();
  715. void moveOutOfSelectedItem();
  716. void moveIntoSelectedItem();
  717. void moveByPages (int);
  718. std::unique_ptr<TreeViewport> viewport;
  719. TreeViewItem* rootItem = nullptr;
  720. std::unique_ptr<InsertPointHighlight> dragInsertPointHighlight;
  721. std::unique_ptr<TargetGroupHighlight> dragTargetGroupHighlight;
  722. int indentSize = -1;
  723. bool defaultOpenness = false, rootItemVisible = true, multiSelectEnabled = false, openCloseButtonsVisible = true;
  724. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (TreeView)
  725. };
  726. } // namespace juce