TreeView.cs 52 KB

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