TreeView.cs 42 KB

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