TreeView.cs 48 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767
  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. namespace Terminal.Gui {
  10. /// <summary>
  11. /// Interface for all non generic members of <see cref="TreeView{T}"/>
  12. /// </summary>
  13. public interface ITreeView {
  14. /// <summary>
  15. /// Contains options for changing how the tree is rendered
  16. /// </summary>
  17. TreeStyle Style { get; set; }
  18. /// <summary>
  19. /// Removes all objects from the tree and clears selection
  20. /// </summary>
  21. void ClearObjects ();
  22. /// <summary>
  23. /// Sets a flag indicating this view needs to be redisplayed because its state has changed.
  24. /// </summary>
  25. void SetNeedsDisplay ();
  26. }
  27. /// <summary>
  28. /// Convenience implementation of generic <see cref="TreeView{T}"/> for any tree were all nodes
  29. /// implement <see cref="ITreeNode"/>
  30. /// </summary>
  31. public class TreeView : TreeView<ITreeNode> {
  32. /// <summary>
  33. /// Creates a new instance of the tree control with absolute positioning and initialises
  34. /// <see cref="TreeBuilder{T}"/> with default <see cref="ITreeNode"/> based builder
  35. /// </summary>
  36. public TreeView ()
  37. {
  38. TreeBuilder = new TreeNodeBuilder ();
  39. AspectGetter = o => o == null ? "Null" : (o.Text ?? o?.ToString () ?? "Unamed Node");
  40. }
  41. }
  42. /// <summary>
  43. /// Hierarchical tree view with expandable branches. Branch objects are dynamically determined
  44. /// when expanded using a user defined <see cref="ITreeBuilder{T}"/>
  45. /// </summary>
  46. public class TreeView<T> : View, ITreeView where T : class {
  47. private int scrollOffsetVertical;
  48. private int scrollOffsetHorizontal;
  49. /// <summary>
  50. /// Determines how sub branches of the tree are dynamically built at runtime as the user
  51. /// expands root nodes
  52. /// </summary>
  53. /// <value></value>
  54. public ITreeBuilder<T> TreeBuilder { get; set; }
  55. /// <summary>
  56. /// private variable for <see cref="SelectedObject"/>
  57. /// </summary>
  58. T selectedObject;
  59. /// <summary>
  60. /// Contains options for changing how the tree is rendered
  61. /// </summary>
  62. public TreeStyle Style { get; set; } = new TreeStyle ();
  63. /// <summary>
  64. /// True to allow multiple objects to be selected at once
  65. /// </summary>
  66. /// <value></value>
  67. public bool MultiSelect { get; set; } = true;
  68. /// <summary>
  69. /// True makes a letter key press navigate to the next visible branch that begins with
  70. /// that letter/digit
  71. /// </summary>
  72. /// <value></value>
  73. public bool AllowLetterBasedNavigation { get; set; } = true;
  74. /// <summary>
  75. /// The currently selected object in the tree. When <see cref="MultiSelect"/> is true this
  76. /// is the object at which the cursor is at
  77. /// </summary>
  78. public T SelectedObject {
  79. get => selectedObject;
  80. set {
  81. var oldValue = selectedObject;
  82. selectedObject = value;
  83. if (!ReferenceEquals (oldValue, value)) {
  84. OnSelectionChanged (new SelectionChangedEventArgs<T> (this, oldValue, value));
  85. }
  86. }
  87. }
  88. /// <summary>
  89. /// This event is raised when an object is activated e.g. by double clicking or
  90. /// pressing <see cref="ObjectActivationKey"/>
  91. /// </summary>
  92. public event Action<ObjectActivatedEventArgs<T>> ObjectActivated;
  93. /// <summary>
  94. /// Key which when pressed triggers <see cref="TreeView{T}.ObjectActivated"/>.
  95. /// Defaults to Enter
  96. /// </summary>
  97. public Key ObjectActivationKey { get; set; } = Key.Enter;
  98. /// <summary>
  99. /// Mouse event to trigger <see cref="TreeView{T}.ObjectActivated"/>.
  100. /// Defaults to double click (<see cref="MouseFlags.Button1DoubleClicked"/>).
  101. /// Set to null to disable this feature.
  102. /// </summary>
  103. /// <value></value>
  104. public MouseFlags? ObjectActivationButton { get; set; } = MouseFlags.Button1DoubleClicked;
  105. /// <summary>
  106. /// Secondary selected regions of tree when <see cref="MultiSelect"/> is true
  107. /// </summary>
  108. private Stack<TreeSelection<T>> multiSelectedRegions = new Stack<TreeSelection<T>> ();
  109. /// <summary>
  110. /// Cached result of <see cref="BuildLineMap"/>
  111. /// </summary>
  112. private IReadOnlyCollection<Branch<T>> cachedLineMap;
  113. /// <summary>
  114. /// Error message to display when the control is not properly initialized at draw time
  115. /// (nodes added but no tree builder set)
  116. /// </summary>
  117. public static ustring NoBuilderError = "ERROR: TreeBuilder Not Set";
  118. /// <summary>
  119. /// Called when the <see cref="SelectedObject"/> changes
  120. /// </summary>
  121. public event EventHandler<SelectionChangedEventArgs<T>> SelectionChanged;
  122. /// <summary>
  123. /// The root objects in the tree, note that this collection is of root objects only
  124. /// </summary>
  125. public IEnumerable<T> Objects { get => roots.Keys; }
  126. /// <summary>
  127. /// Map of root objects to the branches under them. All objects have
  128. /// a <see cref="Branch{T}"/> even if that branch has no children
  129. /// </summary>
  130. internal Dictionary<T, Branch<T>> roots { get; set; } = new Dictionary<T, Branch<T>> ();
  131. /// <summary>
  132. /// The amount of tree view that has been scrolled off the top of the screen (by the user
  133. /// scrolling down)
  134. /// </summary>
  135. /// <remarks>Setting a value of less than 0 will result in a offset of 0. To see changes
  136. /// in the UI call <see cref="View.SetNeedsDisplay()"/></remarks>
  137. public int ScrollOffsetVertical {
  138. get => scrollOffsetVertical;
  139. set {
  140. scrollOffsetVertical = Math.Max (0, value);
  141. }
  142. }
  143. /// <summary>
  144. /// The amount of tree view that has been scrolled to the right (horizontally)
  145. /// </summary>
  146. /// <remarks>Setting a value of less than 0 will result in a offset of 0. To see changes
  147. /// in the UI call <see cref="View.SetNeedsDisplay()"/></remarks>
  148. public int ScrollOffsetHorizontal {
  149. get => scrollOffsetHorizontal;
  150. set {
  151. scrollOffsetHorizontal = Math.Max (0, value);
  152. }
  153. }
  154. /// <summary>
  155. /// The current number of rows in the tree (ignoring the controls bounds)
  156. /// </summary>
  157. public int ContentHeight => BuildLineMap ().Count ();
  158. /// <summary>
  159. /// Returns the string representation of model objects hosted in the tree. Default
  160. /// implementation is to call <see cref="object.ToString"/>
  161. /// </summary>
  162. /// <value></value>
  163. public AspectGetterDelegate<T> AspectGetter { get; set; } = (o) => o.ToString () ?? "";
  164. /// <summary>
  165. /// Creates a new tree view with absolute positioning.
  166. /// Use <see cref="AddObjects(IEnumerable{T})"/> to set set root objects for the tree.
  167. /// Children will not be rendered until you set <see cref="TreeBuilder"/>
  168. /// </summary>
  169. public TreeView () : base ()
  170. {
  171. CanFocus = true;
  172. }
  173. /// <summary>
  174. /// Initialises <see cref="TreeBuilder"/>.Creates a new tree view with absolute
  175. /// positioning. Use <see cref="AddObjects(IEnumerable{T})"/> to set set root
  176. /// objects for the tree.
  177. /// </summary>
  178. public TreeView (ITreeBuilder<T> builder) : this ()
  179. {
  180. TreeBuilder = builder;
  181. }
  182. /// <summary>
  183. /// Adds a new root level object unless it is already a root of the tree
  184. /// </summary>
  185. /// <param name="o"></param>
  186. public void AddObject (T o)
  187. {
  188. if (!roots.ContainsKey (o)) {
  189. roots.Add (o, new Branch<T> (this, null, o));
  190. InvalidateLineMap ();
  191. SetNeedsDisplay ();
  192. }
  193. }
  194. /// <summary>
  195. /// Removes all objects from the tree and clears <see cref="SelectedObject"/>
  196. /// </summary>
  197. public void ClearObjects ()
  198. {
  199. SelectedObject = default (T);
  200. multiSelectedRegions.Clear ();
  201. roots = new Dictionary<T, Branch<T>> ();
  202. InvalidateLineMap ();
  203. SetNeedsDisplay ();
  204. }
  205. /// <summary>
  206. /// Removes the given root object from the tree
  207. /// </summary>
  208. /// <remarks>If <paramref name="o"/> is the currently <see cref="SelectedObject"/> then the
  209. /// selection is cleared</remarks>
  210. /// <param name="o"></param>
  211. public void Remove (T o)
  212. {
  213. if (roots.ContainsKey (o)) {
  214. roots.Remove (o);
  215. InvalidateLineMap ();
  216. SetNeedsDisplay ();
  217. if (Equals (SelectedObject, o)) {
  218. SelectedObject = default (T);
  219. }
  220. }
  221. }
  222. /// <summary>
  223. /// Adds many new root level objects. Objects that are already root objects are ignored
  224. /// </summary>
  225. /// <param name="collection">Objects to add as new root level objects</param>
  226. public void AddObjects (IEnumerable<T> collection)
  227. {
  228. bool objectsAdded = false;
  229. foreach (var o in collection) {
  230. if (!roots.ContainsKey (o)) {
  231. roots.Add (o, new Branch<T> (this, null, o));
  232. objectsAdded = true;
  233. }
  234. }
  235. if (objectsAdded) {
  236. InvalidateLineMap ();
  237. SetNeedsDisplay ();
  238. }
  239. }
  240. /// <summary>
  241. /// Refreshes the state of the object <paramref name="o"/> in the tree. This will
  242. /// recompute children, string representation etc
  243. /// </summary>
  244. /// <remarks>This has no effect if the object is not exposed in the tree.</remarks>
  245. /// <param name="o"></param>
  246. /// <param name="startAtTop">True to also refresh all ancestors of the objects branch
  247. /// (starting with the root). False to refresh only the passed node</param>
  248. public void RefreshObject (T o, bool startAtTop = false)
  249. {
  250. var branch = ObjectToBranch (o);
  251. if (branch != null) {
  252. branch.Refresh (startAtTop);
  253. InvalidateLineMap ();
  254. SetNeedsDisplay ();
  255. }
  256. }
  257. /// <summary>
  258. /// Rebuilds the tree structure for all exposed objects starting with the root objects.
  259. /// Call this method when you know there are changes to the tree but don't know which
  260. /// objects have changed (otherwise use <see cref="RefreshObject(T, bool)"/>)
  261. /// </summary>
  262. public void RebuildTree ()
  263. {
  264. foreach (var branch in roots.Values) {
  265. branch.Rebuild ();
  266. }
  267. InvalidateLineMap ();
  268. SetNeedsDisplay ();
  269. }
  270. /// <summary>
  271. /// Returns the currently expanded children of the passed object. Returns an empty
  272. /// collection if the branch is not exposed or not expanded
  273. /// </summary>
  274. /// <param name="o">An object in the tree</param>
  275. /// <returns></returns>
  276. public IEnumerable<T> GetChildren (T o)
  277. {
  278. var branch = ObjectToBranch (o);
  279. if (branch == null || !branch.IsExpanded) {
  280. return new T [0];
  281. }
  282. return branch.ChildBranches?.Values?.Select (b => b.Model)?.ToArray () ?? new T [0];
  283. }
  284. /// <summary>
  285. /// Returns the parent object of <paramref name="o"/> in the tree. Returns null if
  286. /// the object is not exposed in the tree
  287. /// </summary>
  288. /// <param name="o">An object in the tree</param>
  289. /// <returns></returns>
  290. public T GetParent (T o)
  291. {
  292. return ObjectToBranch (o)?.Parent?.Model;
  293. }
  294. ///<inheritdoc/>
  295. public override void Redraw (Rect bounds)
  296. {
  297. if (roots == null) {
  298. return;
  299. }
  300. if (TreeBuilder == null) {
  301. Move (0, 0);
  302. Driver.AddStr (NoBuilderError);
  303. return;
  304. }
  305. var map = BuildLineMap ();
  306. for (int line = 0; line < bounds.Height; line++) {
  307. var idxToRender = ScrollOffsetVertical + line;
  308. // Is there part of the tree view to render?
  309. if (idxToRender < map.Count) {
  310. // Render the line
  311. map.ElementAt (idxToRender).Draw (Driver, ColorScheme, line, bounds.Width);
  312. } else {
  313. // Else clear the line to prevent stale symbols due to scrolling etc
  314. Move (0, line);
  315. Driver.SetAttribute (ColorScheme.Normal);
  316. Driver.AddStr (new string (' ', bounds.Width));
  317. }
  318. }
  319. }
  320. /// <summary>
  321. /// Returns the index of the object <paramref name="o"/> if it is currently exposed (it's
  322. /// parent(s) have been expanded). This can be used with <see cref="ScrollOffsetVertical"/>
  323. /// and <see cref="View.SetNeedsDisplay()"/> to scroll to a specific object
  324. /// </summary>
  325. /// <remarks>Uses the Equals method and returns the first index at which the object is found
  326. /// or -1 if it is not found</remarks>
  327. /// <param name="o">An object that appears in your tree and is currently exposed</param>
  328. /// <returns>The index the object was found at or -1 if it is not currently revealed or
  329. /// not in the tree at all</returns>
  330. public int GetScrollOffsetOf (T o)
  331. {
  332. var map = BuildLineMap ();
  333. for (int i = 0; i < map.Count; i++) {
  334. if (map.ElementAt (i).Model.Equals (o)) {
  335. return i;
  336. }
  337. }
  338. //object not found
  339. return -1;
  340. }
  341. /// <summary>
  342. /// Returns the maximum width line in the tree including prefix and expansion symbols
  343. /// </summary>
  344. /// <param name="visible">True to consider only rows currently visible (based on window
  345. /// bounds and <see cref="ScrollOffsetVertical"/>. False to calculate the width of
  346. /// every exposed branch in the tree</param>
  347. /// <returns></returns>
  348. public int GetContentWidth (bool visible)
  349. {
  350. var map = BuildLineMap ();
  351. if (map.Count == 0) {
  352. return 0;
  353. }
  354. if (visible) {
  355. //Somehow we managed to scroll off the end of the control
  356. if (ScrollOffsetVertical >= map.Count) {
  357. return 0;
  358. }
  359. // If control has no height to it then there is no visible area for content
  360. if (Bounds.Height == 0) {
  361. return 0;
  362. }
  363. return map.Skip (ScrollOffsetVertical).Take (Bounds.Height).Max (b => b.GetWidth (Driver));
  364. } else {
  365. return map.Max (b => b.GetWidth (Driver));
  366. }
  367. }
  368. /// <summary>
  369. /// Calculates all currently visible/expanded branches (including leafs) and outputs them
  370. /// by index from the top of the screen
  371. /// </summary>
  372. /// <remarks>Index 0 of the returned array is the first item that should be visible in the
  373. /// top of the control, index 1 is the next etc.</remarks>
  374. /// <returns></returns>
  375. private IReadOnlyCollection<Branch<T>> BuildLineMap ()
  376. {
  377. if (cachedLineMap != null) {
  378. return cachedLineMap;
  379. }
  380. List<Branch<T>> toReturn = new List<Branch<T>> ();
  381. foreach (var root in roots.Values) {
  382. toReturn.AddRange (AddToLineMap (root));
  383. }
  384. return cachedLineMap = new ReadOnlyCollection<Branch<T>> (toReturn);
  385. }
  386. private IEnumerable<Branch<T>> AddToLineMap (Branch<T> currentBranch)
  387. {
  388. yield return currentBranch;
  389. if (currentBranch.IsExpanded) {
  390. foreach (var subBranch in currentBranch.ChildBranches.Values) {
  391. foreach (var sub in AddToLineMap (subBranch)) {
  392. yield return sub;
  393. }
  394. }
  395. }
  396. }
  397. /// <inheritdoc/>
  398. public override bool ProcessKey (KeyEvent keyEvent)
  399. {
  400. if (keyEvent.Key == ObjectActivationKey) {
  401. var o = SelectedObject;
  402. if (o != null) {
  403. OnObjectActivated (new ObjectActivatedEventArgs<T> (this, o));
  404. PositionCursor ();
  405. return true;
  406. }
  407. }
  408. if (keyEvent.KeyValue > 0 && keyEvent.KeyValue < 0xFFFF) {
  409. var character = (char)keyEvent.KeyValue;
  410. // if it is a single character pressed without any control keys
  411. if (char.IsLetterOrDigit (character) && AllowLetterBasedNavigation && !keyEvent.IsShift && !keyEvent.IsAlt && !keyEvent.IsCtrl) {
  412. // search for next branch that begins with that letter
  413. var characterAsStr = character.ToString ();
  414. AdjustSelectionToNext (b => AspectGetter (b.Model).StartsWith (characterAsStr, StringComparison.CurrentCultureIgnoreCase));
  415. PositionCursor ();
  416. return true;
  417. }
  418. }
  419. switch (keyEvent.Key) {
  420. case Key.CursorRight:
  421. Expand (SelectedObject);
  422. break;
  423. case Key.CursorRight | Key.CtrlMask:
  424. ExpandAll (SelectedObject);
  425. break;
  426. case Key.CursorLeft:
  427. case Key.CursorLeft | Key.CtrlMask:
  428. CursorLeft (keyEvent.Key.HasFlag (Key.CtrlMask));
  429. break;
  430. case Key.CursorUp:
  431. case Key.CursorUp | Key.ShiftMask:
  432. AdjustSelection (-1, keyEvent.Key.HasFlag (Key.ShiftMask));
  433. break;
  434. case Key.CursorDown:
  435. case Key.CursorDown | Key.ShiftMask:
  436. AdjustSelection (1, keyEvent.Key.HasFlag (Key.ShiftMask));
  437. break;
  438. case Key.CursorUp | Key.CtrlMask:
  439. AdjustSelectionToBranchStart ();
  440. break;
  441. case Key.CursorDown | Key.CtrlMask:
  442. AdjustSelectionToBranchEnd ();
  443. break;
  444. case Key.PageUp:
  445. case Key.PageUp | Key.ShiftMask:
  446. AdjustSelection (-Bounds.Height, keyEvent.Key.HasFlag (Key.ShiftMask));
  447. break;
  448. case Key.PageDown:
  449. case Key.PageDown | Key.ShiftMask:
  450. AdjustSelection (Bounds.Height, keyEvent.Key.HasFlag (Key.ShiftMask));
  451. break;
  452. case Key.A | Key.CtrlMask:
  453. SelectAll ();
  454. break;
  455. case Key.Home:
  456. GoToFirst ();
  457. break;
  458. case Key.End:
  459. GoToEnd ();
  460. break;
  461. default:
  462. // we don't care about this keystroke
  463. return false;
  464. }
  465. PositionCursor ();
  466. return true;
  467. }
  468. /// <summary>
  469. /// Raises the <see cref="ObjectActivated"/> event
  470. /// </summary>
  471. /// <param name="e"></param>
  472. protected virtual void OnObjectActivated (ObjectActivatedEventArgs<T> e)
  473. {
  474. ObjectActivated?.Invoke (e);
  475. }
  476. ///<inheritdoc/>
  477. public override bool MouseEvent (MouseEvent me)
  478. {
  479. // If it is not an event we care about
  480. if (!me.Flags.HasFlag (MouseFlags.Button1Clicked) &&
  481. !me.Flags.HasFlag (ObjectActivationButton ?? MouseFlags.Button1DoubleClicked) &&
  482. !me.Flags.HasFlag (MouseFlags.WheeledDown) &&
  483. !me.Flags.HasFlag (MouseFlags.WheeledUp) &&
  484. !me.Flags.HasFlag (MouseFlags.WheeledRight) &&
  485. !me.Flags.HasFlag (MouseFlags.WheeledLeft)) {
  486. // do nothing
  487. return false;
  488. }
  489. if (!HasFocus && CanFocus) {
  490. SetFocus ();
  491. }
  492. if (me.Flags == MouseFlags.WheeledDown) {
  493. ScrollOffsetVertical++;
  494. SetNeedsDisplay ();
  495. return true;
  496. } else if (me.Flags == MouseFlags.WheeledUp) {
  497. ScrollOffsetVertical--;
  498. SetNeedsDisplay ();
  499. return true;
  500. }
  501. if (me.Flags == MouseFlags.WheeledRight) {
  502. ScrollOffsetHorizontal++;
  503. SetNeedsDisplay ();
  504. return true;
  505. } else if (me.Flags == MouseFlags.WheeledLeft) {
  506. ScrollOffsetHorizontal--;
  507. SetNeedsDisplay ();
  508. return true;
  509. }
  510. if (me.Flags.HasFlag (MouseFlags.Button1Clicked)) {
  511. // The line they clicked on a branch
  512. var clickedBranch = HitTest (me.Y);
  513. if (clickedBranch == null) {
  514. return false;
  515. }
  516. bool isExpandToggleAttempt = clickedBranch.IsHitOnExpandableSymbol (Driver, me.X);
  517. // If we are already selected (double click)
  518. if (Equals (SelectedObject, clickedBranch.Model)) {
  519. isExpandToggleAttempt = true;
  520. }
  521. // if they clicked on the +/- expansion symbol
  522. if (isExpandToggleAttempt) {
  523. if (clickedBranch.IsExpanded) {
  524. clickedBranch.Collapse ();
  525. InvalidateLineMap ();
  526. } else
  527. if (clickedBranch.CanExpand ()) {
  528. clickedBranch.Expand ();
  529. InvalidateLineMap ();
  530. } else {
  531. SelectedObject = clickedBranch.Model; // It is a leaf node
  532. multiSelectedRegions.Clear ();
  533. }
  534. } else {
  535. // It is a first click somewhere in the current line that doesn't look like an expansion/collapse attempt
  536. SelectedObject = clickedBranch.Model;
  537. multiSelectedRegions.Clear ();
  538. }
  539. SetNeedsDisplay ();
  540. return true;
  541. }
  542. // If it is activation via mouse (e.g. double click)
  543. if (ObjectActivationButton.HasValue && me.Flags.HasFlag (ObjectActivationButton.Value)) {
  544. // The line they clicked on a branch
  545. var clickedBranch = HitTest (me.Y);
  546. if (clickedBranch == null) {
  547. return false;
  548. }
  549. // Double click changes the selection to the clicked node as well as triggering
  550. // activation otherwise it feels wierd
  551. SelectedObject = clickedBranch.Model;
  552. SetNeedsDisplay ();
  553. // trigger activation event
  554. OnObjectActivated (new ObjectActivatedEventArgs<T> (this, clickedBranch.Model));
  555. // mouse event is handled.
  556. return true;
  557. }
  558. return false;
  559. }
  560. /// <summary>
  561. /// Returns the branch at the given <paramref name="y"/> client
  562. /// coordinate e.g. following a click event
  563. /// </summary>
  564. /// <param name="y">Client Y position in the controls bounds</param>
  565. /// <returns>The clicked branch or null if outside of tree region</returns>
  566. private Branch<T> HitTest (int y)
  567. {
  568. var map = BuildLineMap ();
  569. var idx = y + ScrollOffsetVertical;
  570. // click is outside any visible nodes
  571. if (idx < 0 || idx >= map.Count) {
  572. return null;
  573. }
  574. // The line they clicked on
  575. return map.ElementAt (idx);
  576. }
  577. /// <summary>
  578. /// Positions the cursor at the start of the selected objects line (if visible)
  579. /// </summary>
  580. public override void PositionCursor ()
  581. {
  582. if (CanFocus && HasFocus && Visible && SelectedObject != null) {
  583. var map = BuildLineMap ();
  584. var idx = map.IndexOf(b => b.Model.Equals (SelectedObject));
  585. // if currently selected line is visible
  586. if (idx - ScrollOffsetVertical >= 0 && idx - ScrollOffsetVertical < Bounds.Height) {
  587. Move (0, idx - ScrollOffsetVertical);
  588. } else {
  589. base.PositionCursor ();
  590. }
  591. } else {
  592. base.PositionCursor ();
  593. }
  594. }
  595. /// <summary>
  596. /// Determines systems behaviour when the left arrow key is pressed. Default behaviour is
  597. /// to collapse the current tree node if possible otherwise changes selection to current
  598. /// branches parent
  599. /// </summary>
  600. protected virtual void CursorLeft (bool ctrl)
  601. {
  602. if (IsExpanded (SelectedObject)) {
  603. if (ctrl) {
  604. CollapseAll (SelectedObject);
  605. } else {
  606. Collapse (SelectedObject);
  607. }
  608. } else {
  609. var parent = GetParent (SelectedObject);
  610. if (parent != null) {
  611. SelectedObject = parent;
  612. AdjustSelection (0);
  613. SetNeedsDisplay ();
  614. }
  615. }
  616. }
  617. /// <summary>
  618. /// Changes the <see cref="SelectedObject"/> to the first root object and resets
  619. /// the <see cref="ScrollOffsetVertical"/> to 0
  620. /// </summary>
  621. public void GoToFirst ()
  622. {
  623. ScrollOffsetVertical = 0;
  624. SelectedObject = roots.Keys.FirstOrDefault ();
  625. SetNeedsDisplay ();
  626. }
  627. /// <summary>
  628. /// Changes the <see cref="SelectedObject"/> to the last object in the tree and scrolls so
  629. /// that it is visible
  630. /// </summary>
  631. public void GoToEnd ()
  632. {
  633. var map = BuildLineMap ();
  634. ScrollOffsetVertical = Math.Max (0, map.Count - Bounds.Height + 1);
  635. SelectedObject = map.Last ().Model;
  636. SetNeedsDisplay ();
  637. }
  638. /// <summary>
  639. /// Changes the <see cref="SelectedObject"/> to <paramref name="toSelect"/> and scrolls to ensure
  640. /// it is visible. Has no effect if <paramref name="toSelect"/> is not exposed in the tree (e.g.
  641. /// its parents are collapsed)
  642. /// </summary>
  643. /// <param name="toSelect"></param>
  644. public void GoTo (T toSelect)
  645. {
  646. if (ObjectToBranch (toSelect) == null) {
  647. return;
  648. }
  649. SelectedObject = toSelect;
  650. EnsureVisible (toSelect);
  651. SetNeedsDisplay ();
  652. }
  653. /// <summary>
  654. /// The number of screen lines to move the currently selected object by. Supports negative
  655. /// <paramref name="offset"/>. Each branch occupies 1 line on screen
  656. /// </summary>
  657. /// <remarks>If nothing is currently selected or the selected object is no longer in the tree
  658. /// then the first object in the tree is selected instead</remarks>
  659. /// <param name="offset">Positive to move the selection down the screen, negative to move it up</param>
  660. /// <param name="expandSelection">True to expand the selection (assuming
  661. /// <see cref="MultiSelect"/> is enabled). False to replace</param>
  662. public void AdjustSelection (int offset, bool expandSelection = false)
  663. {
  664. // if it is not a shift click or we don't allow multi select
  665. if (!expandSelection || !MultiSelect) {
  666. multiSelectedRegions.Clear ();
  667. }
  668. if (SelectedObject == null) {
  669. SelectedObject = roots.Keys.FirstOrDefault ();
  670. } else {
  671. var map = BuildLineMap ();
  672. var idx = map.IndexOf(b => b.Model.Equals (SelectedObject));
  673. if (idx == -1) {
  674. // The current selection has disapeared!
  675. SelectedObject = roots.Keys.FirstOrDefault ();
  676. } else {
  677. var newIdx = Math.Min (Math.Max (0, idx + offset), map.Count - 1);
  678. var newBranch = map.ElementAt(newIdx);
  679. // If it is a multi selection
  680. if (expandSelection && MultiSelect) {
  681. if (multiSelectedRegions.Any ()) {
  682. // expand the existing head selection
  683. var head = multiSelectedRegions.Pop ();
  684. multiSelectedRegions.Push (new TreeSelection<T> (head.Origin, newIdx, map));
  685. } else {
  686. // or start a new multi selection region
  687. multiSelectedRegions.Push (new TreeSelection<T> (map.ElementAt(idx), newIdx, map));
  688. }
  689. }
  690. SelectedObject = newBranch.Model;
  691. EnsureVisible (SelectedObject);
  692. }
  693. }
  694. SetNeedsDisplay ();
  695. }
  696. /// <summary>
  697. /// Moves the selection to the first child in the currently selected level
  698. /// </summary>
  699. public void AdjustSelectionToBranchStart ()
  700. {
  701. var o = SelectedObject;
  702. if (o == null) {
  703. return;
  704. }
  705. var map = BuildLineMap ();
  706. int currentIdx = map.IndexOf(b => Equals (b.Model, o));
  707. if (currentIdx == -1) {
  708. return;
  709. }
  710. var currentBranch = map.ElementAt(currentIdx);
  711. var next = currentBranch;
  712. for (; currentIdx >= 0; currentIdx--) {
  713. //if it is the beginning of the current depth of branch
  714. if (currentBranch.Depth != next.Depth) {
  715. SelectedObject = currentBranch.Model;
  716. EnsureVisible (currentBranch.Model);
  717. SetNeedsDisplay ();
  718. return;
  719. }
  720. // look at next branch up for consideration
  721. currentBranch = next;
  722. next = map.ElementAt(currentIdx);
  723. }
  724. // We ran all the way to top of tree
  725. GoToFirst ();
  726. }
  727. /// <summary>
  728. /// Moves the selection to the last child in the currently selected level
  729. /// </summary>
  730. public void AdjustSelectionToBranchEnd ()
  731. {
  732. var o = SelectedObject;
  733. if (o == null) {
  734. return;
  735. }
  736. var map = BuildLineMap ();
  737. int currentIdx = map.IndexOf(b => Equals (b.Model, o));
  738. if (currentIdx == -1) {
  739. return;
  740. }
  741. var currentBranch = map.ElementAt(currentIdx);
  742. var next = currentBranch;
  743. for (; currentIdx < map.Count; currentIdx++) {
  744. //if it is the end of the current depth of branch
  745. if (currentBranch.Depth != next.Depth) {
  746. SelectedObject = currentBranch.Model;
  747. EnsureVisible (currentBranch.Model);
  748. SetNeedsDisplay ();
  749. return;
  750. }
  751. // look at next branch for consideration
  752. currentBranch = next;
  753. next = map.ElementAt(currentIdx);
  754. }
  755. GoToEnd ();
  756. }
  757. /// <summary>
  758. /// Sets the selection to the next branch that matches the <paramref name="predicate"/>
  759. /// </summary>
  760. /// <param name="predicate"></param>
  761. private void AdjustSelectionToNext (Func<Branch<T>, bool> predicate)
  762. {
  763. var map = BuildLineMap ();
  764. // empty map means we can't select anything anyway
  765. if (map.Count == 0) {
  766. return;
  767. }
  768. // Start searching from the first element in the map
  769. var idxStart = 0;
  770. // or the current selected branch
  771. if (SelectedObject != null) {
  772. idxStart = map.IndexOf(b => Equals (b.Model, SelectedObject));
  773. }
  774. // if currently selected object mysteriously vanished, search from beginning
  775. if (idxStart == -1) {
  776. idxStart = 0;
  777. }
  778. // loop around all indexes and back to first index
  779. for (int idxCur = (idxStart + 1) % map.Count; idxCur != idxStart; idxCur = (idxCur + 1) % map.Count) {
  780. if (predicate (map.ElementAt(idxCur))) {
  781. SelectedObject = map.ElementAt(idxCur).Model;
  782. EnsureVisible (map.ElementAt(idxCur).Model);
  783. SetNeedsDisplay ();
  784. return;
  785. }
  786. }
  787. }
  788. /// <summary>
  789. /// Adjusts the <see cref="ScrollOffsetVertical"/> to ensure the given
  790. /// <paramref name="model"/> is visible. Has no effect if already visible
  791. /// </summary>
  792. public void EnsureVisible (T model)
  793. {
  794. var map = BuildLineMap ();
  795. var idx = map.IndexOf(b => Equals (b.Model, model));
  796. if (idx == -1) {
  797. return;
  798. }
  799. /*this -1 allows for possible horizontal scroll bar in the last row of the control*/
  800. int leaveSpace = Style.LeaveLastRow ? 1 : 0;
  801. if (idx < ScrollOffsetVertical) {
  802. //if user has scrolled up too far to see their selection
  803. ScrollOffsetVertical = idx;
  804. } else if (idx >= ScrollOffsetVertical + Bounds.Height - leaveSpace) {
  805. //if user has scrolled off bottom of visible tree
  806. ScrollOffsetVertical = Math.Max (0, (idx + 1) - (Bounds.Height - leaveSpace));
  807. }
  808. }
  809. /// <summary>
  810. /// Expands the supplied object if it is contained in the tree (either as a root object or
  811. /// as an exposed branch object)
  812. /// </summary>
  813. /// <param name="toExpand">The object to expand</param>
  814. public void Expand (T toExpand)
  815. {
  816. if (toExpand == null) {
  817. return;
  818. }
  819. ObjectToBranch (toExpand)?.Expand ();
  820. InvalidateLineMap ();
  821. SetNeedsDisplay ();
  822. }
  823. /// <summary>
  824. /// Expands the supplied object and all child objects
  825. /// </summary>
  826. /// <param name="toExpand">The object to expand</param>
  827. public void ExpandAll (T toExpand)
  828. {
  829. if (toExpand == null) {
  830. return;
  831. }
  832. ObjectToBranch (toExpand)?.ExpandAll ();
  833. InvalidateLineMap ();
  834. SetNeedsDisplay ();
  835. }
  836. /// <summary>
  837. /// Fully expands all nodes in the tree, if the tree is very big and built dynamically this
  838. /// may take a while (e.g. for file system)
  839. /// </summary>
  840. public void ExpandAll ()
  841. {
  842. foreach (var item in roots) {
  843. item.Value.ExpandAll ();
  844. }
  845. InvalidateLineMap ();
  846. SetNeedsDisplay ();
  847. }
  848. /// <summary>
  849. /// Returns true if the given object <paramref name="o"/> is exposed in the tree and can be
  850. /// expanded otherwise false
  851. /// </summary>
  852. /// <param name="o"></param>
  853. /// <returns></returns>
  854. public bool CanExpand (T o)
  855. {
  856. return ObjectToBranch (o)?.CanExpand () ?? false;
  857. }
  858. /// <summary>
  859. /// Returns true if the given object <paramref name="o"/> is exposed in the tree and
  860. /// expanded otherwise false
  861. /// </summary>
  862. /// <param name="o"></param>
  863. /// <returns></returns>
  864. public bool IsExpanded (T o)
  865. {
  866. return ObjectToBranch (o)?.IsExpanded ?? false;
  867. }
  868. /// <summary>
  869. /// Collapses the supplied object if it is currently expanded
  870. /// </summary>
  871. /// <param name="toCollapse">The object to collapse</param>
  872. public void Collapse (T toCollapse)
  873. {
  874. CollapseImpl (toCollapse, false);
  875. }
  876. /// <summary>
  877. /// Collapses the supplied object if it is currently expanded. Also collapses all children
  878. /// branches (this will only become apparent when/if the user expands it again)
  879. /// </summary>
  880. /// <param name="toCollapse">The object to collapse</param>
  881. public void CollapseAll (T toCollapse)
  882. {
  883. CollapseImpl (toCollapse, true);
  884. }
  885. /// <summary>
  886. /// Collapses all root nodes in the tree
  887. /// </summary>
  888. public void CollapseAll ()
  889. {
  890. foreach (var item in roots) {
  891. item.Value.Collapse ();
  892. }
  893. InvalidateLineMap ();
  894. SetNeedsDisplay ();
  895. }
  896. /// <summary>
  897. /// Implementation of <see cref="Collapse(T)"/> and <see cref="CollapseAll(T)"/>. Performs
  898. /// operation and updates selection if disapeared
  899. /// </summary>
  900. /// <param name="toCollapse"></param>
  901. /// <param name="all"></param>
  902. protected void CollapseImpl (T toCollapse, bool all)
  903. {
  904. if (toCollapse == null) {
  905. return;
  906. }
  907. var branch = ObjectToBranch (toCollapse);
  908. // Nothing to collapse
  909. if (branch == null) {
  910. return;
  911. }
  912. if (all) {
  913. branch.CollapseAll ();
  914. } else {
  915. branch.Collapse ();
  916. }
  917. if (SelectedObject != null && ObjectToBranch (SelectedObject) == null) {
  918. // If the old selection suddenly became invalid then clear it
  919. SelectedObject = null;
  920. }
  921. InvalidateLineMap ();
  922. SetNeedsDisplay ();
  923. }
  924. /// <summary>
  925. /// Clears any cached results of <see cref="BuildLineMap"/>
  926. /// </summary>
  927. protected void InvalidateLineMap ()
  928. {
  929. cachedLineMap = null;
  930. }
  931. /// <summary>
  932. /// Returns the corresponding <see cref="Branch{T}"/> in the tree for
  933. /// <paramref name="toFind"/>. This will not work for objects hidden
  934. /// by their parent being collapsed
  935. /// </summary>
  936. /// <param name="toFind"></param>
  937. /// <returns>The branch for <paramref name="toFind"/> or null if it is not currently
  938. /// exposed in the tree</returns>
  939. private Branch<T> ObjectToBranch (T toFind)
  940. {
  941. return BuildLineMap ().FirstOrDefault (o => o.Model.Equals (toFind));
  942. }
  943. /// <summary>
  944. /// Returns true if the <paramref name="model"/> is either the
  945. /// <see cref="SelectedObject"/> or part of a <see cref="MultiSelect"/>
  946. /// </summary>
  947. /// <param name="model"></param>
  948. /// <returns></returns>
  949. public bool IsSelected (T model)
  950. {
  951. return Equals (SelectedObject, model) ||
  952. (MultiSelect && multiSelectedRegions.Any (s => s.Contains (model)));
  953. }
  954. /// <summary>
  955. /// Returns <see cref="SelectedObject"/> (if not null) and all multi selected objects if
  956. /// <see cref="MultiSelect"/> is true
  957. /// </summary>
  958. /// <returns></returns>
  959. public IEnumerable<T> GetAllSelectedObjects ()
  960. {
  961. var map = BuildLineMap ();
  962. // To determine multi selected objects, start with the line map, that avoids yielding
  963. // hidden nodes that were selected then the parent collapsed e.g. programmatically or
  964. // with mouse click
  965. if (MultiSelect) {
  966. foreach (var m in map.Select (b => b.Model).Where (IsSelected)) {
  967. yield return m;
  968. }
  969. } else {
  970. if (SelectedObject != null) {
  971. yield return SelectedObject;
  972. }
  973. }
  974. }
  975. /// <summary>
  976. /// Selects all objects in the tree when <see cref="MultiSelect"/> is enabled otherwise
  977. /// does nothing
  978. /// </summary>
  979. public void SelectAll ()
  980. {
  981. if (!MultiSelect) {
  982. return;
  983. }
  984. multiSelectedRegions.Clear ();
  985. var map = BuildLineMap ();
  986. if (map.Count == 0) {
  987. return;
  988. }
  989. multiSelectedRegions.Push (new TreeSelection<T> (map.ElementAt(0), map.Count, map));
  990. SetNeedsDisplay ();
  991. OnSelectionChanged (new SelectionChangedEventArgs<T> (this, SelectedObject, SelectedObject));
  992. }
  993. /// <summary>
  994. /// Raises the SelectionChanged event
  995. /// </summary>
  996. /// <param name="e"></param>
  997. protected virtual void OnSelectionChanged (SelectionChangedEventArgs<T> e)
  998. {
  999. SelectionChanged?.Invoke (this, e);
  1000. }
  1001. }
  1002. /// <summary>
  1003. /// Event args for the <see cref="TreeView{T}.ObjectActivated"/> event
  1004. /// </summary>
  1005. /// <typeparam name="T"></typeparam>
  1006. public class ObjectActivatedEventArgs<T> where T : class {
  1007. /// <summary>
  1008. /// The tree in which the activation occurred
  1009. /// </summary>
  1010. /// <value></value>
  1011. public TreeView<T> Tree { get; }
  1012. /// <summary>
  1013. /// The object that was selected at the time of activation
  1014. /// </summary>
  1015. /// <value></value>
  1016. public T ActivatedObject { get; }
  1017. /// <summary>
  1018. /// Creates a new instance documenting activation of the <paramref name="activated"/> object
  1019. /// </summary>
  1020. /// <param name="tree">Tree in which the activation is happening</param>
  1021. /// <param name="activated">What object is being activated</param>
  1022. public ObjectActivatedEventArgs (TreeView<T> tree, T activated)
  1023. {
  1024. Tree = tree;
  1025. ActivatedObject = activated;
  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. class Branch<T> where T : class {
  1055. /// <summary>
  1056. /// True if the branch is expanded to reveal child branches
  1057. /// </summary>
  1058. public bool IsExpanded { get; set; }
  1059. /// <summary>
  1060. /// The users object that is being displayed by this branch of the tree
  1061. /// </summary>
  1062. public T Model { get; private set; }
  1063. /// <summary>
  1064. /// The depth of the current branch. Depth of 0 indicates root level branches
  1065. /// </summary>
  1066. public int Depth { get; private set; } = 0;
  1067. /// <summary>
  1068. /// The children of the current branch. This is null until the first call to
  1069. /// <see cref="FetchChildren"/> to avoid enumerating the entire underlying hierarchy
  1070. /// </summary>
  1071. public Dictionary<T, Branch<T>> ChildBranches { get; set; }
  1072. /// <summary>
  1073. /// The parent <see cref="Branch{T}"/> or null if it is a root.
  1074. /// </summary>
  1075. public Branch<T> Parent { get; private set; }
  1076. private TreeView<T> tree;
  1077. /// <summary>
  1078. /// Declares a new branch of <paramref name="tree"/> in which the users object
  1079. /// <paramref name="model"/> is presented
  1080. /// </summary>
  1081. /// <param name="tree">The UI control in which the branch resides</param>
  1082. /// <param name="parentBranchIfAny">Pass null for root level branches, otherwise
  1083. /// pass the parent</param>
  1084. /// <param name="model">The user's object that should be displayed</param>
  1085. public Branch (TreeView<T> tree, Branch<T> parentBranchIfAny, T model)
  1086. {
  1087. this.tree = tree;
  1088. this.Model = model;
  1089. if (parentBranchIfAny != null) {
  1090. Depth = parentBranchIfAny.Depth + 1;
  1091. Parent = parentBranchIfAny;
  1092. }
  1093. }
  1094. /// <summary>
  1095. /// Fetch the children of this branch. This method populates <see cref="ChildBranches"/>
  1096. /// </summary>
  1097. public virtual void FetchChildren ()
  1098. {
  1099. if (tree.TreeBuilder == null) {
  1100. return;
  1101. }
  1102. var children = tree.TreeBuilder.GetChildren (this.Model) ?? Enumerable.Empty<T> ();
  1103. this.ChildBranches = children.ToDictionary (k => k, val => new Branch<T> (tree, this, val));
  1104. }
  1105. /// <summary>
  1106. /// Returns the width of the line including prefix and the results
  1107. /// of <see cref="TreeView{T}.AspectGetter"/> (the line body).
  1108. /// </summary>
  1109. /// <returns></returns>
  1110. public virtual int GetWidth (ConsoleDriver driver)
  1111. {
  1112. return
  1113. GetLinePrefix (driver).Sum (Rune.ColumnWidth) +
  1114. Rune.ColumnWidth (GetExpandableSymbol (driver)) +
  1115. (tree.AspectGetter (Model) ?? "").Length;
  1116. }
  1117. /// <summary>
  1118. /// Renders the current <see cref="Model"/> on the specified line <paramref name="y"/>
  1119. /// </summary>
  1120. /// <param name="driver"></param>
  1121. /// <param name="colorScheme"></param>
  1122. /// <param name="y"></param>
  1123. /// <param name="availableWidth"></param>
  1124. public virtual void Draw (ConsoleDriver driver, ColorScheme colorScheme, int y, int availableWidth)
  1125. {
  1126. // true if the current line of the tree is the selected one and control has focus
  1127. bool isSelected = tree.IsSelected (Model) && tree.HasFocus;
  1128. Attribute lineColor = isSelected ? colorScheme.Focus : colorScheme.Normal;
  1129. driver.SetAttribute (lineColor);
  1130. // Everything on line before the expansion run and branch text
  1131. Rune [] prefix = GetLinePrefix (driver).ToArray ();
  1132. Rune expansion = GetExpandableSymbol (driver);
  1133. string lineBody = tree.AspectGetter (Model) ?? "";
  1134. tree.Move (0, y);
  1135. // if we have scrolled to the right then bits of the prefix will have dispeared off the screen
  1136. int toSkip = tree.ScrollOffsetHorizontal;
  1137. // Draw the line prefix (all paralell lanes or whitespace and an expand/collapse/leaf symbol)
  1138. foreach (Rune r in prefix) {
  1139. if (toSkip > 0) {
  1140. toSkip--;
  1141. } else {
  1142. driver.AddRune (r);
  1143. availableWidth -= Rune.ColumnWidth (r);
  1144. }
  1145. }
  1146. // pick color for expanded symbol
  1147. if (tree.Style.ColorExpandSymbol || tree.Style.InvertExpandSymbolColors) {
  1148. Attribute color;
  1149. if (tree.Style.ColorExpandSymbol) {
  1150. color = isSelected ? tree.ColorScheme.HotFocus : tree.ColorScheme.HotNormal;
  1151. } else {
  1152. color = lineColor;
  1153. }
  1154. if (tree.Style.InvertExpandSymbolColors) {
  1155. color = new Attribute (color.Background, color.Foreground);
  1156. }
  1157. driver.SetAttribute (color);
  1158. }
  1159. if (toSkip > 0) {
  1160. toSkip--;
  1161. } else {
  1162. driver.AddRune (expansion);
  1163. availableWidth -= Rune.ColumnWidth (expansion);
  1164. }
  1165. // horizontal scrolling has already skipped the prefix but now must also skip some of the line body
  1166. if (toSkip > 0) {
  1167. if (toSkip > lineBody.Length) {
  1168. lineBody = "";
  1169. } else {
  1170. lineBody = lineBody.Substring (toSkip);
  1171. }
  1172. }
  1173. // If body of line is too long
  1174. if (lineBody.Sum (l => Rune.ColumnWidth (l)) > availableWidth) {
  1175. // remaining space is zero and truncate the line
  1176. lineBody = new string (lineBody.TakeWhile (c => (availableWidth -= Rune.ColumnWidth (c)) >= 0).ToArray ());
  1177. availableWidth = 0;
  1178. } else {
  1179. // line is short so remaining width will be whatever comes after the line body
  1180. availableWidth -= lineBody.Length;
  1181. }
  1182. //reset the line color if it was changed for rendering expansion symbol
  1183. driver.SetAttribute (lineColor);
  1184. driver.AddStr (lineBody);
  1185. if (availableWidth > 0) {
  1186. driver.AddStr (new string (' ', availableWidth));
  1187. }
  1188. driver.SetAttribute (colorScheme.Normal);
  1189. }
  1190. /// <summary>
  1191. /// Gets all characters to render prior to the current branches line. This includes indentation
  1192. /// whitespace and any tree branches (if enabled)
  1193. /// </summary>
  1194. /// <param name="driver"></param>
  1195. /// <returns></returns>
  1196. private IEnumerable<Rune> GetLinePrefix (ConsoleDriver driver)
  1197. {
  1198. // If not showing line branches or this is a root object
  1199. if (!tree.Style.ShowBranchLines) {
  1200. for (int i = 0; i < Depth; i++) {
  1201. yield return new Rune (' ');
  1202. }
  1203. yield break;
  1204. }
  1205. // yield indentations with runes appropriate to the state of the parents
  1206. foreach (var cur in GetParentBranches ().Reverse ()) {
  1207. if (cur.IsLast ()) {
  1208. yield return new Rune (' ');
  1209. } else {
  1210. yield return driver.VLine;
  1211. }
  1212. yield return new Rune (' ');
  1213. }
  1214. if (IsLast ()) {
  1215. yield return driver.LLCorner;
  1216. } else {
  1217. yield return driver.LeftTee;
  1218. }
  1219. }
  1220. /// <summary>
  1221. /// Returns all parents starting with the immediate parent and ending at the root
  1222. /// </summary>
  1223. /// <returns></returns>
  1224. private IEnumerable<Branch<T>> GetParentBranches ()
  1225. {
  1226. var cur = Parent;
  1227. while (cur != null) {
  1228. yield return cur;
  1229. cur = cur.Parent;
  1230. }
  1231. }
  1232. /// <summary>
  1233. /// Returns an appropriate symbol for displaying next to the string representation of
  1234. /// the <see cref="Model"/> object to indicate whether it <see cref="IsExpanded"/> or
  1235. /// not (or it is a leaf)
  1236. /// </summary>
  1237. /// <param name="driver"></param>
  1238. /// <returns></returns>
  1239. public Rune GetExpandableSymbol (ConsoleDriver driver)
  1240. {
  1241. var leafSymbol = tree.Style.ShowBranchLines ? driver.HLine : ' ';
  1242. if (IsExpanded) {
  1243. return tree.Style.CollapseableSymbol ?? leafSymbol;
  1244. }
  1245. if (CanExpand ()) {
  1246. return tree.Style.ExpandableSymbol ?? leafSymbol;
  1247. }
  1248. return leafSymbol;
  1249. }
  1250. /// <summary>
  1251. /// Returns true if the current branch can be expanded according to
  1252. /// the <see cref="TreeBuilder{T}"/> or cached children already fetched
  1253. /// </summary>
  1254. /// <returns></returns>
  1255. public bool CanExpand ()
  1256. {
  1257. // if we do not know the children yet
  1258. if (ChildBranches == null) {
  1259. //if there is a rapid method for determining whether there are children
  1260. if (tree.TreeBuilder.SupportsCanExpand) {
  1261. return tree.TreeBuilder.CanExpand (Model);
  1262. }
  1263. //there is no way of knowing whether we can expand without fetching the children
  1264. FetchChildren ();
  1265. }
  1266. //we fetched or already know the children, so return whether we have any
  1267. return ChildBranches.Any ();
  1268. }
  1269. /// <summary>
  1270. /// Expands the current branch if possible
  1271. /// </summary>
  1272. public void Expand ()
  1273. {
  1274. if (ChildBranches == null) {
  1275. FetchChildren ();
  1276. }
  1277. if (ChildBranches.Any ()) {
  1278. IsExpanded = true;
  1279. }
  1280. }
  1281. /// <summary>
  1282. /// Marks the branch as collapsed (<see cref="IsExpanded"/> false)
  1283. /// </summary>
  1284. public void Collapse ()
  1285. {
  1286. IsExpanded = false;
  1287. }
  1288. /// <summary>
  1289. /// Refreshes cached knowledge in this branch e.g. what children an object has
  1290. /// </summary>
  1291. /// <param name="startAtTop">True to also refresh all <see cref="Parent"/>
  1292. /// branches (starting with the root)</param>
  1293. public void Refresh (bool startAtTop)
  1294. {
  1295. // if we must go up and refresh from the top down
  1296. if (startAtTop) {
  1297. Parent?.Refresh (true);
  1298. }
  1299. // we don't want to loose the state of our children so lets be selective about how we refresh
  1300. //if we don't know about any children yet just use the normal method
  1301. if (ChildBranches == null) {
  1302. FetchChildren ();
  1303. } else {
  1304. // we already knew about some children so preserve the state of the old children
  1305. // first gather the new Children
  1306. var newChildren = tree.TreeBuilder?.GetChildren (this.Model) ?? Enumerable.Empty<T> ();
  1307. // Children who no longer appear need to go
  1308. foreach (var toRemove in ChildBranches.Keys.Except (newChildren).ToArray ()) {
  1309. ChildBranches.Remove (toRemove);
  1310. //also if the user has this node selected (its disapearing) so lets change selection to us (the parent object) to be helpful
  1311. if (Equals (tree.SelectedObject, toRemove)) {
  1312. tree.SelectedObject = Model;
  1313. }
  1314. }
  1315. // New children need to be added
  1316. foreach (var newChild in newChildren) {
  1317. // If we don't know about the child yet we need a new branch
  1318. if (!ChildBranches.ContainsKey (newChild)) {
  1319. ChildBranches.Add (newChild, new Branch<T> (tree, this, newChild));
  1320. } else {
  1321. //we already have this object but update the reference anyway incase Equality match but the references are new
  1322. ChildBranches [newChild].Model = newChild;
  1323. }
  1324. }
  1325. }
  1326. }
  1327. /// <summary>
  1328. /// Calls <see cref="Refresh(bool)"/> on the current branch and all expanded children
  1329. /// </summary>
  1330. internal void Rebuild ()
  1331. {
  1332. Refresh (false);
  1333. // if we know about our children
  1334. if (ChildBranches != null) {
  1335. if (IsExpanded) {
  1336. //if we are expanded we need to updatethe visible children
  1337. foreach (var child in ChildBranches) {
  1338. child.Value.Rebuild ();
  1339. }
  1340. } else {
  1341. // we are not expanded so should forget about children because they may not exist anymore
  1342. ChildBranches = null;
  1343. }
  1344. }
  1345. }
  1346. /// <summary>
  1347. /// Returns true if this branch has parents and it is the last node of it's parents
  1348. /// branches (or last root of the tree)
  1349. /// </summary>
  1350. /// <returns></returns>
  1351. private bool IsLast ()
  1352. {
  1353. if (Parent == null) {
  1354. return this == tree.roots.Values.LastOrDefault ();
  1355. }
  1356. return Parent.ChildBranches.Values.LastOrDefault () == this;
  1357. }
  1358. /// <summary>
  1359. /// Returns true if the given x offset on the branch line is the +/- symbol. Returns
  1360. /// false if not showing expansion symbols or leaf node etc
  1361. /// </summary>
  1362. /// <param name="driver"></param>
  1363. /// <param name="x"></param>
  1364. /// <returns></returns>
  1365. internal bool IsHitOnExpandableSymbol (ConsoleDriver driver, int x)
  1366. {
  1367. // if leaf node then we cannot expand
  1368. if (!CanExpand ()) {
  1369. return false;
  1370. }
  1371. // if we could theoretically expand
  1372. if (!IsExpanded && tree.Style.ExpandableSymbol != null) {
  1373. return x == GetLinePrefix (driver).Count ();
  1374. }
  1375. // if we could theoretically collapse
  1376. if (IsExpanded && tree.Style.CollapseableSymbol != null) {
  1377. return x == GetLinePrefix (driver).Count ();
  1378. }
  1379. return false;
  1380. }
  1381. /// <summary>
  1382. /// Expands the current branch and all children branches
  1383. /// </summary>
  1384. internal void ExpandAll ()
  1385. {
  1386. Expand ();
  1387. if (ChildBranches != null) {
  1388. foreach (var child in ChildBranches) {
  1389. child.Value.ExpandAll ();
  1390. }
  1391. }
  1392. }
  1393. /// <summary>
  1394. /// Collapses the current branch and all children branches (even though those branches are
  1395. /// no longer visible they retain collapse/expansion state)
  1396. /// </summary>
  1397. internal void CollapseAll ()
  1398. {
  1399. Collapse ();
  1400. if (ChildBranches != null) {
  1401. foreach (var child in ChildBranches) {
  1402. child.Value.CollapseAll ();
  1403. }
  1404. }
  1405. }
  1406. }
  1407. /// <summary>
  1408. /// Delegates of this type are used to fetch string representations of user's model objects
  1409. /// </summary>
  1410. /// <param name="toRender">The object that is being rendered</param>
  1411. /// <returns></returns>
  1412. public delegate string AspectGetterDelegate<T> (T toRender) where T : class;
  1413. /// <summary>
  1414. /// Event arguments describing a change in selected object in a tree view
  1415. /// </summary>
  1416. public class SelectionChangedEventArgs<T> : EventArgs where T : class {
  1417. /// <summary>
  1418. /// The view in which the change occurred
  1419. /// </summary>
  1420. public TreeView<T> Tree { get; }
  1421. /// <summary>
  1422. /// The previously selected value (can be null)
  1423. /// </summary>
  1424. public T OldValue { get; }
  1425. /// <summary>
  1426. /// The newly selected value in the <see cref="Tree"/> (can be null)
  1427. /// </summary>
  1428. public T NewValue { get; }
  1429. /// <summary>
  1430. /// Creates a new instance of event args describing a change of selection
  1431. /// in <paramref name="tree"/>
  1432. /// </summary>
  1433. /// <param name="tree"></param>
  1434. /// <param name="oldValue"></param>
  1435. /// <param name="newValue"></param>
  1436. public SelectionChangedEventArgs (TreeView<T> tree, T oldValue, T newValue)
  1437. {
  1438. Tree = tree;
  1439. OldValue = oldValue;
  1440. NewValue = newValue;
  1441. }
  1442. }
  1443. static class ReadOnlyCollectionExtensions {
  1444. public static int IndexOf<T> (this IReadOnlyCollection<T> self, Func<T,bool> predicate)
  1445. {
  1446. int i = 0;
  1447. foreach (T element in self) {
  1448. if (predicate(element))
  1449. return i;
  1450. i++;
  1451. }
  1452. return -1;
  1453. }
  1454. public static int IndexOf<T> (this IReadOnlyCollection<T> self, T toFind)
  1455. {
  1456. int i = 0;
  1457. foreach (T element in self) {
  1458. if (Equals(element,toFind))
  1459. return i;
  1460. i++;
  1461. }
  1462. return -1;
  1463. }
  1464. }
  1465. }