Branch.cs 14 KB

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