TreeView.cs 39 KB

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