juce_TreeView.h 40 KB

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