TreeView.cs 49 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771
  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;
  5. using System.Collections.Generic;
  6. using System.Collections.ObjectModel;
  7. using System.Linq;
  8. using NStack;
  9. namespace Terminal.Gui {
  10. /// <summary>
  11. /// Interface for all non generic members of <see cref="TreeView{T}"/>
  12. ///
  13. /// <a href="https://migueldeicaza.github.io/gui.cs/articles/treeview.html">See TreeView Deep Dive for more information</a>.
  14. /// </summary>
  15. public interface ITreeView {
  16. /// <summary>
  17. /// Contains options for changing how the tree is rendered
  18. /// </summary>
  19. TreeStyle Style { get; set; }
  20. /// <summary>
  21. /// Removes all objects from the tree and clears selection
  22. /// </summary>
  23. void ClearObjects ();
  24. /// <summary>
  25. /// Sets a flag indicating this view needs to be redisplayed because its state has changed.
  26. /// </summary>
  27. void SetNeedsDisplay ();
  28. }
  29. /// <summary>
  30. /// Convenience implementation of generic <see cref="TreeView{T}"/> for any tree were all nodes
  31. /// implement <see cref="ITreeNode"/>.
  32. ///
  33. /// <a href="https://migueldeicaza.github.io/gui.cs/articles/treeview.html">See TreeView Deep Dive for more information</a>.
  34. /// </summary>
  35. public class TreeView : TreeView<ITreeNode> {
  36. /// <summary>
  37. /// Creates a new instance of the tree control with absolute positioning and initialises
  38. /// <see cref="TreeBuilder{T}"/> with default <see cref="ITreeNode"/> based builder
  39. /// </summary>
  40. public TreeView ()
  41. {
  42. TreeBuilder = new TreeNodeBuilder ();
  43. AspectGetter = o => o == null ? "Null" : (o.Text ?? o?.ToString () ?? "Unamed Node");
  44. }
  45. }
  46. /// <summary>
  47. /// Hierarchical tree view with expandable branches. Branch objects are dynamically determined
  48. /// when expanded using a user defined <see cref="ITreeBuilder{T}"/>
  49. ///
  50. /// <a href="https://migueldeicaza.github.io/gui.cs/articles/treeview.html">See TreeView Deep Dive for more information</a>.
  51. /// </summary>
  52. public class TreeView<T> : View, ITreeView where T : class {
  53. private int scrollOffsetVertical;
  54. private int scrollOffsetHorizontal;
  55. /// <summary>
  56. /// Determines how sub branches of the tree are dynamically built at runtime as the user
  57. /// expands root nodes
  58. /// </summary>
  59. /// <value></value>
  60. public ITreeBuilder<T> TreeBuilder { get; set; }
  61. /// <summary>
  62. /// private variable for <see cref="SelectedObject"/>
  63. /// </summary>
  64. T selectedObject;
  65. /// <summary>
  66. /// Contains options for changing how the tree is rendered
  67. /// </summary>
  68. public TreeStyle Style { get; set; } = new TreeStyle ();
  69. /// <summary>
  70. /// True to allow multiple objects to be selected at once
  71. /// </summary>
  72. /// <value></value>
  73. public bool MultiSelect { get; set; } = true;
  74. /// <summary>
  75. /// True makes a letter key press navigate to the next visible branch that begins with
  76. /// that letter/digit
  77. /// </summary>
  78. /// <value></value>
  79. public bool AllowLetterBasedNavigation { get; set; } = true;
  80. /// <summary>
  81. /// The currently selected object in the tree. When <see cref="MultiSelect"/> is true this
  82. /// is the object at which the cursor is at
  83. /// </summary>
  84. public T SelectedObject {
  85. get => selectedObject;
  86. set {
  87. var oldValue = selectedObject;
  88. selectedObject = value;
  89. if (!ReferenceEquals (oldValue, value)) {
  90. OnSelectionChanged (new SelectionChangedEventArgs<T> (this, oldValue, value));
  91. }
  92. }
  93. }
  94. /// <summary>
  95. /// This event is raised when an object is activated e.g. by double clicking or
  96. /// pressing <see cref="ObjectActivationKey"/>
  97. /// </summary>
  98. public event Action<ObjectActivatedEventArgs<T>> ObjectActivated;
  99. /// <summary>
  100. /// Key which when pressed triggers <see cref="TreeView{T}.ObjectActivated"/>.
  101. /// Defaults to Enter
  102. /// </summary>
  103. public Key ObjectActivationKey { get; set; } = Key.Enter;
  104. /// <summary>
  105. /// Mouse event to trigger <see cref="TreeView{T}.ObjectActivated"/>.
  106. /// Defaults to double click (<see cref="MouseFlags.Button1DoubleClicked"/>).
  107. /// Set to null to disable this feature.
  108. /// </summary>
  109. /// <value></value>
  110. public MouseFlags? ObjectActivationButton { get; set; } = MouseFlags.Button1DoubleClicked;
  111. /// <summary>
  112. /// Secondary selected regions of tree when <see cref="MultiSelect"/> is true
  113. /// </summary>
  114. private Stack<TreeSelection<T>> multiSelectedRegions = new Stack<TreeSelection<T>> ();
  115. /// <summary>
  116. /// Cached result of <see cref="BuildLineMap"/>
  117. /// </summary>
  118. private IReadOnlyCollection<Branch<T>> cachedLineMap;
  119. /// <summary>
  120. /// Error message to display when the control is not properly initialized at draw time
  121. /// (nodes added but no tree builder set)
  122. /// </summary>
  123. public static ustring NoBuilderError = "ERROR: TreeBuilder Not Set";
  124. /// <summary>
  125. /// Called when the <see cref="SelectedObject"/> changes
  126. /// </summary>
  127. public event EventHandler<SelectionChangedEventArgs<T>> SelectionChanged;
  128. /// <summary>
  129. /// The root objects in the tree, note that this collection is of root objects only
  130. /// </summary>
  131. public IEnumerable<T> Objects { get => roots.Keys; }
  132. /// <summary>
  133. /// Map of root objects to the branches under them. All objects have
  134. /// a <see cref="Branch{T}"/> even if that branch has no children
  135. /// </summary>
  136. internal Dictionary<T, Branch<T>> roots { get; set; } = new Dictionary<T, Branch<T>> ();
  137. /// <summary>
  138. /// The amount of tree view that has been scrolled off the top of the screen (by the user
  139. /// scrolling down)
  140. /// </summary>
  141. /// <remarks>Setting a value of less than 0 will result in a offset of 0. To see changes
  142. /// in the UI call <see cref="View.SetNeedsDisplay()"/></remarks>
  143. public int ScrollOffsetVertical {
  144. get => scrollOffsetVertical;
  145. set {
  146. scrollOffsetVertical = Math.Max (0, value);
  147. }
  148. }
  149. /// <summary>
  150. /// The amount of tree view that has been scrolled to the right (horizontally)
  151. /// </summary>
  152. /// <remarks>Setting a value of less than 0 will result in a offset of 0. To see changes
  153. /// in the UI call <see cref="View.SetNeedsDisplay()"/></remarks>
  154. public int ScrollOffsetHorizontal {
  155. get => scrollOffsetHorizontal;
  156. set {
  157. scrollOffsetHorizontal = Math.Max (0, value);
  158. }
  159. }
  160. /// <summary>
  161. /// The current number of rows in the tree (ignoring the controls bounds)
  162. /// </summary>
  163. public int ContentHeight => BuildLineMap ().Count ();
  164. /// <summary>
  165. /// Returns the string representation of model objects hosted in the tree. Default
  166. /// implementation is to call <see cref="object.ToString"/>
  167. /// </summary>
  168. /// <value></value>
  169. public AspectGetterDelegate<T> AspectGetter { get; set; } = (o) => o.ToString () ?? "";
  170. /// <summary>
  171. /// Creates a new tree view with absolute positioning.
  172. /// Use <see cref="AddObjects(IEnumerable{T})"/> to set set root objects for the tree.
  173. /// Children will not be rendered until you set <see cref="TreeBuilder"/>
  174. /// </summary>
  175. public TreeView () : base ()
  176. {
  177. CanFocus = true;
  178. }
  179. /// <summary>
  180. /// Initialises <see cref="TreeBuilder"/>.Creates a new tree view with absolute
  181. /// positioning. Use <see cref="AddObjects(IEnumerable{T})"/> to set set root
  182. /// objects for the tree.
  183. /// </summary>
  184. public TreeView (ITreeBuilder<T> builder) : this ()
  185. {
  186. TreeBuilder = builder;
  187. }
  188. /// <summary>
  189. /// Adds a new root level object unless it is already a root of the tree
  190. /// </summary>
  191. /// <param name="o"></param>
  192. public void AddObject (T o)
  193. {
  194. if (!roots.ContainsKey (o)) {
  195. roots.Add (o, new Branch<T> (this, null, o));
  196. InvalidateLineMap ();
  197. SetNeedsDisplay ();
  198. }
  199. }
  200. /// <summary>
  201. /// Removes all objects from the tree and clears <see cref="SelectedObject"/>
  202. /// </summary>
  203. public void ClearObjects ()
  204. {
  205. SelectedObject = default (T);
  206. multiSelectedRegions.Clear ();
  207. roots = new Dictionary<T, Branch<T>> ();
  208. InvalidateLineMap ();
  209. SetNeedsDisplay ();
  210. }
  211. /// <summary>
  212. /// Removes the given root object from the tree
  213. /// </summary>
  214. /// <remarks>If <paramref name="o"/> is the currently <see cref="SelectedObject"/> then the
  215. /// selection is cleared</remarks>
  216. /// <param name="o"></param>
  217. public void Remove (T o)
  218. {
  219. if (roots.ContainsKey (o)) {
  220. roots.Remove (o);
  221. InvalidateLineMap ();
  222. SetNeedsDisplay ();
  223. if (Equals (SelectedObject, o)) {
  224. SelectedObject = default (T);
  225. }
  226. }
  227. }
  228. /// <summary>
  229. /// Adds many new root level objects. Objects that are already root objects are ignored
  230. /// </summary>
  231. /// <param name="collection">Objects to add as new root level objects</param>
  232. public void AddObjects (IEnumerable<T> collection)
  233. {
  234. bool objectsAdded = false;
  235. foreach (var o in collection) {
  236. if (!roots.ContainsKey (o)) {
  237. roots.Add (o, new Branch<T> (this, null, o));
  238. objectsAdded = true;
  239. }
  240. }
  241. if (objectsAdded) {
  242. InvalidateLineMap ();
  243. SetNeedsDisplay ();
  244. }
  245. }
  246. /// <summary>
  247. /// Refreshes the state of the object <paramref name="o"/> in the tree. This will
  248. /// recompute children, string representation etc
  249. /// </summary>
  250. /// <remarks>This has no effect if the object is not exposed in the tree.</remarks>
  251. /// <param name="o"></param>
  252. /// <param name="startAtTop">True to also refresh all ancestors of the objects branch
  253. /// (starting with the root). False to refresh only the passed node</param>
  254. public void RefreshObject (T o, bool startAtTop = false)
  255. {
  256. var branch = ObjectToBranch (o);
  257. if (branch != null) {
  258. branch.Refresh (startAtTop);
  259. InvalidateLineMap ();
  260. SetNeedsDisplay ();
  261. }
  262. }
  263. /// <summary>
  264. /// Rebuilds the tree structure for all exposed objects starting with the root objects.
  265. /// Call this method when you know there are changes to the tree but don't know which
  266. /// objects have changed (otherwise use <see cref="RefreshObject(T, bool)"/>)
  267. /// </summary>
  268. public void RebuildTree ()
  269. {
  270. foreach (var branch in roots.Values) {
  271. branch.Rebuild ();
  272. }
  273. InvalidateLineMap ();
  274. SetNeedsDisplay ();
  275. }
  276. /// <summary>
  277. /// Returns the currently expanded children of the passed object. Returns an empty
  278. /// collection if the branch is not exposed or not expanded
  279. /// </summary>
  280. /// <param name="o">An object in the tree</param>
  281. /// <returns></returns>
  282. public IEnumerable<T> GetChildren (T o)
  283. {
  284. var branch = ObjectToBranch (o);
  285. if (branch == null || !branch.IsExpanded) {
  286. return new T [0];
  287. }
  288. return branch.ChildBranches?.Values?.Select (b => b.Model)?.ToArray () ?? new T [0];
  289. }
  290. /// <summary>
  291. /// Returns the parent object of <paramref name="o"/> in the tree. Returns null if
  292. /// the object is not exposed in the tree
  293. /// </summary>
  294. /// <param name="o">An object in the tree</param>
  295. /// <returns></returns>
  296. public T GetParent (T o)
  297. {
  298. return ObjectToBranch (o)?.Parent?.Model;
  299. }
  300. ///<inheritdoc/>
  301. public override void Redraw (Rect bounds)
  302. {
  303. if (roots == null) {
  304. return;
  305. }
  306. if (TreeBuilder == null) {
  307. Move (0, 0);
  308. Driver.AddStr (NoBuilderError);
  309. return;
  310. }
  311. var map = BuildLineMap ();
  312. for (int line = 0; line < bounds.Height; line++) {
  313. var idxToRender = ScrollOffsetVertical + line;
  314. // Is there part of the tree view to render?
  315. if (idxToRender < map.Count) {
  316. // Render the line
  317. map.ElementAt (idxToRender).Draw (Driver, ColorScheme, line, bounds.Width);
  318. } else {
  319. // Else clear the line to prevent stale symbols due to scrolling etc
  320. Move (0, line);
  321. Driver.SetAttribute (ColorScheme.Normal);
  322. Driver.AddStr (new string (' ', bounds.Width));
  323. }
  324. }
  325. }
  326. /// <summary>
  327. /// Returns the index of the object <paramref name="o"/> if it is currently exposed (it's
  328. /// parent(s) have been expanded). This can be used with <see cref="ScrollOffsetVertical"/>
  329. /// and <see cref="View.SetNeedsDisplay()"/> to scroll to a specific object
  330. /// </summary>
  331. /// <remarks>Uses the Equals method and returns the first index at which the object is found
  332. /// or -1 if it is not found</remarks>
  333. /// <param name="o">An object that appears in your tree and is currently exposed</param>
  334. /// <returns>The index the object was found at or -1 if it is not currently revealed or
  335. /// not in the tree at all</returns>
  336. public int GetScrollOffsetOf (T o)
  337. {
  338. var map = BuildLineMap ();
  339. for (int i = 0; i < map.Count; i++) {
  340. if (map.ElementAt (i).Model.Equals (o)) {
  341. return i;
  342. }
  343. }
  344. //object not found
  345. return -1;
  346. }
  347. /// <summary>
  348. /// Returns the maximum width line in the tree including prefix and expansion symbols
  349. /// </summary>
  350. /// <param name="visible">True to consider only rows currently visible (based on window
  351. /// bounds and <see cref="ScrollOffsetVertical"/>. False to calculate the width of
  352. /// every exposed branch in the tree</param>
  353. /// <returns></returns>
  354. public int GetContentWidth (bool visible)
  355. {
  356. var map = BuildLineMap ();
  357. if (map.Count == 0) {
  358. return 0;
  359. }
  360. if (visible) {
  361. //Somehow we managed to scroll off the end of the control
  362. if (ScrollOffsetVertical >= map.Count) {
  363. return 0;
  364. }
  365. // If control has no height to it then there is no visible area for content
  366. if (Bounds.Height == 0) {
  367. return 0;
  368. }
  369. return map.Skip (ScrollOffsetVertical).Take (Bounds.Height).Max (b => b.GetWidth (Driver));
  370. } else {
  371. return map.Max (b => b.GetWidth (Driver));
  372. }
  373. }
  374. /// <summary>
  375. /// Calculates all currently visible/expanded branches (including leafs) and outputs them
  376. /// by index from the top of the screen
  377. /// </summary>
  378. /// <remarks>Index 0 of the returned array is the first item that should be visible in the
  379. /// top of the control, index 1 is the next etc.</remarks>
  380. /// <returns></returns>
  381. private IReadOnlyCollection<Branch<T>> BuildLineMap ()
  382. {
  383. if (cachedLineMap != null) {
  384. return cachedLineMap;
  385. }
  386. List<Branch<T>> toReturn = new List<Branch<T>> ();
  387. foreach (var root in roots.Values) {
  388. toReturn.AddRange (AddToLineMap (root));
  389. }
  390. return cachedLineMap = new ReadOnlyCollection<Branch<T>> (toReturn);
  391. }
  392. private IEnumerable<Branch<T>> AddToLineMap (Branch<T> currentBranch)
  393. {
  394. yield return currentBranch;
  395. if (currentBranch.IsExpanded) {
  396. foreach (var subBranch in currentBranch.ChildBranches.Values) {
  397. foreach (var sub in AddToLineMap (subBranch)) {
  398. yield return sub;
  399. }
  400. }
  401. }
  402. }
  403. /// <inheritdoc/>
  404. public override bool ProcessKey (KeyEvent keyEvent)
  405. {
  406. if (keyEvent.Key == ObjectActivationKey) {
  407. var o = SelectedObject;
  408. if (o != null) {
  409. OnObjectActivated (new ObjectActivatedEventArgs<T> (this, o));
  410. PositionCursor ();
  411. return true;
  412. }
  413. }
  414. if (keyEvent.KeyValue > 0 && keyEvent.KeyValue < 0xFFFF) {
  415. var character = (char)keyEvent.KeyValue;
  416. // if it is a single character pressed without any control keys
  417. if (char.IsLetterOrDigit (character) && AllowLetterBasedNavigation && !keyEvent.IsShift && !keyEvent.IsAlt && !keyEvent.IsCtrl) {
  418. // search for next branch that begins with that letter
  419. var characterAsStr = character.ToString ();
  420. AdjustSelectionToNext (b => AspectGetter (b.Model).StartsWith (characterAsStr, StringComparison.CurrentCultureIgnoreCase));
  421. PositionCursor ();
  422. return true;
  423. }
  424. }
  425. switch (keyEvent.Key) {
  426. case Key.CursorRight:
  427. Expand (SelectedObject);
  428. break;
  429. case Key.CursorRight | Key.CtrlMask:
  430. ExpandAll (SelectedObject);
  431. break;
  432. case Key.CursorLeft:
  433. case Key.CursorLeft | Key.CtrlMask:
  434. CursorLeft (keyEvent.Key.HasFlag (Key.CtrlMask));
  435. break;
  436. case Key.CursorUp:
  437. case Key.CursorUp | Key.ShiftMask:
  438. AdjustSelection (-1, keyEvent.Key.HasFlag (Key.ShiftMask));
  439. break;
  440. case Key.CursorDown:
  441. case Key.CursorDown | Key.ShiftMask:
  442. AdjustSelection (1, keyEvent.Key.HasFlag (Key.ShiftMask));
  443. break;
  444. case Key.CursorUp | Key.CtrlMask:
  445. AdjustSelectionToBranchStart ();
  446. break;
  447. case Key.CursorDown | Key.CtrlMask:
  448. AdjustSelectionToBranchEnd ();
  449. break;
  450. case Key.PageUp:
  451. case Key.PageUp | Key.ShiftMask:
  452. AdjustSelection (-Bounds.Height, keyEvent.Key.HasFlag (Key.ShiftMask));
  453. break;
  454. case Key.PageDown:
  455. case Key.PageDown | Key.ShiftMask:
  456. AdjustSelection (Bounds.Height, keyEvent.Key.HasFlag (Key.ShiftMask));
  457. break;
  458. case Key.A | Key.CtrlMask:
  459. SelectAll ();
  460. break;
  461. case Key.Home:
  462. GoToFirst ();
  463. break;
  464. case Key.End:
  465. GoToEnd ();
  466. break;
  467. default:
  468. // we don't care about this keystroke
  469. return false;
  470. }
  471. PositionCursor ();
  472. return true;
  473. }
  474. /// <summary>
  475. /// Raises the <see cref="ObjectActivated"/> event
  476. /// </summary>
  477. /// <param name="e"></param>
  478. protected virtual void OnObjectActivated (ObjectActivatedEventArgs<T> e)
  479. {
  480. ObjectActivated?.Invoke (e);
  481. }
  482. ///<inheritdoc/>
  483. public override bool MouseEvent (MouseEvent me)
  484. {
  485. // If it is not an event we care about
  486. if (!me.Flags.HasFlag (MouseFlags.Button1Clicked) &&
  487. !me.Flags.HasFlag (ObjectActivationButton ?? MouseFlags.Button1DoubleClicked) &&
  488. !me.Flags.HasFlag (MouseFlags.WheeledDown) &&
  489. !me.Flags.HasFlag (MouseFlags.WheeledUp) &&
  490. !me.Flags.HasFlag (MouseFlags.WheeledRight) &&
  491. !me.Flags.HasFlag (MouseFlags.WheeledLeft)) {
  492. // do nothing
  493. return false;
  494. }
  495. if (!HasFocus && CanFocus) {
  496. SetFocus ();
  497. }
  498. if (me.Flags == MouseFlags.WheeledDown) {
  499. ScrollOffsetVertical++;
  500. SetNeedsDisplay ();
  501. return true;
  502. } else if (me.Flags == MouseFlags.WheeledUp) {
  503. ScrollOffsetVertical--;
  504. SetNeedsDisplay ();
  505. return true;
  506. }
  507. if (me.Flags == MouseFlags.WheeledRight) {
  508. ScrollOffsetHorizontal++;
  509. SetNeedsDisplay ();
  510. return true;
  511. } else if (me.Flags == MouseFlags.WheeledLeft) {
  512. ScrollOffsetHorizontal--;
  513. SetNeedsDisplay ();
  514. return true;
  515. }
  516. if (me.Flags.HasFlag (MouseFlags.Button1Clicked)) {
  517. // The line they clicked on a branch
  518. var clickedBranch = HitTest (me.Y);
  519. if (clickedBranch == null) {
  520. return false;
  521. }
  522. bool isExpandToggleAttempt = clickedBranch.IsHitOnExpandableSymbol (Driver, me.X);
  523. // If we are already selected (double click)
  524. if (Equals (SelectedObject, clickedBranch.Model)) {
  525. isExpandToggleAttempt = true;
  526. }
  527. // if they clicked on the +/- expansion symbol
  528. if (isExpandToggleAttempt) {
  529. if (clickedBranch.IsExpanded) {
  530. clickedBranch.Collapse ();
  531. InvalidateLineMap ();
  532. } else
  533. if (clickedBranch.CanExpand ()) {
  534. clickedBranch.Expand ();
  535. InvalidateLineMap ();
  536. } else {
  537. SelectedObject = clickedBranch.Model; // It is a leaf node
  538. multiSelectedRegions.Clear ();
  539. }
  540. } else {
  541. // It is a first click somewhere in the current line that doesn't look like an expansion/collapse attempt
  542. SelectedObject = clickedBranch.Model;
  543. multiSelectedRegions.Clear ();
  544. }
  545. SetNeedsDisplay ();
  546. return true;
  547. }
  548. // If it is activation via mouse (e.g. double click)
  549. if (ObjectActivationButton.HasValue && me.Flags.HasFlag (ObjectActivationButton.Value)) {
  550. // The line they clicked on a branch
  551. var clickedBranch = HitTest (me.Y);
  552. if (clickedBranch == null) {
  553. return false;
  554. }
  555. // Double click changes the selection to the clicked node as well as triggering
  556. // activation otherwise it feels wierd
  557. SelectedObject = clickedBranch.Model;
  558. SetNeedsDisplay ();
  559. // trigger activation event
  560. OnObjectActivated (new ObjectActivatedEventArgs<T> (this, clickedBranch.Model));
  561. // mouse event is handled.
  562. return true;
  563. }
  564. return false;
  565. }
  566. /// <summary>
  567. /// Returns the branch at the given <paramref name="y"/> client
  568. /// coordinate e.g. following a click event
  569. /// </summary>
  570. /// <param name="y">Client Y position in the controls bounds</param>
  571. /// <returns>The clicked branch or null if outside of tree region</returns>
  572. private Branch<T> HitTest (int y)
  573. {
  574. var map = BuildLineMap ();
  575. var idx = y + ScrollOffsetVertical;
  576. // click is outside any visible nodes
  577. if (idx < 0 || idx >= map.Count) {
  578. return null;
  579. }
  580. // The line they clicked on
  581. return map.ElementAt (idx);
  582. }
  583. /// <summary>
  584. /// Positions the cursor at the start of the selected objects line (if visible)
  585. /// </summary>
  586. public override void PositionCursor ()
  587. {
  588. if (CanFocus && HasFocus && Visible && SelectedObject != null) {
  589. var map = BuildLineMap ();
  590. var idx = map.IndexOf(b => b.Model.Equals (SelectedObject));
  591. // if currently selected line is visible
  592. if (idx - ScrollOffsetVertical >= 0 && idx - ScrollOffsetVertical < Bounds.Height) {
  593. Move (0, idx - ScrollOffsetVertical);
  594. } else {
  595. base.PositionCursor ();
  596. }
  597. } else {
  598. base.PositionCursor ();
  599. }
  600. }
  601. /// <summary>
  602. /// Determines systems behaviour when the left arrow key is pressed. Default behaviour is
  603. /// to collapse the current tree node if possible otherwise changes selection to current
  604. /// branches parent
  605. /// </summary>
  606. protected virtual void CursorLeft (bool ctrl)
  607. {
  608. if (IsExpanded (SelectedObject)) {
  609. if (ctrl) {
  610. CollapseAll (SelectedObject);
  611. } else {
  612. Collapse (SelectedObject);
  613. }
  614. } else {
  615. var parent = GetParent (SelectedObject);
  616. if (parent != null) {
  617. SelectedObject = parent;
  618. AdjustSelection (0);
  619. SetNeedsDisplay ();
  620. }
  621. }
  622. }
  623. /// <summary>
  624. /// Changes the <see cref="SelectedObject"/> to the first root object and resets
  625. /// the <see cref="ScrollOffsetVertical"/> to 0
  626. /// </summary>
  627. public void GoToFirst ()
  628. {
  629. ScrollOffsetVertical = 0;
  630. SelectedObject = roots.Keys.FirstOrDefault ();
  631. SetNeedsDisplay ();
  632. }
  633. /// <summary>
  634. /// Changes the <see cref="SelectedObject"/> to the last object in the tree and scrolls so
  635. /// that it is visible
  636. /// </summary>
  637. public void GoToEnd ()
  638. {
  639. var map = BuildLineMap ();
  640. ScrollOffsetVertical = Math.Max (0, map.Count - Bounds.Height + 1);
  641. SelectedObject = map.Last ().Model;
  642. SetNeedsDisplay ();
  643. }
  644. /// <summary>
  645. /// Changes the <see cref="SelectedObject"/> to <paramref name="toSelect"/> and scrolls to ensure
  646. /// it is visible. Has no effect if <paramref name="toSelect"/> is not exposed in the tree (e.g.
  647. /// its parents are collapsed)
  648. /// </summary>
  649. /// <param name="toSelect"></param>
  650. public void GoTo (T toSelect)
  651. {
  652. if (ObjectToBranch (toSelect) == null) {
  653. return;
  654. }
  655. SelectedObject = toSelect;
  656. EnsureVisible (toSelect);
  657. SetNeedsDisplay ();
  658. }
  659. /// <summary>
  660. /// The number of screen lines to move the currently selected object by. Supports negative
  661. /// <paramref name="offset"/>. Each branch occupies 1 line on screen
  662. /// </summary>
  663. /// <remarks>If nothing is currently selected or the selected object is no longer in the tree
  664. /// then the first object in the tree is selected instead</remarks>
  665. /// <param name="offset">Positive to move the selection down the screen, negative to move it up</param>
  666. /// <param name="expandSelection">True to expand the selection (assuming
  667. /// <see cref="MultiSelect"/> is enabled). False to replace</param>
  668. public void AdjustSelection (int offset, bool expandSelection = false)
  669. {
  670. // if it is not a shift click or we don't allow multi select
  671. if (!expandSelection || !MultiSelect) {
  672. multiSelectedRegions.Clear ();
  673. }
  674. if (SelectedObject == null) {
  675. SelectedObject = roots.Keys.FirstOrDefault ();
  676. } else {
  677. var map = BuildLineMap ();
  678. var idx = map.IndexOf(b => b.Model.Equals (SelectedObject));
  679. if (idx == -1) {
  680. // The current selection has disapeared!
  681. SelectedObject = roots.Keys.FirstOrDefault ();
  682. } else {
  683. var newIdx = Math.Min (Math.Max (0, idx + offset), map.Count - 1);
  684. var newBranch = map.ElementAt(newIdx);
  685. // If it is a multi selection
  686. if (expandSelection && MultiSelect) {
  687. if (multiSelectedRegions.Any ()) {
  688. // expand the existing head selection
  689. var head = multiSelectedRegions.Pop ();
  690. multiSelectedRegions.Push (new TreeSelection<T> (head.Origin, newIdx, map));
  691. } else {
  692. // or start a new multi selection region
  693. multiSelectedRegions.Push (new TreeSelection<T> (map.ElementAt(idx), newIdx, map));
  694. }
  695. }
  696. SelectedObject = newBranch.Model;
  697. EnsureVisible (SelectedObject);
  698. }
  699. }
  700. SetNeedsDisplay ();
  701. }
  702. /// <summary>
  703. /// Moves the selection to the first child in the currently selected level
  704. /// </summary>
  705. public void AdjustSelectionToBranchStart ()
  706. {
  707. var o = SelectedObject;
  708. if (o == null) {
  709. return;
  710. }
  711. var map = BuildLineMap ();
  712. int currentIdx = map.IndexOf(b => Equals (b.Model, o));
  713. if (currentIdx == -1) {
  714. return;
  715. }
  716. var currentBranch = map.ElementAt(currentIdx);
  717. var next = currentBranch;
  718. for (; currentIdx >= 0; currentIdx--) {
  719. //if it is the beginning of the current depth of branch
  720. if (currentBranch.Depth != next.Depth) {
  721. SelectedObject = currentBranch.Model;
  722. EnsureVisible (currentBranch.Model);
  723. SetNeedsDisplay ();
  724. return;
  725. }
  726. // look at next branch up for consideration
  727. currentBranch = next;
  728. next = map.ElementAt(currentIdx);
  729. }
  730. // We ran all the way to top of tree
  731. GoToFirst ();
  732. }
  733. /// <summary>
  734. /// Moves the selection to the last child in the currently selected level
  735. /// </summary>
  736. public void AdjustSelectionToBranchEnd ()
  737. {
  738. var o = SelectedObject;
  739. if (o == null) {
  740. return;
  741. }
  742. var map = BuildLineMap ();
  743. int currentIdx = map.IndexOf(b => Equals (b.Model, o));
  744. if (currentIdx == -1) {
  745. return;
  746. }
  747. var currentBranch = map.ElementAt(currentIdx);
  748. var next = currentBranch;
  749. for (; currentIdx < map.Count; currentIdx++) {
  750. //if it is the end of the current depth of branch
  751. if (currentBranch.Depth != next.Depth) {
  752. SelectedObject = currentBranch.Model;
  753. EnsureVisible (currentBranch.Model);
  754. SetNeedsDisplay ();
  755. return;
  756. }
  757. // look at next branch for consideration
  758. currentBranch = next;
  759. next = map.ElementAt(currentIdx);
  760. }
  761. GoToEnd ();
  762. }
  763. /// <summary>
  764. /// Sets the selection to the next branch that matches the <paramref name="predicate"/>
  765. /// </summary>
  766. /// <param name="predicate"></param>
  767. private void AdjustSelectionToNext (Func<Branch<T>, bool> predicate)
  768. {
  769. var map = BuildLineMap ();
  770. // empty map means we can't select anything anyway
  771. if (map.Count == 0) {
  772. return;
  773. }
  774. // Start searching from the first element in the map
  775. var idxStart = 0;
  776. // or the current selected branch
  777. if (SelectedObject != null) {
  778. idxStart = map.IndexOf(b => Equals (b.Model, SelectedObject));
  779. }
  780. // if currently selected object mysteriously vanished, search from beginning
  781. if (idxStart == -1) {
  782. idxStart = 0;
  783. }
  784. // loop around all indexes and back to first index
  785. for (int idxCur = (idxStart + 1) % map.Count; idxCur != idxStart; idxCur = (idxCur + 1) % map.Count) {
  786. if (predicate (map.ElementAt(idxCur))) {
  787. SelectedObject = map.ElementAt(idxCur).Model;
  788. EnsureVisible (map.ElementAt(idxCur).Model);
  789. SetNeedsDisplay ();
  790. return;
  791. }
  792. }
  793. }
  794. /// <summary>
  795. /// Adjusts the <see cref="ScrollOffsetVertical"/> to ensure the given
  796. /// <paramref name="model"/> is visible. Has no effect if already visible
  797. /// </summary>
  798. public void EnsureVisible (T model)
  799. {
  800. var map = BuildLineMap ();
  801. var idx = map.IndexOf(b => Equals (b.Model, model));
  802. if (idx == -1) {
  803. return;
  804. }
  805. /*this -1 allows for possible horizontal scroll bar in the last row of the control*/
  806. int leaveSpace = Style.LeaveLastRow ? 1 : 0;
  807. if (idx < ScrollOffsetVertical) {
  808. //if user has scrolled up too far to see their selection
  809. ScrollOffsetVertical = idx;
  810. } else if (idx >= ScrollOffsetVertical + Bounds.Height - leaveSpace) {
  811. //if user has scrolled off bottom of visible tree
  812. ScrollOffsetVertical = Math.Max (0, (idx + 1) - (Bounds.Height - leaveSpace));
  813. }
  814. }
  815. /// <summary>
  816. /// Expands the supplied object if it is contained in the tree (either as a root object or
  817. /// as an exposed branch object)
  818. /// </summary>
  819. /// <param name="toExpand">The object to expand</param>
  820. public void Expand (T toExpand)
  821. {
  822. if (toExpand == null) {
  823. return;
  824. }
  825. ObjectToBranch (toExpand)?.Expand ();
  826. InvalidateLineMap ();
  827. SetNeedsDisplay ();
  828. }
  829. /// <summary>
  830. /// Expands the supplied object and all child objects
  831. /// </summary>
  832. /// <param name="toExpand">The object to expand</param>
  833. public void ExpandAll (T toExpand)
  834. {
  835. if (toExpand == null) {
  836. return;
  837. }
  838. ObjectToBranch (toExpand)?.ExpandAll ();
  839. InvalidateLineMap ();
  840. SetNeedsDisplay ();
  841. }
  842. /// <summary>
  843. /// Fully expands all nodes in the tree, if the tree is very big and built dynamically this
  844. /// may take a while (e.g. for file system)
  845. /// </summary>
  846. public void ExpandAll ()
  847. {
  848. foreach (var item in roots) {
  849. item.Value.ExpandAll ();
  850. }
  851. InvalidateLineMap ();
  852. SetNeedsDisplay ();
  853. }
  854. /// <summary>
  855. /// Returns true if the given object <paramref name="o"/> is exposed in the tree and can be
  856. /// expanded otherwise false
  857. /// </summary>
  858. /// <param name="o"></param>
  859. /// <returns></returns>
  860. public bool CanExpand (T o)
  861. {
  862. return ObjectToBranch (o)?.CanExpand () ?? false;
  863. }
  864. /// <summary>
  865. /// Returns true if the given object <paramref name="o"/> is exposed in the tree and
  866. /// expanded otherwise false
  867. /// </summary>
  868. /// <param name="o"></param>
  869. /// <returns></returns>
  870. public bool IsExpanded (T o)
  871. {
  872. return ObjectToBranch (o)?.IsExpanded ?? false;
  873. }
  874. /// <summary>
  875. /// Collapses the supplied object if it is currently expanded
  876. /// </summary>
  877. /// <param name="toCollapse">The object to collapse</param>
  878. public void Collapse (T toCollapse)
  879. {
  880. CollapseImpl (toCollapse, false);
  881. }
  882. /// <summary>
  883. /// Collapses the supplied object if it is currently expanded. Also collapses all children
  884. /// branches (this will only become apparent when/if the user expands it again)
  885. /// </summary>
  886. /// <param name="toCollapse">The object to collapse</param>
  887. public void CollapseAll (T toCollapse)
  888. {
  889. CollapseImpl (toCollapse, true);
  890. }
  891. /// <summary>
  892. /// Collapses all root nodes in the tree
  893. /// </summary>
  894. public void CollapseAll ()
  895. {
  896. foreach (var item in roots) {
  897. item.Value.Collapse ();
  898. }
  899. InvalidateLineMap ();
  900. SetNeedsDisplay ();
  901. }
  902. /// <summary>
  903. /// Implementation of <see cref="Collapse(T)"/> and <see cref="CollapseAll(T)"/>. Performs
  904. /// operation and updates selection if disapeared
  905. /// </summary>
  906. /// <param name="toCollapse"></param>
  907. /// <param name="all"></param>
  908. protected void CollapseImpl (T toCollapse, bool all)
  909. {
  910. if (toCollapse == null) {
  911. return;
  912. }
  913. var branch = ObjectToBranch (toCollapse);
  914. // Nothing to collapse
  915. if (branch == null) {
  916. return;
  917. }
  918. if (all) {
  919. branch.CollapseAll ();
  920. } else {
  921. branch.Collapse ();
  922. }
  923. if (SelectedObject != null && ObjectToBranch (SelectedObject) == null) {
  924. // If the old selection suddenly became invalid then clear it
  925. SelectedObject = null;
  926. }
  927. InvalidateLineMap ();
  928. SetNeedsDisplay ();
  929. }
  930. /// <summary>
  931. /// Clears any cached results of <see cref="BuildLineMap"/>
  932. /// </summary>
  933. protected void InvalidateLineMap ()
  934. {
  935. cachedLineMap = null;
  936. }
  937. /// <summary>
  938. /// Returns the corresponding <see cref="Branch{T}"/> in the tree for
  939. /// <paramref name="toFind"/>. This will not work for objects hidden
  940. /// by their parent being collapsed
  941. /// </summary>
  942. /// <param name="toFind"></param>
  943. /// <returns>The branch for <paramref name="toFind"/> or null if it is not currently
  944. /// exposed in the tree</returns>
  945. private Branch<T> ObjectToBranch (T toFind)
  946. {
  947. return BuildLineMap ().FirstOrDefault (o => o.Model.Equals (toFind));
  948. }
  949. /// <summary>
  950. /// Returns true if the <paramref name="model"/> is either the
  951. /// <see cref="SelectedObject"/> or part of a <see cref="MultiSelect"/>
  952. /// </summary>
  953. /// <param name="model"></param>
  954. /// <returns></returns>
  955. public bool IsSelected (T model)
  956. {
  957. return Equals (SelectedObject, model) ||
  958. (MultiSelect && multiSelectedRegions.Any (s => s.Contains (model)));
  959. }
  960. /// <summary>
  961. /// Returns <see cref="SelectedObject"/> (if not null) and all multi selected objects if
  962. /// <see cref="MultiSelect"/> is true
  963. /// </summary>
  964. /// <returns></returns>
  965. public IEnumerable<T> GetAllSelectedObjects ()
  966. {
  967. var map = BuildLineMap ();
  968. // To determine multi selected objects, start with the line map, that avoids yielding
  969. // hidden nodes that were selected then the parent collapsed e.g. programmatically or
  970. // with mouse click
  971. if (MultiSelect) {
  972. foreach (var m in map.Select (b => b.Model).Where (IsSelected)) {
  973. yield return m;
  974. }
  975. } else {
  976. if (SelectedObject != null) {
  977. yield return SelectedObject;
  978. }
  979. }
  980. }
  981. /// <summary>
  982. /// Selects all objects in the tree when <see cref="MultiSelect"/> is enabled otherwise
  983. /// does nothing
  984. /// </summary>
  985. public void SelectAll ()
  986. {
  987. if (!MultiSelect) {
  988. return;
  989. }
  990. multiSelectedRegions.Clear ();
  991. var map = BuildLineMap ();
  992. if (map.Count == 0) {
  993. return;
  994. }
  995. multiSelectedRegions.Push (new TreeSelection<T> (map.ElementAt(0), map.Count, map));
  996. SetNeedsDisplay ();
  997. OnSelectionChanged (new SelectionChangedEventArgs<T> (this, SelectedObject, SelectedObject));
  998. }
  999. /// <summary>
  1000. /// Raises the SelectionChanged event
  1001. /// </summary>
  1002. /// <param name="e"></param>
  1003. protected virtual void OnSelectionChanged (SelectionChangedEventArgs<T> e)
  1004. {
  1005. SelectionChanged?.Invoke (this, e);
  1006. }
  1007. }
  1008. /// <summary>
  1009. /// Event args for the <see cref="TreeView{T}.ObjectActivated"/> event
  1010. /// </summary>
  1011. /// <typeparam name="T"></typeparam>
  1012. public class ObjectActivatedEventArgs<T> where T : class {
  1013. /// <summary>
  1014. /// The tree in which the activation occurred
  1015. /// </summary>
  1016. /// <value></value>
  1017. public TreeView<T> Tree { get; }
  1018. /// <summary>
  1019. /// The object that was selected at the time of activation
  1020. /// </summary>
  1021. /// <value></value>
  1022. public T ActivatedObject { get; }
  1023. /// <summary>
  1024. /// Creates a new instance documenting activation of the <paramref name="activated"/> object
  1025. /// </summary>
  1026. /// <param name="tree">Tree in which the activation is happening</param>
  1027. /// <param name="activated">What object is being activated</param>
  1028. public ObjectActivatedEventArgs (TreeView<T> tree, T activated)
  1029. {
  1030. Tree = tree;
  1031. ActivatedObject = activated;
  1032. }
  1033. }
  1034. class TreeSelection<T> where T : class {
  1035. public Branch<T> Origin { get; }
  1036. private HashSet<T> included = new HashSet<T> ();
  1037. /// <summary>
  1038. /// Creates a new selection between two branches in the tree
  1039. /// </summary>
  1040. /// <param name="from"></param>
  1041. /// <param name="toIndex"></param>
  1042. /// <param name="map"></param>
  1043. public TreeSelection (Branch<T> from, int toIndex, IReadOnlyCollection<Branch<T>> map)
  1044. {
  1045. Origin = from;
  1046. included.Add (Origin.Model);
  1047. var oldIdx = map.IndexOf(from);
  1048. var lowIndex = Math.Min (oldIdx, toIndex);
  1049. var highIndex = Math.Max (oldIdx, toIndex);
  1050. // Select everything between the old and new indexes
  1051. foreach (var alsoInclude in map.Skip (lowIndex).Take (highIndex - lowIndex)) {
  1052. included.Add (alsoInclude.Model);
  1053. }
  1054. }
  1055. public bool Contains (T model)
  1056. {
  1057. return included.Contains (model);
  1058. }
  1059. }
  1060. class Branch<T> where T : class {
  1061. /// <summary>
  1062. /// True if the branch is expanded to reveal child branches
  1063. /// </summary>
  1064. public bool IsExpanded { get; set; }
  1065. /// <summary>
  1066. /// The users object that is being displayed by this branch of the tree
  1067. /// </summary>
  1068. public T Model { get; private set; }
  1069. /// <summary>
  1070. /// The depth of the current branch. Depth of 0 indicates root level branches
  1071. /// </summary>
  1072. public int Depth { get; private set; } = 0;
  1073. /// <summary>
  1074. /// The children of the current branch. This is null until the first call to
  1075. /// <see cref="FetchChildren"/> to avoid enumerating the entire underlying hierarchy
  1076. /// </summary>
  1077. public Dictionary<T, Branch<T>> ChildBranches { get; set; }
  1078. /// <summary>
  1079. /// The parent <see cref="Branch{T}"/> or null if it is a root.
  1080. /// </summary>
  1081. public Branch<T> Parent { get; private set; }
  1082. private TreeView<T> tree;
  1083. /// <summary>
  1084. /// Declares a new branch of <paramref name="tree"/> in which the users object
  1085. /// <paramref name="model"/> is presented
  1086. /// </summary>
  1087. /// <param name="tree">The UI control in which the branch resides</param>
  1088. /// <param name="parentBranchIfAny">Pass null for root level branches, otherwise
  1089. /// pass the parent</param>
  1090. /// <param name="model">The user's object that should be displayed</param>
  1091. public Branch (TreeView<T> tree, Branch<T> parentBranchIfAny, T model)
  1092. {
  1093. this.tree = tree;
  1094. this.Model = model;
  1095. if (parentBranchIfAny != null) {
  1096. Depth = parentBranchIfAny.Depth + 1;
  1097. Parent = parentBranchIfAny;
  1098. }
  1099. }
  1100. /// <summary>
  1101. /// Fetch the children of this branch. This method populates <see cref="ChildBranches"/>
  1102. /// </summary>
  1103. public virtual void FetchChildren ()
  1104. {
  1105. if (tree.TreeBuilder == null) {
  1106. return;
  1107. }
  1108. var children = tree.TreeBuilder.GetChildren (this.Model) ?? Enumerable.Empty<T> ();
  1109. this.ChildBranches = children.ToDictionary (k => k, val => new Branch<T> (tree, this, val));
  1110. }
  1111. /// <summary>
  1112. /// Returns the width of the line including prefix and the results
  1113. /// of <see cref="TreeView{T}.AspectGetter"/> (the line body).
  1114. /// </summary>
  1115. /// <returns></returns>
  1116. public virtual int GetWidth (ConsoleDriver driver)
  1117. {
  1118. return
  1119. GetLinePrefix (driver).Sum (Rune.ColumnWidth) +
  1120. Rune.ColumnWidth (GetExpandableSymbol (driver)) +
  1121. (tree.AspectGetter (Model) ?? "").Length;
  1122. }
  1123. /// <summary>
  1124. /// Renders the current <see cref="Model"/> on the specified line <paramref name="y"/>
  1125. /// </summary>
  1126. /// <param name="driver"></param>
  1127. /// <param name="colorScheme"></param>
  1128. /// <param name="y"></param>
  1129. /// <param name="availableWidth"></param>
  1130. public virtual void Draw (ConsoleDriver driver, ColorScheme colorScheme, int y, int availableWidth)
  1131. {
  1132. // true if the current line of the tree is the selected one and control has focus
  1133. bool isSelected = tree.IsSelected (Model) && tree.HasFocus;
  1134. Attribute lineColor = isSelected ? colorScheme.Focus : colorScheme.Normal;
  1135. driver.SetAttribute (lineColor);
  1136. // Everything on line before the expansion run and branch text
  1137. Rune [] prefix = GetLinePrefix (driver).ToArray ();
  1138. Rune expansion = GetExpandableSymbol (driver);
  1139. string lineBody = tree.AspectGetter (Model) ?? "";
  1140. tree.Move (0, y);
  1141. // if we have scrolled to the right then bits of the prefix will have dispeared off the screen
  1142. int toSkip = tree.ScrollOffsetHorizontal;
  1143. // Draw the line prefix (all paralell lanes or whitespace and an expand/collapse/leaf symbol)
  1144. foreach (Rune r in prefix) {
  1145. if (toSkip > 0) {
  1146. toSkip--;
  1147. } else {
  1148. driver.AddRune (r);
  1149. availableWidth -= Rune.ColumnWidth (r);
  1150. }
  1151. }
  1152. // pick color for expanded symbol
  1153. if (tree.Style.ColorExpandSymbol || tree.Style.InvertExpandSymbolColors) {
  1154. Attribute color;
  1155. if (tree.Style.ColorExpandSymbol) {
  1156. color = isSelected ? tree.ColorScheme.HotFocus : tree.ColorScheme.HotNormal;
  1157. } else {
  1158. color = lineColor;
  1159. }
  1160. if (tree.Style.InvertExpandSymbolColors) {
  1161. color = new Attribute (color.Background, color.Foreground);
  1162. }
  1163. driver.SetAttribute (color);
  1164. }
  1165. if (toSkip > 0) {
  1166. toSkip--;
  1167. } else {
  1168. driver.AddRune (expansion);
  1169. availableWidth -= Rune.ColumnWidth (expansion);
  1170. }
  1171. // horizontal scrolling has already skipped the prefix but now must also skip some of the line body
  1172. if (toSkip > 0) {
  1173. if (toSkip > lineBody.Length) {
  1174. lineBody = "";
  1175. } else {
  1176. lineBody = lineBody.Substring (toSkip);
  1177. }
  1178. }
  1179. // If body of line is too long
  1180. if (lineBody.Sum (l => Rune.ColumnWidth (l)) > availableWidth) {
  1181. // remaining space is zero and truncate the line
  1182. lineBody = new string (lineBody.TakeWhile (c => (availableWidth -= Rune.ColumnWidth (c)) >= 0).ToArray ());
  1183. availableWidth = 0;
  1184. } else {
  1185. // line is short so remaining width will be whatever comes after the line body
  1186. availableWidth -= lineBody.Length;
  1187. }
  1188. //reset the line color if it was changed for rendering expansion symbol
  1189. driver.SetAttribute (lineColor);
  1190. driver.AddStr (lineBody);
  1191. if (availableWidth > 0) {
  1192. driver.AddStr (new string (' ', availableWidth));
  1193. }
  1194. driver.SetAttribute (colorScheme.Normal);
  1195. }
  1196. /// <summary>
  1197. /// Gets all characters to render prior to the current branches line. This includes indentation
  1198. /// whitespace and any tree branches (if enabled)
  1199. /// </summary>
  1200. /// <param name="driver"></param>
  1201. /// <returns></returns>
  1202. private IEnumerable<Rune> GetLinePrefix (ConsoleDriver driver)
  1203. {
  1204. // If not showing line branches or this is a root object
  1205. if (!tree.Style.ShowBranchLines) {
  1206. for (int i = 0; i < Depth; i++) {
  1207. yield return new Rune (' ');
  1208. }
  1209. yield break;
  1210. }
  1211. // yield indentations with runes appropriate to the state of the parents
  1212. foreach (var cur in GetParentBranches ().Reverse ()) {
  1213. if (cur.IsLast ()) {
  1214. yield return new Rune (' ');
  1215. } else {
  1216. yield return driver.VLine;
  1217. }
  1218. yield return new Rune (' ');
  1219. }
  1220. if (IsLast ()) {
  1221. yield return driver.LLCorner;
  1222. } else {
  1223. yield return driver.LeftTee;
  1224. }
  1225. }
  1226. /// <summary>
  1227. /// Returns all parents starting with the immediate parent and ending at the root
  1228. /// </summary>
  1229. /// <returns></returns>
  1230. private IEnumerable<Branch<T>> GetParentBranches ()
  1231. {
  1232. var cur = Parent;
  1233. while (cur != null) {
  1234. yield return cur;
  1235. cur = cur.Parent;
  1236. }
  1237. }
  1238. /// <summary>
  1239. /// Returns an appropriate symbol for displaying next to the string representation of
  1240. /// the <see cref="Model"/> object to indicate whether it <see cref="IsExpanded"/> or
  1241. /// not (or it is a leaf)
  1242. /// </summary>
  1243. /// <param name="driver"></param>
  1244. /// <returns></returns>
  1245. public Rune GetExpandableSymbol (ConsoleDriver driver)
  1246. {
  1247. var leafSymbol = tree.Style.ShowBranchLines ? driver.HLine : ' ';
  1248. if (IsExpanded) {
  1249. return tree.Style.CollapseableSymbol ?? leafSymbol;
  1250. }
  1251. if (CanExpand ()) {
  1252. return tree.Style.ExpandableSymbol ?? leafSymbol;
  1253. }
  1254. return leafSymbol;
  1255. }
  1256. /// <summary>
  1257. /// Returns true if the current branch can be expanded according to
  1258. /// the <see cref="TreeBuilder{T}"/> or cached children already fetched
  1259. /// </summary>
  1260. /// <returns></returns>
  1261. public bool CanExpand ()
  1262. {
  1263. // if we do not know the children yet
  1264. if (ChildBranches == null) {
  1265. //if there is a rapid method for determining whether there are children
  1266. if (tree.TreeBuilder.SupportsCanExpand) {
  1267. return tree.TreeBuilder.CanExpand (Model);
  1268. }
  1269. //there is no way of knowing whether we can expand without fetching the children
  1270. FetchChildren ();
  1271. }
  1272. //we fetched or already know the children, so return whether we have any
  1273. return ChildBranches.Any ();
  1274. }
  1275. /// <summary>
  1276. /// Expands the current branch if possible
  1277. /// </summary>
  1278. public void Expand ()
  1279. {
  1280. if (ChildBranches == null) {
  1281. FetchChildren ();
  1282. }
  1283. if (ChildBranches.Any ()) {
  1284. IsExpanded = true;
  1285. }
  1286. }
  1287. /// <summary>
  1288. /// Marks the branch as collapsed (<see cref="IsExpanded"/> false)
  1289. /// </summary>
  1290. public void Collapse ()
  1291. {
  1292. IsExpanded = false;
  1293. }
  1294. /// <summary>
  1295. /// Refreshes cached knowledge in this branch e.g. what children an object has
  1296. /// </summary>
  1297. /// <param name="startAtTop">True to also refresh all <see cref="Parent"/>
  1298. /// branches (starting with the root)</param>
  1299. public void Refresh (bool startAtTop)
  1300. {
  1301. // if we must go up and refresh from the top down
  1302. if (startAtTop) {
  1303. Parent?.Refresh (true);
  1304. }
  1305. // we don't want to loose the state of our children so lets be selective about how we refresh
  1306. //if we don't know about any children yet just use the normal method
  1307. if (ChildBranches == null) {
  1308. FetchChildren ();
  1309. } else {
  1310. // we already knew about some children so preserve the state of the old children
  1311. // first gather the new Children
  1312. var newChildren = tree.TreeBuilder?.GetChildren (this.Model) ?? Enumerable.Empty<T> ();
  1313. // Children who no longer appear need to go
  1314. foreach (var toRemove in ChildBranches.Keys.Except (newChildren).ToArray ()) {
  1315. ChildBranches.Remove (toRemove);
  1316. //also if the user has this node selected (its disapearing) so lets change selection to us (the parent object) to be helpful
  1317. if (Equals (tree.SelectedObject, toRemove)) {
  1318. tree.SelectedObject = Model;
  1319. }
  1320. }
  1321. // New children need to be added
  1322. foreach (var newChild in newChildren) {
  1323. // If we don't know about the child yet we need a new branch
  1324. if (!ChildBranches.ContainsKey (newChild)) {
  1325. ChildBranches.Add (newChild, new Branch<T> (tree, this, newChild));
  1326. } else {
  1327. //we already have this object but update the reference anyway incase Equality match but the references are new
  1328. ChildBranches [newChild].Model = newChild;
  1329. }
  1330. }
  1331. }
  1332. }
  1333. /// <summary>
  1334. /// Calls <see cref="Refresh(bool)"/> on the current branch and all expanded children
  1335. /// </summary>
  1336. internal void Rebuild ()
  1337. {
  1338. Refresh (false);
  1339. // if we know about our children
  1340. if (ChildBranches != null) {
  1341. if (IsExpanded) {
  1342. //if we are expanded we need to updatethe visible children
  1343. foreach (var child in ChildBranches) {
  1344. child.Value.Rebuild ();
  1345. }
  1346. } else {
  1347. // we are not expanded so should forget about children because they may not exist anymore
  1348. ChildBranches = null;
  1349. }
  1350. }
  1351. }
  1352. /// <summary>
  1353. /// Returns true if this branch has parents and it is the last node of it's parents
  1354. /// branches (or last root of the tree)
  1355. /// </summary>
  1356. /// <returns></returns>
  1357. private bool IsLast ()
  1358. {
  1359. if (Parent == null) {
  1360. return this == tree.roots.Values.LastOrDefault ();
  1361. }
  1362. return Parent.ChildBranches.Values.LastOrDefault () == this;
  1363. }
  1364. /// <summary>
  1365. /// Returns true if the given x offset on the branch line is the +/- symbol. Returns
  1366. /// false if not showing expansion symbols or leaf node etc
  1367. /// </summary>
  1368. /// <param name="driver"></param>
  1369. /// <param name="x"></param>
  1370. /// <returns></returns>
  1371. internal bool IsHitOnExpandableSymbol (ConsoleDriver driver, int x)
  1372. {
  1373. // if leaf node then we cannot expand
  1374. if (!CanExpand ()) {
  1375. return false;
  1376. }
  1377. // if we could theoretically expand
  1378. if (!IsExpanded && tree.Style.ExpandableSymbol != null) {
  1379. return x == GetLinePrefix (driver).Count ();
  1380. }
  1381. // if we could theoretically collapse
  1382. if (IsExpanded && tree.Style.CollapseableSymbol != null) {
  1383. return x == GetLinePrefix (driver).Count ();
  1384. }
  1385. return false;
  1386. }
  1387. /// <summary>
  1388. /// Expands the current branch and all children branches
  1389. /// </summary>
  1390. internal void ExpandAll ()
  1391. {
  1392. Expand ();
  1393. if (ChildBranches != null) {
  1394. foreach (var child in ChildBranches) {
  1395. child.Value.ExpandAll ();
  1396. }
  1397. }
  1398. }
  1399. /// <summary>
  1400. /// Collapses the current branch and all children branches (even though those branches are
  1401. /// no longer visible they retain collapse/expansion state)
  1402. /// </summary>
  1403. internal void CollapseAll ()
  1404. {
  1405. Collapse ();
  1406. if (ChildBranches != null) {
  1407. foreach (var child in ChildBranches) {
  1408. child.Value.CollapseAll ();
  1409. }
  1410. }
  1411. }
  1412. }
  1413. /// <summary>
  1414. /// Delegates of this type are used to fetch string representations of user's model objects
  1415. /// </summary>
  1416. /// <param name="toRender">The object that is being rendered</param>
  1417. /// <returns></returns>
  1418. public delegate string AspectGetterDelegate<T> (T toRender) where T : class;
  1419. /// <summary>
  1420. /// Event arguments describing a change in selected object in a tree view
  1421. /// </summary>
  1422. public class SelectionChangedEventArgs<T> : EventArgs where T : class {
  1423. /// <summary>
  1424. /// The view in which the change occurred
  1425. /// </summary>
  1426. public TreeView<T> Tree { get; }
  1427. /// <summary>
  1428. /// The previously selected value (can be null)
  1429. /// </summary>
  1430. public T OldValue { get; }
  1431. /// <summary>
  1432. /// The newly selected value in the <see cref="Tree"/> (can be null)
  1433. /// </summary>
  1434. public T NewValue { get; }
  1435. /// <summary>
  1436. /// Creates a new instance of event args describing a change of selection
  1437. /// in <paramref name="tree"/>
  1438. /// </summary>
  1439. /// <param name="tree"></param>
  1440. /// <param name="oldValue"></param>
  1441. /// <param name="newValue"></param>
  1442. public SelectionChangedEventArgs (TreeView<T> tree, T oldValue, T newValue)
  1443. {
  1444. Tree = tree;
  1445. OldValue = oldValue;
  1446. NewValue = newValue;
  1447. }
  1448. }
  1449. static class ReadOnlyCollectionExtensions {
  1450. public static int IndexOf<T> (this IReadOnlyCollection<T> self, Func<T,bool> predicate)
  1451. {
  1452. int i = 0;
  1453. foreach (T element in self) {
  1454. if (predicate(element))
  1455. return i;
  1456. i++;
  1457. }
  1458. return -1;
  1459. }
  1460. public static int IndexOf<T> (this IReadOnlyCollection<T> self, T toFind)
  1461. {
  1462. int i = 0;
  1463. foreach (T element in self) {
  1464. if (Equals(element,toFind))
  1465. return i;
  1466. i++;
  1467. }
  1468. return -1;
  1469. }
  1470. }
  1471. }