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 52KB

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