View.Navigation.cs 27 KB

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