TreeView.cs 43 KB

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