TreeView.cs 52 KB

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