TreeView.cs 52 KB

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