Branch.cs 17 KB

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