View.Navigation.cs 30 KB

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