TreeView.cs 45 KB

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