TreeView.cs 34 KB

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