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.

juce_TreeView.h 40KB

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