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.cpp 53KB

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