TreeView.cs 35 KB

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