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.

937 lines
41KB

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