TreeView.cs 52 KB

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