juce_TreeView.cpp 52 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916
  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, &e.source);
  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.get());
  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 std::unique_ptr<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.get();
  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. std::unique_ptr<XmlElement> TreeView::getOpennessState (bool alsoIncludeScrollPosition) const
  497. {
  498. std::unique_ptr<XmlElement> e;
  499. if (rootItem != nullptr)
  500. {
  501. e.reset (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. dragInsertPointHighlight.reset (new InsertPointHighlight());
  827. dragTargetGroupHighlight.reset (new TargetGroupHighlight());
  828. addAndMakeVisible (dragInsertPointHighlight.get());
  829. addAndMakeVisible (dragTargetGroupHighlight.get());
  830. }
  831. dragInsertPointHighlight->setTargetPosition (insertPos, viewport->getViewWidth());
  832. dragTargetGroupHighlight->setTargetPosition (insertPos.item);
  833. }
  834. void TreeView::hideDragHighlight() noexcept
  835. {
  836. dragInsertPointHighlight.reset();
  837. dragTargetGroupHighlight.reset();
  838. }
  839. void TreeView::handleDrag (const StringArray& files, const SourceDetails& dragSourceDetails)
  840. {
  841. const bool scrolled = viewport->autoScroll (dragSourceDetails.localPosition.x,
  842. dragSourceDetails.localPosition.y, 20, 10);
  843. InsertPoint insertPos (*this, files, dragSourceDetails);
  844. if (insertPos.item != nullptr)
  845. {
  846. if (scrolled || dragInsertPointHighlight == nullptr
  847. || dragInsertPointHighlight->lastItem != insertPos.item
  848. || dragInsertPointHighlight->lastIndex != insertPos.insertIndex)
  849. {
  850. if (files.size() > 0 ? insertPos.item->isInterestedInFileDrag (files)
  851. : insertPos.item->isInterestedInDragSource (dragSourceDetails))
  852. showDragHighlight (insertPos);
  853. else
  854. hideDragHighlight();
  855. }
  856. }
  857. else
  858. {
  859. hideDragHighlight();
  860. }
  861. }
  862. void TreeView::handleDrop (const StringArray& files, const SourceDetails& dragSourceDetails)
  863. {
  864. hideDragHighlight();
  865. InsertPoint insertPos (*this, files, dragSourceDetails);
  866. if (insertPos.item == nullptr)
  867. insertPos.item = rootItem;
  868. if (insertPos.item != nullptr)
  869. {
  870. if (files.size() > 0)
  871. {
  872. if (insertPos.item->isInterestedInFileDrag (files))
  873. insertPos.item->filesDropped (files, insertPos.insertIndex);
  874. }
  875. else
  876. {
  877. if (insertPos.item->isInterestedInDragSource (dragSourceDetails))
  878. insertPos.item->itemDropped (dragSourceDetails, insertPos.insertIndex);
  879. }
  880. }
  881. }
  882. //==============================================================================
  883. bool TreeView::isInterestedInFileDrag (const StringArray&)
  884. {
  885. return true;
  886. }
  887. void TreeView::fileDragEnter (const StringArray& files, int x, int y)
  888. {
  889. fileDragMove (files, x, y);
  890. }
  891. void TreeView::fileDragMove (const StringArray& files, int x, int y)
  892. {
  893. handleDrag (files, SourceDetails (var(), this, { x, y }));
  894. }
  895. void TreeView::fileDragExit (const StringArray&)
  896. {
  897. hideDragHighlight();
  898. }
  899. void TreeView::filesDropped (const StringArray& files, int x, int y)
  900. {
  901. handleDrop (files, SourceDetails (var(), this, { x, y }));
  902. }
  903. bool TreeView::isInterestedInDragSource (const SourceDetails& /*dragSourceDetails*/)
  904. {
  905. return true;
  906. }
  907. void TreeView::itemDragEnter (const SourceDetails& dragSourceDetails)
  908. {
  909. itemDragMove (dragSourceDetails);
  910. }
  911. void TreeView::itemDragMove (const SourceDetails& dragSourceDetails)
  912. {
  913. handleDrag (StringArray(), dragSourceDetails);
  914. }
  915. void TreeView::itemDragExit (const SourceDetails& /*dragSourceDetails*/)
  916. {
  917. hideDragHighlight();
  918. }
  919. void TreeView::itemDropped (const SourceDetails& dragSourceDetails)
  920. {
  921. handleDrop (StringArray(), dragSourceDetails);
  922. }
  923. //==============================================================================
  924. TreeViewItem::TreeViewItem()
  925. : selected (false),
  926. redrawNeeded (true),
  927. drawLinesInside (false),
  928. drawLinesSet (false),
  929. drawsInLeftMargin (false),
  930. drawsInRightMargin (false),
  931. openness (opennessDefault)
  932. {
  933. static int nextUID = 0;
  934. uid = nextUID++;
  935. }
  936. TreeViewItem::~TreeViewItem()
  937. {
  938. }
  939. String TreeViewItem::getUniqueName() const
  940. {
  941. return {};
  942. }
  943. void TreeViewItem::itemOpennessChanged (bool)
  944. {
  945. }
  946. int TreeViewItem::getNumSubItems() const noexcept
  947. {
  948. return subItems.size();
  949. }
  950. TreeViewItem* TreeViewItem::getSubItem (const int index) const noexcept
  951. {
  952. return subItems[index];
  953. }
  954. void TreeViewItem::clearSubItems()
  955. {
  956. if (ownerView != nullptr)
  957. {
  958. const ScopedLock sl (ownerView->nodeAlterationLock);
  959. if (! subItems.isEmpty())
  960. {
  961. removeAllSubItemsFromList();
  962. treeHasChanged();
  963. }
  964. }
  965. else
  966. {
  967. removeAllSubItemsFromList();
  968. }
  969. }
  970. void TreeViewItem::removeAllSubItemsFromList()
  971. {
  972. for (int i = subItems.size(); --i >= 0;)
  973. removeSubItemFromList (i, true);
  974. }
  975. void TreeViewItem::addSubItem (TreeViewItem* const newItem, const int insertPosition)
  976. {
  977. if (newItem != nullptr)
  978. {
  979. newItem->parentItem = nullptr;
  980. newItem->setOwnerView (ownerView);
  981. newItem->y = 0;
  982. newItem->itemHeight = newItem->getItemHeight();
  983. newItem->totalHeight = 0;
  984. newItem->itemWidth = newItem->getItemWidth();
  985. newItem->totalWidth = 0;
  986. newItem->parentItem = this;
  987. if (ownerView != nullptr)
  988. {
  989. const ScopedLock sl (ownerView->nodeAlterationLock);
  990. subItems.insert (insertPosition, newItem);
  991. treeHasChanged();
  992. if (newItem->isOpen())
  993. newItem->itemOpennessChanged (true);
  994. }
  995. else
  996. {
  997. subItems.insert (insertPosition, newItem);
  998. if (newItem->isOpen())
  999. newItem->itemOpennessChanged (true);
  1000. }
  1001. }
  1002. }
  1003. void TreeViewItem::removeSubItem (int index, bool deleteItem)
  1004. {
  1005. if (ownerView != nullptr)
  1006. {
  1007. const ScopedLock sl (ownerView->nodeAlterationLock);
  1008. if (removeSubItemFromList (index, deleteItem))
  1009. treeHasChanged();
  1010. }
  1011. else
  1012. {
  1013. removeSubItemFromList (index, deleteItem);
  1014. }
  1015. }
  1016. bool TreeViewItem::removeSubItemFromList (int index, bool deleteItem)
  1017. {
  1018. if (auto* child = subItems[index])
  1019. {
  1020. child->parentItem = nullptr;
  1021. subItems.remove (index, deleteItem);
  1022. return true;
  1023. }
  1024. return false;
  1025. }
  1026. TreeViewItem::Openness TreeViewItem::getOpenness() const noexcept
  1027. {
  1028. return (Openness) openness;
  1029. }
  1030. void TreeViewItem::setOpenness (Openness newOpenness)
  1031. {
  1032. const bool wasOpen = isOpen();
  1033. openness = newOpenness;
  1034. const bool isNowOpen = isOpen();
  1035. if (isNowOpen != wasOpen)
  1036. {
  1037. treeHasChanged();
  1038. itemOpennessChanged (isNowOpen);
  1039. }
  1040. }
  1041. bool TreeViewItem::isOpen() const noexcept
  1042. {
  1043. if (openness == opennessDefault)
  1044. return ownerView != nullptr && ownerView->defaultOpenness;
  1045. return openness == opennessOpen;
  1046. }
  1047. void TreeViewItem::setOpen (const bool shouldBeOpen)
  1048. {
  1049. if (isOpen() != shouldBeOpen)
  1050. setOpenness (shouldBeOpen ? opennessOpen
  1051. : opennessClosed);
  1052. }
  1053. bool TreeViewItem::isFullyOpen() const noexcept
  1054. {
  1055. if (! isOpen())
  1056. return false;
  1057. for (auto* i : subItems)
  1058. if (! i->isFullyOpen())
  1059. return false;
  1060. return true;
  1061. }
  1062. void TreeViewItem::restoreToDefaultOpenness()
  1063. {
  1064. setOpenness (opennessDefault);
  1065. }
  1066. bool TreeViewItem::isSelected() const noexcept
  1067. {
  1068. return selected;
  1069. }
  1070. void TreeViewItem::deselectAllRecursively (TreeViewItem* itemToIgnore)
  1071. {
  1072. if (this != itemToIgnore)
  1073. setSelected (false, false);
  1074. for (auto* i : subItems)
  1075. i->deselectAllRecursively (itemToIgnore);
  1076. }
  1077. void TreeViewItem::setSelected (const bool shouldBeSelected,
  1078. const bool deselectOtherItemsFirst,
  1079. const NotificationType notify)
  1080. {
  1081. if (shouldBeSelected && ! canBeSelected())
  1082. return;
  1083. if (deselectOtherItemsFirst)
  1084. getTopLevelItem()->deselectAllRecursively (this);
  1085. if (shouldBeSelected != selected)
  1086. {
  1087. selected = shouldBeSelected;
  1088. if (ownerView != nullptr)
  1089. ownerView->repaint();
  1090. if (notify != dontSendNotification)
  1091. itemSelectionChanged (shouldBeSelected);
  1092. }
  1093. }
  1094. void TreeViewItem::paintItem (Graphics&, int, int)
  1095. {
  1096. }
  1097. void TreeViewItem::paintOpenCloseButton (Graphics& g, const Rectangle<float>& area, Colour backgroundColour, bool isMouseOver)
  1098. {
  1099. getOwnerView()->getLookAndFeel()
  1100. .drawTreeviewPlusMinusBox (g, area, backgroundColour, isOpen(), isMouseOver);
  1101. }
  1102. void TreeViewItem::paintHorizontalConnectingLine (Graphics& g, const Line<float>& line)
  1103. {
  1104. g.setColour (ownerView->findColour (TreeView::linesColourId));
  1105. g.drawLine (line);
  1106. }
  1107. void TreeViewItem::paintVerticalConnectingLine (Graphics& g, const Line<float>& line)
  1108. {
  1109. g.setColour (ownerView->findColour (TreeView::linesColourId));
  1110. g.drawLine (line);
  1111. }
  1112. void TreeViewItem::itemClicked (const MouseEvent&)
  1113. {
  1114. }
  1115. void TreeViewItem::itemDoubleClicked (const MouseEvent&)
  1116. {
  1117. if (mightContainSubItems())
  1118. setOpen (! isOpen());
  1119. }
  1120. void TreeViewItem::itemSelectionChanged (bool)
  1121. {
  1122. }
  1123. String TreeViewItem::getTooltip()
  1124. {
  1125. return {};
  1126. }
  1127. void TreeViewItem::ownerViewChanged (TreeView*)
  1128. {
  1129. }
  1130. var TreeViewItem::getDragSourceDescription()
  1131. {
  1132. return {};
  1133. }
  1134. bool TreeViewItem::isInterestedInFileDrag (const StringArray&)
  1135. {
  1136. return false;
  1137. }
  1138. void TreeViewItem::filesDropped (const StringArray& /*files*/, int /*insertIndex*/)
  1139. {
  1140. }
  1141. bool TreeViewItem::isInterestedInDragSource (const DragAndDropTarget::SourceDetails& /*dragSourceDetails*/)
  1142. {
  1143. return false;
  1144. }
  1145. void TreeViewItem::itemDropped (const DragAndDropTarget::SourceDetails& /*dragSourceDetails*/, int /*insertIndex*/)
  1146. {
  1147. }
  1148. Rectangle<int> TreeViewItem::getItemPosition (const bool relativeToTreeViewTopLeft) const noexcept
  1149. {
  1150. auto indentX = getIndentX();
  1151. auto width = itemWidth;
  1152. if (ownerView != nullptr && width < 0)
  1153. width = ownerView->viewport->getViewWidth() - indentX;
  1154. Rectangle<int> r (indentX, y, jmax (0, width), totalHeight);
  1155. if (relativeToTreeViewTopLeft && ownerView != nullptr)
  1156. r -= ownerView->viewport->getViewPosition();
  1157. return r;
  1158. }
  1159. void TreeViewItem::treeHasChanged() const noexcept
  1160. {
  1161. if (ownerView != nullptr)
  1162. ownerView->itemsChanged();
  1163. }
  1164. void TreeViewItem::repaintItem() const
  1165. {
  1166. if (ownerView != nullptr && areAllParentsOpen())
  1167. ownerView->viewport->repaint (getItemPosition (true).withLeft (0));
  1168. }
  1169. bool TreeViewItem::areAllParentsOpen() const noexcept
  1170. {
  1171. return parentItem == nullptr
  1172. || (parentItem->isOpen() && parentItem->areAllParentsOpen());
  1173. }
  1174. void TreeViewItem::updatePositions (int newY)
  1175. {
  1176. y = newY;
  1177. itemHeight = getItemHeight();
  1178. totalHeight = itemHeight;
  1179. itemWidth = getItemWidth();
  1180. totalWidth = jmax (itemWidth, 0) + getIndentX();
  1181. if (isOpen())
  1182. {
  1183. newY += totalHeight;
  1184. for (auto* i : subItems)
  1185. {
  1186. i->updatePositions (newY);
  1187. newY += i->totalHeight;
  1188. totalHeight += i->totalHeight;
  1189. totalWidth = jmax (totalWidth, i->totalWidth);
  1190. }
  1191. }
  1192. }
  1193. TreeViewItem* TreeViewItem::getDeepestOpenParentItem() noexcept
  1194. {
  1195. TreeViewItem* result = this;
  1196. TreeViewItem* item = this;
  1197. while (item->parentItem != nullptr)
  1198. {
  1199. item = item->parentItem;
  1200. if (! item->isOpen())
  1201. result = item;
  1202. }
  1203. return result;
  1204. }
  1205. void TreeViewItem::setOwnerView (TreeView* const newOwner) noexcept
  1206. {
  1207. ownerView = newOwner;
  1208. for (auto* i : subItems)
  1209. {
  1210. i->setOwnerView (newOwner);
  1211. i->ownerViewChanged (newOwner);
  1212. }
  1213. }
  1214. int TreeViewItem::getIndentX() const noexcept
  1215. {
  1216. int x = ownerView->rootItemVisible ? 1 : 0;
  1217. if (! ownerView->openCloseButtonsVisible)
  1218. --x;
  1219. for (auto* p = parentItem; p != nullptr; p = p->parentItem)
  1220. ++x;
  1221. return x * ownerView->getIndentSize();
  1222. }
  1223. void TreeViewItem::setDrawsInLeftMargin (bool canDrawInLeftMargin) noexcept
  1224. {
  1225. drawsInLeftMargin = canDrawInLeftMargin;
  1226. }
  1227. void TreeViewItem::setDrawsInRightMargin (bool canDrawInRightMargin) noexcept
  1228. {
  1229. drawsInRightMargin = canDrawInRightMargin;
  1230. }
  1231. namespace TreeViewHelpers
  1232. {
  1233. static int calculateDepth (const TreeViewItem* item, const bool rootIsVisible) noexcept
  1234. {
  1235. jassert (item != nullptr);
  1236. int depth = rootIsVisible ? 0 : -1;
  1237. for (auto* p = item->getParentItem(); p != nullptr; p = p->getParentItem())
  1238. ++depth;
  1239. return depth;
  1240. }
  1241. }
  1242. bool TreeViewItem::areLinesDrawn() const
  1243. {
  1244. return drawLinesSet ? drawLinesInside
  1245. : (ownerView != nullptr && ownerView->getLookAndFeel().areLinesDrawnForTreeView (*ownerView));
  1246. }
  1247. void TreeViewItem::paintRecursively (Graphics& g, int width)
  1248. {
  1249. jassert (ownerView != nullptr);
  1250. if (ownerView == nullptr)
  1251. return;
  1252. auto indent = getIndentX();
  1253. auto itemW = (itemWidth < 0 || drawsInRightMargin) ? width - indent : itemWidth;
  1254. {
  1255. Graphics::ScopedSaveState ss (g);
  1256. g.setOrigin (indent, 0);
  1257. if (g.reduceClipRegion (drawsInLeftMargin ? -indent : 0, 0,
  1258. drawsInLeftMargin ? itemW + indent : itemW, itemHeight))
  1259. {
  1260. if (isSelected())
  1261. g.fillAll (ownerView->findColour (TreeView::selectedItemBackgroundColourId));
  1262. else
  1263. g.fillAll ((getRowNumberInTree() % 2 == 0) ? ownerView->findColour (TreeView::oddItemsColourId)
  1264. : ownerView->findColour (TreeView::evenItemsColourId));
  1265. paintItem (g, itemWidth < 0 ? width - indent : itemWidth, itemHeight);
  1266. }
  1267. }
  1268. auto halfH = itemHeight * 0.5f;
  1269. auto indentWidth = ownerView->getIndentSize();
  1270. auto depth = TreeViewHelpers::calculateDepth (this, ownerView->rootItemVisible);
  1271. if (depth >= 0 && ownerView->openCloseButtonsVisible)
  1272. {
  1273. auto x = (depth + 0.5f) * indentWidth;
  1274. const bool parentLinesDrawn = parentItem != nullptr && parentItem->areLinesDrawn();
  1275. if (parentLinesDrawn)
  1276. paintVerticalConnectingLine (g, Line<float> (x, 0, x, isLastOfSiblings() ? halfH : (float) itemHeight));
  1277. if (parentLinesDrawn || (parentItem == nullptr && areLinesDrawn()))
  1278. paintHorizontalConnectingLine (g, Line<float> (x, halfH, x + indentWidth / 2, halfH));
  1279. {
  1280. auto* p = parentItem;
  1281. int d = depth;
  1282. while (p != nullptr && --d >= 0)
  1283. {
  1284. x -= (float) indentWidth;
  1285. if ((p->parentItem == nullptr || p->parentItem->areLinesDrawn()) && ! p->isLastOfSiblings())
  1286. p->paintVerticalConnectingLine (g, Line<float> (x, 0, x, (float) itemHeight));
  1287. p = p->parentItem;
  1288. }
  1289. }
  1290. if (mightContainSubItems())
  1291. {
  1292. auto backgroundColour = ownerView->findColour (TreeView::backgroundColourId);
  1293. paintOpenCloseButton (g, Rectangle<float> ((float) (depth * indentWidth), 0, (float) indentWidth, (float) itemHeight),
  1294. backgroundColour.isTransparent() ? Colours::white : backgroundColour,
  1295. ownerView->viewport->getContentComp()->isMouseOverButton (this));
  1296. }
  1297. }
  1298. if (isOpen())
  1299. {
  1300. auto clip = g.getClipBounds();
  1301. for (auto* ti : subItems)
  1302. {
  1303. auto relY = ti->y - y;
  1304. if (relY >= clip.getBottom())
  1305. break;
  1306. if (relY + ti->totalHeight >= clip.getY())
  1307. {
  1308. Graphics::ScopedSaveState ss (g);
  1309. g.setOrigin (0, relY);
  1310. if (g.reduceClipRegion (0, 0, width, ti->totalHeight))
  1311. ti->paintRecursively (g, width);
  1312. }
  1313. }
  1314. }
  1315. }
  1316. bool TreeViewItem::isLastOfSiblings() const noexcept
  1317. {
  1318. return parentItem == nullptr
  1319. || parentItem->subItems.getLast() == this;
  1320. }
  1321. int TreeViewItem::getIndexInParent() const noexcept
  1322. {
  1323. return parentItem == nullptr ? 0
  1324. : parentItem->subItems.indexOf (this);
  1325. }
  1326. TreeViewItem* TreeViewItem::getTopLevelItem() noexcept
  1327. {
  1328. return parentItem == nullptr ? this
  1329. : parentItem->getTopLevelItem();
  1330. }
  1331. int TreeViewItem::getNumRows() const noexcept
  1332. {
  1333. int num = 1;
  1334. if (isOpen())
  1335. for (auto* i : subItems)
  1336. num += i->getNumRows();
  1337. return num;
  1338. }
  1339. TreeViewItem* TreeViewItem::getItemOnRow (int index) noexcept
  1340. {
  1341. if (index == 0)
  1342. return this;
  1343. if (index > 0 && isOpen())
  1344. {
  1345. --index;
  1346. for (auto* i : subItems)
  1347. {
  1348. if (index == 0)
  1349. return i;
  1350. auto numRows = i->getNumRows();
  1351. if (numRows > index)
  1352. return i->getItemOnRow (index);
  1353. index -= numRows;
  1354. }
  1355. }
  1356. return nullptr;
  1357. }
  1358. TreeViewItem* TreeViewItem::findItemRecursively (int targetY) noexcept
  1359. {
  1360. if (isPositiveAndBelow (targetY, totalHeight))
  1361. {
  1362. auto h = itemHeight;
  1363. if (targetY < h)
  1364. return this;
  1365. if (isOpen())
  1366. {
  1367. targetY -= h;
  1368. for (auto* i : subItems)
  1369. {
  1370. if (targetY < i->totalHeight)
  1371. return i->findItemRecursively (targetY);
  1372. targetY -= i->totalHeight;
  1373. }
  1374. }
  1375. }
  1376. return nullptr;
  1377. }
  1378. int TreeViewItem::countSelectedItemsRecursively (int depth) const noexcept
  1379. {
  1380. int total = isSelected() ? 1 : 0;
  1381. if (depth != 0)
  1382. for (auto* i : subItems)
  1383. total += i->countSelectedItemsRecursively (depth - 1);
  1384. return total;
  1385. }
  1386. TreeViewItem* TreeViewItem::getSelectedItemWithIndex (int index) noexcept
  1387. {
  1388. if (isSelected())
  1389. {
  1390. if (index == 0)
  1391. return this;
  1392. --index;
  1393. }
  1394. if (index >= 0)
  1395. {
  1396. for (auto* i : subItems)
  1397. {
  1398. if (auto* found = i->getSelectedItemWithIndex (index))
  1399. return found;
  1400. index -= i->countSelectedItemsRecursively (-1);
  1401. }
  1402. }
  1403. return nullptr;
  1404. }
  1405. int TreeViewItem::getRowNumberInTree() const noexcept
  1406. {
  1407. if (parentItem != nullptr && ownerView != nullptr)
  1408. {
  1409. if (! parentItem->isOpen())
  1410. return parentItem->getRowNumberInTree();
  1411. int n = 1 + parentItem->getRowNumberInTree();
  1412. int ourIndex = parentItem->subItems.indexOf (this);
  1413. jassert (ourIndex >= 0);
  1414. while (--ourIndex >= 0)
  1415. n += parentItem->subItems [ourIndex]->getNumRows();
  1416. if (parentItem->parentItem == nullptr
  1417. && ! ownerView->rootItemVisible)
  1418. --n;
  1419. return n;
  1420. }
  1421. return 0;
  1422. }
  1423. void TreeViewItem::setLinesDrawnForSubItems (const bool drawLines) noexcept
  1424. {
  1425. drawLinesInside = drawLines;
  1426. drawLinesSet = true;
  1427. }
  1428. TreeViewItem* TreeViewItem::getNextVisibleItem (const bool recurse) const noexcept
  1429. {
  1430. if (recurse && isOpen() && ! subItems.isEmpty())
  1431. return subItems.getFirst();
  1432. if (parentItem != nullptr)
  1433. {
  1434. const int nextIndex = parentItem->subItems.indexOf (this) + 1;
  1435. if (nextIndex >= parentItem->subItems.size())
  1436. return parentItem->getNextVisibleItem (false);
  1437. return parentItem->subItems [nextIndex];
  1438. }
  1439. return nullptr;
  1440. }
  1441. static String escapeSlashesInTreeViewItemName (const String& s)
  1442. {
  1443. return s.replaceCharacter ('/', '\\');
  1444. }
  1445. String TreeViewItem::getItemIdentifierString() const
  1446. {
  1447. String s;
  1448. if (parentItem != nullptr)
  1449. s = parentItem->getItemIdentifierString();
  1450. return s + "/" + escapeSlashesInTreeViewItemName (getUniqueName());
  1451. }
  1452. TreeViewItem* TreeViewItem::findItemFromIdentifierString (const String& identifierString)
  1453. {
  1454. auto thisId = "/" + escapeSlashesInTreeViewItemName (getUniqueName());
  1455. if (thisId == identifierString)
  1456. return this;
  1457. if (identifierString.startsWith (thisId + "/"))
  1458. {
  1459. auto remainingPath = identifierString.substring (thisId.length());
  1460. const bool wasOpen = isOpen();
  1461. setOpen (true);
  1462. for (auto* i : subItems)
  1463. if (auto* item = i->findItemFromIdentifierString (remainingPath))
  1464. return item;
  1465. setOpen (wasOpen);
  1466. }
  1467. return nullptr;
  1468. }
  1469. void TreeViewItem::restoreOpennessState (const XmlElement& e)
  1470. {
  1471. if (e.hasTagName ("CLOSED"))
  1472. {
  1473. setOpen (false);
  1474. }
  1475. else if (e.hasTagName ("OPEN"))
  1476. {
  1477. setOpen (true);
  1478. Array<TreeViewItem*> items;
  1479. items.addArray (subItems);
  1480. forEachXmlChildElement (e, n)
  1481. {
  1482. auto id = n->getStringAttribute ("id");
  1483. for (int i = 0; i < items.size(); ++i)
  1484. {
  1485. auto* ti = items.getUnchecked(i);
  1486. if (ti->getUniqueName() == id)
  1487. {
  1488. ti->restoreOpennessState (*n);
  1489. items.remove (i);
  1490. break;
  1491. }
  1492. }
  1493. }
  1494. // for any items that weren't mentioned in the XML, reset them to default:
  1495. for (auto* i : items)
  1496. i->restoreToDefaultOpenness();
  1497. }
  1498. }
  1499. std::unique_ptr<XmlElement> TreeViewItem::getOpennessState() const
  1500. {
  1501. return std::unique_ptr<XmlElement> (getOpennessState (true));
  1502. }
  1503. XmlElement* TreeViewItem::getOpennessState (bool canReturnNull) const
  1504. {
  1505. auto name = getUniqueName();
  1506. if (name.isNotEmpty())
  1507. {
  1508. XmlElement* e;
  1509. if (isOpen())
  1510. {
  1511. if (canReturnNull && ownerView != nullptr && ownerView->defaultOpenness && isFullyOpen())
  1512. return nullptr;
  1513. e = new XmlElement ("OPEN");
  1514. for (int i = subItems.size(); --i >= 0;)
  1515. e->prependChildElement (subItems.getUnchecked(i)->getOpennessState (true));
  1516. }
  1517. else
  1518. {
  1519. if (canReturnNull && ownerView != nullptr && ! ownerView->defaultOpenness)
  1520. return nullptr;
  1521. e = new XmlElement ("CLOSED");
  1522. }
  1523. e->setAttribute ("id", name);
  1524. return e;
  1525. }
  1526. // trying to save the openness for an element that has no name - this won't
  1527. // work because it needs the names to identify what to open.
  1528. jassertfalse;
  1529. return nullptr;
  1530. }
  1531. //==============================================================================
  1532. TreeViewItem::OpennessRestorer::OpennessRestorer (TreeViewItem& item)
  1533. : treeViewItem (item),
  1534. oldOpenness (item.getOpennessState())
  1535. {
  1536. }
  1537. TreeViewItem::OpennessRestorer::~OpennessRestorer()
  1538. {
  1539. if (oldOpenness != nullptr)
  1540. treeViewItem.restoreOpennessState (*oldOpenness);
  1541. }
  1542. } // namespace juce