Branch.cs 13 KB

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