View.Navigation.cs 28 KB

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