TreeView.cs 43 KB

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