TreeView.cs 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477
  1. // This code is based on http://objectlistview.sourceforge.net (GPLv3 tree/list controls by [email protected])
  2. using System;
  3. using System.Collections.Generic;
  4. using System.Linq;
  5. namespace Terminal.Gui {
  6. /// <summary>
  7. /// Hierarchical tree view with expandable branches. Branch objects are dynamically determined when expanded using a user defined <see cref="ChildrenGetterDelegate"/>
  8. /// </summary>
  9. public class TreeView : View
  10. {
  11. /// <summary>
  12. /// Default implementation of a <see cref="ChildrenGetterDelegate"/>, returns an empty collection (i.e. no children)
  13. /// </summary>
  14. static ChildrenGetterDelegate DefaultChildrenGetter = (s)=>{return new object[0];};
  15. /// <summary>
  16. /// This is the delegate that will be used to fetch the children of a model object
  17. /// </summary>
  18. public ChildrenGetterDelegate ChildrenGetter {
  19. get { return childrenGetter ?? DefaultChildrenGetter; }
  20. set { childrenGetter = value; }
  21. }
  22. private ChildrenGetterDelegate childrenGetter;
  23. private CanExpandGetterDelegate canExpandGetter;
  24. /// <summary>
  25. /// Optional delegate where <see cref="ChildrenGetter"/> is expensive. This should quickly return true/false for whether an object is expandable. (e.g. indicating to a user that all folders can be expanded because they are folders without having to calculate contents)
  26. /// </summary>
  27. /// <remarks>When this is null <see cref="ChildrenGetter"/> is used directly to determine if a node should be expandable</remarks>
  28. public CanExpandGetterDelegate CanExpandGetter {
  29. get { return canExpandGetter; }
  30. set { canExpandGetter = value; }
  31. }
  32. /// <summary>
  33. /// The currently selected object in the tree
  34. /// </summary>
  35. public object SelectedObject {get;set;}
  36. /// <summary>
  37. /// The root objects in the tree, note that this collection is of root objects only
  38. /// </summary>
  39. public IEnumerable<object> Objects {get=>roots.Keys;}
  40. /// <summary>
  41. /// Map of root objects to the branches under them. All objects have a <see cref="Branch"/> even if that branch has no children
  42. /// </summary>
  43. Dictionary<object,Branch> roots {get; set;} = new Dictionary<object, Branch>();
  44. /// <summary>
  45. /// The amount of tree view that has been scrolled off the top of the screen (by the user scrolling down)
  46. /// </summary>
  47. public int ScrollOffset {get; private set;}
  48. /// <summary>
  49. /// Creates a new tree view with absolute positioning. Use <see cref="AddObjects(IEnumerable{object})"/> to set set root objects for the tree
  50. /// </summary>
  51. public TreeView ():base()
  52. {
  53. CanFocus = true;
  54. }
  55. /// <summary>
  56. /// Adds a new root level object unless it is already a root of the tree
  57. /// </summary>
  58. /// <param name="o"></param>
  59. public void AddObject(object o)
  60. {
  61. if(!roots.ContainsKey(o)) {
  62. roots.Add(o,new Branch(this,null,o));
  63. SetNeedsDisplay();
  64. }
  65. }
  66. /// <summary>
  67. /// Removes all objects from the tree and clears <see cref="SelectedObject"/>
  68. /// </summary>
  69. public void ClearObjects()
  70. {
  71. SelectedObject = null;
  72. roots = new Dictionary<object, Branch>();
  73. SetNeedsDisplay();
  74. }
  75. /// <summary>
  76. /// Removes the given root object from the tree
  77. /// </summary>
  78. /// <remarks>If <paramref name="o"/> is the currently <see cref="SelectedObject"/> then the selection is cleared</remarks>
  79. /// <param name="o"></param>
  80. public void Remove(object o)
  81. {
  82. if(roots.ContainsKey(o)) {
  83. roots.Remove(o);
  84. SetNeedsDisplay();
  85. if(Equals(SelectedObject,o))
  86. SelectedObject = null;
  87. }
  88. }
  89. /// <summary>
  90. /// Adds many new root level objects. Objects that are already root objects are ignored
  91. /// </summary>
  92. /// <param name="collection">Objects to add as new root level objects</param>
  93. public void AddObjects(IEnumerable<object> collection)
  94. {
  95. bool objectsAdded = false;
  96. foreach(var o in collection) {
  97. if (!roots.ContainsKey (o)) {
  98. roots.Add(o,new Branch(this,null,o));
  99. objectsAdded = true;
  100. }
  101. }
  102. if(objectsAdded)
  103. SetNeedsDisplay();
  104. }
  105. /// <summary>
  106. /// Returns the string representation of model objects hosted in the tree. Default implementation is to call <see cref="object.ToString"/>
  107. /// </summary>
  108. /// <value></value>
  109. public AspectGetterDelegate AspectGetter {get;set;} = (o)=>o.ToString();
  110. ///<inheritdoc/>
  111. public override void Redraw (Rect bounds)
  112. {
  113. if(roots == null)
  114. return;
  115. var map = BuildLineMap();
  116. for(int line = 0 ; line < bounds.Height; line++){
  117. var idxToRender = ScrollOffset + line;
  118. // Is there part of the tree view to render?
  119. if(idxToRender < map.Length) {
  120. // Render the line
  121. map[idxToRender].Draw(Driver,ColorScheme,line,bounds.Width);
  122. } else {
  123. // Else clear the line to prevent stale symbols due to scrolling etc
  124. Move(0,line);
  125. Driver.SetAttribute(ColorScheme.Normal);
  126. Driver.AddStr(new string(' ',bounds.Width));
  127. }
  128. }
  129. }
  130. /// <summary>
  131. /// Calculates all currently visible/expanded branches (including leafs) and outputs them by index from the top of the screen
  132. /// </summary>
  133. /// <remarks>Index 0 of the returned array is the first item that should be visible in the top of the control, index 1 is the next etc.</remarks>
  134. /// <returns></returns>
  135. private Branch[] BuildLineMap()
  136. {
  137. List<Branch> toReturn = new List<Branch>();
  138. foreach(var root in roots.Values) {
  139. toReturn.AddRange(AddToLineMap(root));
  140. }
  141. return toReturn.ToArray();
  142. }
  143. private IEnumerable<Branch> AddToLineMap (Branch currentBranch)
  144. {
  145. yield return currentBranch;
  146. if(currentBranch.IsExpanded){
  147. foreach(var subBranch in currentBranch.ChildBranches.Values){
  148. foreach(var sub in AddToLineMap(subBranch)) {
  149. yield return sub;
  150. }
  151. }
  152. }
  153. }
  154. /// <summary>
  155. /// Symbol to use for expanded branch nodes to indicate to the user that they can be collapsed. Defaults to '-'
  156. /// </summary>
  157. public char ExpandedSymbol {get;set;} = '-';
  158. /// <summary>
  159. /// Symbol to use for branch nodes that can be expanded to indicate this to the user. Defaults to '+'
  160. /// </summary>
  161. public char ExpandableSymbol {get;set;} = '+';
  162. /// <summary>
  163. /// Symbol to use for branch nodes that cannot be expanded (as they have no children). Defaults to space ' '
  164. /// </summary>
  165. public char LeafSymbol {get;set;} = ' ';
  166. /// <inheritdoc/>
  167. public override bool ProcessKey (KeyEvent keyEvent)
  168. {
  169. switch (keyEvent.Key) {
  170. case Key.CursorRight:
  171. Expand(SelectedObject);
  172. break;
  173. case Key.CursorLeft:
  174. Collapse(SelectedObject);
  175. break;
  176. case Key.CursorUp:
  177. AdjustSelection(-1);
  178. break;
  179. case Key.CursorDown:
  180. AdjustSelection(1);
  181. break;
  182. case Key.PageUp:
  183. AdjustSelection(-Bounds.Height);
  184. break;
  185. case Key.PageDown:
  186. AdjustSelection(Bounds.Height);
  187. break;
  188. case Key.Home:
  189. GoToFirst();
  190. break;
  191. case Key.End:
  192. GoToEnd();
  193. break;
  194. }
  195. PositionCursor ();
  196. return true;
  197. }
  198. /// <summary>
  199. /// Changes the <see cref="SelectedObject"/> to the first root object and resets the <see cref="ScrollOffset"/> to 0
  200. /// </summary>
  201. public void GoToFirst()
  202. {
  203. ScrollOffset = 0;
  204. SelectedObject = roots.Keys.FirstOrDefault();
  205. SetNeedsDisplay();
  206. }
  207. /// <summary>
  208. /// Changes the <see cref="SelectedObject"/> to the last object in the tree and scrolls so that it is visible
  209. /// </summary>
  210. public void GoToEnd ()
  211. {
  212. var map = BuildLineMap();
  213. ScrollOffset = Math.Max(0,map.Length - Bounds.Height +1);
  214. SelectedObject = map.Last().Model;
  215. SetNeedsDisplay();
  216. }
  217. /// <summary>
  218. /// Changes the selected object by a number of screen lines
  219. /// </summary>
  220. /// <remarks>If nothing is currently selected the first root is selected. If the selected object is no longer in the tree the first object is selected</remarks>
  221. /// <param name="offset"></param>
  222. private void AdjustSelection (int offset)
  223. {
  224. if(SelectedObject == null){
  225. SelectedObject = roots.Keys.FirstOrDefault();
  226. }
  227. else {
  228. var map = BuildLineMap();
  229. var idx = Array.FindIndex(map,b=>b.Model.Equals(SelectedObject));
  230. if(idx == -1) {
  231. // The current selection has disapeared!
  232. SelectedObject = roots.Keys.FirstOrDefault();
  233. }
  234. else {
  235. var newIdx = Math.Min(Math.Max(0,idx+offset),map.Length-1);
  236. SelectedObject = map[newIdx].Model;
  237. if(newIdx < ScrollOffset) {
  238. //if user has scrolled up too far to see their selection
  239. ScrollOffset = newIdx;
  240. }
  241. else if(newIdx >= ScrollOffset + Bounds.Height){
  242. //if user has scrolled off bottom of visible tree
  243. ScrollOffset = Math.Max(0,(newIdx+1) - Bounds.Height);
  244. }
  245. }
  246. }
  247. SetNeedsDisplay();
  248. }
  249. /// <summary>
  250. /// Expands the supplied object if it is contained in the tree (either as a root object or as an exposed branch object)
  251. /// </summary>
  252. /// <param name="toExpand">The object to expand</param>
  253. public void Expand(object toExpand)
  254. {
  255. if(toExpand == null)
  256. return;
  257. ObjectToBranch(toExpand)?.Expand();
  258. SetNeedsDisplay();
  259. }
  260. /// <summary>
  261. /// Collapses the supplied object if it is currently expanded
  262. /// </summary>
  263. /// <param name="toCollapse">The object to collapse</param>
  264. public void Collapse(object toCollapse)
  265. {
  266. if(toCollapse == null)
  267. return;
  268. ObjectToBranch(toCollapse)?.Collapse();
  269. SetNeedsDisplay();
  270. }
  271. /// <summary>
  272. /// Returns the corresponding <see cref="Branch"/> in the tree for <paramref name="toFind"/>. This will not work for objects hidden by their parent being collapsed
  273. /// </summary>
  274. /// <param name="toFind"></param>
  275. /// <returns>The branch for <paramref name="toFind"/> or null if it is not currently exposed in the tree</returns>
  276. private Branch ObjectToBranch(object toFind)
  277. {
  278. return BuildLineMap().FirstOrDefault(o=>o.Model.Equals(toFind));
  279. }
  280. }
  281. class Branch
  282. {
  283. /// <summary>
  284. /// True if the branch is expanded to reveal child branches
  285. /// </summary>
  286. public bool IsExpanded {get;set;}
  287. /// <summary>
  288. /// The users object that is being displayed by this branch of the tree
  289. /// </summary>
  290. public object Model {get;set;}
  291. /// <summary>
  292. /// The depth of the current branch. Depth of 0 indicates root level branches
  293. /// </summary>
  294. public int Depth {get;set;} = 0;
  295. /// <summary>
  296. /// The children of the current branch. This is null until the first call to <see cref="FetchChildren"/> to avoid enumerating the entire underlying hierarchy
  297. /// </summary>
  298. public Dictionary<object,Branch> ChildBranches {get;set;}
  299. private TreeView tree;
  300. /// <summary>
  301. /// Declares a new branch of <paramref name="tree"/> in which the users object <paramref name="model"/> is presented
  302. /// </summary>
  303. /// <param name="tree">The UI control in which the branch resides</param>
  304. /// <param name="parentBranchIfAny">Pass null for root level branches, otherwise pass the parent</param>
  305. /// <param name="model">The user's object that should be displayed</param>
  306. public Branch(TreeView tree,Branch parentBranchIfAny,object model)
  307. {
  308. this.tree = tree;
  309. this.Model = model;
  310. if(parentBranchIfAny != null) {
  311. Depth = parentBranchIfAny.Depth +1;
  312. }
  313. }
  314. /// <summary>
  315. /// Fetch the children of this branch. This method populates <see cref="ChildBranches"/>
  316. /// </summary>
  317. public virtual void FetchChildren()
  318. {
  319. if (tree.ChildrenGetter == null)
  320. return;
  321. this.ChildBranches = tree.ChildrenGetter(this.Model).ToDictionary(k=>k,val=>new Branch(tree,this,val));
  322. }
  323. /// <summary>
  324. /// Renders the current <see cref="Model"/> on the specified line <paramref name="y"/>
  325. /// </summary>
  326. /// <param name="driver"></param>
  327. /// <param name="colorScheme"></param>
  328. /// <param name="y"></param>
  329. /// <param name="availableWidth"></param>
  330. public virtual void Draw(ConsoleDriver driver,ColorScheme colorScheme, int y, int availableWidth)
  331. {
  332. string representation = new string(' ',Depth) + GetExpandableIcon() + tree.AspectGetter(Model);
  333. tree.Move(0,y);
  334. driver.SetAttribute(tree.SelectedObject == Model ?
  335. colorScheme.HotFocus :
  336. colorScheme.Normal);
  337. driver.AddStr(representation.PadRight(availableWidth));
  338. }
  339. /// <summary>
  340. /// Returns an appropriate symbol for displaying next to the string representation of the <see cref="Model"/> object to indicate whether it <see cref="IsExpanded"/> or not (or it is a leaf)
  341. /// </summary>
  342. /// <returns></returns>
  343. public char GetExpandableIcon()
  344. {
  345. if(IsExpanded)
  346. return tree.ExpandedSymbol;
  347. if(ChildBranches == null) {
  348. //if there is a rapid method for determining whether there are children
  349. if(tree.CanExpandGetter != null) {
  350. return tree.CanExpandGetter(Model) ? tree.ExpandableSymbol : tree.LeafSymbol;
  351. }
  352. //there is no way of knowing whether we can expand without fetching the children
  353. FetchChildren();
  354. }
  355. //we fetched or already know the children, so return whether we are a leaf or a expandable branch
  356. return ChildBranches.Any() ? tree.ExpandableSymbol : tree.LeafSymbol;
  357. }
  358. /// <summary>
  359. /// Expands the current branch if possible
  360. /// </summary>
  361. public void Expand()
  362. {
  363. if(ChildBranches == null) {
  364. FetchChildren();
  365. }
  366. if (ChildBranches.Any ()) {
  367. IsExpanded = true;
  368. }
  369. }
  370. internal void Collapse ()
  371. {
  372. IsExpanded = false;
  373. }
  374. }
  375. /// <summary>
  376. /// Delegates of this type are used to fetch the children of the given model object
  377. /// </summary>
  378. /// <param name="model">The parent whose children should be fetched</param>
  379. /// <returns>An enumerable over the children</returns>
  380. public delegate IEnumerable<object> ChildrenGetterDelegate(object model);
  381. /// <summary>
  382. /// Delegates of this type are used to fetch string representations of user's model objects
  383. /// </summary>
  384. /// <param name="model"></param>
  385. /// <returns></returns>
  386. public delegate string AspectGetterDelegate(object model);
  387. /// <summary>
  388. /// Delegates of this type are used to quickly display to the user whether a given user object can be expanded when fetching it's children is expensive (e.g. indicating to a user that all 1000 folders can be expanded because they are folders without having to calculate contents)
  389. /// </summary>
  390. /// <param name="model"></param>
  391. /// <returns></returns>
  392. public delegate bool CanExpandGetterDelegate(object model);
  393. }