TreeView.cs 43 KB

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