TreeView.cs 52 KB

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