TreeView.cs 52 KB

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