TreeView.cs 40 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382
  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. /// <summary>
  568. /// Returns the object in the tree list that is currently visible
  569. /// at the provided point. Returns null if no object is at that location.
  570. /// <remarks>
  571. /// </remarks>
  572. /// If you have screen cordinates then use <see cref="View.ScreenToView(int, int)"/>
  573. /// to translate these into the client area of the <see cref="TreeView{T}"/>.
  574. /// </summary>
  575. /// <param name="point">Point with the <see cref="View.Bounds"/> of the <see cref="TreeView{T}"/></param>
  576. /// <returns></returns>
  577. public T HitTest (Point point)
  578. {
  579. return HitTest (point.Y)?.Model;
  580. }
  581. ///<inheritdoc/>
  582. public override bool MouseEvent (MouseEvent me)
  583. {
  584. // If it is not an event we care about
  585. if (!me.Flags.HasFlag (MouseFlags.Button1Clicked) &&
  586. !me.Flags.HasFlag (ObjectActivationButton ?? MouseFlags.Button1DoubleClicked) &&
  587. !me.Flags.HasFlag (MouseFlags.WheeledDown) &&
  588. !me.Flags.HasFlag (MouseFlags.WheeledUp) &&
  589. !me.Flags.HasFlag (MouseFlags.WheeledRight) &&
  590. !me.Flags.HasFlag (MouseFlags.WheeledLeft)) {
  591. // do nothing
  592. return false;
  593. }
  594. if (!HasFocus && CanFocus) {
  595. SetFocus ();
  596. }
  597. if (me.Flags == MouseFlags.WheeledDown) {
  598. ScrollDown ();
  599. return true;
  600. } else if (me.Flags == MouseFlags.WheeledUp) {
  601. ScrollUp ();
  602. return true;
  603. }
  604. if (me.Flags == MouseFlags.WheeledRight) {
  605. ScrollOffsetHorizontal++;
  606. SetNeedsDisplay ();
  607. return true;
  608. } else if (me.Flags == MouseFlags.WheeledLeft) {
  609. ScrollOffsetHorizontal--;
  610. SetNeedsDisplay ();
  611. return true;
  612. }
  613. if (me.Flags.HasFlag (MouseFlags.Button1Clicked)) {
  614. // The line they clicked on a branch
  615. var clickedBranch = HitTest (me.Y);
  616. if (clickedBranch == null) {
  617. return false;
  618. }
  619. bool isExpandToggleAttempt = clickedBranch.IsHitOnExpandableSymbol (Driver, me.X);
  620. // If we are already selected (double click)
  621. if (Equals (SelectedObject, clickedBranch.Model)) {
  622. isExpandToggleAttempt = true;
  623. }
  624. // if they clicked on the +/- expansion symbol
  625. if (isExpandToggleAttempt) {
  626. if (clickedBranch.IsExpanded) {
  627. clickedBranch.Collapse ();
  628. InvalidateLineMap ();
  629. } else
  630. if (clickedBranch.CanExpand ()) {
  631. clickedBranch.Expand ();
  632. InvalidateLineMap ();
  633. } else {
  634. SelectedObject = clickedBranch.Model; // It is a leaf node
  635. multiSelectedRegions.Clear ();
  636. }
  637. } else {
  638. // It is a first click somewhere in the current line that doesn't look like an expansion/collapse attempt
  639. SelectedObject = clickedBranch.Model;
  640. multiSelectedRegions.Clear ();
  641. }
  642. SetNeedsDisplay ();
  643. return true;
  644. }
  645. // If it is activation via mouse (e.g. double click)
  646. if (ObjectActivationButton.HasValue && me.Flags.HasFlag (ObjectActivationButton.Value)) {
  647. // The line they clicked on a branch
  648. var clickedBranch = HitTest (me.Y);
  649. if (clickedBranch == null) {
  650. return false;
  651. }
  652. // Double click changes the selection to the clicked node as well as triggering
  653. // activation otherwise it feels wierd
  654. SelectedObject = clickedBranch.Model;
  655. SetNeedsDisplay ();
  656. // trigger activation event
  657. OnObjectActivated (new ObjectActivatedEventArgs<T> (this, clickedBranch.Model));
  658. // mouse event is handled.
  659. return true;
  660. }
  661. return false;
  662. }
  663. /// <summary>
  664. /// Returns the branch at the given <paramref name="y"/> client
  665. /// coordinate e.g. following a click event
  666. /// </summary>
  667. /// <param name="y">Client Y position in the controls bounds</param>
  668. /// <returns>The clicked branch or null if outside of tree region</returns>
  669. private Branch<T> HitTest (int y)
  670. {
  671. var map = BuildLineMap ();
  672. var idx = y + ScrollOffsetVertical;
  673. // click is outside any visible nodes
  674. if (idx < 0 || idx >= map.Count) {
  675. return null;
  676. }
  677. // The line they clicked on
  678. return map.ElementAt (idx);
  679. }
  680. /// <summary>
  681. /// Positions the cursor at the start of the selected objects line (if visible)
  682. /// </summary>
  683. public override void PositionCursor ()
  684. {
  685. if (CanFocus && HasFocus && Visible && SelectedObject != null) {
  686. var map = BuildLineMap ();
  687. var idx = map.IndexOf (b => b.Model.Equals (SelectedObject));
  688. // if currently selected line is visible
  689. if (idx - ScrollOffsetVertical >= 0 && idx - ScrollOffsetVertical < Bounds.Height) {
  690. Move (0, idx - ScrollOffsetVertical);
  691. } else {
  692. base.PositionCursor ();
  693. }
  694. } else {
  695. base.PositionCursor ();
  696. }
  697. }
  698. /// <summary>
  699. /// Determines systems behaviour when the left arrow key is pressed. Default behaviour is
  700. /// to collapse the current tree node if possible otherwise changes selection to current
  701. /// branches parent
  702. /// </summary>
  703. protected virtual void CursorLeft (bool ctrl)
  704. {
  705. if (IsExpanded (SelectedObject)) {
  706. if (ctrl) {
  707. CollapseAll (SelectedObject);
  708. } else {
  709. Collapse (SelectedObject);
  710. }
  711. } else {
  712. var parent = GetParent (SelectedObject);
  713. if (parent != null) {
  714. SelectedObject = parent;
  715. AdjustSelection (0);
  716. SetNeedsDisplay ();
  717. }
  718. }
  719. }
  720. /// <summary>
  721. /// Changes the <see cref="SelectedObject"/> to the first root object and resets
  722. /// the <see cref="ScrollOffsetVertical"/> to 0
  723. /// </summary>
  724. public void GoToFirst ()
  725. {
  726. ScrollOffsetVertical = 0;
  727. SelectedObject = roots.Keys.FirstOrDefault ();
  728. SetNeedsDisplay ();
  729. }
  730. /// <summary>
  731. /// Changes the <see cref="SelectedObject"/> to the last object in the tree and scrolls so
  732. /// that it is visible
  733. /// </summary>
  734. public void GoToEnd ()
  735. {
  736. var map = BuildLineMap ();
  737. ScrollOffsetVertical = Math.Max (0, map.Count - Bounds.Height + 1);
  738. SelectedObject = map.Last ().Model;
  739. SetNeedsDisplay ();
  740. }
  741. /// <summary>
  742. /// Changes the <see cref="SelectedObject"/> to <paramref name="toSelect"/> and scrolls to ensure
  743. /// it is visible. Has no effect if <paramref name="toSelect"/> is not exposed in the tree (e.g.
  744. /// its parents are collapsed)
  745. /// </summary>
  746. /// <param name="toSelect"></param>
  747. public void GoTo (T toSelect)
  748. {
  749. if (ObjectToBranch (toSelect) == null) {
  750. return;
  751. }
  752. SelectedObject = toSelect;
  753. EnsureVisible (toSelect);
  754. SetNeedsDisplay ();
  755. }
  756. /// <summary>
  757. /// The number of screen lines to move the currently selected object by. Supports negative
  758. /// <paramref name="offset"/>. Each branch occupies 1 line on screen
  759. /// </summary>
  760. /// <remarks>If nothing is currently selected or the selected object is no longer in the tree
  761. /// then the first object in the tree is selected instead</remarks>
  762. /// <param name="offset">Positive to move the selection down the screen, negative to move it up</param>
  763. /// <param name="expandSelection">True to expand the selection (assuming
  764. /// <see cref="MultiSelect"/> is enabled). False to replace</param>
  765. public void AdjustSelection (int offset, bool expandSelection = false)
  766. {
  767. // if it is not a shift click or we don't allow multi select
  768. if (!expandSelection || !MultiSelect) {
  769. multiSelectedRegions.Clear ();
  770. }
  771. if (SelectedObject == null) {
  772. SelectedObject = roots.Keys.FirstOrDefault ();
  773. } else {
  774. var map = BuildLineMap ();
  775. var idx = map.IndexOf (b => b.Model.Equals (SelectedObject));
  776. if (idx == -1) {
  777. // The current selection has disapeared!
  778. SelectedObject = roots.Keys.FirstOrDefault ();
  779. } else {
  780. var newIdx = Math.Min (Math.Max (0, idx + offset), map.Count - 1);
  781. var newBranch = map.ElementAt (newIdx);
  782. // If it is a multi selection
  783. if (expandSelection && MultiSelect) {
  784. if (multiSelectedRegions.Any ()) {
  785. // expand the existing head selection
  786. var head = multiSelectedRegions.Pop ();
  787. multiSelectedRegions.Push (new TreeSelection<T> (head.Origin, newIdx, map));
  788. } else {
  789. // or start a new multi selection region
  790. multiSelectedRegions.Push (new TreeSelection<T> (map.ElementAt (idx), newIdx, map));
  791. }
  792. }
  793. SelectedObject = newBranch.Model;
  794. EnsureVisible (SelectedObject);
  795. }
  796. }
  797. SetNeedsDisplay ();
  798. }
  799. /// <summary>
  800. /// Moves the selection to the first child in the currently selected level
  801. /// </summary>
  802. public void AdjustSelectionToBranchStart ()
  803. {
  804. var o = SelectedObject;
  805. if (o == null) {
  806. return;
  807. }
  808. var map = BuildLineMap ();
  809. int currentIdx = map.IndexOf (b => Equals (b.Model, o));
  810. if (currentIdx == -1) {
  811. return;
  812. }
  813. var currentBranch = map.ElementAt (currentIdx);
  814. var next = currentBranch;
  815. for (; currentIdx >= 0; currentIdx--) {
  816. //if it is the beginning of the current depth of branch
  817. if (currentBranch.Depth != next.Depth) {
  818. SelectedObject = currentBranch.Model;
  819. EnsureVisible (currentBranch.Model);
  820. SetNeedsDisplay ();
  821. return;
  822. }
  823. // look at next branch up for consideration
  824. currentBranch = next;
  825. next = map.ElementAt (currentIdx);
  826. }
  827. // We ran all the way to top of tree
  828. GoToFirst ();
  829. }
  830. /// <summary>
  831. /// Moves the selection to the last child in the currently selected level
  832. /// </summary>
  833. public void AdjustSelectionToBranchEnd ()
  834. {
  835. var o = SelectedObject;
  836. if (o == null) {
  837. return;
  838. }
  839. var map = BuildLineMap ();
  840. int currentIdx = map.IndexOf (b => Equals (b.Model, o));
  841. if (currentIdx == -1) {
  842. return;
  843. }
  844. var currentBranch = map.ElementAt (currentIdx);
  845. var next = currentBranch;
  846. for (; currentIdx < map.Count; currentIdx++) {
  847. //if it is the end of the current depth of branch
  848. if (currentBranch.Depth != next.Depth) {
  849. SelectedObject = currentBranch.Model;
  850. EnsureVisible (currentBranch.Model);
  851. SetNeedsDisplay ();
  852. return;
  853. }
  854. // look at next branch for consideration
  855. currentBranch = next;
  856. next = map.ElementAt (currentIdx);
  857. }
  858. GoToEnd ();
  859. }
  860. /// <summary>
  861. /// Sets the selection to the next branch that matches the <paramref name="predicate"/>
  862. /// </summary>
  863. /// <param name="predicate"></param>
  864. private void AdjustSelectionToNext (Func<Branch<T>, bool> predicate)
  865. {
  866. var map = BuildLineMap ();
  867. // empty map means we can't select anything anyway
  868. if (map.Count == 0) {
  869. return;
  870. }
  871. // Start searching from the first element in the map
  872. var idxStart = 0;
  873. // or the current selected branch
  874. if (SelectedObject != null) {
  875. idxStart = map.IndexOf (b => Equals (b.Model, SelectedObject));
  876. }
  877. // if currently selected object mysteriously vanished, search from beginning
  878. if (idxStart == -1) {
  879. idxStart = 0;
  880. }
  881. // loop around all indexes and back to first index
  882. for (int idxCur = (idxStart + 1) % map.Count; idxCur != idxStart; idxCur = (idxCur + 1) % map.Count) {
  883. if (predicate (map.ElementAt (idxCur))) {
  884. SelectedObject = map.ElementAt (idxCur).Model;
  885. EnsureVisible (map.ElementAt (idxCur).Model);
  886. SetNeedsDisplay ();
  887. return;
  888. }
  889. }
  890. }
  891. /// <summary>
  892. /// Adjusts the <see cref="ScrollOffsetVertical"/> to ensure the given
  893. /// <paramref name="model"/> is visible. Has no effect if already visible
  894. /// </summary>
  895. public void EnsureVisible (T model)
  896. {
  897. var map = BuildLineMap ();
  898. var idx = map.IndexOf (b => Equals (b.Model, model));
  899. if (idx == -1) {
  900. return;
  901. }
  902. /*this -1 allows for possible horizontal scroll bar in the last row of the control*/
  903. int leaveSpace = Style.LeaveLastRow ? 1 : 0;
  904. if (idx < ScrollOffsetVertical) {
  905. //if user has scrolled up too far to see their selection
  906. ScrollOffsetVertical = idx;
  907. } else if (idx >= ScrollOffsetVertical + Bounds.Height - leaveSpace) {
  908. //if user has scrolled off bottom of visible tree
  909. ScrollOffsetVertical = Math.Max (0, (idx + 1) - (Bounds.Height - leaveSpace));
  910. }
  911. }
  912. /// <summary>
  913. /// Expands the currently <see cref="SelectedObject"/>
  914. /// </summary>
  915. public void Expand ()
  916. {
  917. Expand (SelectedObject);
  918. }
  919. /// <summary>
  920. /// Expands the supplied object if it is contained in the tree (either as a root object or
  921. /// as an exposed branch object)
  922. /// </summary>
  923. /// <param name="toExpand">The object to expand</param>
  924. public void Expand (T toExpand)
  925. {
  926. if (toExpand == null) {
  927. return;
  928. }
  929. ObjectToBranch (toExpand)?.Expand ();
  930. InvalidateLineMap ();
  931. SetNeedsDisplay ();
  932. }
  933. /// <summary>
  934. /// Expands the supplied object and all child objects
  935. /// </summary>
  936. /// <param name="toExpand">The object to expand</param>
  937. public void ExpandAll (T toExpand)
  938. {
  939. if (toExpand == null) {
  940. return;
  941. }
  942. ObjectToBranch (toExpand)?.ExpandAll ();
  943. InvalidateLineMap ();
  944. SetNeedsDisplay ();
  945. }
  946. /// <summary>
  947. /// Fully expands all nodes in the tree, if the tree is very big and built dynamically this
  948. /// may take a while (e.g. for file system)
  949. /// </summary>
  950. public void ExpandAll ()
  951. {
  952. foreach (var item in roots) {
  953. item.Value.ExpandAll ();
  954. }
  955. InvalidateLineMap ();
  956. SetNeedsDisplay ();
  957. }
  958. /// <summary>
  959. /// Returns true if the given object <paramref name="o"/> is exposed in the tree and can be
  960. /// expanded otherwise false
  961. /// </summary>
  962. /// <param name="o"></param>
  963. /// <returns></returns>
  964. public bool CanExpand (T o)
  965. {
  966. return ObjectToBranch (o)?.CanExpand () ?? false;
  967. }
  968. /// <summary>
  969. /// Returns true if the given object <paramref name="o"/> is exposed in the tree and
  970. /// expanded otherwise false
  971. /// </summary>
  972. /// <param name="o"></param>
  973. /// <returns></returns>
  974. public bool IsExpanded (T o)
  975. {
  976. return ObjectToBranch (o)?.IsExpanded ?? false;
  977. }
  978. /// <summary>
  979. /// Collapses the <see cref="SelectedObject"/>
  980. /// </summary>
  981. public void Collapse ()
  982. {
  983. Collapse (selectedObject);
  984. }
  985. /// <summary>
  986. /// Collapses the supplied object if it is currently expanded
  987. /// </summary>
  988. /// <param name="toCollapse">The object to collapse</param>
  989. public void Collapse (T toCollapse)
  990. {
  991. CollapseImpl (toCollapse, false);
  992. }
  993. /// <summary>
  994. /// Collapses the supplied object if it is currently expanded. Also collapses all children
  995. /// branches (this will only become apparent when/if the user expands it again)
  996. /// </summary>
  997. /// <param name="toCollapse">The object to collapse</param>
  998. public void CollapseAll (T toCollapse)
  999. {
  1000. CollapseImpl (toCollapse, true);
  1001. }
  1002. /// <summary>
  1003. /// Collapses all root nodes in the tree
  1004. /// </summary>
  1005. public void CollapseAll ()
  1006. {
  1007. foreach (var item in roots) {
  1008. item.Value.Collapse ();
  1009. }
  1010. InvalidateLineMap ();
  1011. SetNeedsDisplay ();
  1012. }
  1013. /// <summary>
  1014. /// Implementation of <see cref="Collapse(T)"/> and <see cref="CollapseAll(T)"/>. Performs
  1015. /// operation and updates selection if disapeared
  1016. /// </summary>
  1017. /// <param name="toCollapse"></param>
  1018. /// <param name="all"></param>
  1019. protected void CollapseImpl (T toCollapse, bool all)
  1020. {
  1021. if (toCollapse == null) {
  1022. return;
  1023. }
  1024. var branch = ObjectToBranch (toCollapse);
  1025. // Nothing to collapse
  1026. if (branch == null) {
  1027. return;
  1028. }
  1029. if (all) {
  1030. branch.CollapseAll ();
  1031. } else {
  1032. branch.Collapse ();
  1033. }
  1034. if (SelectedObject != null && ObjectToBranch (SelectedObject) == null) {
  1035. // If the old selection suddenly became invalid then clear it
  1036. SelectedObject = null;
  1037. }
  1038. InvalidateLineMap ();
  1039. SetNeedsDisplay ();
  1040. }
  1041. /// <summary>
  1042. /// Clears any cached results of <see cref="BuildLineMap"/>
  1043. /// </summary>
  1044. protected void InvalidateLineMap ()
  1045. {
  1046. cachedLineMap = null;
  1047. }
  1048. /// <summary>
  1049. /// Returns the corresponding <see cref="Branch{T}"/> in the tree for
  1050. /// <paramref name="toFind"/>. This will not work for objects hidden
  1051. /// by their parent being collapsed
  1052. /// </summary>
  1053. /// <param name="toFind"></param>
  1054. /// <returns>The branch for <paramref name="toFind"/> or null if it is not currently
  1055. /// exposed in the tree</returns>
  1056. private Branch<T> ObjectToBranch (T toFind)
  1057. {
  1058. return BuildLineMap ().FirstOrDefault (o => o.Model.Equals (toFind));
  1059. }
  1060. /// <summary>
  1061. /// Returns true if the <paramref name="model"/> is either the
  1062. /// <see cref="SelectedObject"/> or part of a <see cref="MultiSelect"/>
  1063. /// </summary>
  1064. /// <param name="model"></param>
  1065. /// <returns></returns>
  1066. public bool IsSelected (T model)
  1067. {
  1068. return Equals (SelectedObject, model) ||
  1069. (MultiSelect && multiSelectedRegions.Any (s => s.Contains (model)));
  1070. }
  1071. /// <summary>
  1072. /// Returns <see cref="SelectedObject"/> (if not null) and all multi selected objects if
  1073. /// <see cref="MultiSelect"/> is true
  1074. /// </summary>
  1075. /// <returns></returns>
  1076. public IEnumerable<T> GetAllSelectedObjects ()
  1077. {
  1078. var map = BuildLineMap ();
  1079. // To determine multi selected objects, start with the line map, that avoids yielding
  1080. // hidden nodes that were selected then the parent collapsed e.g. programmatically or
  1081. // with mouse click
  1082. if (MultiSelect) {
  1083. foreach (var m in map.Select (b => b.Model).Where (IsSelected)) {
  1084. yield return m;
  1085. }
  1086. } else {
  1087. if (SelectedObject != null) {
  1088. yield return SelectedObject;
  1089. }
  1090. }
  1091. }
  1092. /// <summary>
  1093. /// Selects all objects in the tree when <see cref="MultiSelect"/> is enabled otherwise
  1094. /// does nothing
  1095. /// </summary>
  1096. public void SelectAll ()
  1097. {
  1098. if (!MultiSelect) {
  1099. return;
  1100. }
  1101. multiSelectedRegions.Clear ();
  1102. var map = BuildLineMap ();
  1103. if (map.Count == 0) {
  1104. return;
  1105. }
  1106. multiSelectedRegions.Push (new TreeSelection<T> (map.ElementAt (0), map.Count, map));
  1107. SetNeedsDisplay ();
  1108. OnSelectionChanged (new SelectionChangedEventArgs<T> (this, SelectedObject, SelectedObject));
  1109. }
  1110. /// <summary>
  1111. /// Raises the SelectionChanged event
  1112. /// </summary>
  1113. /// <param name="e"></param>
  1114. protected virtual void OnSelectionChanged (SelectionChangedEventArgs<T> e)
  1115. {
  1116. SelectionChanged?.Invoke (this, e);
  1117. }
  1118. }
  1119. class TreeSelection<T> where T : class {
  1120. public Branch<T> Origin { get; }
  1121. private HashSet<T> included = new HashSet<T> ();
  1122. /// <summary>
  1123. /// Creates a new selection between two branches in the tree
  1124. /// </summary>
  1125. /// <param name="from"></param>
  1126. /// <param name="toIndex"></param>
  1127. /// <param name="map"></param>
  1128. public TreeSelection (Branch<T> from, int toIndex, IReadOnlyCollection<Branch<T>> map)
  1129. {
  1130. Origin = from;
  1131. included.Add (Origin.Model);
  1132. var oldIdx = map.IndexOf (from);
  1133. var lowIndex = Math.Min (oldIdx, toIndex);
  1134. var highIndex = Math.Max (oldIdx, toIndex);
  1135. // Select everything between the old and new indexes
  1136. foreach (var alsoInclude in map.Skip (lowIndex).Take (highIndex - lowIndex)) {
  1137. included.Add (alsoInclude.Model);
  1138. }
  1139. }
  1140. public bool Contains (T model)
  1141. {
  1142. return included.Contains (model);
  1143. }
  1144. }
  1145. }