TreeView.cs 42 KB

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