TreeView.cs 39 KB

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