TreeView.cs 43 KB

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