View.Navigation.cs 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865
  1. using System.Diagnostics;
  2. using System.Reflection.Metadata.Ecma335;
  3. using Microsoft.CodeAnalysis.Operations;
  4. using static Terminal.Gui.FakeDriver;
  5. namespace Terminal.Gui;
  6. public partial class View // Focus and cross-view navigation management (TabStop, TabIndex, etc...)
  7. {
  8. #region HasFocus
  9. // Backs `HasFocus` and is the ultimate source of truth whether a View has focus or not.
  10. private bool _hasFocus;
  11. /// <summary>
  12. /// Gets or sets whether this view has focus.
  13. /// </summary>
  14. /// <remarks>
  15. /// <para>
  16. /// Only Views that are visible, enabled, and have <see cref="CanFocus"/> set to <see langword="true"/> are focusable. If
  17. /// these conditions are not met when this property is set to <see langword="true"/> <see cref="HasFocus"/> will not change.
  18. /// </para>
  19. /// <para>
  20. /// Setting this property causes the <see cref="OnHasFocusChanging"/> and <see cref="OnHasFocusChanged"/> virtual methods (and <see cref="HasFocusChanging"/> and
  21. /// <see cref="HasFocusChanged"/> events to be raised). If the event is cancelled, <see cref="HasFocus"/> will not be changed.
  22. /// </para>
  23. /// <para>
  24. /// Setting this property to <see langword="true"/> will recursively set <see cref="HasFocus"/> to
  25. /// <see langword="true"/> for all SuperViews up the hierarchy.
  26. /// </para>
  27. /// <para>
  28. /// Setting this property to <see langword="true"/> will cause the subview furthest down the hierarchy that is
  29. /// focusable to also gain focus (as long as <see cref="TabStop"/>
  30. /// </para>
  31. /// <para>
  32. /// Setting this property to <see langword="false"/> will cause <see cref="ApplicationNavigation.MoveNextView"/> to set
  33. /// the focus on the next view to be focused.
  34. /// </para>
  35. /// </remarks>
  36. public bool HasFocus
  37. {
  38. set
  39. {
  40. if (HasFocus != value)
  41. {
  42. if (value)
  43. {
  44. // NOTE: If Application.Navigation is null, we pass null to FocusChanging. For unit tests.
  45. if (FocusChanging (Application.Navigation?.GetFocused ()))
  46. {
  47. // The change happened
  48. // HasFocus is now true
  49. }
  50. }
  51. else
  52. {
  53. FocusChanged (null);
  54. }
  55. }
  56. }
  57. get => _hasFocus;
  58. }
  59. /// <summary>
  60. /// Causes this view to be focused. Calling this method has the same effect as setting <see cref="HasFocus"/> to
  61. /// <see langword="true"/> but with the added benefit of returning a value indicating whether the focus was set.
  62. /// </summary>
  63. public bool SetFocus ()
  64. {
  65. return FocusChanging (Application.Navigation?.GetFocused ());
  66. }
  67. /// <summary>
  68. /// INTERNAL: Called when focus is going to change to this view. This method is called by <see cref="SetFocus"/> and other methods that
  69. /// set or remove focus from a view.
  70. /// </summary>
  71. /// <param name="previousFocusedView">The previously focused view. If <see langword="null"/> there is no previously focused view.</param>
  72. /// <param name="traversingUp"></param>
  73. /// <returns><see langword="true"/> if <see cref="HasFocus"/> was changed to <see langword="true"/>.</returns>
  74. /// <exception cref="InvalidOperationException"></exception>
  75. private bool FocusChanging ([CanBeNull] View previousFocusedView, bool traversingUp = false)
  76. {
  77. Debug.Assert (ApplicationNavigation.IsInHierarchy (SuperView, this));
  78. // Pre-conditions
  79. if (_hasFocus)
  80. {
  81. return false;
  82. }
  83. if (CanFocus && SuperView is { CanFocus: false })
  84. {
  85. Debug.WriteLine($@"WARNING: Attempt to FocusChanging where SuperView.CanFocus == false. {this}");
  86. return false;
  87. }
  88. if (!CanBeVisible (this) || !Enabled)
  89. {
  90. return false;
  91. }
  92. if (!CanFocus)
  93. {
  94. return false;
  95. }
  96. bool previousValue = HasFocus;
  97. if (!traversingUp)
  98. {
  99. if (NotifyFocusChanging (previousFocusedView))
  100. {
  101. return false;
  102. }
  103. // If we're here, we can be focused. But we may have subviews.
  104. // Restore focus to the previously most focused subview in the subview-hierarchy
  105. if (RestoreFocus (TabStop))
  106. {
  107. // A subview was focused. We're done because the subview has focus and it recursed up the superview hierarchy.
  108. return true;
  109. }
  110. // Couldn't restore focus, so use Advance to navigate to the next focusable subview
  111. if (AdvanceFocus (NavigationDirection.Forward, TabBehavior.TabStop))
  112. {
  113. // A subview was focused. We're done because the subview has focus and it recursed up the superview hierarchy.
  114. return true;
  115. }
  116. }
  117. // If we're here, we're the most-focusable view in the application OR we're traversing up the superview hierarchy.
  118. // If we previously had a subview with focus (`Focused = subview`), we need to make sure that all subviews down the `subview`-hierarchy LeaveFocus.
  119. // LeaveFocus will recurse down the subview hierarchy and will also set PreviouslyMostFocused
  120. View focused = Focused;
  121. focused?.FocusChanged (this, true);
  122. // We need to ensure all superviews up the superview hierarchy have focus.
  123. // Any of them may cancel gaining focus. In which case we need to back out.
  124. if (SuperView is { HasFocus: false } sv)
  125. {
  126. // Tell EnterFocus that we're traversing up the superview hierarchy
  127. if (!sv.FocusChanging (previousFocusedView, true))
  128. {
  129. // The change was cancelled
  130. return false;
  131. }
  132. }
  133. // If we're here:
  134. // - we're the most-focusable view in the application
  135. // - all superviews up the superview hierarchy have focus.
  136. // - By setting _hasFocus to true we definitively change HasFocus for this view.
  137. // Get whatever peer has focus, if any
  138. View focusedPeer = SuperView?.Focused;
  139. _hasFocus = true;
  140. // Ensure that the peer loses focus
  141. focusedPeer?.FocusChanged (this, true);
  142. // We're the most focused view in the application, we need to set the focused view to this view.
  143. Application.Navigation?.SetFocused (this);
  144. SetNeedsDisplay ();
  145. // Post-conditions - prove correctness
  146. if (HasFocus == previousValue)
  147. {
  148. throw new InvalidOperationException ($"FocusChanging was not cancelled and the HasFocus value did not change.");
  149. }
  150. return true;
  151. }
  152. private bool NotifyFocusChanging (View leavingView)
  153. {
  154. // Call the virtual method
  155. if (OnHasFocusChanging (leavingView))
  156. {
  157. // The event was cancelled
  158. return true;
  159. }
  160. var args = new FocusEventArgs (leavingView, this);
  161. HasFocusChanging?.Invoke (this, args);
  162. if (args.Cancel)
  163. {
  164. // The event was cancelled
  165. return true;
  166. }
  167. return false;
  168. }
  169. /// <summary>Virtual method invoked when the focus is changing to this View.</summary>
  170. /// <param name="currentlyFocusedView">The view that is currently Focused. May be <see langword="null"/>.</param>
  171. /// <returns> <see langword="true"/>, if the event is to be cancelled, <see langword="false"/> otherwise.</returns>
  172. protected virtual bool OnHasFocusChanging ([CanBeNull] View currentlyFocusedView)
  173. {
  174. return false;
  175. }
  176. /// <summary>Raised when the view is gaining (entering) focus. Can be cancelled.</summary>
  177. public event EventHandler<FocusEventArgs> HasFocusChanging;
  178. /// <summary>
  179. /// Called when focus has changed to another view.
  180. /// </summary>
  181. /// <param name="focusedVew">The view that now has focus. If <see langword="null"/> there is no view that has focus.</param>
  182. /// <exception cref="InvalidOperationException"></exception>
  183. private void FocusChanged ([CanBeNull] View focusedVew, bool traversingDown = false)
  184. {
  185. // Pre-conditions
  186. if (!_hasFocus)
  187. {
  188. throw new InvalidOperationException ($"FocusChanged should not be called if the view does not have focus.");
  189. }
  190. // If enteringView is null, we need to find the view that should get focus, and SetFocus on it.
  191. if (!traversingDown && focusedVew is null)
  192. {
  193. if (SuperView?._previouslyMostFocused is { } && SuperView?._previouslyMostFocused != this)
  194. {
  195. SuperView?._previouslyMostFocused?.SetFocus ();
  196. // The above will cause FocusChanged, so we can return
  197. return;
  198. }
  199. if (SuperView is {} && SuperView.AdvanceFocus (NavigationDirection.Forward, TabStop))
  200. {
  201. // The above will cause FocusChanged, so we can return
  202. return;
  203. }
  204. //if (Application.Navigation is { })
  205. //{
  206. // // Temporarily ensure this view can't get focus
  207. // bool prevCanFocus = _canFocus;
  208. // _canFocus = false;
  209. // ApplicationNavigation.MoveNextView ();
  210. // _canFocus = prevCanFocus;
  211. // // The above will cause LeaveFocus, so we can return
  212. // return;
  213. //}
  214. // No other focusable view to be found. Just "leave" us...
  215. }
  216. // Before we can leave focus, we need to make sure that all views down the subview-hierarchy have left focus.
  217. View mostFocused = MostFocused;
  218. if (mostFocused is { } && (focusedVew is null || mostFocused != focusedVew))
  219. {
  220. // Start at the bottom and work our way up to us
  221. View bottom = mostFocused;
  222. while (bottom is { } && bottom != this)
  223. {
  224. if (bottom.HasFocus)
  225. {
  226. bottom.FocusChanged (focusedVew, true);
  227. }
  228. bottom = bottom.SuperView;
  229. }
  230. _previouslyMostFocused = mostFocused;
  231. }
  232. bool previousValue = HasFocus;
  233. // Call the virtual method - NOTE: Leave cannot be cancelled
  234. OnHasFocusChanged (focusedVew);
  235. var args = new FocusEventArgs (focusedVew, this);
  236. HasFocusChanged?.Invoke (this, args);
  237. // Get whatever peer has focus, if any
  238. View focusedPeer = SuperView?.Focused;
  239. _hasFocus = false;
  240. if (!traversingDown && CanFocus && Visible && Enabled)
  241. {
  242. // Now ensure all views up the superview-hierarchy are unfocused
  243. if (SuperView is { HasFocus: true } && focusedPeer == this)
  244. {
  245. SuperView.FocusChanged (focusedVew);
  246. }
  247. }
  248. // Post-conditions - prove correctness
  249. if (HasFocus == previousValue)
  250. {
  251. throw new InvalidOperationException ($"LeaveFocus and the HasFocus value did not change.");
  252. }
  253. SetNeedsDisplay ();
  254. }
  255. /// <summary>
  256. /// Caches the most focused subview when this view is losing focus. This is used by <see cref="RestoreFocus"/>.
  257. /// </summary>
  258. [CanBeNull]
  259. private View _previouslyMostFocused;
  260. /// <summary>Virtual method invoked after another view gets focus. May be <see langword="null"/>.</summary>
  261. /// <param name="focusedVew">The view is now focused.</param>
  262. protected virtual void OnHasFocusChanged ([CanBeNull] View focusedVew)
  263. {
  264. return;
  265. }
  266. /// <summary>Raised when the view is gaining (entering) focus. Can not be cancelled.</summary>
  267. public event EventHandler<FocusEventArgs> HasFocusChanged;
  268. #endregion HasFocus
  269. /// <summary>
  270. /// Advances the focus to the next or previous view in <see cref="View.TabIndexes"/>, based on
  271. /// <paramref name="direction"/>.
  272. /// itself.
  273. /// </summary>
  274. /// <remarks>
  275. /// <para>
  276. /// If there is no next/previous view, the focus is set to the view itself.
  277. /// </para>
  278. /// </remarks>
  279. /// <param name="direction"></param>
  280. /// <param name="behavior"></param>
  281. /// <returns>
  282. /// <see langword="true"/> if focus was changed to another subview (or stayed on this one), <see langword="false"/>
  283. /// otherwise.
  284. /// </returns>
  285. public bool AdvanceFocus (NavigationDirection direction, TabBehavior? behavior)
  286. {
  287. if (!CanBeVisible (this)) // TODO: is this check needed?
  288. {
  289. return false;
  290. }
  291. if (TabIndexes is null || TabIndexes.Count == 0)
  292. {
  293. return false;
  294. }
  295. View focused = Focused;
  296. if (focused is {} && focused.AdvanceFocus (direction, behavior))
  297. {
  298. return true;
  299. }
  300. View[] index = GetScopedTabIndexes (direction, behavior);
  301. if (index.Length == 0)
  302. {
  303. return false;
  304. }
  305. var focusedIndex = index.IndexOf (Focused);
  306. int next = 0;
  307. if (focusedIndex < index.Length - 1)
  308. {
  309. next = focusedIndex + 1;
  310. }
  311. else
  312. {
  313. if (behavior == TabBehavior.TabGroup && behavior == TabStop && SuperView?.TabStop == TabBehavior.TabGroup)
  314. {
  315. // Go down the subview-hierarchy and leave
  316. // BUGBUG: This doesn't seem right
  317. Focused.HasFocus = false;
  318. // TODO: Should we check the return value of SetHasFocus?
  319. return false;
  320. }
  321. }
  322. View view = index [next];
  323. if (view.HasFocus)
  324. {
  325. // We could not advance
  326. return true;
  327. }
  328. // The subview does not have focus, but at least one other that can. Can this one be focused?
  329. return view.FocusChanging (Focused);
  330. }
  331. /// <summary>
  332. /// INTERNAL API to restore focus to the subview that had focus before this view lost focus.
  333. /// </summary>
  334. /// <returns>
  335. /// Returns true if focus was restored to a subview, false otherwise.
  336. /// </returns>
  337. internal bool RestoreFocus (TabBehavior? behavior)
  338. {
  339. if (Focused is null && _subviews?.Count > 0)
  340. {
  341. if (_previouslyMostFocused is { }/* && (behavior is null || _previouslyMostFocused.TabStop == behavior)*/)
  342. {
  343. return _previouslyMostFocused.SetFocus ();
  344. }
  345. return false;
  346. }
  347. return false;
  348. }
  349. /// <summary>
  350. /// Returns the most focused Subview down the subview-hierarchy.
  351. /// </summary>
  352. /// <value>The most focused Subview, or <see langword="null"/> if no Subview is focused.</value>
  353. public View MostFocused
  354. {
  355. get
  356. {
  357. // TODO: Remove this API. It's duplicative of Application.Navigation.GetFocused.
  358. if (Focused is null)
  359. {
  360. return null;
  361. }
  362. View most = Focused!.MostFocused;
  363. if (most is { })
  364. {
  365. return most;
  366. }
  367. return Focused;
  368. }
  369. }
  370. ///// <summary>
  371. ///// Internal API that causes <paramref name="viewToEnterFocus"/> to enter focus.
  372. ///// <paramref name="viewToEnterFocus"/> must be a subview.
  373. ///// Recursively sets focus up the superview hierarchy.
  374. ///// </summary>
  375. ///// <param name="viewToEnterFocus"></param>
  376. ///// <returns><see langword="true"/> if <paramref name="viewToEnterFocus"/> got focus.</returns>
  377. //private bool SetFocus (View viewToEnterFocus)
  378. //{
  379. // if (viewToEnterFocus is null)
  380. // {
  381. // return false;
  382. // }
  383. // if (!viewToEnterFocus.CanFocus || !viewToEnterFocus.Visible || !viewToEnterFocus.Enabled)
  384. // {
  385. // return false;
  386. // }
  387. // // If viewToEnterFocus is already the focused view, don't do anything
  388. // if (Focused?._hasFocus == true && Focused == viewToEnterFocus)
  389. // {
  390. // return false;
  391. // }
  392. // // If a subview has focus and viewToEnterFocus is the focused view's superview OR viewToEnterFocus is this view,
  393. // // then make viewToEnterFocus.HasFocus = true and return
  394. // if ((Focused?._hasFocus == true && Focused?.SuperView == viewToEnterFocus) || viewToEnterFocus == this)
  395. // {
  396. // if (!viewToEnterFocus._hasFocus)
  397. // {
  398. // viewToEnterFocus._hasFocus = true;
  399. // }
  400. // // viewToEnterFocus is already focused
  401. // return true;
  402. // }
  403. // // Make sure that viewToEnterFocus is a subview of this view
  404. // View c;
  405. // for (c = viewToEnterFocus._superView; c != null; c = c._superView)
  406. // {
  407. // if (c == this)
  408. // {
  409. // break;
  410. // }
  411. // }
  412. // if (c is null)
  413. // {
  414. // throw new ArgumentException (@$"The specified view {viewToEnterFocus} is not part of the hierarchy of {this}.");
  415. // }
  416. // // If a subview has focus, make it leave focus. This will leave focus up the hierarchy.
  417. // Focused?.SetHasFocus (false, viewToEnterFocus);
  418. // // make viewToEnterFocus Focused and enter focus
  419. // View f = Focused;
  420. // Focused = viewToEnterFocus;
  421. // Focused?.SetHasFocus (true, f, true);
  422. // Focused?.FocusDeepest (null, NavigationDirection.Forward);
  423. // // Recursively set focus up the superview hierarchy
  424. // if (SuperView is { })
  425. // {
  426. // // BUGBUG: If focus is cancelled at any point, we should stop and restore focus to the previous focused view
  427. // SuperView.SetFocus (this);
  428. // }
  429. // else
  430. // {
  431. // // BUGBUG: this makes no sense in the new design
  432. // // If there is no SuperView, then this is a top-level view
  433. // SetFocus (this);
  434. // }
  435. // // TODO: Temporary hack to make Application.Navigation.FocusChanged work
  436. // if (HasFocus && Focused.Focused is null)
  437. // {
  438. // Application.Navigation?.SetFocused (Focused);
  439. // }
  440. // // TODO: This is a temporary hack to make overlapped non-Toplevels have a zorder. See also: View.OnDrawContent.
  441. // if (viewToEnterFocus is { } && (viewToEnterFocus.TabStop == TabBehavior.TabGroup && viewToEnterFocus.Arrangement.HasFlag (ViewArrangement.Overlapped)))
  442. // {
  443. // viewToEnterFocus.TabIndex = 0;
  444. // }
  445. // return true;
  446. //}
  447. #if AUTO_CANFOCUS
  448. // BUGBUG: This is a poor API design. Automatic behavior like this is non-obvious and should be avoided. Instead, callers to Add should be explicit about what they want.
  449. // Set to true in Add() to indicate that the view being added to a SuperView has CanFocus=true.
  450. // Makes it so CanFocus will update the SuperView's CanFocus property.
  451. internal bool _addingViewSoCanFocusAlsoUpdatesSuperView;
  452. // Used to cache CanFocus on subviews when CanFocus is set to false so that it can be restored when CanFocus is changed back to true
  453. private bool _oldCanFocus;
  454. #endif
  455. private bool _canFocus;
  456. /// <summary>Gets or sets a value indicating whether this <see cref="View"/> can be focused.</summary>
  457. /// <remarks>
  458. /// <para>
  459. /// <see cref="SuperView"/> must also have <see cref="CanFocus"/> set to <see langword="true"/>.
  460. /// </para>
  461. /// <para>
  462. /// When set to <see langword="false"/>, if an attempt is made to make this view focused, the focus will be set to
  463. /// the next focusable view.
  464. /// </para>
  465. /// <para>
  466. /// When set to <see langword="false"/>, the <see cref="TabIndex"/> will be set to -1.
  467. /// </para>
  468. /// <para>
  469. /// When set to <see langword="false"/>, the values of <see cref="CanFocus"/> and <see cref="TabIndex"/> for all
  470. /// subviews will be cached so that when <see cref="CanFocus"/> is set back to <see langword="true"/>, the subviews
  471. /// will be restored to their previous values.
  472. /// </para>
  473. /// <para>
  474. /// Changing this property to <see langword="true"/> will cause <see cref="TabStop"/> to be set to
  475. /// <see cref="TabBehavior.TabStop"/>" as a convenience. Changing this property to
  476. /// <see langword="false"/> will have no effect on <see cref="TabStop"/>.
  477. /// </para>
  478. /// </remarks>
  479. public bool CanFocus
  480. {
  481. get => _canFocus;
  482. set
  483. {
  484. if (_canFocus == value)
  485. {
  486. return;
  487. }
  488. _canFocus = value;
  489. if (TabStop is null && _canFocus)
  490. {
  491. TabStop = TabBehavior.TabStop;
  492. }
  493. if (!_canFocus && HasFocus)
  494. {
  495. // If CanFocus is set to false and this view has focus, make it leave focus
  496. HasFocus = false;
  497. }
  498. if (_canFocus && !HasFocus && Visible && SuperView is { } && SuperView.Focused is null )
  499. {
  500. // If CanFocus is set to true and this view does not have focus, make it enter focus
  501. SetFocus ();
  502. }
  503. OnCanFocusChanged ();
  504. }
  505. }
  506. /// <summary>Raised when <see cref="CanFocus"/> has been changed.</summary>
  507. /// <remarks>
  508. /// Raised by the <see cref="OnCanFocusChanged"/> virtual method.
  509. /// </remarks>
  510. public event EventHandler CanFocusChanged;
  511. /// <summary>Gets the currently focused Subview of this view, or <see langword="null"/> if nothing is focused.</summary>
  512. [CanBeNull]
  513. public View Focused
  514. {
  515. get { return Subviews.FirstOrDefault (v => v.HasFocus); }
  516. }
  517. /// <summary>
  518. /// Focuses the deepest focusable view in <see cref="View.TabIndexes"/> if one exists. If there are no views in
  519. /// <see cref="View.TabIndexes"/> then the focus is set to the view itself.
  520. /// </summary>
  521. /// <param name="direction"></param>
  522. /// <param name="behavior"></param>
  523. /// <returns><see langword="true"/> if a subview other than this was focused.</returns>
  524. public bool FocusDeepest (NavigationDirection direction, TabBehavior? behavior)
  525. {
  526. View deepest = FindDeepestFocusableView (direction, behavior);
  527. if (deepest is { })
  528. {
  529. return deepest.SetFocus ();
  530. }
  531. return SetFocus ();
  532. }
  533. [CanBeNull]
  534. private View FindDeepestFocusableView (NavigationDirection direction, TabBehavior? behavior)
  535. {
  536. var indicies = GetScopedTabIndexes (direction, behavior);
  537. foreach (View v in indicies)
  538. {
  539. if (v.TabIndexes.Count == 0)
  540. {
  541. return v;
  542. }
  543. return v.FindDeepestFocusableView (direction, behavior);
  544. }
  545. return null;
  546. }
  547. /// <summary>Returns a value indicating if this View is currently on Top (Active)</summary>
  548. public bool IsCurrentTop => Application.Current == this;
  549. /// <summary>Invoked when the <see cref="CanFocus"/> property from a view is changed.</summary>
  550. /// <remarks>
  551. /// Raises the <see cref="CanFocusChanged"/> event.
  552. /// </remarks>
  553. public virtual void OnCanFocusChanged () { CanFocusChanged?.Invoke (this, EventArgs.Empty); }
  554. #region Tab/Focus Handling
  555. #nullable enable
  556. private List<View>? _tabIndexes;
  557. // TODO: This should be a get-only property?
  558. // BUGBUG: This returns an AsReadOnly list, but isn't declared as such.
  559. /// <summary>Gets a list of the subviews that are a <see cref="TabStop"/>.</summary>
  560. /// <value>The tabIndexes.</value>
  561. public IList<View> TabIndexes => _tabIndexes?.AsReadOnly () ?? _empty;
  562. /// <summary>
  563. /// Gets TabIndexes that are scoped to the specified behavior and direction. If behavior is null, all TabIndexes are returned.
  564. /// </summary>
  565. /// <param name="direction"></param>
  566. /// <param name="behavior"></param>
  567. /// <returns></returns>GetScopedTabIndexes
  568. private View [] GetScopedTabIndexes (NavigationDirection direction, TabBehavior? behavior)
  569. {
  570. IEnumerable<View>? indicies;
  571. if (behavior.HasValue)
  572. {
  573. indicies = _tabIndexes?.Where (v => v.TabStop == behavior && v is { CanFocus: true, Visible: true, Enabled: true });
  574. }
  575. else
  576. {
  577. indicies = _tabIndexes?.Where (v => v is { CanFocus: true, Visible: true, Enabled: true });
  578. }
  579. if (direction == NavigationDirection.Backward)
  580. {
  581. indicies = indicies?.Reverse ();
  582. }
  583. return indicies?.ToArray () ?? Array.Empty<View> ();
  584. }
  585. private int? _tabIndex; // null indicates the view has not yet been added to TabIndexes
  586. private int? _oldTabIndex;
  587. /// <summary>
  588. /// Indicates the order of the current <see cref="View"/> in <see cref="TabIndexes"/> list.
  589. /// </summary>
  590. /// <remarks>
  591. /// <para>
  592. /// If <see langword="null"/>, the view is not part of the tab order.
  593. /// </para>
  594. /// <para>
  595. /// On set, if <see cref="SuperView"/> is <see langword="null"/> or has not TabStops, <see cref="TabIndex"/> will
  596. /// be set to 0.
  597. /// </para>
  598. /// <para>
  599. /// On set, if <see cref="SuperView"/> has only one TabStop, <see cref="TabIndex"/> will be set to 0.
  600. /// </para>
  601. /// <para>
  602. /// See also <seealso cref="TabStop"/>.
  603. /// </para>
  604. /// </remarks>
  605. public int? TabIndex
  606. {
  607. get => _tabIndex;
  608. // TOOD: This should be a get-only property. Introduce SetTabIndex (int value) (or similar).
  609. set
  610. {
  611. // Once a view is in the tab order, it should not be removed from the tab order; set TabStop to NoStop instead.
  612. Debug.Assert (value >= 0);
  613. Debug.Assert (value is { });
  614. if (SuperView?._tabIndexes is null || SuperView?._tabIndexes.Count == 1)
  615. {
  616. // BUGBUG: Property setters should set the property to the value passed in and not have side effects.
  617. _tabIndex = 0;
  618. return;
  619. }
  620. if (_tabIndex == value && TabIndexes.IndexOf (this) == value)
  621. {
  622. return;
  623. }
  624. _tabIndex = value > SuperView!.TabIndexes.Count - 1 ? SuperView._tabIndexes.Count - 1 :
  625. value < 0 ? 0 : value;
  626. _tabIndex = GetGreatestTabIndexInSuperView ((int)_tabIndex);
  627. if (SuperView._tabIndexes.IndexOf (this) != _tabIndex)
  628. {
  629. // BUGBUG: we have to use _tabIndexes and not TabIndexes because TabIndexes returns is a read-only version of _tabIndexes
  630. SuperView._tabIndexes.Remove (this);
  631. SuperView._tabIndexes.Insert ((int)_tabIndex, this);
  632. UpdatePeerTabIndexes ();
  633. }
  634. return;
  635. // Updates the <see cref="TabIndex"/>s of the views in the <see cref="SuperView"/>'s to match their order in <see cref="TabIndexes"/>.
  636. void UpdatePeerTabIndexes ()
  637. {
  638. if (SuperView is null)
  639. {
  640. return;
  641. }
  642. var i = 0;
  643. foreach (View superViewTabStop in SuperView._tabIndexes)
  644. {
  645. if (superViewTabStop._tabIndex is null)
  646. {
  647. continue;
  648. }
  649. superViewTabStop._tabIndex = i;
  650. i++;
  651. }
  652. }
  653. }
  654. }
  655. /// <summary>
  656. /// Gets the greatest <see cref="TabIndex"/> of the <see cref="SuperView"/>'s <see cref="TabIndexes"/> that is less
  657. /// than or equal to <paramref name="idx"/>.
  658. /// </summary>
  659. /// <param name="idx"></param>
  660. /// <returns>The minimum of <paramref name="idx"/> and the <see cref="SuperView"/>'s <see cref="TabIndexes"/>.</returns>
  661. private int GetGreatestTabIndexInSuperView (int idx)
  662. {
  663. if (SuperView is null)
  664. {
  665. return 0;
  666. }
  667. var i = 0;
  668. foreach (View superViewTabStop in SuperView._tabIndexes)
  669. {
  670. if (superViewTabStop._tabIndex is null || superViewTabStop == this)
  671. {
  672. continue;
  673. }
  674. i++;
  675. }
  676. return Math.Min (i, idx);
  677. }
  678. private TabBehavior? _tabStop;
  679. /// <summary>
  680. /// Gets or sets the behavior of <see cref="AdvanceFocus"/> for keyboard navigation.
  681. /// </summary>
  682. /// <remarks>
  683. /// <para>
  684. /// If <see langword="null"/> the tab stop has not been set and setting <see cref="CanFocus"/> to true will set it
  685. /// to
  686. /// <see cref="TabBehavior.TabStop"/>.
  687. /// </para>
  688. /// <para>
  689. /// TabStop is independent of <see cref="CanFocus"/>. If <see cref="CanFocus"/> is <see langword="false"/>, the
  690. /// view will not gain
  691. /// focus even if this property is set and vice-versa.
  692. /// </para>
  693. /// <para>
  694. /// The default <see cref="TabBehavior.TabStop"/> keys are <see cref="Application.NextTabKey"/> (<c>Key.Tab</c>) and <see cref="Application.PrevTabKey"/> (<c>Key>Tab.WithShift</c>).
  695. /// </para>
  696. /// <para>
  697. /// The default <see cref="TabBehavior.TabGroup"/> keys are <see cref="Application.NextTabGroupKey"/> (<c>Key.F6</c>) and <see cref="Application.PrevTabGroupKey"/> (<c>Key>Key.F6.WithShift</c>).
  698. /// </para>
  699. /// </remarks>
  700. public TabBehavior? TabStop
  701. {
  702. get => _tabStop;
  703. set
  704. {
  705. if (_tabStop == value)
  706. {
  707. return;
  708. }
  709. Debug.Assert (value is { });
  710. if (_tabStop is null && TabIndex is null)
  711. {
  712. // This view has not yet been added to TabIndexes (TabStop has not been set previously).
  713. TabIndex = GetGreatestTabIndexInSuperView (SuperView is { } ? SuperView._tabIndexes.Count : 0);
  714. }
  715. _tabStop = value;
  716. }
  717. }
  718. #endregion Tab/Focus Handling
  719. }