Branch.cs 14 KB

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