TreeView.cs 53 KB

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