Branch.cs 13 KB

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