TreeView.cs 44 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515
  1. // This code is based on http://objectlistview.sourceforge.net (GPLv3 tree/list controls
  2. // by [email protected]). Phillip has explicitly granted permission for his design
  3. // and code to be used in this library under the MIT license.
  4. using System.Text;
  5. using System;
  6. using System.Collections.Generic;
  7. using System.Collections.ObjectModel;
  8. using System.Linq;
  9. using Terminal.Gui;
  10. namespace Terminal.Gui {
  11. /// <summary>
  12. /// Interface for all non generic members of <see cref="TreeView{T}"/>.
  13. ///
  14. /// <a href="https://gui-cs.github.io/Terminal.Gui/articles/treeview.html">See TreeView Deep Dive for more information</a>.
  15. /// </summary>
  16. public interface ITreeView {
  17. /// <summary>
  18. /// Contains options for changing how the tree is rendered.
  19. /// </summary>
  20. TreeStyle Style { get; set; }
  21. /// <summary>
  22. /// Removes all objects from the tree and clears selection.
  23. /// </summary>
  24. void ClearObjects ();
  25. /// <summary>
  26. /// Sets a flag indicating this view needs to be redisplayed because its state has changed.
  27. /// </summary>
  28. void SetNeedsDisplay ();
  29. }
  30. /// <summary>
  31. /// Convenience implementation of generic <see cref="TreeView{T}"/> for any tree were all nodes
  32. /// implement <see cref="ITreeNode"/>.
  33. ///
  34. /// <a href="https://gui-cs.github.io/Terminal.Gui/articles/treeview.html">See TreeView Deep Dive for more information</a>.
  35. /// </summary>
  36. public class TreeView : TreeView<ITreeNode> {
  37. /// <summary>
  38. /// Creates a new instance of the tree control with absolute positioning and initialises
  39. /// <see cref="TreeBuilder{T}"/> with default <see cref="ITreeNode"/> based builder.
  40. /// </summary>
  41. public TreeView ()
  42. {
  43. TreeBuilder = new TreeNodeBuilder ();
  44. AspectGetter = o => o == null ? "Null" : (o.Text ?? o?.ToString () ?? "Unamed Node");
  45. }
  46. }
  47. /// <summary>
  48. /// Hierarchical tree view with expandable branches. Branch objects are dynamically determined
  49. /// when expanded using a user defined <see cref="ITreeBuilder{T}"/>.
  50. ///
  51. /// <a href="https://gui-cs.github.io/Terminal.Gui/articles/treeview.html">See TreeView Deep Dive for more information</a>.
  52. /// </summary>
  53. public class TreeView<T> : View, ITreeView where T : class {
  54. private int scrollOffsetVertical;
  55. private int scrollOffsetHorizontal;
  56. /// <summary>
  57. /// Determines how sub branches of the tree are dynamically built at runtime as the user
  58. /// expands root nodes.
  59. /// </summary>
  60. /// <value></value>
  61. public ITreeBuilder<T> TreeBuilder { get; set; }
  62. /// <summary>
  63. /// private variable for <see cref="SelectedObject"/>
  64. /// </summary>
  65. T selectedObject;
  66. /// <summary>
  67. /// Contains options for changing how the tree is rendered.
  68. /// </summary>
  69. public TreeStyle Style { get; set; } = new TreeStyle ();
  70. /// <summary>
  71. /// True to allow multiple objects to be selected at once.
  72. /// </summary>
  73. /// <value></value>
  74. public bool MultiSelect { get; set; } = true;
  75. /// <summary>
  76. /// Maximum number of nodes that can be expanded in any given branch.
  77. /// </summary>
  78. public int MaxDepth { get; set; } = 100;
  79. /// <summary>
  80. /// True makes a letter key press navigate to the next visible branch that begins with
  81. /// that letter/digit.
  82. /// </summary>
  83. /// <value></value>
  84. public bool AllowLetterBasedNavigation { get; set; } = true;
  85. /// <summary>
  86. /// The currently selected object in the tree. When <see cref="MultiSelect"/> is true this
  87. /// is the object at which the cursor is at.
  88. /// </summary>
  89. public T SelectedObject {
  90. get => selectedObject;
  91. set {
  92. var oldValue = selectedObject;
  93. selectedObject = value;
  94. if (!ReferenceEquals (oldValue, value)) {
  95. OnSelectionChanged (new SelectionChangedEventArgs<T> (this, oldValue, value));
  96. }
  97. }
  98. }
  99. /// <summary>
  100. /// This event is raised when an object is activated e.g. by double clicking or
  101. /// pressing <see cref="ObjectActivationKey"/>.
  102. /// </summary>
  103. public event EventHandler<ObjectActivatedEventArgs<T>> ObjectActivated;
  104. /// <summary>
  105. /// Key which when pressed triggers <see cref="TreeView{T}.ObjectActivated"/>.
  106. /// Defaults to Enter.
  107. /// </summary>
  108. public Key ObjectActivationKey {
  109. get => objectActivationKey;
  110. set {
  111. if (objectActivationKey != value) {
  112. ReplaceKeyBinding (ObjectActivationKey, value);
  113. objectActivationKey = value;
  114. }
  115. }
  116. }
  117. /// <summary>
  118. /// Mouse event to trigger <see cref="TreeView{T}.ObjectActivated"/>.
  119. /// Defaults to double click (<see cref="MouseFlags.Button1DoubleClicked"/>).
  120. /// Set to null to disable this feature.
  121. /// </summary>
  122. /// <value></value>
  123. public MouseFlags? ObjectActivationButton { get; set; } = MouseFlags.Button1DoubleClicked;
  124. /// <summary>
  125. /// Delegate for multi colored tree views. Return the <see cref="ColorScheme"/> to use
  126. /// for each passed object or null to use the default.
  127. /// </summary>
  128. public Func<T, ColorScheme> ColorGetter { get; set; }
  129. /// <summary>
  130. /// Secondary selected regions of tree when <see cref="MultiSelect"/> is true.
  131. /// </summary>
  132. private Stack<TreeSelection<T>> multiSelectedRegions = new Stack<TreeSelection<T>> ();
  133. /// <summary>
  134. /// Cached result of <see cref="BuildLineMap"/>
  135. /// </summary>
  136. private IReadOnlyCollection<Branch<T>> cachedLineMap;
  137. /// <summary>
  138. /// Error message to display when the control is not properly initialized at draw time
  139. /// (nodes added but no tree builder set).
  140. /// </summary>
  141. public static string NoBuilderError = "ERROR: TreeBuilder Not Set";
  142. private Key objectActivationKey = Key.Enter;
  143. /// <summary>
  144. /// Called when the <see cref="SelectedObject"/> changes.
  145. /// </summary>
  146. public event EventHandler<SelectionChangedEventArgs<T>> SelectionChanged;
  147. /// <summary>
  148. /// Called once for each visible row during rendering. Can be used
  149. /// to make last minute changes to color or text rendered
  150. /// </summary>
  151. public event EventHandler<DrawTreeViewLineEventArgs<T>> DrawLine;
  152. /// <summary>
  153. /// The root objects in the tree, note that this collection is of root objects only.
  154. /// </summary>
  155. public IEnumerable<T> Objects { get => roots.Keys; }
  156. /// <summary>
  157. /// Map of root objects to the branches under them. All objects have
  158. /// a <see cref="Branch{T}"/> even if that branch has no children.
  159. /// </summary>
  160. internal Dictionary<T, Branch<T>> roots { get; set; } = new Dictionary<T, Branch<T>> ();
  161. /// <summary>
  162. /// The amount of tree view that has been scrolled off the top of the screen (by the user
  163. /// scrolling down).
  164. /// </summary>
  165. /// <remarks>Setting a value of less than 0 will result in a offset of 0. To see changes
  166. /// in the UI call <see cref="View.SetNeedsDisplay()"/>.</remarks>
  167. public int ScrollOffsetVertical {
  168. get => scrollOffsetVertical;
  169. set {
  170. scrollOffsetVertical = Math.Max (0, value);
  171. }
  172. }
  173. /// <summary>
  174. /// The amount of tree view that has been scrolled to the right (horizontally).
  175. /// </summary>
  176. /// <remarks>Setting a value of less than 0 will result in a offset of 0. To see changes
  177. /// in the UI call <see cref="View.SetNeedsDisplay()"/>.</remarks>
  178. public int ScrollOffsetHorizontal {
  179. get => scrollOffsetHorizontal;
  180. set {
  181. scrollOffsetHorizontal = Math.Max (0, value);
  182. }
  183. }
  184. /// <summary>
  185. /// The current number of rows in the tree (ignoring the controls bounds).
  186. /// </summary>
  187. public int ContentHeight => BuildLineMap ().Count ();
  188. /// <summary>
  189. /// Returns the string representation of model objects hosted in the tree. Default
  190. /// implementation is to call <see cref="object.ToString"/>.
  191. /// </summary>
  192. /// <value></value>
  193. public AspectGetterDelegate<T> AspectGetter { get; set; } = (o) => o.ToString () ?? "";
  194. CursorVisibility desiredCursorVisibility = CursorVisibility.Invisible;
  195. /// <summary>
  196. /// Interface for filtering which lines of the tree are displayed
  197. /// e.g. to provide text searching. Defaults to <see langword="null"/>
  198. /// (no filtering).
  199. /// </summary>
  200. public ITreeViewFilter<T> Filter = null;
  201. /// <summary>
  202. /// Get / Set the wished cursor when the tree is focused.
  203. /// Only applies when <see cref="MultiSelect"/> is true.
  204. /// Defaults to <see cref="CursorVisibility.Invisible"/>.
  205. /// </summary>
  206. public CursorVisibility DesiredCursorVisibility {
  207. get {
  208. return MultiSelect ? desiredCursorVisibility : CursorVisibility.Invisible;
  209. }
  210. set {
  211. if (desiredCursorVisibility != value) {
  212. desiredCursorVisibility = value;
  213. if (HasFocus) {
  214. Application.Driver.SetCursorVisibility (DesiredCursorVisibility);
  215. }
  216. }
  217. }
  218. }
  219. /// <summary>
  220. /// Creates a new tree view with absolute positioning.
  221. /// Use <see cref="AddObjects(IEnumerable{T})"/> to set set root objects for the tree.
  222. /// Children will not be rendered until you set <see cref="TreeBuilder"/>.
  223. /// </summary>
  224. public TreeView () : base ()
  225. {
  226. CanFocus = true;
  227. // Things this view knows how to do
  228. AddCommand (Command.PageUp, () => { MovePageUp (false); return true; });
  229. AddCommand (Command.PageDown, () => { MovePageDown (false); return true; });
  230. AddCommand (Command.PageUpExtend, () => { MovePageUp (true); return true; });
  231. AddCommand (Command.PageDownExtend, () => { MovePageDown (true); return true; });
  232. AddCommand (Command.Expand, () => { Expand (); return true; });
  233. AddCommand (Command.ExpandAll, () => { ExpandAll (SelectedObject); return true; });
  234. AddCommand (Command.Collapse, () => { CursorLeft (false); return true; });
  235. AddCommand (Command.CollapseAll, () => { CursorLeft (true); return true; });
  236. AddCommand (Command.LineUp, () => { AdjustSelection (-1, false); return true; });
  237. AddCommand (Command.LineUpExtend, () => { AdjustSelection (-1, true); return true; });
  238. AddCommand (Command.LineUpToFirstBranch, () => { AdjustSelectionToBranchStart (); return true; });
  239. AddCommand (Command.LineDown, () => { AdjustSelection (1, false); return true; });
  240. AddCommand (Command.LineDownExtend, () => { AdjustSelection (1, true); return true; });
  241. AddCommand (Command.LineDownToLastBranch, () => { AdjustSelectionToBranchEnd (); return true; });
  242. AddCommand (Command.TopHome, () => { GoToFirst (); return true; });
  243. AddCommand (Command.BottomEnd, () => { GoToEnd (); return true; });
  244. AddCommand (Command.SelectAll, () => { SelectAll (); return true; });
  245. AddCommand (Command.ScrollUp, () => { ScrollUp (); return true; });
  246. AddCommand (Command.ScrollDown, () => { ScrollDown (); return true; });
  247. AddCommand (Command.Accept, () => { ActivateSelectedObjectIfAny (); return true; });
  248. // Default keybindings for this view
  249. AddKeyBinding (Key.PageUp, Command.PageUp);
  250. AddKeyBinding (Key.PageDown, Command.PageDown);
  251. AddKeyBinding (Key.PageUp | Key.ShiftMask, Command.PageUpExtend);
  252. AddKeyBinding (Key.PageDown | Key.ShiftMask, Command.PageDownExtend);
  253. AddKeyBinding (Key.CursorRight, Command.Expand);
  254. AddKeyBinding (Key.CursorRight | Key.CtrlMask, Command.ExpandAll);
  255. AddKeyBinding (Key.CursorLeft, Command.Collapse);
  256. AddKeyBinding (Key.CursorLeft | Key.CtrlMask, Command.CollapseAll);
  257. AddKeyBinding (Key.CursorUp, Command.LineUp);
  258. AddKeyBinding (Key.CursorUp | Key.ShiftMask, Command.LineUpExtend);
  259. AddKeyBinding (Key.CursorUp | Key.CtrlMask, Command.LineUpToFirstBranch);
  260. AddKeyBinding (Key.CursorDown, Command.LineDown);
  261. AddKeyBinding (Key.CursorDown | Key.ShiftMask, Command.LineDownExtend);
  262. AddKeyBinding (Key.CursorDown | Key.CtrlMask, Command.LineDownToLastBranch);
  263. AddKeyBinding (Key.Home, Command.TopHome);
  264. AddKeyBinding (Key.End, Command.BottomEnd);
  265. AddKeyBinding (Key.A | Key.CtrlMask, Command.SelectAll);
  266. AddKeyBinding (ObjectActivationKey, Command.Accept);
  267. }
  268. /// <summary>
  269. /// Initialises <see cref="TreeBuilder"/>.Creates a new tree view with absolute
  270. /// positioning. Use <see cref="AddObjects(IEnumerable{T})"/> to set set root
  271. /// objects for the tree.
  272. /// </summary>
  273. public TreeView (ITreeBuilder<T> builder) : this ()
  274. {
  275. TreeBuilder = builder;
  276. }
  277. ///<inheritdoc/>
  278. public override bool OnEnter (View view)
  279. {
  280. Application.Driver.SetCursorVisibility (DesiredCursorVisibility);
  281. if (SelectedObject == null && Objects.Any ()) {
  282. SelectedObject = Objects.First ();
  283. }
  284. return base.OnEnter (view);
  285. }
  286. /// <summary>
  287. /// Adds a new root level object unless it is already a root of the tree.
  288. /// </summary>
  289. /// <param name="o"></param>
  290. public void AddObject (T o)
  291. {
  292. if (!roots.ContainsKey (o)) {
  293. roots.Add (o, new Branch<T> (this, null, o));
  294. InvalidateLineMap ();
  295. SetNeedsDisplay ();
  296. }
  297. }
  298. /// <summary>
  299. /// Removes all objects from the tree and clears <see cref="SelectedObject"/>.
  300. /// </summary>
  301. public void ClearObjects ()
  302. {
  303. SelectedObject = default (T);
  304. multiSelectedRegions.Clear ();
  305. roots = new Dictionary<T, Branch<T>> ();
  306. InvalidateLineMap ();
  307. SetNeedsDisplay ();
  308. }
  309. /// <summary>
  310. /// Removes the given root object from the tree
  311. /// </summary>
  312. /// <remarks>If <paramref name="o"/> is the currently <see cref="SelectedObject"/> then the
  313. /// selection is cleared</remarks>.
  314. /// <param name="o"></param>
  315. public void Remove (T o)
  316. {
  317. if (roots.ContainsKey (o)) {
  318. roots.Remove (o);
  319. InvalidateLineMap ();
  320. SetNeedsDisplay ();
  321. if (Equals (SelectedObject, o)) {
  322. SelectedObject = default (T);
  323. }
  324. }
  325. }
  326. /// <summary>
  327. /// Adds many new root level objects. Objects that are already root objects are ignored.
  328. /// </summary>
  329. /// <param name="collection">Objects to add as new root level objects.</param>.\
  330. public void AddObjects (IEnumerable<T> collection)
  331. {
  332. bool objectsAdded = false;
  333. foreach (var o in collection) {
  334. if (!roots.ContainsKey (o)) {
  335. roots.Add (o, new Branch<T> (this, null, o));
  336. objectsAdded = true;
  337. }
  338. }
  339. if (objectsAdded) {
  340. InvalidateLineMap ();
  341. SetNeedsDisplay ();
  342. }
  343. }
  344. /// <summary>
  345. /// Refreshes the state of the object <paramref name="o"/> in the tree. This will
  346. /// recompute children, string representation etc.
  347. /// </summary>
  348. /// <remarks>This has no effect if the object is not exposed in the tree.</remarks>
  349. /// <param name="o"></param>
  350. /// <param name="startAtTop">True to also refresh all ancestors of the objects branch
  351. /// (starting with the root). False to refresh only the passed node.</param>
  352. public void RefreshObject (T o, bool startAtTop = false)
  353. {
  354. var branch = ObjectToBranch (o);
  355. if (branch != null) {
  356. branch.Refresh (startAtTop);
  357. InvalidateLineMap ();
  358. SetNeedsDisplay ();
  359. }
  360. }
  361. /// <summary>
  362. /// Rebuilds the tree structure for all exposed objects starting with the root objects.
  363. /// Call this method when you know there are changes to the tree but don't know which
  364. /// objects have changed (otherwise use <see cref="RefreshObject(T, bool)"/>).
  365. /// </summary>
  366. public void RebuildTree ()
  367. {
  368. foreach (var branch in roots.Values) {
  369. branch.Rebuild ();
  370. }
  371. InvalidateLineMap ();
  372. SetNeedsDisplay ();
  373. }
  374. /// <summary>
  375. /// Returns the currently expanded children of the passed object. Returns an empty
  376. /// collection if the branch is not exposed or not expanded.
  377. /// </summary>
  378. /// <param name="o">An object in the tree.</param>
  379. /// <returns></returns>
  380. public IEnumerable<T> GetChildren (T o)
  381. {
  382. var branch = ObjectToBranch (o);
  383. if (branch == null || !branch.IsExpanded) {
  384. return new T [0];
  385. }
  386. return branch.ChildBranches?.Values?.Select (b => b.Model)?.ToArray () ?? new T [0];
  387. }
  388. /// <summary>
  389. /// Returns the parent object of <paramref name="o"/> in the tree. Returns null if
  390. /// the object is not exposed in the tree.
  391. /// </summary>
  392. /// <param name="o">An object in the tree.</param>
  393. /// <returns></returns>
  394. public T GetParent (T o)
  395. {
  396. return ObjectToBranch (o)?.Parent?.Model;
  397. }
  398. ///<inheritdoc/>
  399. public override void OnDrawContent (Rect contentArea)
  400. {
  401. if (roots == null) {
  402. return;
  403. }
  404. if (TreeBuilder == null) {
  405. Move (0, 0);
  406. Driver.AddStr (NoBuilderError);
  407. return;
  408. }
  409. var map = BuildLineMap ();
  410. for (int line = 0; line < Bounds.Height; line++) {
  411. var idxToRender = ScrollOffsetVertical + line;
  412. // Is there part of the tree view to render?
  413. if (idxToRender < map.Count) {
  414. // Render the line
  415. map.ElementAt (idxToRender).Draw (Driver, ColorScheme, line, Bounds.Width);
  416. } else {
  417. // Else clear the line to prevent stale symbols due to scrolling etc
  418. Move (0, line);
  419. Driver.SetAttribute (GetNormalColor ());
  420. Driver.AddStr (new string (' ', Bounds.Width));
  421. }
  422. }
  423. }
  424. /// <summary>
  425. /// Returns the index of the object <paramref name="o"/> if it is currently exposed (it's
  426. /// parent(s) have been expanded). This can be used with <see cref="ScrollOffsetVertical"/>
  427. /// and <see cref="View.SetNeedsDisplay()"/> to scroll to a specific object.
  428. /// </summary>
  429. /// <remarks>Uses the Equals method and returns the first index at which the object is found
  430. /// or -1 if it is not found.</remarks>
  431. /// <param name="o">An object that appears in your tree and is currently exposed.</param>
  432. /// <returns>The index the object was found at or -1 if it is not currently revealed or
  433. /// not in the tree at all.</returns>
  434. public int GetScrollOffsetOf (T o)
  435. {
  436. var map = BuildLineMap ();
  437. for (int i = 0; i < map.Count; i++) {
  438. if (map.ElementAt (i).Model.Equals (o)) {
  439. return i;
  440. }
  441. }
  442. //object not found
  443. return -1;
  444. }
  445. /// <summary>
  446. /// Returns the maximum width line in the tree including prefix and expansion symbols.
  447. /// </summary>
  448. /// <param name="visible">True to consider only rows currently visible (based on window
  449. /// bounds and <see cref="ScrollOffsetVertical"/>. False to calculate the width of
  450. /// every exposed branch in the tree.</param>
  451. /// <returns></returns>
  452. public int GetContentWidth (bool visible)
  453. {
  454. var map = BuildLineMap ();
  455. if (map.Count == 0) {
  456. return 0;
  457. }
  458. if (visible) {
  459. //Somehow we managed to scroll off the end of the control
  460. if (ScrollOffsetVertical >= map.Count) {
  461. return 0;
  462. }
  463. // If control has no height to it then there is no visible area for content
  464. if (Bounds.Height == 0) {
  465. return 0;
  466. }
  467. return map.Skip (ScrollOffsetVertical).Take (Bounds.Height).Max (b => b.GetWidth (Driver));
  468. } else {
  469. return map.Max (b => b.GetWidth (Driver));
  470. }
  471. }
  472. /// <summary>
  473. /// Calculates all currently visible/expanded branches (including leafs) and outputs them
  474. /// by index from the top of the screen.
  475. /// </summary>
  476. /// <remarks>Index 0 of the returned array is the first item that should be visible in the
  477. /// top of the control, index 1 is the next etc.</remarks>
  478. /// <returns></returns>
  479. internal IReadOnlyCollection<Branch<T>> BuildLineMap ()
  480. {
  481. if (cachedLineMap != null) {
  482. return cachedLineMap;
  483. }
  484. List<Branch<T>> toReturn = new List<Branch<T>> ();
  485. foreach (var root in roots.Values) {
  486. var toAdd = AddToLineMap (root, false, out var isMatch);
  487. if(isMatch)
  488. {
  489. toReturn.AddRange (toAdd);
  490. }
  491. }
  492. cachedLineMap = new ReadOnlyCollection<Branch<T>> (toReturn);
  493. // Update the collection used for search-typing
  494. KeystrokeNavigator.Collection = cachedLineMap.Select (b => AspectGetter (b.Model)).ToArray ();
  495. return cachedLineMap;
  496. }
  497. private bool IsFilterMatch (Branch<T> branch)
  498. {
  499. return Filter?.IsMatch(branch.Model) ?? true;
  500. }
  501. private IEnumerable<Branch<T>> AddToLineMap (Branch<T> currentBranch,bool parentMatches, out bool match)
  502. {
  503. bool weMatch = IsFilterMatch(currentBranch);
  504. bool anyChildMatches = false;
  505. var toReturn = new List<Branch<T>>();
  506. var children = new List<Branch<T>>();
  507. if (currentBranch.IsExpanded) {
  508. foreach (var subBranch in currentBranch.ChildBranches.Values) {
  509. foreach (var sub in AddToLineMap (subBranch, weMatch, out var childMatch)) {
  510. if(childMatch)
  511. {
  512. children.Add(sub);
  513. anyChildMatches = true;
  514. }
  515. }
  516. }
  517. }
  518. if(parentMatches || weMatch || anyChildMatches)
  519. {
  520. match = true;
  521. toReturn.Add(currentBranch);
  522. }
  523. else{
  524. match = false;
  525. }
  526. toReturn.AddRange(children);
  527. return toReturn;
  528. }
  529. /// <summary>
  530. /// Gets the <see cref="CollectionNavigator"/> that searches the <see cref="Objects"/> collection as
  531. /// the user types.
  532. /// </summary>
  533. public CollectionNavigator KeystrokeNavigator { get; private set; } = new CollectionNavigator ();
  534. /// <inheritdoc/>
  535. public override bool ProcessKey (KeyEvent keyEvent)
  536. {
  537. if (!Enabled) {
  538. return false;
  539. }
  540. try {
  541. // First of all deal with any registered keybindings
  542. var result = InvokeKeybindings (keyEvent);
  543. if (result != null) {
  544. return (bool)result;
  545. }
  546. // If not a keybinding, is the key a searchable key press?
  547. if (CollectionNavigator.IsCompatibleKey (keyEvent) && AllowLetterBasedNavigation) {
  548. IReadOnlyCollection<Branch<T>> map;
  549. // If there has been a call to InvalidateMap since the last time
  550. // we need a new one to reflect the new exposed tree state
  551. map = BuildLineMap ();
  552. // Find the current selected object within the tree
  553. var current = map.IndexOf (b => b.Model == SelectedObject);
  554. var newIndex = KeystrokeNavigator?.GetNextMatchingItem (current, (char)keyEvent.KeyValue);
  555. if (newIndex is int && newIndex != -1) {
  556. SelectedObject = map.ElementAt ((int)newIndex).Model;
  557. EnsureVisible (selectedObject);
  558. SetNeedsDisplay ();
  559. return true;
  560. }
  561. }
  562. } finally {
  563. PositionCursor ();
  564. }
  565. return base.ProcessKey (keyEvent);
  566. }
  567. /// <summary>
  568. /// <para>Triggers the <see cref="ObjectActivated"/> event with the <see cref="SelectedObject"/>.</para>
  569. ///
  570. /// <para>This method also ensures that the selected object is visible.</para>
  571. /// </summary>
  572. public void ActivateSelectedObjectIfAny ()
  573. {
  574. var o = SelectedObject;
  575. if (o != null) {
  576. OnObjectActivated (new ObjectActivatedEventArgs<T> (this, o));
  577. PositionCursor ();
  578. }
  579. }
  580. /// <summary>
  581. /// <para>
  582. /// Returns the Y coordinate within the <see cref="View.Bounds"/> of the
  583. /// tree at which <paramref name="toFind"/> would be displayed or null if
  584. /// it is not currently exposed (e.g. its parent is collapsed).
  585. /// </para>
  586. /// <para>
  587. /// Note that the returned value can be negative if the TreeView is scrolled
  588. /// down and the <paramref name="toFind"/> object is off the top of the view.
  589. /// </para>
  590. /// </summary>
  591. /// <param name="toFind"></param>
  592. /// <returns></returns>
  593. public int? GetObjectRow (T toFind)
  594. {
  595. var idx = BuildLineMap ().IndexOf (o => o.Model.Equals (toFind));
  596. if (idx == -1)
  597. return null;
  598. return idx - ScrollOffsetVertical;
  599. }
  600. /// <summary>
  601. /// <para>Moves the <see cref="SelectedObject"/> to the next item that begins with <paramref name="character"/>.</para>
  602. /// <para>This method will loop back to the start of the tree if reaching the end without finding a match.</para>
  603. /// </summary>
  604. /// <param name="character">The first character of the next item you want selected.</param>
  605. /// <param name="caseSensitivity">Case sensitivity of the search.</param>
  606. public void AdjustSelectionToNextItemBeginningWith (char character, StringComparison caseSensitivity = StringComparison.CurrentCultureIgnoreCase)
  607. {
  608. // search for next branch that begins with that letter
  609. var characterAsStr = character.ToString ();
  610. AdjustSelectionToNext (b => AspectGetter (b.Model).StartsWith (characterAsStr, caseSensitivity));
  611. PositionCursor ();
  612. }
  613. /// <summary>
  614. /// Moves the selection up by the height of the control (1 page).
  615. /// </summary>
  616. /// <param name="expandSelection">True if the navigation should add the covered nodes to the selected current selection.</param>
  617. /// <exception cref="NotImplementedException"></exception>
  618. public void MovePageUp (bool expandSelection = false)
  619. {
  620. AdjustSelection (-Bounds.Height, expandSelection);
  621. }
  622. /// <summary>
  623. /// Moves the selection down by the height of the control (1 page).
  624. /// </summary>
  625. /// <param name="expandSelection">True if the navigation should add the covered nodes to the selected current selection.</param>
  626. /// <exception cref="NotImplementedException"></exception>
  627. public void MovePageDown (bool expandSelection = false)
  628. {
  629. AdjustSelection (Bounds.Height, expandSelection);
  630. }
  631. /// <summary>
  632. /// Scrolls the view area down a single line without changing the current selection.
  633. /// </summary>
  634. public void ScrollDown ()
  635. {
  636. if (ScrollOffsetVertical <= ContentHeight - 2) {
  637. ScrollOffsetVertical++;
  638. SetNeedsDisplay ();
  639. }
  640. }
  641. /// <summary>
  642. /// Scrolls the view area up a single line without changing the current selection.
  643. /// </summary>
  644. public void ScrollUp ()
  645. {
  646. if (scrollOffsetVertical > 0) {
  647. ScrollOffsetVertical--;
  648. SetNeedsDisplay ();
  649. }
  650. }
  651. /// <summary>
  652. /// Raises the <see cref="ObjectActivated"/> event.
  653. /// </summary>
  654. /// <param name="e"></param>
  655. protected virtual void OnObjectActivated (ObjectActivatedEventArgs<T> e)
  656. {
  657. ObjectActivated?.Invoke (this, e);
  658. }
  659. /// <summary>
  660. /// Returns the object in the tree list that is currently visible.
  661. /// at the provided row. Returns null if no object is at that location.
  662. /// <remarks>
  663. /// </remarks>
  664. /// If you have screen coordinates then use <see cref="View.ScreenToView(int, int)"/>
  665. /// to translate these into the client area of the <see cref="TreeView{T}"/>.
  666. /// </summary>
  667. /// <param name="row">The row of the <see cref="View.Bounds"/> of the <see cref="TreeView{T}"/>.</param>
  668. /// <returns>The object currently displayed on this row or null.</returns>
  669. public T GetObjectOnRow (int row)
  670. {
  671. return HitTest (row)?.Model;
  672. }
  673. ///<inheritdoc/>
  674. public override bool MouseEvent (MouseEvent me)
  675. {
  676. // If it is not an event we care about
  677. if (!me.Flags.HasFlag (MouseFlags.Button1Clicked) &&
  678. !me.Flags.HasFlag (ObjectActivationButton ?? MouseFlags.Button1DoubleClicked) &&
  679. !me.Flags.HasFlag (MouseFlags.WheeledDown) &&
  680. !me.Flags.HasFlag (MouseFlags.WheeledUp) &&
  681. !me.Flags.HasFlag (MouseFlags.WheeledRight) &&
  682. !me.Flags.HasFlag (MouseFlags.WheeledLeft)) {
  683. // do nothing
  684. return false;
  685. }
  686. if (!HasFocus && CanFocus) {
  687. SetFocus ();
  688. }
  689. if (me.Flags == MouseFlags.WheeledDown) {
  690. ScrollDown ();
  691. return true;
  692. } else if (me.Flags == MouseFlags.WheeledUp) {
  693. ScrollUp ();
  694. return true;
  695. }
  696. if (me.Flags == MouseFlags.WheeledRight) {
  697. ScrollOffsetHorizontal++;
  698. SetNeedsDisplay ();
  699. return true;
  700. } else if (me.Flags == MouseFlags.WheeledLeft) {
  701. ScrollOffsetHorizontal--;
  702. SetNeedsDisplay ();
  703. return true;
  704. }
  705. if (me.Flags.HasFlag (MouseFlags.Button1Clicked)) {
  706. // The line they clicked on a branch
  707. var clickedBranch = HitTest (me.Y);
  708. if (clickedBranch == null) {
  709. return false;
  710. }
  711. bool isExpandToggleAttempt = clickedBranch.IsHitOnExpandableSymbol (Driver, me.X);
  712. // If we are already selected (double click)
  713. if (Equals (SelectedObject, clickedBranch.Model)) {
  714. isExpandToggleAttempt = true;
  715. }
  716. // if they clicked on the +/- expansion symbol
  717. if (isExpandToggleAttempt) {
  718. if (clickedBranch.IsExpanded) {
  719. clickedBranch.Collapse ();
  720. InvalidateLineMap ();
  721. } else
  722. if (clickedBranch.CanExpand ()) {
  723. clickedBranch.Expand ();
  724. InvalidateLineMap ();
  725. } else {
  726. SelectedObject = clickedBranch.Model; // It is a leaf node
  727. multiSelectedRegions.Clear ();
  728. }
  729. } else {
  730. // It is a first click somewhere in the current line that doesn't look like an expansion/collapse attempt
  731. SelectedObject = clickedBranch.Model;
  732. multiSelectedRegions.Clear ();
  733. }
  734. SetNeedsDisplay ();
  735. return true;
  736. }
  737. // If it is activation via mouse (e.g. double click)
  738. if (ObjectActivationButton.HasValue && me.Flags.HasFlag (ObjectActivationButton.Value)) {
  739. // The line they clicked on a branch
  740. var clickedBranch = HitTest (me.Y);
  741. if (clickedBranch == null) {
  742. return false;
  743. }
  744. // Double click changes the selection to the clicked node as well as triggering
  745. // activation otherwise it feels wierd
  746. SelectedObject = clickedBranch.Model;
  747. SetNeedsDisplay ();
  748. // trigger activation event
  749. OnObjectActivated (new ObjectActivatedEventArgs<T> (this, clickedBranch.Model));
  750. // mouse event is handled.
  751. return true;
  752. }
  753. return false;
  754. }
  755. /// <summary>
  756. /// Returns the branch at the given <paramref name="y"/> client
  757. /// coordinate e.g. following a click event.
  758. /// </summary>
  759. /// <param name="y">Client Y position in the controls bounds.</param>
  760. /// <returns>The clicked branch or null if outside of tree region.</returns>
  761. private Branch<T> HitTest (int y)
  762. {
  763. var map = BuildLineMap ();
  764. var idx = y + ScrollOffsetVertical;
  765. // click is outside any visible nodes
  766. if (idx < 0 || idx >= map.Count) {
  767. return null;
  768. }
  769. // The line they clicked on
  770. return map.ElementAt (idx);
  771. }
  772. /// <summary>
  773. /// Positions the cursor at the start of the selected objects line (if visible).
  774. /// </summary>
  775. public override void PositionCursor ()
  776. {
  777. if (CanFocus && HasFocus && Visible && SelectedObject != null) {
  778. var map = BuildLineMap ();
  779. var idx = map.IndexOf (b => b.Model.Equals (SelectedObject));
  780. // if currently selected line is visible
  781. if (idx - ScrollOffsetVertical >= 0 && idx - ScrollOffsetVertical < Bounds.Height) {
  782. Move (0, idx - ScrollOffsetVertical);
  783. } else {
  784. base.PositionCursor ();
  785. }
  786. } else {
  787. base.PositionCursor ();
  788. }
  789. }
  790. /// <summary>
  791. /// Determines systems behaviour when the left arrow key is pressed. Default behaviour is
  792. /// to collapse the current tree node if possible otherwise changes selection to current
  793. /// branches parent.
  794. /// </summary>
  795. protected virtual void CursorLeft (bool ctrl)
  796. {
  797. if (IsExpanded (SelectedObject)) {
  798. if (ctrl) {
  799. CollapseAll (SelectedObject);
  800. } else {
  801. Collapse (SelectedObject);
  802. }
  803. } else {
  804. var parent = GetParent (SelectedObject);
  805. if (parent != null) {
  806. SelectedObject = parent;
  807. AdjustSelection (0);
  808. SetNeedsDisplay ();
  809. }
  810. }
  811. }
  812. /// <summary>
  813. /// Changes the <see cref="SelectedObject"/> to the first root object and resets
  814. /// the <see cref="ScrollOffsetVertical"/> to 0.
  815. /// </summary>
  816. public void GoToFirst ()
  817. {
  818. ScrollOffsetVertical = 0;
  819. SelectedObject = roots.Keys.FirstOrDefault ();
  820. SetNeedsDisplay ();
  821. }
  822. /// <summary>
  823. /// Changes the <see cref="SelectedObject"/> to the last object in the tree and scrolls so
  824. /// that it is visible.
  825. /// </summary>
  826. public void GoToEnd ()
  827. {
  828. var map = BuildLineMap ();
  829. ScrollOffsetVertical = Math.Max (0, map.Count - Bounds.Height + 1);
  830. SelectedObject = map.LastOrDefault ()?.Model;
  831. SetNeedsDisplay ();
  832. }
  833. /// <summary>
  834. /// Changes the <see cref="SelectedObject"/> to <paramref name="toSelect"/> and scrolls to ensure
  835. /// it is visible. Has no effect if <paramref name="toSelect"/> is not exposed in the tree (e.g.
  836. /// its parents are collapsed).
  837. /// </summary>
  838. /// <param name="toSelect"></param>
  839. public void GoTo (T toSelect)
  840. {
  841. if (ObjectToBranch (toSelect) == null) {
  842. return;
  843. }
  844. SelectedObject = toSelect;
  845. EnsureVisible (toSelect);
  846. SetNeedsDisplay ();
  847. }
  848. /// <summary>
  849. /// The number of screen lines to move the currently selected object by. Supports negative values.
  850. /// <paramref name="offset"/>. Each branch occupies 1 line on screen.
  851. /// </summary>
  852. /// <remarks>If nothing is currently selected or the selected object is no longer in the tree
  853. /// then the first object in the tree is selected instead.</remarks>
  854. /// <param name="offset">Positive to move the selection down the screen, negative to move it up</param>
  855. /// <param name="expandSelection">True to expand the selection (assuming
  856. /// <see cref="MultiSelect"/> is enabled). False to replace.</param>
  857. public void AdjustSelection (int offset, bool expandSelection = false)
  858. {
  859. // if it is not a shift click or we don't allow multi select
  860. if (!expandSelection || !MultiSelect) {
  861. multiSelectedRegions.Clear ();
  862. }
  863. if (SelectedObject == null) {
  864. SelectedObject = roots.Keys.FirstOrDefault ();
  865. } else {
  866. var map = BuildLineMap ();
  867. var idx = map.IndexOf (b => b.Model.Equals (SelectedObject));
  868. if (idx == -1) {
  869. // The current selection has disapeared!
  870. SelectedObject = roots.Keys.FirstOrDefault ();
  871. } else {
  872. var newIdx = Math.Min (Math.Max (0, idx + offset), map.Count - 1);
  873. var newBranch = map.ElementAt (newIdx);
  874. // If it is a multi selection
  875. if (expandSelection && MultiSelect) {
  876. if (multiSelectedRegions.Any ()) {
  877. // expand the existing head selection
  878. var head = multiSelectedRegions.Pop ();
  879. multiSelectedRegions.Push (new TreeSelection<T> (head.Origin, newIdx, map));
  880. } else {
  881. // or start a new multi selection region
  882. multiSelectedRegions.Push (new TreeSelection<T> (map.ElementAt (idx), newIdx, map));
  883. }
  884. }
  885. SelectedObject = newBranch.Model;
  886. EnsureVisible (SelectedObject);
  887. }
  888. }
  889. SetNeedsDisplay ();
  890. }
  891. /// <summary>
  892. /// Moves the selection to the first child in the currently selected level.
  893. /// </summary>
  894. public void AdjustSelectionToBranchStart ()
  895. {
  896. var o = SelectedObject;
  897. if (o == null) {
  898. return;
  899. }
  900. var map = BuildLineMap ();
  901. int currentIdx = map.IndexOf (b => Equals (b.Model, o));
  902. if (currentIdx == -1) {
  903. return;
  904. }
  905. var currentBranch = map.ElementAt (currentIdx);
  906. var next = currentBranch;
  907. for (; currentIdx >= 0; currentIdx--) {
  908. //if it is the beginning of the current depth of branch
  909. if (currentBranch.Depth != next.Depth) {
  910. SelectedObject = currentBranch.Model;
  911. EnsureVisible (currentBranch.Model);
  912. SetNeedsDisplay ();
  913. return;
  914. }
  915. // look at next branch up for consideration
  916. currentBranch = next;
  917. next = map.ElementAt (currentIdx);
  918. }
  919. // We ran all the way to top of tree
  920. GoToFirst ();
  921. }
  922. /// <summary>
  923. /// Moves the selection to the last child in the currently selected level.
  924. /// </summary>
  925. public void AdjustSelectionToBranchEnd ()
  926. {
  927. var o = SelectedObject;
  928. if (o == null) {
  929. return;
  930. }
  931. var map = BuildLineMap ();
  932. int currentIdx = map.IndexOf (b => Equals (b.Model, o));
  933. if (currentIdx == -1) {
  934. return;
  935. }
  936. var currentBranch = map.ElementAt (currentIdx);
  937. var next = currentBranch;
  938. for (; currentIdx < map.Count; currentIdx++) {
  939. //if it is the end of the current depth of branch
  940. if (currentBranch.Depth != next.Depth) {
  941. SelectedObject = currentBranch.Model;
  942. EnsureVisible (currentBranch.Model);
  943. SetNeedsDisplay ();
  944. return;
  945. }
  946. // look at next branch for consideration
  947. currentBranch = next;
  948. next = map.ElementAt (currentIdx);
  949. }
  950. GoToEnd ();
  951. }
  952. /// <summary>
  953. /// Sets the selection to the next branch that matches the <paramref name="predicate"/>.
  954. /// </summary>
  955. /// <param name="predicate"></param>
  956. private void AdjustSelectionToNext (Func<Branch<T>, bool> predicate)
  957. {
  958. var map = BuildLineMap ();
  959. // empty map means we can't select anything anyway
  960. if (map.Count == 0) {
  961. return;
  962. }
  963. // Start searching from the first element in the map
  964. var idxStart = 0;
  965. // or the current selected branch
  966. if (SelectedObject != null) {
  967. idxStart = map.IndexOf (b => Equals (b.Model, SelectedObject));
  968. }
  969. // if currently selected object mysteriously vanished, search from beginning
  970. if (idxStart == -1) {
  971. idxStart = 0;
  972. }
  973. // loop around all indexes and back to first index
  974. for (int idxCur = (idxStart + 1) % map.Count; idxCur != idxStart; idxCur = (idxCur + 1) % map.Count) {
  975. if (predicate (map.ElementAt (idxCur))) {
  976. SelectedObject = map.ElementAt (idxCur).Model;
  977. EnsureVisible (map.ElementAt (idxCur).Model);
  978. SetNeedsDisplay ();
  979. return;
  980. }
  981. }
  982. }
  983. /// <summary>
  984. /// Adjusts the <see cref="ScrollOffsetVertical"/> to ensure the given
  985. /// <paramref name="model"/> is visible. Has no effect if already visible.
  986. /// </summary>
  987. public void EnsureVisible (T model)
  988. {
  989. var map = BuildLineMap ();
  990. var idx = map.IndexOf (b => Equals (b.Model, model));
  991. if (idx == -1) {
  992. return;
  993. }
  994. /*this -1 allows for possible horizontal scroll bar in the last row of the control*/
  995. int leaveSpace = Style.LeaveLastRow ? 1 : 0;
  996. if (idx < ScrollOffsetVertical) {
  997. //if user has scrolled up too far to see their selection
  998. ScrollOffsetVertical = idx;
  999. } else if (idx >= ScrollOffsetVertical + Bounds.Height - leaveSpace) {
  1000. //if user has scrolled off bottom of visible tree
  1001. ScrollOffsetVertical = Math.Max (0, (idx + 1) - (Bounds.Height - leaveSpace));
  1002. }
  1003. }
  1004. /// <summary>
  1005. /// Expands the currently <see cref="SelectedObject"/>.
  1006. /// </summary>
  1007. public void Expand ()
  1008. {
  1009. Expand (SelectedObject);
  1010. }
  1011. /// <summary>
  1012. /// Expands the supplied object if it is contained in the tree (either as a root object or
  1013. /// as an exposed branch object).
  1014. /// </summary>
  1015. /// <param name="toExpand">The object to expand.</param>
  1016. public void Expand (T toExpand)
  1017. {
  1018. if (toExpand == null) {
  1019. return;
  1020. }
  1021. ObjectToBranch (toExpand)?.Expand ();
  1022. InvalidateLineMap ();
  1023. SetNeedsDisplay ();
  1024. }
  1025. /// <summary>
  1026. /// Expands the supplied object and all child objects.
  1027. /// </summary>
  1028. /// <param name="toExpand">The object to expand.</param>
  1029. public void ExpandAll (T toExpand)
  1030. {
  1031. if (toExpand == null) {
  1032. return;
  1033. }
  1034. ObjectToBranch (toExpand)?.ExpandAll ();
  1035. InvalidateLineMap ();
  1036. SetNeedsDisplay ();
  1037. }
  1038. /// <summary>
  1039. /// Fully expands all nodes in the tree, if the tree is very big and built dynamically this
  1040. /// may take a while (e.g. for file system).
  1041. /// </summary>
  1042. public void ExpandAll ()
  1043. {
  1044. foreach (var item in roots) {
  1045. item.Value.ExpandAll ();
  1046. }
  1047. InvalidateLineMap ();
  1048. SetNeedsDisplay ();
  1049. }
  1050. /// <summary>
  1051. /// Returns true if the given object <paramref name="o"/> is exposed in the tree and can be
  1052. /// expanded otherwise false.
  1053. /// </summary>
  1054. /// <param name="o"></param>
  1055. /// <returns></returns>
  1056. public bool CanExpand (T o)
  1057. {
  1058. return ObjectToBranch (o)?.CanExpand () ?? false;
  1059. }
  1060. /// <summary>
  1061. /// Returns true if the given object <paramref name="o"/> is exposed in the tree and
  1062. /// expanded otherwise false.
  1063. /// </summary>
  1064. /// <param name="o"></param>
  1065. /// <returns></returns>
  1066. public bool IsExpanded (T o)
  1067. {
  1068. return ObjectToBranch (o)?.IsExpanded ?? false;
  1069. }
  1070. /// <summary>
  1071. /// Collapses the <see cref="SelectedObject"/>
  1072. /// </summary>
  1073. public void Collapse ()
  1074. {
  1075. Collapse (selectedObject);
  1076. }
  1077. /// <summary>
  1078. /// Collapses the supplied object if it is currently expanded .
  1079. /// </summary>
  1080. /// <param name="toCollapse">The object to collapse.</param>
  1081. public void Collapse (T toCollapse)
  1082. {
  1083. CollapseImpl (toCollapse, false);
  1084. }
  1085. /// <summary>
  1086. /// Collapses the supplied object if it is currently expanded. Also collapses all children
  1087. /// branches (this will only become apparent when/if the user expands it again).
  1088. /// </summary>
  1089. /// <param name="toCollapse">The object to collapse.</param>
  1090. public void CollapseAll (T toCollapse)
  1091. {
  1092. CollapseImpl (toCollapse, true);
  1093. }
  1094. /// <summary>
  1095. /// Collapses all root nodes in the tree.
  1096. /// </summary>
  1097. public void CollapseAll ()
  1098. {
  1099. foreach (var item in roots) {
  1100. item.Value.Collapse ();
  1101. }
  1102. InvalidateLineMap ();
  1103. SetNeedsDisplay ();
  1104. }
  1105. /// <summary>
  1106. /// Implementation of <see cref="Collapse(T)"/> and <see cref="CollapseAll(T)"/>. Performs
  1107. /// operation and updates selection if disapeared.
  1108. /// </summary>
  1109. /// <param name="toCollapse"></param>
  1110. /// <param name="all"></param>
  1111. protected void CollapseImpl (T toCollapse, bool all)
  1112. {
  1113. if (toCollapse == null) {
  1114. return;
  1115. }
  1116. var branch = ObjectToBranch (toCollapse);
  1117. // Nothing to collapse
  1118. if (branch == null) {
  1119. return;
  1120. }
  1121. if (all) {
  1122. branch.CollapseAll ();
  1123. } else {
  1124. branch.Collapse ();
  1125. }
  1126. if (SelectedObject != null && ObjectToBranch (SelectedObject) == null) {
  1127. // If the old selection suddenly became invalid then clear it
  1128. SelectedObject = null;
  1129. }
  1130. InvalidateLineMap ();
  1131. SetNeedsDisplay ();
  1132. }
  1133. /// <summary>
  1134. /// Clears any cached results of the tree state.
  1135. /// </summary>
  1136. public void InvalidateLineMap ()
  1137. {
  1138. cachedLineMap = null;
  1139. }
  1140. /// <summary>
  1141. /// Returns the corresponding <see cref="Branch{T}"/> in the tree for
  1142. /// <paramref name="toFind"/>. This will not work for objects hidden
  1143. /// by their parent being collapsed.
  1144. /// </summary>
  1145. /// <param name="toFind"></param>
  1146. /// <returns>The branch for <paramref name="toFind"/> or null if it is not currently
  1147. /// exposed in the tree.</returns>
  1148. private Branch<T> ObjectToBranch (T toFind)
  1149. {
  1150. return BuildLineMap ().FirstOrDefault (o => o.Model.Equals (toFind));
  1151. }
  1152. /// <summary>
  1153. /// Returns true if the <paramref name="model"/> is either the
  1154. /// <see cref="SelectedObject"/> or part of a <see cref="MultiSelect"/>.
  1155. /// </summary>
  1156. /// <param name="model"></param>
  1157. /// <returns></returns>
  1158. public bool IsSelected (T model)
  1159. {
  1160. return Equals (SelectedObject, model) ||
  1161. (MultiSelect && multiSelectedRegions.Any (s => s.Contains (model)));
  1162. }
  1163. /// <summary>
  1164. /// Returns <see cref="SelectedObject"/> (if not null) and all multi selected objects if
  1165. /// <see cref="MultiSelect"/> is true
  1166. /// </summary>
  1167. /// <returns></returns>
  1168. public IEnumerable<T> GetAllSelectedObjects ()
  1169. {
  1170. var map = BuildLineMap ();
  1171. // To determine multi selected objects, start with the line map, that avoids yielding
  1172. // hidden nodes that were selected then the parent collapsed e.g. programmatically or
  1173. // with mouse click
  1174. if (MultiSelect) {
  1175. foreach (var m in map.Select (b => b.Model).Where (IsSelected)) {
  1176. yield return m;
  1177. }
  1178. } else {
  1179. if (SelectedObject != null) {
  1180. yield return SelectedObject;
  1181. }
  1182. }
  1183. }
  1184. /// <summary>
  1185. /// Selects all objects in the tree when <see cref="MultiSelect"/> is enabled otherwise
  1186. /// does nothing.
  1187. /// </summary>
  1188. public void SelectAll ()
  1189. {
  1190. if (!MultiSelect) {
  1191. return;
  1192. }
  1193. multiSelectedRegions.Clear ();
  1194. var map = BuildLineMap ();
  1195. if (map.Count == 0) {
  1196. return;
  1197. }
  1198. multiSelectedRegions.Push (new TreeSelection<T> (map.ElementAt (0), map.Count, map));
  1199. SetNeedsDisplay ();
  1200. OnSelectionChanged (new SelectionChangedEventArgs<T> (this, SelectedObject, SelectedObject));
  1201. }
  1202. /// <summary>
  1203. /// Raises the SelectionChanged event.
  1204. /// </summary>
  1205. /// <param name="e"></param>
  1206. protected virtual void OnSelectionChanged (SelectionChangedEventArgs<T> e)
  1207. {
  1208. SelectionChanged?.Invoke (this, e);
  1209. }
  1210. /// <summary>
  1211. /// Raises the DrawLine event
  1212. /// </summary>
  1213. /// <param name="e"></param>
  1214. internal void OnDrawLine (DrawTreeViewLineEventArgs<T> e)
  1215. {
  1216. DrawLine?.Invoke(this,e);
  1217. }
  1218. }
  1219. /// <summary>
  1220. /// Event args for the <see cref="TreeView{T}.DrawLine"/> event
  1221. /// </summary>
  1222. /// <typeparam name="T"></typeparam>
  1223. public class DrawTreeViewLineEventArgs<T> where T : class{
  1224. /// <summary>
  1225. /// The object at this line in the tree
  1226. /// </summary>
  1227. public T Model {get;init;}
  1228. /// <summary>
  1229. /// The <see cref="TreeView{T}"/> that is performing the
  1230. /// rendering.
  1231. /// </summary>
  1232. public TreeView<T> Tree {get; init;}
  1233. /// <summary>
  1234. /// The line within tree view bounds that is being rendered
  1235. /// </summary>
  1236. public int Y {get;init;}
  1237. /// <summary>
  1238. /// Set to true to cancel drawing (e.g. if you have already manually
  1239. /// drawn content).
  1240. /// </summary>
  1241. public bool Handled {get;set;}
  1242. /// <summary>
  1243. /// The rune and color of each symbol that will be rendered. Note
  1244. /// that only <see cref="ColorScheme.Normal"/> is respected. You
  1245. /// can modify these to change what is rendered.
  1246. /// </summary>
  1247. /// <remarks>
  1248. /// Changing the length of this collection may result in corrupt rendering
  1249. /// </remarks>
  1250. public List<RuneCell> RuneCells {get; init;}
  1251. }
  1252. class TreeSelection<T> where T : class {
  1253. public Branch<T> Origin { get; }
  1254. private HashSet<T> included = new HashSet<T> ();
  1255. /// <summary>
  1256. /// Creates a new selection between two branches in the tree
  1257. /// </summary>
  1258. /// <param name="from"></param>
  1259. /// <param name="toIndex"></param>
  1260. /// <param name="map"></param>
  1261. public TreeSelection (Branch<T> from, int toIndex, IReadOnlyCollection<Branch<T>> map)
  1262. {
  1263. Origin = from;
  1264. included.Add (Origin.Model);
  1265. var oldIdx = map.IndexOf (from);
  1266. var lowIndex = Math.Min (oldIdx, toIndex);
  1267. var highIndex = Math.Max (oldIdx, toIndex);
  1268. // Select everything between the old and new indexes
  1269. foreach (var alsoInclude in map.Skip (lowIndex).Take (highIndex - lowIndex)) {
  1270. included.Add (alsoInclude.Model);
  1271. }
  1272. }
  1273. public bool Contains (T model)
  1274. {
  1275. return included.Contains (model);
  1276. }
  1277. }
  1278. }