TreeView.cs 52 KB

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