TreeView.cs 43 KB

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