TreeView.cs 13 KB

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