TreeView.cs 42 KB

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