Branch.cs 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. namespace Terminal.Gui.Trees {
  5. class Branch<T> where T : class {
  6. /// <summary>
  7. /// True if the branch is expanded to reveal child branches.
  8. /// </summary>
  9. public bool IsExpanded { get; set; }
  10. /// <summary>
  11. /// The users object that is being displayed by this branch of the tree.
  12. /// </summary>
  13. public T Model { get; private set; }
  14. /// <summary>
  15. /// The depth of the current branch. Depth of 0 indicates root level branches.
  16. /// </summary>
  17. public int Depth { get; private set; } = 0;
  18. /// <summary>
  19. /// The children of the current branch. This is null until the first call to
  20. /// <see cref="FetchChildren"/> to avoid enumerating the entire underlying hierarchy.
  21. /// </summary>
  22. public Dictionary<T, Branch<T>> ChildBranches { get; set; }
  23. /// <summary>
  24. /// The parent <see cref="Branch{T}"/> or null if it is a root.
  25. /// </summary>
  26. public Branch<T> Parent { get; private set; }
  27. private TreeView<T> tree;
  28. /// <summary>
  29. /// Declares a new branch of <paramref name="tree"/> in which the users object
  30. /// <paramref name="model"/> is presented.
  31. /// </summary>
  32. /// <param name="tree">The UI control in which the branch resides.</param>
  33. /// <param name="parentBranchIfAny">Pass null for root level branches, otherwise
  34. /// pass the parent.</param>
  35. /// <param name="model">The user's object that should be displayed.</param>
  36. public Branch (TreeView<T> tree, Branch<T> parentBranchIfAny, T model)
  37. {
  38. this.tree = tree;
  39. this.Model = model;
  40. if (parentBranchIfAny != null) {
  41. Depth = parentBranchIfAny.Depth + 1;
  42. Parent = parentBranchIfAny;
  43. }
  44. }
  45. /// <summary>
  46. /// Fetch the children of this branch. This method populates <see cref="ChildBranches"/>.
  47. /// </summary>
  48. public virtual void FetchChildren ()
  49. {
  50. if (tree.TreeBuilder == null) {
  51. return;
  52. }
  53. IEnumerable<T> children;
  54. if (Depth >= tree.MaxDepth) {
  55. children = Enumerable.Empty<T> ();
  56. }
  57. else {
  58. children = tree.TreeBuilder.GetChildren (this.Model) ?? Enumerable.Empty<T> ();
  59. }
  60. this.ChildBranches = children.ToDictionary (k => k, val => new Branch<T> (tree, this, val));
  61. }
  62. /// <summary>
  63. /// Returns the width of the line including prefix and the results
  64. /// of <see cref="TreeView{T}.AspectGetter"/> (the line body).
  65. /// </summary>
  66. /// <returns></returns>
  67. public virtual int GetWidth (ConsoleDriver driver)
  68. {
  69. return
  70. GetLinePrefix (driver).Sum (Rune.ColumnWidth) +
  71. Rune.ColumnWidth (GetExpandableSymbol (driver)) +
  72. (tree.AspectGetter (Model) ?? "").Length;
  73. }
  74. /// <summary>
  75. /// Renders the current <see cref="Model"/> on the specified line <paramref name="y"/>.
  76. /// </summary>
  77. /// <param name="driver"></param>
  78. /// <param name="colorScheme"></param>
  79. /// <param name="y"></param>
  80. /// <param name="availableWidth"></param>
  81. public virtual void Draw (ConsoleDriver driver, ColorScheme colorScheme, int y, int availableWidth)
  82. {
  83. // true if the current line of the tree is the selected one and control has focus
  84. bool isSelected = tree.IsSelected (Model);
  85. Attribute textColor = isSelected ? (tree.HasFocus ? colorScheme.Focus : colorScheme.HotNormal) : colorScheme.Normal;
  86. Attribute symbolColor = tree.Style.HighlightModelTextOnly ? colorScheme.Normal : textColor;
  87. // Everything on line before the expansion run and branch text
  88. Rune [] prefix = GetLinePrefix (driver).ToArray ();
  89. Rune expansion = GetExpandableSymbol (driver);
  90. string lineBody = tree.AspectGetter (Model) ?? "";
  91. tree.Move (0, y);
  92. // if we have scrolled to the right then bits of the prefix will have dispeared off the screen
  93. int toSkip = tree.ScrollOffsetHorizontal;
  94. driver.SetAttribute (symbolColor);
  95. // Draw the line prefix (all parallel lanes or whitespace and an expand/collapse/leaf symbol)
  96. foreach (Rune r in prefix) {
  97. if (toSkip > 0) {
  98. toSkip--;
  99. } else {
  100. driver.AddRune (r);
  101. availableWidth -= Rune.ColumnWidth (r);
  102. }
  103. }
  104. // pick color for expanded symbol
  105. if (tree.Style.ColorExpandSymbol || tree.Style.InvertExpandSymbolColors) {
  106. Attribute color = symbolColor;
  107. if (tree.Style.ColorExpandSymbol) {
  108. if (isSelected) {
  109. color = tree.Style.HighlightModelTextOnly ? colorScheme.HotNormal : (tree.HasFocus ? tree.ColorScheme.HotFocus : tree.ColorScheme.HotNormal);
  110. } else {
  111. color = tree.ColorScheme.HotNormal;
  112. }
  113. } else {
  114. color = symbolColor;
  115. }
  116. if (tree.Style.InvertExpandSymbolColors) {
  117. color = new Attribute (color.Background, color.Foreground);
  118. }
  119. driver.SetAttribute (color);
  120. }
  121. if (toSkip > 0) {
  122. toSkip--;
  123. } else {
  124. driver.AddRune (expansion);
  125. availableWidth -= Rune.ColumnWidth (expansion);
  126. }
  127. // horizontal scrolling has already skipped the prefix but now must also skip some of the line body
  128. if (toSkip > 0) {
  129. if (toSkip > lineBody.Length) {
  130. lineBody = "";
  131. } else {
  132. lineBody = lineBody.Substring (toSkip);
  133. }
  134. }
  135. // If body of line is too long
  136. if (lineBody.Sum (l => Rune.ColumnWidth (l)) > availableWidth) {
  137. // remaining space is zero and truncate the line
  138. lineBody = new string (lineBody.TakeWhile (c => (availableWidth -= Rune.ColumnWidth (c)) >= 0).ToArray ());
  139. availableWidth = 0;
  140. } else {
  141. // line is short so remaining width will be whatever comes after the line body
  142. availableWidth -= lineBody.Length;
  143. }
  144. // default behaviour is for model to use the color scheme
  145. // of the tree view
  146. var modelColor = textColor;
  147. // if custom color delegate invoke it
  148. if (tree.ColorGetter != null) {
  149. var modelScheme = tree.ColorGetter (Model);
  150. // if custom color scheme is defined for this Model
  151. if (modelScheme != null) {
  152. // use it
  153. modelColor = isSelected ? modelScheme.Focus : modelScheme.Normal;
  154. }
  155. }
  156. driver.SetAttribute (modelColor);
  157. driver.AddStr (lineBody);
  158. if (availableWidth > 0) {
  159. driver.SetAttribute (symbolColor);
  160. driver.AddStr (new string (' ', availableWidth));
  161. }
  162. driver.SetAttribute (colorScheme.Normal);
  163. }
  164. /// <summary>
  165. /// Gets all characters to render prior to the current branches line. This includes indentation
  166. /// whitespace and any tree branches (if enabled).
  167. /// </summary>
  168. /// <param name="driver"></param>
  169. /// <returns></returns>
  170. private IEnumerable<Rune> GetLinePrefix (ConsoleDriver driver)
  171. {
  172. // If not showing line branches or this is a root object.
  173. if (!tree.Style.ShowBranchLines) {
  174. for (int i = 0; i < Depth; i++) {
  175. yield return new Rune (' ');
  176. }
  177. yield break;
  178. }
  179. // yield indentations with runes appropriate to the state of the parents
  180. foreach (var cur in GetParentBranches ().Reverse ()) {
  181. if (cur.IsLast ()) {
  182. yield return new Rune (' ');
  183. } else {
  184. yield return driver.VLine;
  185. }
  186. yield return new Rune (' ');
  187. }
  188. if (IsLast ()) {
  189. yield return driver.LLCorner;
  190. } else {
  191. yield return driver.LeftTee;
  192. }
  193. }
  194. /// <summary>
  195. /// Returns all parents starting with the immediate parent and ending at the root.
  196. /// </summary>
  197. /// <returns></returns>
  198. private IEnumerable<Branch<T>> GetParentBranches ()
  199. {
  200. var cur = Parent;
  201. while (cur != null) {
  202. yield return cur;
  203. cur = cur.Parent;
  204. }
  205. }
  206. /// <summary>
  207. /// Returns an appropriate symbol for displaying next to the string representation of
  208. /// the <see cref="Model"/> object to indicate whether it <see cref="IsExpanded"/> or
  209. /// not (or it is a leaf).
  210. /// </summary>
  211. /// <param name="driver"></param>
  212. /// <returns></returns>
  213. public Rune GetExpandableSymbol (ConsoleDriver driver)
  214. {
  215. var leafSymbol = tree.Style.ShowBranchLines ? driver.HLine : ' ';
  216. if (IsExpanded) {
  217. return tree.Style.CollapseableSymbol ?? leafSymbol;
  218. }
  219. if (CanExpand ()) {
  220. return tree.Style.ExpandableSymbol ?? leafSymbol;
  221. }
  222. return leafSymbol;
  223. }
  224. /// <summary>
  225. /// Returns true if the current branch can be expanded according to
  226. /// the <see cref="TreeBuilder{T}"/> or cached children already fetched.
  227. /// </summary>
  228. /// <returns></returns>
  229. public bool CanExpand ()
  230. {
  231. // if we do not know the children yet
  232. if (ChildBranches == null) {
  233. //if there is a rapid method for determining whether there are children
  234. if (tree.TreeBuilder.SupportsCanExpand) {
  235. return tree.TreeBuilder.CanExpand (Model);
  236. }
  237. //there is no way of knowing whether we can expand without fetching the children
  238. FetchChildren ();
  239. }
  240. //we fetched or already know the children, so return whether we have any
  241. return ChildBranches.Any ();
  242. }
  243. /// <summary>
  244. /// Expands the current branch if possible.
  245. /// </summary>
  246. public void Expand ()
  247. {
  248. if (ChildBranches == null) {
  249. FetchChildren ();
  250. }
  251. if (ChildBranches.Any ()) {
  252. IsExpanded = true;
  253. }
  254. }
  255. /// <summary>
  256. /// Marks the branch as collapsed (<see cref="IsExpanded"/> false).
  257. /// </summary>
  258. public void Collapse ()
  259. {
  260. IsExpanded = false;
  261. }
  262. /// <summary>
  263. /// Refreshes cached knowledge in this branch e.g. what children an object has.
  264. /// </summary>
  265. /// <param name="startAtTop">True to also refresh all <see cref="Parent"/>
  266. /// branches (starting with the root).</param>
  267. public void Refresh (bool startAtTop)
  268. {
  269. // if we must go up and refresh from the top down
  270. if (startAtTop) {
  271. Parent?.Refresh (true);
  272. }
  273. // we don't want to loose the state of our children so lets be selective about how we refresh
  274. //if we don't know about any children yet just use the normal method
  275. if (ChildBranches == null) {
  276. FetchChildren ();
  277. } else {
  278. // we already knew about some children so preserve the state of the old children
  279. // first gather the new Children
  280. var newChildren = tree.TreeBuilder?.GetChildren (this.Model) ?? Enumerable.Empty<T> ();
  281. // Children who no longer appear need to go
  282. foreach (var toRemove in ChildBranches.Keys.Except (newChildren).ToArray ()) {
  283. ChildBranches.Remove (toRemove);
  284. //also if the user has this node selected (its disapearing) so lets change selection to us (the parent object) to be helpful
  285. if (Equals (tree.SelectedObject, toRemove)) {
  286. tree.SelectedObject = Model;
  287. }
  288. }
  289. // New children need to be added
  290. foreach (var newChild in newChildren) {
  291. // If we don't know about the child yet we need a new branch
  292. if (!ChildBranches.ContainsKey (newChild)) {
  293. ChildBranches.Add (newChild, new Branch<T> (tree, this, newChild));
  294. } else {
  295. //we already have this object but update the reference anyway incase Equality match but the references are new
  296. ChildBranches [newChild].Model = newChild;
  297. }
  298. }
  299. }
  300. }
  301. /// <summary>
  302. /// Calls <see cref="Refresh(bool)"/> on the current branch and all expanded children.
  303. /// </summary>
  304. internal void Rebuild ()
  305. {
  306. Refresh (false);
  307. // if we know about our children
  308. if (ChildBranches != null) {
  309. if (IsExpanded) {
  310. //if we are expanded we need to updatethe visible children
  311. foreach (var child in ChildBranches) {
  312. child.Value.Rebuild ();
  313. }
  314. } else {
  315. // we are not expanded so should forget about children because they may not exist anymore
  316. ChildBranches = null;
  317. }
  318. }
  319. }
  320. /// <summary>
  321. /// Returns true if this branch has parents and it is the last node of it's parents
  322. /// branches (or last root of the tree).
  323. /// </summary>
  324. /// <returns></returns>
  325. private bool IsLast ()
  326. {
  327. if (Parent == null) {
  328. return this == tree.roots.Values.LastOrDefault ();
  329. }
  330. return Parent.ChildBranches.Values.LastOrDefault () == this;
  331. }
  332. /// <summary>
  333. /// Returns true if the given x offset on the branch line is the +/- symbol. Returns
  334. /// false if not showing expansion symbols or leaf node etc.
  335. /// </summary>
  336. /// <param name="driver"></param>
  337. /// <param name="x"></param>
  338. /// <returns></returns>
  339. internal bool IsHitOnExpandableSymbol (ConsoleDriver driver, int x)
  340. {
  341. // if leaf node then we cannot expand
  342. if (!CanExpand ()) {
  343. return false;
  344. }
  345. // if we could theoretically expand
  346. if (!IsExpanded && tree.Style.ExpandableSymbol != null) {
  347. return x == GetLinePrefix (driver).Count ();
  348. }
  349. // if we could theoretically collapse
  350. if (IsExpanded && tree.Style.CollapseableSymbol != null) {
  351. return x == GetLinePrefix (driver).Count ();
  352. }
  353. return false;
  354. }
  355. /// <summary>
  356. /// Expands the current branch and all children branches.
  357. /// </summary>
  358. internal void ExpandAll ()
  359. {
  360. Expand ();
  361. if (ChildBranches != null) {
  362. foreach (var child in ChildBranches) {
  363. child.Value.ExpandAll ();
  364. }
  365. }
  366. }
  367. /// <summary>
  368. /// Collapses the current branch and all children branches (even though those branches are
  369. /// no longer visible they retain collapse/expansion state).
  370. /// </summary>
  371. internal void CollapseAll ()
  372. {
  373. Collapse ();
  374. if (ChildBranches != null) {
  375. foreach (var child in ChildBranches) {
  376. child.Value.CollapseAll ();
  377. }
  378. }
  379. }
  380. }
  381. }