Branch.cs 17 KB

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