TreeView.cs 42 KB

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