TreeView.cs 53 KB

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