Branch.cs 17 KB

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