TreeView.cs 52 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601
  1. // This code is based on http://objectlistview.sourceforge.net (GPLv3 tree/list controls
  2. // by [email protected]). Phillip has explicitly granted permission for his design
  3. // and code to be used in this library under the MIT license.
  4. using System.Collections.ObjectModel;
  5. namespace Terminal.Gui;
  6. /// <summary>
  7. /// Interface for all non-generic members of <see cref="TreeView{T}"/>.
  8. /// <a href="../docs/treeview.md">See TreeView Deep Dive for more information</a>.
  9. /// </summary>
  10. public interface ITreeView
  11. {
  12. /// <summary>Contains options for changing how the tree is rendered.</summary>
  13. TreeStyle Style { get; set; }
  14. /// <summary>Removes all objects from the tree and clears selection.</summary>
  15. void ClearObjects ();
  16. /// <summary>Sets a flag indicating this view needs to be redisplayed because its state has changed.</summary>
  17. void SetNeedsDisplay ();
  18. }
  19. /// <summary>
  20. /// Convenience implementation of generic <see cref="TreeView{T}"/> for any tree were all nodes implement
  21. /// <see cref="ITreeNode"/>. <a href="../docs/treeview.md">See TreeView Deep Dive for more information</a>.
  22. /// </summary>
  23. public class TreeView : TreeView<ITreeNode>
  24. {
  25. /// <summary>
  26. /// Creates a new instance of the tree control with absolute positioning and initialises
  27. /// <see cref="TreeBuilder{T}"/> with default <see cref="ITreeNode"/> based builder.
  28. /// </summary>
  29. public TreeView ()
  30. {
  31. CanFocus = true;
  32. TreeBuilder = new TreeNodeBuilder ();
  33. AspectGetter = o => o is null ? "Null" : o.Text ?? o?.ToString () ?? "Unnamed Node";
  34. }
  35. }
  36. /// <summary>
  37. /// Hierarchical tree view with expandable branches. Branch objects are dynamically determined when expanded using
  38. /// a user defined <see cref="ITreeBuilder{T}"/>.
  39. /// <a href="../docs/treeview.md">See TreeView Deep Dive for more information</a>.
  40. /// </summary>
  41. public class TreeView<T> : View, ITreeView where T : class
  42. {
  43. /// <summary>
  44. /// Error message to display when the control is not properly initialized at draw time (nodes added but no tree
  45. /// builder set).
  46. /// </summary>
  47. public static string NoBuilderError = "ERROR: TreeBuilder Not Set";
  48. /// <summary>
  49. /// Interface for filtering which lines of the tree are displayed e.g. to provide text searching. Defaults to
  50. /// <see langword="null"/> (no filtering).
  51. /// </summary>
  52. public ITreeViewFilter<T> Filter = null;
  53. /// <summary>Secondary selected regions of tree when <see cref="MultiSelect"/> is true.</summary>
  54. private readonly Stack<TreeSelection<T>> multiSelectedRegions = new ();
  55. /// <summary>Cached result of <see cref="BuildLineMap"/></summary>
  56. private IReadOnlyCollection<Branch<T>> cachedLineMap;
  57. private KeyCode objectActivationKey = KeyCode.Enter;
  58. private int scrollOffsetHorizontal;
  59. private int scrollOffsetVertical;
  60. /// <summary>private variable for <see cref="SelectedObject"/></summary>
  61. private T selectedObject;
  62. /// <summary>
  63. /// Creates a new tree view with absolute positioning. Use <see cref="AddObjects(IEnumerable{T})"/> to set
  64. /// root objects for the tree. Children will not be rendered until you set <see cref="TreeBuilder"/>.
  65. /// </summary>
  66. public TreeView ()
  67. {
  68. CanFocus = true;
  69. // Things this view knows how to do
  70. AddCommand (
  71. Command.PageUp,
  72. () =>
  73. {
  74. MovePageUp ();
  75. return true;
  76. }
  77. );
  78. AddCommand (
  79. Command.PageDown,
  80. () =>
  81. {
  82. MovePageDown ();
  83. return true;
  84. }
  85. );
  86. AddCommand (
  87. Command.PageUpExtend,
  88. () =>
  89. {
  90. MovePageUp (true);
  91. return true;
  92. }
  93. );
  94. AddCommand (
  95. Command.PageDownExtend,
  96. () =>
  97. {
  98. MovePageDown (true);
  99. return true;
  100. }
  101. );
  102. AddCommand (
  103. Command.Expand,
  104. () =>
  105. {
  106. Expand ();
  107. return true;
  108. }
  109. );
  110. AddCommand (
  111. Command.ExpandAll,
  112. () =>
  113. {
  114. ExpandAll (SelectedObject);
  115. return true;
  116. }
  117. );
  118. AddCommand (
  119. Command.Collapse,
  120. () =>
  121. {
  122. CursorLeft (false);
  123. return true;
  124. }
  125. );
  126. AddCommand (
  127. Command.CollapseAll,
  128. () =>
  129. {
  130. CursorLeft (true);
  131. return true;
  132. }
  133. );
  134. AddCommand (
  135. Command.Up,
  136. () =>
  137. {
  138. AdjustSelection (-1);
  139. return true;
  140. }
  141. );
  142. AddCommand (
  143. Command.UpExtend,
  144. () =>
  145. {
  146. AdjustSelection (-1, true);
  147. return true;
  148. }
  149. );
  150. AddCommand (
  151. Command.LineUpToFirstBranch,
  152. () =>
  153. {
  154. AdjustSelectionToBranchStart ();
  155. return true;
  156. }
  157. );
  158. AddCommand (
  159. Command.Down,
  160. () =>
  161. {
  162. AdjustSelection (1);
  163. return true;
  164. }
  165. );
  166. AddCommand (
  167. Command.DownExtend,
  168. () =>
  169. {
  170. AdjustSelection (1, true);
  171. return true;
  172. }
  173. );
  174. AddCommand (
  175. Command.LineDownToLastBranch,
  176. () =>
  177. {
  178. AdjustSelectionToBranchEnd ();
  179. return true;
  180. }
  181. );
  182. AddCommand (
  183. Command.Start,
  184. () =>
  185. {
  186. GoToFirst ();
  187. return true;
  188. }
  189. );
  190. AddCommand (
  191. Command.End,
  192. () =>
  193. {
  194. GoToEnd ();
  195. return true;
  196. }
  197. );
  198. AddCommand (
  199. Command.SelectAll,
  200. () =>
  201. {
  202. SelectAll ();
  203. return true;
  204. }
  205. );
  206. AddCommand (
  207. Command.ScrollUp,
  208. () =>
  209. {
  210. ScrollUp ();
  211. return true;
  212. }
  213. );
  214. AddCommand (
  215. Command.ScrollDown,
  216. () =>
  217. {
  218. ScrollDown ();
  219. return true;
  220. }
  221. );
  222. AddCommand (Command.Select, ActivateSelectedObjectIfAny);
  223. AddCommand (Command.Accept, ActivateSelectedObjectIfAny);
  224. // Default keybindings for this view
  225. KeyBindings.Add (Key.PageUp, Command.PageUp);
  226. KeyBindings.Add (Key.PageDown, Command.PageDown);
  227. KeyBindings.Add (Key.PageUp.WithShift, Command.PageUpExtend);
  228. KeyBindings.Add (Key.PageDown.WithShift, Command.PageDownExtend);
  229. KeyBindings.Add (Key.CursorRight, Command.Expand);
  230. KeyBindings.Add (Key.CursorRight.WithCtrl, Command.ExpandAll);
  231. KeyBindings.Add (Key.CursorLeft, Command.Collapse);
  232. KeyBindings.Add (Key.CursorLeft.WithCtrl, Command.CollapseAll);
  233. KeyBindings.Add (Key.CursorUp, Command.Up);
  234. KeyBindings.Add (Key.CursorUp.WithShift, Command.UpExtend);
  235. KeyBindings.Add (Key.CursorUp.WithCtrl, Command.LineUpToFirstBranch);
  236. KeyBindings.Add (Key.CursorDown, Command.Down);
  237. KeyBindings.Add (Key.CursorDown.WithShift, Command.DownExtend);
  238. KeyBindings.Add (Key.CursorDown.WithCtrl, Command.LineDownToLastBranch);
  239. KeyBindings.Add (Key.Home, Command.Start);
  240. KeyBindings.Add (Key.End, Command.End);
  241. KeyBindings.Add (Key.A.WithCtrl, Command.SelectAll);
  242. KeyBindings.Add (ObjectActivationKey, Command.Select);
  243. }
  244. /// <summary>
  245. /// Initialises <see cref="TreeBuilder"/>.Creates a new tree view with absolute positioning. Use
  246. /// <see cref="AddObjects(IEnumerable{T})"/> to set root objects for the tree.
  247. /// </summary>
  248. public TreeView (ITreeBuilder<T> builder) : this () { TreeBuilder = builder; }
  249. /// <summary>True makes a letter key press navigate to the next visible branch that begins with that letter/digit.</summary>
  250. /// <value></value>
  251. public bool AllowLetterBasedNavigation { get; set; } = true;
  252. /// <summary>
  253. /// Returns the string representation of model objects hosted in the tree. Default implementation is to call
  254. /// <see cref="object.ToString"/>.
  255. /// </summary>
  256. /// <value></value>
  257. public AspectGetterDelegate<T> AspectGetter { get; set; } = o => o.ToString () ?? "";
  258. /// <summary>
  259. /// Delegate for multi-colored tree views. Return the <see cref="ColorScheme"/> to use for each passed object or
  260. /// null to use the default.
  261. /// </summary>
  262. public Func<T, ColorScheme> ColorGetter { get; set; }
  263. /// <summary>The current number of rows in the tree (ignoring the controls bounds).</summary>
  264. public int ContentHeight => BuildLineMap ().Count ();
  265. /// <summary>
  266. /// Gets the <see cref="CollectionNavigator"/> that searches the <see cref="Objects"/> collection as the user
  267. /// types.
  268. /// </summary>
  269. public CollectionNavigator KeystrokeNavigator { get; } = new ();
  270. /// <summary>Maximum number of nodes that can be expanded in any given branch.</summary>
  271. public int MaxDepth { get; set; } = 100;
  272. /// <summary>True to allow multiple objects to be selected at once.</summary>
  273. /// <value></value>
  274. public bool MultiSelect { get; set; } = true;
  275. /// <summary>
  276. /// Mouse event to trigger <see cref="TreeView{T}.ObjectActivated"/>. Defaults to double click (
  277. /// <see cref="MouseFlags.Button1DoubleClicked"/>). Set to null to disable this feature.
  278. /// </summary>
  279. /// <value></value>
  280. public MouseFlags? ObjectActivationButton { get; set; } = MouseFlags.Button1DoubleClicked;
  281. // TODO: Update to use Key instead of KeyCode
  282. /// <summary>Key which when pressed triggers <see cref="TreeView{T}.ObjectActivated"/>. Defaults to Enter.</summary>
  283. public KeyCode ObjectActivationKey
  284. {
  285. get => objectActivationKey;
  286. set
  287. {
  288. if (objectActivationKey != value)
  289. {
  290. KeyBindings.ReplaceKey (ObjectActivationKey, value);
  291. objectActivationKey = value;
  292. SetNeedsDisplay ();
  293. }
  294. }
  295. }
  296. /// <summary>The root objects in the tree, note that this collection is of root objects only.</summary>
  297. public IEnumerable<T> Objects => roots.Keys;
  298. /// <summary>The amount of tree view that has been scrolled to the right (horizontally).</summary>
  299. /// <remarks>
  300. /// Setting a value of less than 0 will result in a offset of 0. To see changes in the UI call
  301. /// <see cref="View.SetNeedsDisplay()"/>.
  302. /// </remarks>
  303. public int ScrollOffsetHorizontal
  304. {
  305. get => scrollOffsetHorizontal;
  306. set
  307. {
  308. scrollOffsetHorizontal = Math.Max (0, value);
  309. SetNeedsDisplay ();
  310. }
  311. }
  312. /// <summary>The amount of tree view that has been scrolled off the top of the screen (by the user scrolling down).</summary>
  313. /// <remarks>
  314. /// Setting a value of less than 0 will result in an offset of 0. To see changes in the UI call
  315. /// <see cref="View.SetNeedsDisplay()"/>.
  316. /// </remarks>
  317. public int ScrollOffsetVertical
  318. {
  319. get => scrollOffsetVertical;
  320. set
  321. {
  322. scrollOffsetVertical = Math.Max (0, value);
  323. SetNeedsDisplay ();
  324. }
  325. }
  326. /// <summary>
  327. /// The currently selected object in the tree. When <see cref="MultiSelect"/> is true this is the object at which
  328. /// the cursor is at.
  329. /// </summary>
  330. public T SelectedObject
  331. {
  332. get => selectedObject;
  333. set
  334. {
  335. T oldValue = selectedObject;
  336. selectedObject = value;
  337. if (!ReferenceEquals (oldValue, value))
  338. {
  339. OnSelectionChanged (new SelectionChangedEventArgs<T> (this, oldValue, value));
  340. }
  341. }
  342. }
  343. /// <summary>Determines how sub-branches of the tree are dynamically built at runtime as the user expands root nodes.</summary>
  344. /// <value></value>
  345. public ITreeBuilder<T> TreeBuilder { get; set; }
  346. /// <summary>
  347. /// Map of root objects to the branches under them. All objects have a <see cref="Branch{T}"/> even if that branch
  348. /// has no children.
  349. /// </summary>
  350. internal Dictionary<T, Branch<T>> roots { get; set; } = new ();
  351. /// <summary>Contains options for changing how the tree is rendered.</summary>
  352. public TreeStyle Style { get; set; } = new ();
  353. /// <summary>Removes all objects from the tree and clears <see cref="SelectedObject"/>.</summary>
  354. public void ClearObjects ()
  355. {
  356. SelectedObject = default (T);
  357. multiSelectedRegions.Clear ();
  358. roots = new Dictionary<T, Branch<T>> ();
  359. InvalidateLineMap ();
  360. SetNeedsDisplay ();
  361. }
  362. /// <summary>
  363. /// <para>Triggers the <see cref="ObjectActivated"/> event with the <see cref="SelectedObject"/>.</para>
  364. /// <para>This method also ensures that the selected object is visible.</para>
  365. /// </summary>
  366. /// <returns><see langword="true"/> if <see cref="ObjectActivated"/> was fired.</returns>
  367. public bool? ActivateSelectedObjectIfAny ()
  368. {
  369. // By default, Command.Accept calls OnAccept, so we need to call it here to ensure that the event is fired.
  370. if (RaiseAcceptEvent () == true)
  371. {
  372. return true;
  373. }
  374. T o = SelectedObject;
  375. if (o is { })
  376. {
  377. // TODO: Should this be cancelable?
  378. ObjectActivatedEventArgs<T> e = new (this, o);
  379. OnObjectActivated (e);
  380. return true;
  381. }
  382. return false;
  383. }
  384. /// <summary>Adds a new root level object unless it is already a root of the tree.</summary>
  385. /// <param name="o"></param>
  386. public void AddObject (T o)
  387. {
  388. if (!roots.ContainsKey (o))
  389. {
  390. roots.Add (o, new Branch<T> (this, null, o));
  391. InvalidateLineMap ();
  392. SetNeedsDisplay ();
  393. }
  394. }
  395. /// <summary>Adds many new root level objects. Objects that are already root objects are ignored.</summary>
  396. /// <param name="collection">Objects to add as new root level objects.</param>
  397. /// .\
  398. public void AddObjects (IEnumerable<T> collection)
  399. {
  400. var objectsAdded = false;
  401. foreach (T o in collection)
  402. {
  403. if (!roots.ContainsKey (o))
  404. {
  405. roots.Add (o, new Branch<T> (this, null, o));
  406. objectsAdded = true;
  407. }
  408. }
  409. if (objectsAdded)
  410. {
  411. InvalidateLineMap ();
  412. SetNeedsDisplay ();
  413. }
  414. }
  415. /// <summary>
  416. /// The number of screen lines to move the currently selected object by. Supports negative values.
  417. /// <paramref name="offset"/>. Each branch occupies 1 line on screen.
  418. /// </summary>
  419. /// <remarks>
  420. /// If nothing is currently selected or the selected object is no longer in the tree then the first object in the
  421. /// tree is selected instead.
  422. /// </remarks>
  423. /// <param name="offset">Positive to move the selection down the screen, negative to move it up</param>
  424. /// <param name="expandSelection">
  425. /// True to expand the selection (assuming <see cref="MultiSelect"/> is enabled). False to
  426. /// replace.
  427. /// </param>
  428. public void AdjustSelection (int offset, bool expandSelection = false)
  429. {
  430. // if it is not a shift click, or we don't allow multi select
  431. if (!expandSelection || !MultiSelect)
  432. {
  433. multiSelectedRegions.Clear ();
  434. }
  435. if (SelectedObject is null)
  436. {
  437. SelectedObject = roots.Keys.FirstOrDefault ();
  438. }
  439. else
  440. {
  441. IReadOnlyCollection<Branch<T>> map = BuildLineMap ();
  442. int idx = map.IndexOf (b => b.Model.Equals (SelectedObject));
  443. if (idx == -1)
  444. {
  445. // The current selection has disappeared!
  446. SelectedObject = roots.Keys.FirstOrDefault ();
  447. }
  448. else
  449. {
  450. int newIdx = Math.Min (Math.Max (0, idx + offset), map.Count - 1);
  451. Branch<T> newBranch = map.ElementAt (newIdx);
  452. // If it is a multi selection
  453. if (expandSelection && MultiSelect)
  454. {
  455. if (multiSelectedRegions.Any ())
  456. {
  457. // expand the existing head selection
  458. TreeSelection<T> head = multiSelectedRegions.Pop ();
  459. multiSelectedRegions.Push (new TreeSelection<T> (head.Origin, newIdx, map));
  460. }
  461. else
  462. {
  463. // or start a new multi selection region
  464. multiSelectedRegions.Push (new TreeSelection<T> (map.ElementAt (idx), newIdx, map));
  465. }
  466. }
  467. SelectedObject = newBranch.Model;
  468. EnsureVisible (SelectedObject);
  469. }
  470. }
  471. SetNeedsDisplay ();
  472. }
  473. /// <summary>Moves the selection to the last child in the currently selected level.</summary>
  474. public void AdjustSelectionToBranchEnd ()
  475. {
  476. T o = SelectedObject;
  477. if (o is null)
  478. {
  479. return;
  480. }
  481. IReadOnlyCollection<Branch<T>> map = BuildLineMap ();
  482. int currentIdx = map.IndexOf (b => Equals (b.Model, o));
  483. if (currentIdx == -1)
  484. {
  485. return;
  486. }
  487. Branch<T> currentBranch = map.ElementAt (currentIdx);
  488. Branch<T> next = currentBranch;
  489. for (; currentIdx < map.Count; currentIdx++)
  490. {
  491. //if it is the end of the current depth of branch
  492. if (currentBranch.Depth != next.Depth)
  493. {
  494. SelectedObject = currentBranch.Model;
  495. EnsureVisible (currentBranch.Model);
  496. SetNeedsDisplay ();
  497. return;
  498. }
  499. // look at next branch for consideration
  500. currentBranch = next;
  501. next = map.ElementAt (currentIdx);
  502. }
  503. GoToEnd ();
  504. }
  505. /// <summary>Moves the selection to the first child in the currently selected level.</summary>
  506. public void AdjustSelectionToBranchStart ()
  507. {
  508. T o = SelectedObject;
  509. if (o is null)
  510. {
  511. return;
  512. }
  513. IReadOnlyCollection<Branch<T>> map = BuildLineMap ();
  514. int currentIdx = map.IndexOf (b => Equals (b.Model, o));
  515. if (currentIdx == -1)
  516. {
  517. return;
  518. }
  519. Branch<T> currentBranch = map.ElementAt (currentIdx);
  520. Branch<T> next = currentBranch;
  521. for (; currentIdx >= 0; currentIdx--)
  522. {
  523. //if it is the beginning of the current depth of branch
  524. if (currentBranch.Depth != next.Depth)
  525. {
  526. SelectedObject = currentBranch.Model;
  527. EnsureVisible (currentBranch.Model);
  528. SetNeedsDisplay ();
  529. return;
  530. }
  531. // look at next branch up for consideration
  532. currentBranch = next;
  533. next = map.ElementAt (currentIdx);
  534. }
  535. // We ran all the way to top of tree
  536. GoToFirst ();
  537. }
  538. /// <summary>
  539. /// <para>Moves the <see cref="SelectedObject"/> to the next item that begins with <paramref name="character"/>.</para>
  540. /// <para>This method will loop back to the start of the tree if reaching the end without finding a match.</para>
  541. /// </summary>
  542. /// <param name="character">The first character of the next item you want selected.</param>
  543. /// <param name="caseSensitivity">Case sensitivity of the search.</param>
  544. public void AdjustSelectionToNextItemBeginningWith (
  545. char character,
  546. StringComparison caseSensitivity = StringComparison.CurrentCultureIgnoreCase
  547. )
  548. {
  549. // search for next branch that begins with that letter
  550. var characterAsStr = character.ToString ();
  551. AdjustSelectionToNext (b => AspectGetter (b.Model).StartsWith (characterAsStr, caseSensitivity));
  552. }
  553. /// <summary>
  554. /// Returns true if the given object <paramref name="o"/> is exposed in the tree and can be expanded otherwise
  555. /// false.
  556. /// </summary>
  557. /// <param name="o"></param>
  558. /// <returns></returns>
  559. public bool CanExpand (T o) { return ObjectToBranch (o)?.CanExpand () ?? false; }
  560. /// <summary>Collapses the <see cref="SelectedObject"/></summary>
  561. public void Collapse () { Collapse (selectedObject); }
  562. /// <summary>Collapses the supplied object if it is currently expanded .</summary>
  563. /// <param name="toCollapse">The object to collapse.</param>
  564. public void Collapse (T toCollapse) { CollapseImpl (toCollapse, false); }
  565. /// <summary>
  566. /// Collapses the supplied object if it is currently expanded. Also collapses all children branches (this will
  567. /// only become apparent when/if the user expands it again).
  568. /// </summary>
  569. /// <param name="toCollapse">The object to collapse.</param>
  570. public void CollapseAll (T toCollapse) { CollapseImpl (toCollapse, true); }
  571. /// <summary>Collapses all root nodes in the tree.</summary>
  572. public void CollapseAll ()
  573. {
  574. foreach (KeyValuePair<T, Branch<T>> item in roots)
  575. {
  576. item.Value.Collapse ();
  577. }
  578. InvalidateLineMap ();
  579. SetNeedsDisplay ();
  580. }
  581. /// <summary>
  582. /// Called once for each visible row during rendering. Can be used to make last minute changes to color or text
  583. /// rendered
  584. /// </summary>
  585. public event EventHandler<DrawTreeViewLineEventArgs<T>> DrawLine;
  586. /// <summary>
  587. /// Adjusts the <see cref="ScrollOffsetVertical"/> to ensure the given <paramref name="model"/> is visible. Has no
  588. /// effect if already visible.
  589. /// </summary>
  590. public void EnsureVisible (T model)
  591. {
  592. IReadOnlyCollection<Branch<T>> map = BuildLineMap ();
  593. int idx = map.IndexOf (b => Equals (b.Model, model));
  594. if (idx == -1)
  595. {
  596. return;
  597. }
  598. /*this -1 allows for possible horizontal scroll bar in the last row of the control*/
  599. int leaveSpace = Style.LeaveLastRow ? 1 : 0;
  600. if (idx < ScrollOffsetVertical)
  601. {
  602. //if user has scrolled up too far to see their selection
  603. ScrollOffsetVertical = idx;
  604. }
  605. else if (idx >= ScrollOffsetVertical + Viewport.Height - leaveSpace)
  606. {
  607. //if user has scrolled off bottom of visible tree
  608. ScrollOffsetVertical = Math.Max (0, idx + 1 - (Viewport.Height - leaveSpace));
  609. }
  610. }
  611. /// <summary>Expands the currently <see cref="SelectedObject"/>.</summary>
  612. public void Expand () { Expand (SelectedObject); }
  613. /// <summary>
  614. /// Expands the supplied object if it is contained in the tree (either as a root object or as an exposed branch
  615. /// object).
  616. /// </summary>
  617. /// <param name="toExpand">The object to expand.</param>
  618. public void Expand (T toExpand)
  619. {
  620. if (toExpand is null)
  621. {
  622. return;
  623. }
  624. ObjectToBranch (toExpand)?.Expand ();
  625. InvalidateLineMap ();
  626. SetNeedsDisplay ();
  627. }
  628. /// <summary>Expands the supplied object and all child objects.</summary>
  629. /// <param name="toExpand">The object to expand.</param>
  630. public void ExpandAll (T toExpand)
  631. {
  632. if (toExpand is null)
  633. {
  634. return;
  635. }
  636. ObjectToBranch (toExpand)?.ExpandAll ();
  637. InvalidateLineMap ();
  638. SetNeedsDisplay ();
  639. }
  640. /// <summary>
  641. /// Fully expands all nodes in the tree, if the tree is very big and built dynamically this may take a while (e.g.
  642. /// for file system).
  643. /// </summary>
  644. public void ExpandAll ()
  645. {
  646. foreach (KeyValuePair<T, Branch<T>> item in roots)
  647. {
  648. item.Value.ExpandAll ();
  649. }
  650. InvalidateLineMap ();
  651. SetNeedsDisplay ();
  652. }
  653. /// <summary>
  654. /// Returns <see cref="SelectedObject"/> (if not null) and all multi selected objects if <see cref="MultiSelect"/>
  655. /// is true
  656. /// </summary>
  657. /// <returns></returns>
  658. public IEnumerable<T> GetAllSelectedObjects ()
  659. {
  660. IReadOnlyCollection<Branch<T>> map = BuildLineMap ();
  661. // To determine multi selected objects, start with the line map, that avoids yielding
  662. // hidden nodes that were selected then the parent collapsed e.g. programmatically or
  663. // with mouse click
  664. if (MultiSelect)
  665. {
  666. foreach (T m in map.Select (b => b.Model).Where (IsSelected))
  667. {
  668. yield return m;
  669. }
  670. }
  671. else
  672. {
  673. if (SelectedObject is { })
  674. {
  675. yield return SelectedObject;
  676. }
  677. }
  678. }
  679. /// <summary>
  680. /// Returns the currently expanded children of the passed object. Returns an empty collection if the branch is not
  681. /// exposed or not expanded.
  682. /// </summary>
  683. /// <param name="o">An object in the tree.</param>
  684. /// <returns></returns>
  685. public IEnumerable<T> GetChildren (T o)
  686. {
  687. Branch<T> branch = ObjectToBranch (o);
  688. if (branch is null || !branch.IsExpanded)
  689. {
  690. return new T [0];
  691. }
  692. return branch.ChildBranches?.Values?.Select (b => b.Model)?.ToArray () ?? new T [0];
  693. }
  694. /// <summary>Returns the maximum width line in the tree including prefix and expansion symbols.</summary>
  695. /// <param name="visible">
  696. /// True to consider only rows currently visible (based on window bounds and
  697. /// <see cref="ScrollOffsetVertical"/>. False to calculate the width of every exposed branch in the tree.
  698. /// </param>
  699. /// <returns></returns>
  700. public int GetContentWidth (bool visible)
  701. {
  702. IReadOnlyCollection<Branch<T>> map = BuildLineMap ();
  703. if (map.Count == 0)
  704. {
  705. return 0;
  706. }
  707. if (visible)
  708. {
  709. //Somehow we managed to scroll off the end of the control
  710. if (ScrollOffsetVertical >= map.Count)
  711. {
  712. return 0;
  713. }
  714. // If control has no height to it then there is no visible area for content
  715. if (Viewport.Height == 0)
  716. {
  717. return 0;
  718. }
  719. return map.Skip (ScrollOffsetVertical).Take (Viewport.Height).Max (b => b.GetWidth (Driver));
  720. }
  721. return map.Max (b => b.GetWidth (Driver));
  722. }
  723. /// <summary>
  724. /// Returns the object in the tree list that is currently visible. at the provided row. Returns null if no object
  725. /// is at that location.
  726. /// <remarks></remarks>
  727. /// If you have screen coordinates then use <see cref="View.ScreenToFrame"/> to translate these into the client area of
  728. /// the <see cref="TreeView{T}"/>.
  729. /// </summary>
  730. /// <param name="row">The row of the <see cref="View.Viewport"/> of the <see cref="TreeView{T}"/>.</param>
  731. /// <returns>The object currently displayed on this row or null.</returns>
  732. public T GetObjectOnRow (int row) { return HitTest (row)?.Model; }
  733. /// <summary>
  734. /// <para>
  735. /// Returns the Y coordinate within the <see cref="View.Viewport"/> of the tree at which <paramref name="toFind"/>
  736. /// would be displayed or null if it is not currently exposed (e.g. its parent is collapsed).
  737. /// </para>
  738. /// <para>
  739. /// Note that the returned value can be negative if the TreeView is scrolled down and the
  740. /// <paramref name="toFind"/> object is off the top of the view.
  741. /// </para>
  742. /// </summary>
  743. /// <param name="toFind"></param>
  744. /// <returns></returns>
  745. public int? GetObjectRow (T toFind)
  746. {
  747. int idx = BuildLineMap ().IndexOf (o => o.Model.Equals (toFind));
  748. if (idx == -1)
  749. {
  750. return null;
  751. }
  752. return idx - ScrollOffsetVertical;
  753. }
  754. /// <summary>
  755. /// Returns the parent object of <paramref name="o"/> in the tree. Returns null if the object is not exposed in
  756. /// the tree.
  757. /// </summary>
  758. /// <param name="o">An object in the tree.</param>
  759. /// <returns></returns>
  760. public T GetParent (T o) { return ObjectToBranch (o)?.Parent?.Model; }
  761. /// <summary>
  762. /// Returns the index of the object <paramref name="o"/> if it is currently exposed (it's parent(s) have been
  763. /// expanded). This can be used with <see cref="ScrollOffsetVertical"/> and <see cref="View.SetNeedsDisplay()"/> to
  764. /// scroll to a specific object.
  765. /// </summary>
  766. /// <remarks>Uses the Equals method and returns the first index at which the object is found or -1 if it is not found.</remarks>
  767. /// <param name="o">An object that appears in your tree and is currently exposed.</param>
  768. /// <returns>The index the object was found at or -1 if it is not currently revealed or not in the tree at all.</returns>
  769. public int GetScrollOffsetOf (T o)
  770. {
  771. IReadOnlyCollection<Branch<T>> map = BuildLineMap ();
  772. for (var i = 0; i < map.Count; i++)
  773. {
  774. if (map.ElementAt (i).Model.Equals (o))
  775. {
  776. return i;
  777. }
  778. }
  779. //object not found
  780. return -1;
  781. }
  782. /// <summary>
  783. /// Changes the <see cref="SelectedObject"/> to <paramref name="toSelect"/> and scrolls to ensure it is visible.
  784. /// Has no effect if <paramref name="toSelect"/> is not exposed in the tree (e.g. its parents are collapsed).
  785. /// </summary>
  786. /// <param name="toSelect"></param>
  787. public void GoTo (T toSelect)
  788. {
  789. if (ObjectToBranch (toSelect) is null)
  790. {
  791. return;
  792. }
  793. SelectedObject = toSelect;
  794. EnsureVisible (toSelect);
  795. SetNeedsDisplay ();
  796. }
  797. /// <summary>Changes the <see cref="SelectedObject"/> to the last object in the tree and scrolls so that it is visible.</summary>
  798. public void GoToEnd ()
  799. {
  800. IReadOnlyCollection<Branch<T>> map = BuildLineMap ();
  801. ScrollOffsetVertical = Math.Max (0, map.Count - Viewport.Height + 1);
  802. SelectedObject = map.LastOrDefault ()?.Model;
  803. SetNeedsDisplay ();
  804. }
  805. /// <summary>
  806. /// Changes the <see cref="SelectedObject"/> to the first root object and resets the
  807. /// <see cref="ScrollOffsetVertical"/> to 0.
  808. /// </summary>
  809. public void GoToFirst ()
  810. {
  811. ScrollOffsetVertical = 0;
  812. SelectedObject = roots.Keys.FirstOrDefault ();
  813. SetNeedsDisplay ();
  814. }
  815. /// <summary>Clears any cached results of the tree state.</summary>
  816. public void InvalidateLineMap () { cachedLineMap = null; }
  817. /// <summary>Returns true if the given object <paramref name="o"/> is exposed in the tree and expanded otherwise false.</summary>
  818. /// <param name="o"></param>
  819. /// <returns></returns>
  820. public bool IsExpanded (T o) { return ObjectToBranch (o)?.IsExpanded ?? false; }
  821. /// <summary>
  822. /// Returns true if the <paramref name="model"/> is either the <see cref="SelectedObject"/> or part of a
  823. /// <see cref="MultiSelect"/>.
  824. /// </summary>
  825. /// <param name="model"></param>
  826. /// <returns></returns>
  827. public bool IsSelected (T model) { return Equals (SelectedObject, model) || (MultiSelect && multiSelectedRegions.Any (s => s.Contains (model))); }
  828. // BUGBUG: OnMouseEvent is internal. TreeView should not be overriding.
  829. ///<inheritdoc/>
  830. protected internal override bool OnMouseEvent (MouseEvent me)
  831. {
  832. // If it is not an event we care about
  833. if (!me.Flags.HasFlag (MouseFlags.Button1Clicked)
  834. && !me.Flags.HasFlag (ObjectActivationButton ?? MouseFlags.Button1DoubleClicked)
  835. && !me.Flags.HasFlag (MouseFlags.WheeledDown)
  836. && !me.Flags.HasFlag (MouseFlags.WheeledUp)
  837. && !me.Flags.HasFlag (MouseFlags.WheeledRight)
  838. && !me.Flags.HasFlag (MouseFlags.WheeledLeft))
  839. {
  840. // do nothing
  841. return base.OnMouseEvent (me);
  842. }
  843. if (!HasFocus && CanFocus)
  844. {
  845. SetFocus ();
  846. }
  847. if (me.Flags == MouseFlags.WheeledDown)
  848. {
  849. ScrollDown ();
  850. return true;
  851. }
  852. if (me.Flags == MouseFlags.WheeledUp)
  853. {
  854. ScrollUp ();
  855. return true;
  856. }
  857. if (me.Flags == MouseFlags.WheeledRight)
  858. {
  859. ScrollOffsetHorizontal++;
  860. SetNeedsDisplay ();
  861. return true;
  862. }
  863. if (me.Flags == MouseFlags.WheeledLeft)
  864. {
  865. ScrollOffsetHorizontal--;
  866. SetNeedsDisplay ();
  867. return true;
  868. }
  869. if (me.Flags.HasFlag (MouseFlags.Button1Clicked))
  870. {
  871. // The line they clicked on a branch
  872. Branch<T> clickedBranch = HitTest (me.Position.Y);
  873. if (clickedBranch is null)
  874. {
  875. return false;
  876. }
  877. bool isExpandToggleAttempt = clickedBranch.IsHitOnExpandableSymbol (Driver, me.Position.X);
  878. // If we are already selected (double click)
  879. if (Equals (SelectedObject, clickedBranch.Model))
  880. {
  881. isExpandToggleAttempt = true;
  882. }
  883. // if they clicked on the +/- expansion symbol
  884. if (isExpandToggleAttempt)
  885. {
  886. if (clickedBranch.IsExpanded)
  887. {
  888. clickedBranch.Collapse ();
  889. InvalidateLineMap ();
  890. }
  891. else if (clickedBranch.CanExpand ())
  892. {
  893. clickedBranch.Expand ();
  894. InvalidateLineMap ();
  895. }
  896. else
  897. {
  898. SelectedObject = clickedBranch.Model; // It is a leaf node
  899. multiSelectedRegions.Clear ();
  900. }
  901. }
  902. else
  903. {
  904. // It is a first click somewhere in the current line that doesn't look like an expansion/collapse attempt
  905. SelectedObject = clickedBranch.Model;
  906. multiSelectedRegions.Clear ();
  907. }
  908. SetNeedsDisplay ();
  909. return true;
  910. }
  911. // If it is activation via mouse (e.g. double click)
  912. if (ObjectActivationButton.HasValue && me.Flags.HasFlag (ObjectActivationButton.Value))
  913. {
  914. // The line they clicked on a branch
  915. Branch<T> clickedBranch = HitTest (me.Position.Y);
  916. if (clickedBranch is null)
  917. {
  918. return false;
  919. }
  920. // Double click changes the selection to the clicked node as well as triggering
  921. // activation otherwise it feels wierd
  922. SelectedObject = clickedBranch.Model;
  923. SetNeedsDisplay ();
  924. // trigger activation event
  925. OnObjectActivated (new ObjectActivatedEventArgs<T> (this, clickedBranch.Model));
  926. // mouse event is handled.
  927. return true;
  928. }
  929. return false;
  930. }
  931. /// <summary>Moves the selection down by the height of the control (1 page).</summary>
  932. /// <param name="expandSelection">True if the navigation should add the covered nodes to the selected current selection.</param>
  933. /// <exception cref="NotImplementedException"></exception>
  934. public void MovePageDown (bool expandSelection = false) { AdjustSelection (Viewport.Height, expandSelection); }
  935. /// <summary>Moves the selection up by the height of the control (1 page).</summary>
  936. /// <param name="expandSelection">True if the navigation should add the covered nodes to the selected current selection.</param>
  937. /// <exception cref="NotImplementedException"></exception>
  938. public void MovePageUp (bool expandSelection = false) { AdjustSelection (-Viewport.Height, expandSelection); }
  939. /// <summary>
  940. /// This event is raised when an object is activated e.g. by double clicking or pressing
  941. /// <see cref="ObjectActivationKey"/>.
  942. /// </summary>
  943. public event EventHandler<ObjectActivatedEventArgs<T>> ObjectActivated;
  944. ///<inheritdoc/>
  945. public override void OnDrawContent (Rectangle viewport)
  946. {
  947. if (roots is null)
  948. {
  949. return;
  950. }
  951. if (TreeBuilder is null)
  952. {
  953. Move (0, 0);
  954. Driver.AddStr (NoBuilderError);
  955. return;
  956. }
  957. IReadOnlyCollection<Branch<T>> map = BuildLineMap ();
  958. for (var line = 0; line < Viewport.Height; line++)
  959. {
  960. int idxToRender = ScrollOffsetVertical + line;
  961. // Is there part of the tree view to render?
  962. if (idxToRender < map.Count)
  963. {
  964. // Render the line
  965. map.ElementAt (idxToRender).Draw (Driver, ColorScheme, line, Viewport.Width);
  966. }
  967. else
  968. {
  969. // Else clear the line to prevent stale symbols due to scrolling etc
  970. Move (0, line);
  971. Driver.SetAttribute (GetNormalColor ());
  972. Driver.AddStr (new string (' ', Viewport.Width));
  973. }
  974. }
  975. }
  976. ///<inheritdoc/>
  977. protected override void OnHasFocusChanged (bool newHasFocus, [CanBeNull] View currentFocused, [CanBeNull] View newFocused)
  978. {
  979. if (newHasFocus)
  980. {
  981. // If there is no selected object and there are objects in the tree, select the first one
  982. if (SelectedObject is null && Objects.Any ())
  983. {
  984. SelectedObject = Objects.First ();
  985. }
  986. }
  987. }
  988. /// <inheritdoc/>
  989. public override bool OnProcessKeyDown (Key keyEvent)
  990. {
  991. if (!Enabled)
  992. {
  993. return false;
  994. }
  995. // BUGBUG: this should move to OnInvokingKeyBindings
  996. // If not a keybinding, is the key a searchable key press?
  997. if (CollectionNavigatorBase.IsCompatibleKey (keyEvent) && AllowLetterBasedNavigation)
  998. {
  999. IReadOnlyCollection<Branch<T>> map;
  1000. // If there has been a call to InvalidateMap since the last time
  1001. // we need a new one to reflect the new exposed tree state
  1002. map = BuildLineMap ();
  1003. // Find the current selected object within the tree
  1004. int current = map.IndexOf (b => b.Model == SelectedObject);
  1005. int? newIndex = KeystrokeNavigator?.GetNextMatchingItem (current, (char)keyEvent);
  1006. if (newIndex is int && newIndex != -1)
  1007. {
  1008. SelectedObject = map.ElementAt ((int)newIndex).Model;
  1009. EnsureVisible (selectedObject);
  1010. SetNeedsDisplay ();
  1011. return true;
  1012. }
  1013. }
  1014. return false;
  1015. }
  1016. /// <summary>Positions the cursor at the start of the selected objects line (if visible).</summary>
  1017. public override Point? PositionCursor ()
  1018. {
  1019. if (CanFocus && HasFocus && Visible && SelectedObject is { })
  1020. {
  1021. IReadOnlyCollection<Branch<T>> map = BuildLineMap ();
  1022. int idx = map.IndexOf (b => b.Model.Equals (SelectedObject));
  1023. // if currently selected line is visible
  1024. if (idx - ScrollOffsetVertical >= 0 && idx - ScrollOffsetVertical < Viewport.Height)
  1025. {
  1026. Move (0, idx - ScrollOffsetVertical);
  1027. return MultiSelect ? new (0, idx - ScrollOffsetVertical) : null ;
  1028. }
  1029. }
  1030. return base.PositionCursor ();
  1031. }
  1032. /// <summary>
  1033. /// Rebuilds the tree structure for all exposed objects starting with the root objects. Call this method when you
  1034. /// know there are changes to the tree but don't know which objects have changed (otherwise use
  1035. /// <see cref="RefreshObject(T, bool)"/>).
  1036. /// </summary>
  1037. public void RebuildTree ()
  1038. {
  1039. foreach (Branch<T> branch in roots.Values)
  1040. {
  1041. branch.Rebuild ();
  1042. }
  1043. InvalidateLineMap ();
  1044. SetNeedsDisplay ();
  1045. }
  1046. /// <summary>
  1047. /// Refreshes the state of the object <paramref name="o"/> in the tree. This will recompute children, string
  1048. /// representation etc.
  1049. /// </summary>
  1050. /// <remarks>This has no effect if the object is not exposed in the tree.</remarks>
  1051. /// <param name="o"></param>
  1052. /// <param name="startAtTop">
  1053. /// True to also refresh all ancestors of the objects branch (starting with the root). False to
  1054. /// refresh only the passed node.
  1055. /// </param>
  1056. public void RefreshObject (T o, bool startAtTop = false)
  1057. {
  1058. Branch<T> branch = ObjectToBranch (o);
  1059. if (branch is { })
  1060. {
  1061. branch.Refresh (startAtTop);
  1062. InvalidateLineMap ();
  1063. SetNeedsDisplay ();
  1064. }
  1065. }
  1066. /// <summary>Removes the given root object from the tree</summary>
  1067. /// <remarks>If <paramref name="o"/> is the currently <see cref="SelectedObject"/> then the selection is cleared</remarks>
  1068. /// .
  1069. /// <param name="o"></param>
  1070. public void Remove (T o)
  1071. {
  1072. if (roots.ContainsKey (o))
  1073. {
  1074. roots.Remove (o);
  1075. InvalidateLineMap ();
  1076. SetNeedsDisplay ();
  1077. if (Equals (SelectedObject, o))
  1078. {
  1079. SelectedObject = default (T);
  1080. }
  1081. }
  1082. }
  1083. /// <summary>Scrolls the view area down a single line without changing the current selection.</summary>
  1084. public void ScrollDown ()
  1085. {
  1086. if (ScrollOffsetVertical <= ContentHeight - 2)
  1087. {
  1088. ScrollOffsetVertical++;
  1089. SetNeedsDisplay ();
  1090. }
  1091. }
  1092. /// <summary>Scrolls the view area up a single line without changing the current selection.</summary>
  1093. public void ScrollUp ()
  1094. {
  1095. if (scrollOffsetVertical > 0)
  1096. {
  1097. ScrollOffsetVertical--;
  1098. SetNeedsDisplay ();
  1099. }
  1100. }
  1101. /// <summary>Selects all objects in the tree when <see cref="MultiSelect"/> is enabled otherwise does nothing.</summary>
  1102. public void SelectAll ()
  1103. {
  1104. if (!MultiSelect)
  1105. {
  1106. return;
  1107. }
  1108. multiSelectedRegions.Clear ();
  1109. IReadOnlyCollection<Branch<T>> map = BuildLineMap ();
  1110. if (map.Count == 0)
  1111. {
  1112. return;
  1113. }
  1114. multiSelectedRegions.Push (new TreeSelection<T> (map.ElementAt (0), map.Count, map));
  1115. SetNeedsDisplay ();
  1116. OnSelectionChanged (new SelectionChangedEventArgs<T> (this, SelectedObject, SelectedObject));
  1117. }
  1118. /// <summary>Called when the <see cref="SelectedObject"/> changes.</summary>
  1119. public event EventHandler<SelectionChangedEventArgs<T>> SelectionChanged;
  1120. /// <summary>
  1121. /// Implementation of <see cref="Collapse(T)"/> and <see cref="CollapseAll(T)"/>. Performs operation and updates
  1122. /// selection if disappeared.
  1123. /// </summary>
  1124. /// <param name="toCollapse"></param>
  1125. /// <param name="all"></param>
  1126. protected void CollapseImpl (T toCollapse, bool all)
  1127. {
  1128. if (toCollapse is null)
  1129. {
  1130. return;
  1131. }
  1132. Branch<T> branch = ObjectToBranch (toCollapse);
  1133. // Nothing to collapse
  1134. if (branch is null)
  1135. {
  1136. return;
  1137. }
  1138. if (all)
  1139. {
  1140. branch.CollapseAll ();
  1141. }
  1142. else
  1143. {
  1144. branch.Collapse ();
  1145. }
  1146. if (SelectedObject is { } && ObjectToBranch (SelectedObject) is null)
  1147. {
  1148. // If the old selection suddenly became invalid then clear it
  1149. SelectedObject = null;
  1150. }
  1151. InvalidateLineMap ();
  1152. SetNeedsDisplay ();
  1153. }
  1154. /// <summary>
  1155. /// Determines systems behaviour when the left arrow key is pressed. Default behaviour is to collapse the current
  1156. /// tree node if possible otherwise changes selection to current branches parent.
  1157. /// </summary>
  1158. protected virtual void CursorLeft (bool ctrl)
  1159. {
  1160. if (IsExpanded (SelectedObject))
  1161. {
  1162. if (ctrl)
  1163. {
  1164. CollapseAll (SelectedObject);
  1165. }
  1166. else
  1167. {
  1168. Collapse (SelectedObject);
  1169. }
  1170. }
  1171. else
  1172. {
  1173. T parent = GetParent (SelectedObject);
  1174. if (parent is { })
  1175. {
  1176. SelectedObject = parent;
  1177. AdjustSelection (0);
  1178. SetNeedsDisplay ();
  1179. }
  1180. }
  1181. }
  1182. /// <inheritdoc/>
  1183. protected override void Dispose (bool disposing)
  1184. {
  1185. base.Dispose (disposing);
  1186. ColorGetter = null;
  1187. }
  1188. /// <summary>Raises the <see cref="ObjectActivated"/> event.</summary>
  1189. /// <param name="e"></param>
  1190. protected virtual void OnObjectActivated (ObjectActivatedEventArgs<T> e) { ObjectActivated?.Invoke (this, e); }
  1191. /// <summary>Raises the SelectionChanged event.</summary>
  1192. /// <param name="e"></param>
  1193. protected virtual void OnSelectionChanged (SelectionChangedEventArgs<T> e) { SelectionChanged?.Invoke (this, e); }
  1194. /// <summary>
  1195. /// Calculates all currently visible/expanded branches (including leafs) and outputs them by index from the top of
  1196. /// the screen.
  1197. /// </summary>
  1198. /// <remarks>
  1199. /// Index 0 of the returned array is the first item that should be visible in the top of the control, index 1 is
  1200. /// the next etc.
  1201. /// </remarks>
  1202. /// <returns></returns>
  1203. internal IReadOnlyCollection<Branch<T>> BuildLineMap ()
  1204. {
  1205. if (cachedLineMap is { })
  1206. {
  1207. return cachedLineMap;
  1208. }
  1209. List<Branch<T>> toReturn = new ();
  1210. foreach (Branch<T> root in roots.Values)
  1211. {
  1212. IEnumerable<Branch<T>> toAdd = AddToLineMap (root, false, out bool isMatch);
  1213. if (isMatch)
  1214. {
  1215. toReturn.AddRange (toAdd);
  1216. }
  1217. }
  1218. cachedLineMap = new ReadOnlyCollection<Branch<T>> (toReturn);
  1219. // Update the collection used for search-typing
  1220. KeystrokeNavigator.Collection = cachedLineMap.Select (b => AspectGetter (b.Model)).ToArray ();
  1221. return cachedLineMap;
  1222. }
  1223. /// <summary>Raises the DrawLine event</summary>
  1224. /// <param name="e"></param>
  1225. internal void OnDrawLine (DrawTreeViewLineEventArgs<T> e) { DrawLine?.Invoke (this, e); }
  1226. private IEnumerable<Branch<T>> AddToLineMap (Branch<T> currentBranch, bool parentMatches, out bool match)
  1227. {
  1228. bool weMatch = IsFilterMatch (currentBranch);
  1229. var anyChildMatches = false;
  1230. List<Branch<T>> toReturn = new ();
  1231. List<Branch<T>> children = new ();
  1232. if (currentBranch.IsExpanded)
  1233. {
  1234. foreach (Branch<T> subBranch in currentBranch.ChildBranches.Values)
  1235. {
  1236. foreach (Branch<T> sub in AddToLineMap (subBranch, weMatch, out bool childMatch))
  1237. {
  1238. if (childMatch)
  1239. {
  1240. children.Add (sub);
  1241. anyChildMatches = true;
  1242. }
  1243. }
  1244. }
  1245. }
  1246. if (parentMatches || weMatch || anyChildMatches)
  1247. {
  1248. match = true;
  1249. toReturn.Add (currentBranch);
  1250. }
  1251. else
  1252. {
  1253. match = false;
  1254. }
  1255. toReturn.AddRange (children);
  1256. return toReturn;
  1257. }
  1258. /// <summary>Sets the selection to the next branch that matches the <paramref name="predicate"/>.</summary>
  1259. /// <param name="predicate"></param>
  1260. private void AdjustSelectionToNext (Func<Branch<T>, bool> predicate)
  1261. {
  1262. IReadOnlyCollection<Branch<T>> map = BuildLineMap ();
  1263. // empty map means we can't select anything anyway
  1264. if (map.Count == 0)
  1265. {
  1266. return;
  1267. }
  1268. // Start searching from the first element in the map
  1269. var idxStart = 0;
  1270. // or the current selected branch
  1271. if (SelectedObject is { })
  1272. {
  1273. idxStart = map.IndexOf (b => Equals (b.Model, SelectedObject));
  1274. }
  1275. // if currently selected object mysteriously vanished, search from beginning
  1276. if (idxStart == -1)
  1277. {
  1278. idxStart = 0;
  1279. }
  1280. // loop around all indexes and back to first index
  1281. for (int idxCur = (idxStart + 1) % map.Count; idxCur != idxStart; idxCur = (idxCur + 1) % map.Count)
  1282. {
  1283. if (predicate (map.ElementAt (idxCur)))
  1284. {
  1285. SelectedObject = map.ElementAt (idxCur).Model;
  1286. EnsureVisible (map.ElementAt (idxCur).Model);
  1287. SetNeedsDisplay ();
  1288. return;
  1289. }
  1290. }
  1291. }
  1292. /// <summary>Returns the branch at the given <paramref name="y"/> client coordinate e.g. following a click event.</summary>
  1293. /// <param name="y">Client Y position in the controls bounds.</param>
  1294. /// <returns>The clicked branch or null if outside of tree region.</returns>
  1295. private Branch<T> HitTest (int y)
  1296. {
  1297. IReadOnlyCollection<Branch<T>> map = BuildLineMap ();
  1298. int idx = y + ScrollOffsetVertical;
  1299. // click is outside any visible nodes
  1300. if (idx < 0 || idx >= map.Count)
  1301. {
  1302. return null;
  1303. }
  1304. // The line they clicked on
  1305. return map.ElementAt (idx);
  1306. }
  1307. private bool IsFilterMatch (Branch<T> branch) { return Filter?.IsMatch (branch.Model) ?? true; }
  1308. /// <summary>
  1309. /// Returns the corresponding <see cref="Branch{T}"/> in the tree for <paramref name="toFind"/>. This will not
  1310. /// work for objects hidden by their parent being collapsed.
  1311. /// </summary>
  1312. /// <param name="toFind"></param>
  1313. /// <returns>The branch for <paramref name="toFind"/> or null if it is not currently exposed in the tree.</returns>
  1314. private Branch<T> ObjectToBranch (T toFind) { return BuildLineMap ().FirstOrDefault (o => o.Model.Equals (toFind)); }
  1315. }
  1316. internal class TreeSelection<T> where T : class
  1317. {
  1318. private readonly HashSet<T> included = new ();
  1319. /// <summary>Creates a new selection between two branches in the tree</summary>
  1320. /// <param name="from"></param>
  1321. /// <param name="toIndex"></param>
  1322. /// <param name="map"></param>
  1323. public TreeSelection (Branch<T> from, int toIndex, IReadOnlyCollection<Branch<T>> map)
  1324. {
  1325. Origin = from;
  1326. included.Add (Origin.Model);
  1327. int oldIdx = map.IndexOf (from);
  1328. int lowIndex = Math.Min (oldIdx, toIndex);
  1329. int highIndex = Math.Max (oldIdx, toIndex);
  1330. // Select everything between the old and new indexes
  1331. foreach (Branch<T> alsoInclude in map.Skip (lowIndex).Take (highIndex - lowIndex))
  1332. {
  1333. included.Add (alsoInclude.Model);
  1334. }
  1335. }
  1336. public Branch<T> Origin { get; }
  1337. public bool Contains (T model) { return included.Contains (model); }
  1338. }