TreeView.cs 46 KB

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