TreeView.cs 53 KB

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