TreeView.cs 46 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695
  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. } else
  521. if (clickedBranch.CanExpand ()) {
  522. clickedBranch.Expand ();
  523. } else {
  524. SelectedObject = clickedBranch.Model; // It is a leaf node
  525. multiSelectedRegions.Clear ();
  526. }
  527. } else {
  528. // It is a first click somewhere in the current line that doesn't look like an expansion/collapse attempt
  529. SelectedObject = clickedBranch.Model;
  530. multiSelectedRegions.Clear ();
  531. }
  532. SetNeedsDisplay ();
  533. return true;
  534. }
  535. return false;
  536. }
  537. /// <summary>
  538. /// Positions the cursor at the start of the selected objects line (if visible)
  539. /// </summary>
  540. public override void PositionCursor ()
  541. {
  542. if (CanFocus && HasFocus && Visible && SelectedObject != null) {
  543. var map = BuildLineMap ();
  544. var idx = Array.FindIndex (map, b => b.Model.Equals (SelectedObject));
  545. // if currently selected line is visible
  546. if (idx - ScrollOffsetVertical >= 0 && idx - ScrollOffsetVertical < Bounds.Height) {
  547. Move (0, idx - ScrollOffsetVertical);
  548. } else {
  549. base.PositionCursor ();
  550. }
  551. } else {
  552. base.PositionCursor ();
  553. }
  554. }
  555. /// <summary>
  556. /// Determines systems behaviour when the left arrow key is pressed. Default behaviour is
  557. /// to collapse the current tree node if possible otherwise changes selection to current
  558. /// branches parent
  559. /// </summary>
  560. protected virtual void CursorLeft (bool ctrl)
  561. {
  562. if (IsExpanded (SelectedObject)) {
  563. if (ctrl) {
  564. CollapseAll (SelectedObject);
  565. } else {
  566. Collapse (SelectedObject);
  567. }
  568. } else {
  569. var parent = GetParent (SelectedObject);
  570. if (parent != null) {
  571. SelectedObject = parent;
  572. AdjustSelection (0);
  573. SetNeedsDisplay ();
  574. }
  575. }
  576. }
  577. /// <summary>
  578. /// Changes the <see cref="SelectedObject"/> to the first root object and resets
  579. /// the <see cref="ScrollOffsetVertical"/> to 0
  580. /// </summary>
  581. public void GoToFirst ()
  582. {
  583. ScrollOffsetVertical = 0;
  584. SelectedObject = roots.Keys.FirstOrDefault ();
  585. SetNeedsDisplay ();
  586. }
  587. /// <summary>
  588. /// Changes the <see cref="SelectedObject"/> to the last object in the tree and scrolls so
  589. /// that it is visible
  590. /// </summary>
  591. public void GoToEnd ()
  592. {
  593. var map = BuildLineMap ();
  594. ScrollOffsetVertical = Math.Max (0, map.Length - Bounds.Height + 1);
  595. SelectedObject = map.Last ().Model;
  596. SetNeedsDisplay ();
  597. }
  598. /// <summary>
  599. /// Changes the <see cref="SelectedObject"/> to <paramref name="toSelect"/> and scrolls to ensure
  600. /// it is visible. Has no effect if <paramref name="toSelect"/> is not exposed in the tree (e.g.
  601. /// its parents are collapsed)
  602. /// </summary>
  603. /// <param name="toSelect"></param>
  604. public void GoTo(T toSelect)
  605. {
  606. if(ObjectToBranch(toSelect) == null) {
  607. return;
  608. }
  609. SelectedObject = toSelect;
  610. EnsureVisible(toSelect);
  611. SetNeedsDisplay();
  612. }
  613. /// <summary>
  614. /// The number of screen lines to move the currently selected object by. Supports negative
  615. /// <paramref name="offset"/>. Each branch occupies 1 line on screen
  616. /// </summary>
  617. /// <remarks>If nothing is currently selected or the selected object is no longer in the tree
  618. /// then the first object in the tree is selected instead</remarks>
  619. /// <param name="offset">Positive to move the selection down the screen, negative to move it up</param>
  620. /// <param name="expandSelection">True to expand the selection (assuming
  621. /// <see cref="MultiSelect"/> is enabled). False to replace</param>
  622. public void AdjustSelection (int offset, bool expandSelection = false)
  623. {
  624. // if it is not a shift click or we don't allow multi select
  625. if (!expandSelection || !MultiSelect) {
  626. multiSelectedRegions.Clear ();
  627. }
  628. if (SelectedObject == null) {
  629. SelectedObject = roots.Keys.FirstOrDefault ();
  630. } else {
  631. var map = BuildLineMap ();
  632. var idx = Array.FindIndex (map, b => b.Model.Equals (SelectedObject));
  633. if (idx == -1) {
  634. // The current selection has disapeared!
  635. SelectedObject = roots.Keys.FirstOrDefault ();
  636. } else {
  637. var newIdx = Math.Min (Math.Max (0, idx + offset), map.Length - 1);
  638. var newBranch = map [newIdx];
  639. // If it is a multi selection
  640. if (expandSelection && MultiSelect) {
  641. if (multiSelectedRegions.Any ()) {
  642. // expand the existing head selection
  643. var head = multiSelectedRegions.Pop ();
  644. multiSelectedRegions.Push (new TreeSelection<T> (head.Origin, newIdx, map));
  645. } else {
  646. // or start a new multi selection region
  647. multiSelectedRegions.Push (new TreeSelection<T> (map [idx], newIdx, map));
  648. }
  649. }
  650. SelectedObject = newBranch.Model;
  651. EnsureVisible (SelectedObject);
  652. }
  653. }
  654. SetNeedsDisplay ();
  655. }
  656. /// <summary>
  657. /// Moves the selection to the first child in the currently selected level
  658. /// </summary>
  659. public void AdjustSelectionToBranchStart ()
  660. {
  661. var o = SelectedObject;
  662. if (o == null) {
  663. return;
  664. }
  665. var map = BuildLineMap ();
  666. int currentIdx = Array.FindIndex (map, b => Equals (b.Model, o));
  667. if (currentIdx == -1) {
  668. return;
  669. }
  670. var currentBranch = map [currentIdx];
  671. var next = currentBranch;
  672. for (; currentIdx >= 0; currentIdx--) {
  673. //if it is the beginning of the current depth of branch
  674. if (currentBranch.Depth != next.Depth) {
  675. SelectedObject = currentBranch.Model;
  676. EnsureVisible (currentBranch.Model);
  677. SetNeedsDisplay ();
  678. return;
  679. }
  680. // look at next branch up for consideration
  681. currentBranch = next;
  682. next = map [currentIdx];
  683. }
  684. // We ran all the way to top of tree
  685. GoToFirst ();
  686. }
  687. /// <summary>
  688. /// Moves the selection to the last child in the currently selected level
  689. /// </summary>
  690. public void AdjustSelectionToBranchEnd ()
  691. {
  692. var o = SelectedObject;
  693. if (o == null) {
  694. return;
  695. }
  696. var map = BuildLineMap ();
  697. int currentIdx = Array.FindIndex (map, b => Equals (b.Model, o));
  698. if (currentIdx == -1) {
  699. return;
  700. }
  701. var currentBranch = map [currentIdx];
  702. var next = currentBranch;
  703. for (; currentIdx < map.Length; currentIdx++) {
  704. //if it is the end of the current depth of branch
  705. if (currentBranch.Depth != next.Depth) {
  706. SelectedObject = currentBranch.Model;
  707. EnsureVisible (currentBranch.Model);
  708. SetNeedsDisplay ();
  709. return;
  710. }
  711. // look at next branch for consideration
  712. currentBranch = next;
  713. next = map [currentIdx];
  714. }
  715. GoToEnd ();
  716. }
  717. /// <summary>
  718. /// Sets the selection to the next branch that matches the <paramref name="predicate"/>
  719. /// </summary>
  720. /// <param name="predicate"></param>
  721. private void AdjustSelectionToNext (Func<Branch<T>, bool> predicate)
  722. {
  723. var map = BuildLineMap ();
  724. // empty map means we can't select anything anyway
  725. if (map.Length == 0) {
  726. return;
  727. }
  728. // Start searching from the first element in the map
  729. var idxStart = 0;
  730. // or the current selected branch
  731. if (SelectedObject != null) {
  732. idxStart = Array.FindIndex (map, b => Equals (b.Model, SelectedObject));
  733. }
  734. // if currently selected object mysteriously vanished, search from beginning
  735. if (idxStart == -1) {
  736. idxStart = 0;
  737. }
  738. // loop around all indexes and back to first index
  739. for (int idxCur = (idxStart + 1) % map.Length; idxCur != idxStart; idxCur = (idxCur + 1) % map.Length) {
  740. if (predicate (map [idxCur])) {
  741. SelectedObject = map [idxCur].Model;
  742. EnsureVisible (map [idxCur].Model);
  743. SetNeedsDisplay ();
  744. return;
  745. }
  746. }
  747. }
  748. /// <summary>
  749. /// Adjusts the <see cref="ScrollOffsetVertical"/> to ensure the given
  750. /// <paramref name="model"/> is visible. Has no effect if already visible
  751. /// </summary>
  752. public void EnsureVisible (T model)
  753. {
  754. var map = BuildLineMap ();
  755. var idx = Array.FindIndex (map, b => Equals (b.Model, model));
  756. if (idx == -1) {
  757. return;
  758. }
  759. /*this -1 allows for possible horizontal scroll bar in the last row of the control*/
  760. int leaveSpace = Style.LeaveLastRow ? 1 : 0;
  761. if (idx < ScrollOffsetVertical) {
  762. //if user has scrolled up too far to see their selection
  763. ScrollOffsetVertical = idx;
  764. } else if (idx >= ScrollOffsetVertical + Bounds.Height - leaveSpace) {
  765. //if user has scrolled off bottom of visible tree
  766. ScrollOffsetVertical = Math.Max (0, (idx + 1) - (Bounds.Height - leaveSpace));
  767. }
  768. }
  769. /// <summary>
  770. /// Expands the supplied object if it is contained in the tree (either as a root object or
  771. /// as an exposed branch object)
  772. /// </summary>
  773. /// <param name="toExpand">The object to expand</param>
  774. public void Expand (T toExpand)
  775. {
  776. if (toExpand == null) {
  777. return;
  778. }
  779. ObjectToBranch (toExpand)?.Expand ();
  780. InvalidateLineMap ();
  781. SetNeedsDisplay ();
  782. }
  783. /// <summary>
  784. /// Expands the supplied object and all child objects
  785. /// </summary>
  786. /// <param name="toExpand">The object to expand</param>
  787. public void ExpandAll (T toExpand)
  788. {
  789. if (toExpand == null) {
  790. return;
  791. }
  792. ObjectToBranch (toExpand)?.ExpandAll ();
  793. InvalidateLineMap ();
  794. SetNeedsDisplay ();
  795. }
  796. /// <summary>
  797. /// Fully expands all nodes in the tree, if the tree is very big and built dynamically this
  798. /// may take a while (e.g. for file system)
  799. /// </summary>
  800. public void ExpandAll ()
  801. {
  802. foreach (var item in roots) {
  803. item.Value.ExpandAll ();
  804. }
  805. InvalidateLineMap ();
  806. SetNeedsDisplay ();
  807. }
  808. /// <summary>
  809. /// Returns true if the given object <paramref name="o"/> is exposed in the tree and can be
  810. /// expanded otherwise false
  811. /// </summary>
  812. /// <param name="o"></param>
  813. /// <returns></returns>
  814. public bool CanExpand (T o)
  815. {
  816. return ObjectToBranch (o)?.CanExpand () ?? false;
  817. }
  818. /// <summary>
  819. /// Returns true if the given object <paramref name="o"/> is exposed in the tree and
  820. /// expanded otherwise false
  821. /// </summary>
  822. /// <param name="o"></param>
  823. /// <returns></returns>
  824. public bool IsExpanded (T o)
  825. {
  826. return ObjectToBranch (o)?.IsExpanded ?? false;
  827. }
  828. /// <summary>
  829. /// Collapses the supplied object if it is currently expanded
  830. /// </summary>
  831. /// <param name="toCollapse">The object to collapse</param>
  832. public void Collapse (T toCollapse)
  833. {
  834. CollapseImpl (toCollapse, false);
  835. }
  836. /// <summary>
  837. /// Collapses the supplied object if it is currently expanded. Also collapses all children
  838. /// branches (this will only become apparent when/if the user expands it again)
  839. /// </summary>
  840. /// <param name="toCollapse">The object to collapse</param>
  841. public void CollapseAll (T toCollapse)
  842. {
  843. CollapseImpl (toCollapse, true);
  844. }
  845. /// <summary>
  846. /// Collapses all root nodes in the tree
  847. /// </summary>
  848. public void CollapseAll ()
  849. {
  850. foreach (var item in roots) {
  851. item.Value.Collapse ();
  852. }
  853. InvalidateLineMap ();
  854. SetNeedsDisplay ();
  855. }
  856. /// <summary>
  857. /// Implementation of <see cref="Collapse(T)"/> and <see cref="CollapseAll(T)"/>. Performs
  858. /// operation and updates selection if disapeared
  859. /// </summary>
  860. /// <param name="toCollapse"></param>
  861. /// <param name="all"></param>
  862. protected void CollapseImpl (T toCollapse, bool all)
  863. {
  864. if (toCollapse == null) {
  865. return;
  866. }
  867. var branch = ObjectToBranch (toCollapse);
  868. // Nothing to collapse
  869. if (branch == null) {
  870. return;
  871. }
  872. if (all) {
  873. branch.CollapseAll ();
  874. } else {
  875. branch.Collapse ();
  876. }
  877. if (SelectedObject != null && ObjectToBranch (SelectedObject) == null) {
  878. // If the old selection suddenly became invalid then clear it
  879. SelectedObject = null;
  880. }
  881. InvalidateLineMap ();
  882. SetNeedsDisplay ();
  883. }
  884. /// <summary>
  885. /// Clears any cached results of <see cref="BuildLineMap"/>
  886. /// </summary>
  887. protected void InvalidateLineMap ()
  888. {
  889. cachedLineMap = null;
  890. }
  891. /// <summary>
  892. /// Returns the corresponding <see cref="Branch{T}"/> in the tree for
  893. /// <paramref name="toFind"/>. This will not work for objects hidden
  894. /// by their parent being collapsed
  895. /// </summary>
  896. /// <param name="toFind"></param>
  897. /// <returns>The branch for <paramref name="toFind"/> or null if it is not currently
  898. /// exposed in the tree</returns>
  899. private Branch<T> ObjectToBranch (T toFind)
  900. {
  901. return BuildLineMap ().FirstOrDefault (o => o.Model.Equals (toFind));
  902. }
  903. /// <summary>
  904. /// Returns true if the <paramref name="model"/> is either the
  905. /// <see cref="SelectedObject"/> or part of a <see cref="MultiSelect"/>
  906. /// </summary>
  907. /// <param name="model"></param>
  908. /// <returns></returns>
  909. public bool IsSelected (T model)
  910. {
  911. return Equals (SelectedObject, model) ||
  912. (MultiSelect && multiSelectedRegions.Any (s => s.Contains (model)));
  913. }
  914. /// <summary>
  915. /// Returns <see cref="SelectedObject"/> (if not null) and all multi selected objects if
  916. /// <see cref="MultiSelect"/> is true
  917. /// </summary>
  918. /// <returns></returns>
  919. public IEnumerable<T> GetAllSelectedObjects ()
  920. {
  921. var map = BuildLineMap ();
  922. // To determine multi selected objects, start with the line map, that avoids yielding
  923. // hidden nodes that were selected then the parent collapsed e.g. programmatically or
  924. // with mouse click
  925. if (MultiSelect) {
  926. foreach (var m in map.Select (b => b.Model).Where (IsSelected)) {
  927. yield return m;
  928. }
  929. } else {
  930. if (SelectedObject != null) {
  931. yield return SelectedObject;
  932. }
  933. }
  934. }
  935. /// <summary>
  936. /// Selects all objects in the tree when <see cref="MultiSelect"/> is enabled otherwise
  937. /// does nothing
  938. /// </summary>
  939. public void SelectAll ()
  940. {
  941. if (!MultiSelect) {
  942. return;
  943. }
  944. multiSelectedRegions.Clear ();
  945. var map = BuildLineMap ();
  946. if (map.Length == 0) {
  947. return;
  948. }
  949. multiSelectedRegions.Push (new TreeSelection<T> (map [0], map.Length, map));
  950. SetNeedsDisplay ();
  951. OnSelectionChanged (new SelectionChangedEventArgs<T> (this, SelectedObject, SelectedObject));
  952. }
  953. /// <summary>
  954. /// Raises the SelectionChanged event
  955. /// </summary>
  956. /// <param name="e"></param>
  957. protected virtual void OnSelectionChanged (SelectionChangedEventArgs<T> e)
  958. {
  959. SelectionChanged?.Invoke (this, e);
  960. }
  961. }
  962. /// <summary>
  963. /// Event args for the <see cref="TreeView{T}.ObjectActivated"/> event
  964. /// </summary>
  965. /// <typeparam name="T"></typeparam>
  966. public class ObjectActivatedEventArgs<T> where T : class {
  967. /// <summary>
  968. /// The tree in which the activation occurred
  969. /// </summary>
  970. /// <value></value>
  971. public TreeView<T> Tree { get; }
  972. /// <summary>
  973. /// The object that was selected at the time of activation
  974. /// </summary>
  975. /// <value></value>
  976. public T ActivatedObject { get; }
  977. /// <summary>
  978. /// Creates a new instance documenting activation of the <paramref name="activated"/> object
  979. /// </summary>
  980. /// <param name="tree">Tree in which the activation is happening</param>
  981. /// <param name="activated">What object is being activated</param>
  982. public ObjectActivatedEventArgs (TreeView<T> tree, T activated)
  983. {
  984. Tree = tree;
  985. ActivatedObject = activated;
  986. }
  987. }
  988. class TreeSelection<T> where T : class {
  989. public Branch<T> Origin { get; }
  990. private HashSet<T> included = new HashSet<T> ();
  991. /// <summary>
  992. /// Creates a new selection between two branches in the tree
  993. /// </summary>
  994. /// <param name="from"></param>
  995. /// <param name="toIndex"></param>
  996. /// <param name="map"></param>
  997. public TreeSelection (Branch<T> from, int toIndex, Branch<T> [] map)
  998. {
  999. Origin = from;
  1000. included.Add (Origin.Model);
  1001. var oldIdx = Array.IndexOf (map, from);
  1002. var lowIndex = Math.Min (oldIdx, toIndex);
  1003. var highIndex = Math.Max (oldIdx, toIndex);
  1004. // Select everything between the old and new indexes
  1005. foreach (var alsoInclude in map.Skip (lowIndex).Take (highIndex - lowIndex)) {
  1006. included.Add (alsoInclude.Model);
  1007. }
  1008. }
  1009. public bool Contains (T model)
  1010. {
  1011. return included.Contains (model);
  1012. }
  1013. }
  1014. class Branch<T> where T : class {
  1015. /// <summary>
  1016. /// True if the branch is expanded to reveal child branches
  1017. /// </summary>
  1018. public bool IsExpanded { get; set; }
  1019. /// <summary>
  1020. /// The users object that is being displayed by this branch of the tree
  1021. /// </summary>
  1022. public T Model { get; private set; }
  1023. /// <summary>
  1024. /// The depth of the current branch. Depth of 0 indicates root level branches
  1025. /// </summary>
  1026. public int Depth { get; private set; } = 0;
  1027. /// <summary>
  1028. /// The children of the current branch. This is null until the first call to
  1029. /// <see cref="FetchChildren"/> to avoid enumerating the entire underlying hierarchy
  1030. /// </summary>
  1031. public Dictionary<T, Branch<T>> ChildBranches { get; set; }
  1032. /// <summary>
  1033. /// The parent <see cref="Branch{T}"/> or null if it is a root.
  1034. /// </summary>
  1035. public Branch<T> Parent { get; private set; }
  1036. private TreeView<T> tree;
  1037. /// <summary>
  1038. /// Declares a new branch of <paramref name="tree"/> in which the users object
  1039. /// <paramref name="model"/> is presented
  1040. /// </summary>
  1041. /// <param name="tree">The UI control in which the branch resides</param>
  1042. /// <param name="parentBranchIfAny">Pass null for root level branches, otherwise
  1043. /// pass the parent</param>
  1044. /// <param name="model">The user's object that should be displayed</param>
  1045. public Branch (TreeView<T> tree, Branch<T> parentBranchIfAny, T model)
  1046. {
  1047. this.tree = tree;
  1048. this.Model = model;
  1049. if (parentBranchIfAny != null) {
  1050. Depth = parentBranchIfAny.Depth + 1;
  1051. Parent = parentBranchIfAny;
  1052. }
  1053. }
  1054. /// <summary>
  1055. /// Fetch the children of this branch. This method populates <see cref="ChildBranches"/>
  1056. /// </summary>
  1057. public virtual void FetchChildren ()
  1058. {
  1059. if (tree.TreeBuilder == null) {
  1060. return;
  1061. }
  1062. var children = tree.TreeBuilder.GetChildren (this.Model) ?? Enumerable.Empty<T> ();
  1063. this.ChildBranches = children.ToDictionary (k => k, val => new Branch<T> (tree, this, val));
  1064. }
  1065. /// <summary>
  1066. /// Returns the width of the line including prefix and the results
  1067. /// of <see cref="TreeView{T}.AspectGetter"/> (the line body).
  1068. /// </summary>
  1069. /// <returns></returns>
  1070. public virtual int GetWidth (ConsoleDriver driver)
  1071. {
  1072. return
  1073. GetLinePrefix (driver).Sum (Rune.ColumnWidth) +
  1074. Rune.ColumnWidth (GetExpandableSymbol (driver)) +
  1075. (tree.AspectGetter (Model) ?? "").Length;
  1076. }
  1077. /// <summary>
  1078. /// Renders the current <see cref="Model"/> on the specified line <paramref name="y"/>
  1079. /// </summary>
  1080. /// <param name="driver"></param>
  1081. /// <param name="colorScheme"></param>
  1082. /// <param name="y"></param>
  1083. /// <param name="availableWidth"></param>
  1084. public virtual void Draw (ConsoleDriver driver, ColorScheme colorScheme, int y, int availableWidth)
  1085. {
  1086. // true if the current line of the tree is the selected one and control has focus
  1087. bool isSelected = tree.IsSelected (Model) && tree.HasFocus;
  1088. Attribute lineColor = isSelected ? colorScheme.Focus : colorScheme.Normal;
  1089. driver.SetAttribute (lineColor);
  1090. // Everything on line before the expansion run and branch text
  1091. Rune [] prefix = GetLinePrefix (driver).ToArray ();
  1092. Rune expansion = GetExpandableSymbol (driver);
  1093. string lineBody = tree.AspectGetter (Model) ?? "";
  1094. tree.Move (0, y);
  1095. // if we have scrolled to the right then bits of the prefix will have dispeared off the screen
  1096. int toSkip = tree.ScrollOffsetHorizontal;
  1097. // Draw the line prefix (all paralell lanes or whitespace and an expand/collapse/leaf symbol)
  1098. foreach (Rune r in prefix) {
  1099. if (toSkip > 0) {
  1100. toSkip--;
  1101. } else {
  1102. driver.AddRune (r);
  1103. availableWidth -= Rune.ColumnWidth (r);
  1104. }
  1105. }
  1106. // pick color for expanded symbol
  1107. if (tree.Style.ColorExpandSymbol || tree.Style.InvertExpandSymbolColors) {
  1108. Attribute color;
  1109. if (tree.Style.ColorExpandSymbol) {
  1110. color = isSelected ? tree.ColorScheme.HotFocus : tree.ColorScheme.HotNormal;
  1111. } else {
  1112. color = lineColor;
  1113. }
  1114. if (tree.Style.InvertExpandSymbolColors) {
  1115. color = new Attribute (color.Background, color.Foreground);
  1116. }
  1117. driver.SetAttribute (color);
  1118. }
  1119. if (toSkip > 0) {
  1120. toSkip--;
  1121. } else {
  1122. driver.AddRune (expansion);
  1123. availableWidth -= Rune.ColumnWidth (expansion);
  1124. }
  1125. // horizontal scrolling has already skipped the prefix but now must also skip some of the line body
  1126. if (toSkip > 0) {
  1127. if (toSkip > lineBody.Length) {
  1128. lineBody = "";
  1129. } else {
  1130. lineBody = lineBody.Substring (toSkip);
  1131. }
  1132. }
  1133. // If body of line is too long
  1134. if (lineBody.Sum (l => Rune.ColumnWidth (l)) > availableWidth) {
  1135. // remaining space is zero and truncate the line
  1136. lineBody = new string (lineBody.TakeWhile (c => (availableWidth -= Rune.ColumnWidth (c)) >= 0).ToArray ());
  1137. availableWidth = 0;
  1138. } else {
  1139. // line is short so remaining width will be whatever comes after the line body
  1140. availableWidth -= lineBody.Length;
  1141. }
  1142. //reset the line color if it was changed for rendering expansion symbol
  1143. driver.SetAttribute (lineColor);
  1144. driver.AddStr (lineBody);
  1145. if (availableWidth > 0) {
  1146. driver.AddStr (new string (' ', availableWidth));
  1147. }
  1148. driver.SetAttribute (colorScheme.Normal);
  1149. }
  1150. /// <summary>
  1151. /// Gets all characters to render prior to the current branches line. This includes indentation
  1152. /// whitespace and any tree branches (if enabled)
  1153. /// </summary>
  1154. /// <param name="driver"></param>
  1155. /// <returns></returns>
  1156. private IEnumerable<Rune> GetLinePrefix (ConsoleDriver driver)
  1157. {
  1158. // If not showing line branches or this is a root object
  1159. if (!tree.Style.ShowBranchLines) {
  1160. for (int i = 0; i < Depth; i++) {
  1161. yield return new Rune (' ');
  1162. }
  1163. yield break;
  1164. }
  1165. // yield indentations with runes appropriate to the state of the parents
  1166. foreach (var cur in GetParentBranches ().Reverse ()) {
  1167. if (cur.IsLast ()) {
  1168. yield return new Rune (' ');
  1169. } else {
  1170. yield return driver.VLine;
  1171. }
  1172. yield return new Rune (' ');
  1173. }
  1174. if (IsLast ()) {
  1175. yield return driver.LLCorner;
  1176. } else {
  1177. yield return driver.LeftTee;
  1178. }
  1179. }
  1180. /// <summary>
  1181. /// Returns all parents starting with the immediate parent and ending at the root
  1182. /// </summary>
  1183. /// <returns></returns>
  1184. private IEnumerable<Branch<T>> GetParentBranches ()
  1185. {
  1186. var cur = Parent;
  1187. while (cur != null) {
  1188. yield return cur;
  1189. cur = cur.Parent;
  1190. }
  1191. }
  1192. /// <summary>
  1193. /// Returns an appropriate symbol for displaying next to the string representation of
  1194. /// the <see cref="Model"/> object to indicate whether it <see cref="IsExpanded"/> or
  1195. /// not (or it is a leaf)
  1196. /// </summary>
  1197. /// <param name="driver"></param>
  1198. /// <returns></returns>
  1199. public Rune GetExpandableSymbol (ConsoleDriver driver)
  1200. {
  1201. var leafSymbol = tree.Style.ShowBranchLines ? driver.HLine : ' ';
  1202. if (IsExpanded) {
  1203. return tree.Style.CollapseableSymbol ?? leafSymbol;
  1204. }
  1205. if (CanExpand ()) {
  1206. return tree.Style.ExpandableSymbol ?? leafSymbol;
  1207. }
  1208. return leafSymbol;
  1209. }
  1210. /// <summary>
  1211. /// Returns true if the current branch can be expanded according to
  1212. /// the <see cref="TreeBuilder{T}"/> or cached children already fetched
  1213. /// </summary>
  1214. /// <returns></returns>
  1215. public bool CanExpand ()
  1216. {
  1217. // if we do not know the children yet
  1218. if (ChildBranches == null) {
  1219. //if there is a rapid method for determining whether there are children
  1220. if (tree.TreeBuilder.SupportsCanExpand) {
  1221. return tree.TreeBuilder.CanExpand (Model);
  1222. }
  1223. //there is no way of knowing whether we can expand without fetching the children
  1224. FetchChildren ();
  1225. }
  1226. //we fetched or already know the children, so return whether we have any
  1227. return ChildBranches.Any ();
  1228. }
  1229. /// <summary>
  1230. /// Expands the current branch if possible
  1231. /// </summary>
  1232. public void Expand ()
  1233. {
  1234. if (ChildBranches == null) {
  1235. FetchChildren ();
  1236. }
  1237. if (ChildBranches.Any ()) {
  1238. IsExpanded = true;
  1239. }
  1240. }
  1241. /// <summary>
  1242. /// Marks the branch as collapsed (<see cref="IsExpanded"/> false)
  1243. /// </summary>
  1244. public void Collapse ()
  1245. {
  1246. IsExpanded = false;
  1247. }
  1248. /// <summary>
  1249. /// Refreshes cached knowledge in this branch e.g. what children an object has
  1250. /// </summary>
  1251. /// <param name="startAtTop">True to also refresh all <see cref="Parent"/>
  1252. /// branches (starting with the root)</param>
  1253. public void Refresh (bool startAtTop)
  1254. {
  1255. // if we must go up and refresh from the top down
  1256. if (startAtTop) {
  1257. Parent?.Refresh (true);
  1258. }
  1259. // we don't want to loose the state of our children so lets be selective about how we refresh
  1260. //if we don't know about any children yet just use the normal method
  1261. if (ChildBranches == null) {
  1262. FetchChildren ();
  1263. } else {
  1264. // we already knew about some children so preserve the state of the old children
  1265. // first gather the new Children
  1266. var newChildren = tree.TreeBuilder?.GetChildren (this.Model) ?? Enumerable.Empty<T> ();
  1267. // Children who no longer appear need to go
  1268. foreach (var toRemove in ChildBranches.Keys.Except (newChildren).ToArray ()) {
  1269. ChildBranches.Remove (toRemove);
  1270. //also if the user has this node selected (its disapearing) so lets change selection to us (the parent object) to be helpful
  1271. if (Equals (tree.SelectedObject, toRemove)) {
  1272. tree.SelectedObject = Model;
  1273. }
  1274. }
  1275. // New children need to be added
  1276. foreach (var newChild in newChildren) {
  1277. // If we don't know about the child yet we need a new branch
  1278. if (!ChildBranches.ContainsKey (newChild)) {
  1279. ChildBranches.Add (newChild, new Branch<T> (tree, this, newChild));
  1280. } else {
  1281. //we already have this object but update the reference anyway incase Equality match but the references are new
  1282. ChildBranches [newChild].Model = newChild;
  1283. }
  1284. }
  1285. }
  1286. }
  1287. /// <summary>
  1288. /// Calls <see cref="Refresh(bool)"/> on the current branch and all expanded children
  1289. /// </summary>
  1290. internal void Rebuild ()
  1291. {
  1292. Refresh (false);
  1293. // if we know about our children
  1294. if (ChildBranches != null) {
  1295. if (IsExpanded) {
  1296. //if we are expanded we need to updatethe visible children
  1297. foreach (var child in ChildBranches) {
  1298. child.Value.Rebuild ();
  1299. }
  1300. } else {
  1301. // we are not expanded so should forget about children because they may not exist anymore
  1302. ChildBranches = null;
  1303. }
  1304. }
  1305. }
  1306. /// <summary>
  1307. /// Returns true if this branch has parents and it is the last node of it's parents
  1308. /// branches (or last root of the tree)
  1309. /// </summary>
  1310. /// <returns></returns>
  1311. private bool IsLast ()
  1312. {
  1313. if (Parent == null) {
  1314. return this == tree.roots.Values.LastOrDefault ();
  1315. }
  1316. return Parent.ChildBranches.Values.LastOrDefault () == this;
  1317. }
  1318. /// <summary>
  1319. /// Returns true if the given x offset on the branch line is the +/- symbol. Returns
  1320. /// false if not showing expansion symbols or leaf node etc
  1321. /// </summary>
  1322. /// <param name="driver"></param>
  1323. /// <param name="x"></param>
  1324. /// <returns></returns>
  1325. internal bool IsHitOnExpandableSymbol (ConsoleDriver driver, int x)
  1326. {
  1327. // if leaf node then we cannot expand
  1328. if (!CanExpand ()) {
  1329. return false;
  1330. }
  1331. // if we could theoretically expand
  1332. if (!IsExpanded && tree.Style.ExpandableSymbol != null) {
  1333. return x == GetLinePrefix (driver).Count ();
  1334. }
  1335. // if we could theoretically collapse
  1336. if (IsExpanded && tree.Style.CollapseableSymbol != null) {
  1337. return x == GetLinePrefix (driver).Count ();
  1338. }
  1339. return false;
  1340. }
  1341. /// <summary>
  1342. /// Expands the current branch and all children branches
  1343. /// </summary>
  1344. internal void ExpandAll ()
  1345. {
  1346. Expand ();
  1347. if (ChildBranches != null) {
  1348. foreach (var child in ChildBranches) {
  1349. child.Value.ExpandAll ();
  1350. }
  1351. }
  1352. }
  1353. /// <summary>
  1354. /// Collapses the current branch and all children branches (even though those branches are
  1355. /// no longer visible they retain collapse/expansion state)
  1356. /// </summary>
  1357. internal void CollapseAll ()
  1358. {
  1359. Collapse ();
  1360. if (ChildBranches != null) {
  1361. foreach (var child in ChildBranches) {
  1362. child.Value.CollapseAll ();
  1363. }
  1364. }
  1365. }
  1366. }
  1367. /// <summary>
  1368. /// Delegates of this type are used to fetch string representations of user's model objects
  1369. /// </summary>
  1370. /// <param name="toRender">The object that is being rendered</param>
  1371. /// <returns></returns>
  1372. public delegate string AspectGetterDelegate<T> (T toRender) where T : class;
  1373. /// <summary>
  1374. /// Event arguments describing a change in selected object in a tree view
  1375. /// </summary>
  1376. public class SelectionChangedEventArgs<T> : EventArgs where T : class {
  1377. /// <summary>
  1378. /// The view in which the change occurred
  1379. /// </summary>
  1380. public TreeView<T> Tree { get; }
  1381. /// <summary>
  1382. /// The previously selected value (can be null)
  1383. /// </summary>
  1384. public T OldValue { get; }
  1385. /// <summary>
  1386. /// The newly selected value in the <see cref="Tree"/> (can be null)
  1387. /// </summary>
  1388. public T NewValue { get; }
  1389. /// <summary>
  1390. /// Creates a new instance of event args describing a change of selection
  1391. /// in <paramref name="tree"/>
  1392. /// </summary>
  1393. /// <param name="tree"></param>
  1394. /// <param name="oldValue"></param>
  1395. /// <param name="newValue"></param>
  1396. public SelectionChangedEventArgs (TreeView<T> tree, T oldValue, T newValue)
  1397. {
  1398. Tree = tree;
  1399. OldValue = oldValue;
  1400. NewValue = newValue;
  1401. }
  1402. }
  1403. }