TreeView.cs 51 KB

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