View.Navigation.cs 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825
  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. if (Focused is null && _subviews?.Count > 0)
  246. {
  247. if (_previouslyFocused is { })
  248. {
  249. return _previouslyFocused.SetFocus ();
  250. }
  251. return false;
  252. }
  253. return false;
  254. }
  255. private View? FindDeepestFocusableView (NavigationDirection direction, TabBehavior? behavior)
  256. {
  257. View [] indicies = GetFocusChain (direction, behavior);
  258. foreach (View v in indicies)
  259. {
  260. return v.FindDeepestFocusableView (direction, behavior);
  261. }
  262. return null;
  263. }
  264. #region HasFocus
  265. // Backs `HasFocus` and is the ultimate source of truth whether a View has focus or not.
  266. private bool _hasFocus;
  267. /// <summary>
  268. /// Gets or sets whether this view has focus.
  269. /// </summary>
  270. /// <remarks>
  271. /// <para>
  272. /// Only Views that are visible, enabled, and have <see cref="CanFocus"/> set to <see langword="true"/> are
  273. /// focusable. If
  274. /// these conditions are not met when this property is set to <see langword="true"/> <see cref="HasFocus"/> will
  275. /// not change.
  276. /// </para>
  277. /// <para>
  278. /// Setting this property causes the <see cref="OnHasFocusChanging"/> and <see cref="OnHasFocusChanged"/> virtual
  279. /// methods (and <see cref="HasFocusChanging"/> and
  280. /// <see cref="HasFocusChanged"/> events to be raised). If the event is cancelled, <see cref="HasFocus"/> will not
  281. /// be changed.
  282. /// </para>
  283. /// <para>
  284. /// Setting this property to <see langword="true"/> will recursively set <see cref="HasFocus"/> to
  285. /// <see langword="true"/> for all SuperViews up the hierarchy.
  286. /// </para>
  287. /// <para>
  288. /// Setting this property to <see langword="true"/> will cause the subview furthest down the hierarchy that is
  289. /// focusable to also gain focus (as long as <see cref="TabStop"/>
  290. /// </para>
  291. /// <para>
  292. /// Setting this property to <see langword="false"/> will cause <see cref="AdvanceFocus"/> to set
  293. /// the focus on the next view to be focused.
  294. /// </para>
  295. /// </remarks>
  296. public bool HasFocus
  297. {
  298. set
  299. {
  300. if (HasFocus == value)
  301. {
  302. return;
  303. }
  304. if (value)
  305. {
  306. // NOTE: If Application.Navigation is null, we pass null to FocusChanging. For unit tests.
  307. (bool focusSet, bool _) = SetHasFocusTrue (Application.Navigation?.GetFocused ());
  308. if (focusSet)
  309. {
  310. // The change happened
  311. // HasFocus is now true
  312. }
  313. }
  314. else
  315. {
  316. SetHasFocusFalse (null);
  317. }
  318. }
  319. get => _hasFocus;
  320. }
  321. /// <summary>
  322. /// Causes this view to be focused. Calling this method has the same effect as setting <see cref="HasFocus"/> to
  323. /// <see langword="true"/> but with the added benefit of returning a value indicating whether the focus was set.
  324. /// </summary>
  325. public bool SetFocus ()
  326. {
  327. (bool focusSet, bool _) = SetHasFocusTrue (Application.Navigation?.GetFocused ());
  328. return focusSet;
  329. }
  330. /// <summary>
  331. /// A cache of the subview that was focused when this view last lost focus. This is used by <see cref="RestoreFocus"/>.
  332. /// </summary>
  333. private View? _previouslyFocused;
  334. /// <summary>
  335. /// INTERNAL: Called when focus is going to change to this view. This method is called by <see cref="SetFocus"/> and
  336. /// other methods that
  337. /// set or remove focus from a view.
  338. /// </summary>
  339. /// <param name="previousFocusedView">
  340. /// The previously focused view. If <see langword="null"/> there is no previously focused
  341. /// view.
  342. /// </param>
  343. /// <param name="traversingUp"></param>
  344. /// <returns><see langword="true"/> if <see cref="HasFocus"/> was changed to <see langword="true"/>.</returns>
  345. /// <exception cref="InvalidOperationException"></exception>
  346. private (bool focusSet, bool cancelled) SetHasFocusTrue (View? previousFocusedView, bool traversingUp = false)
  347. {
  348. Debug.Assert (ApplicationNavigation.IsInHierarchy (SuperView, this));
  349. // Pre-conditions
  350. if (_hasFocus)
  351. {
  352. return (false, false);
  353. }
  354. var thisAsAdornment = this as Adornment;
  355. View? superViewOrParent = thisAsAdornment?.Parent ?? SuperView;
  356. if (CanFocus && superViewOrParent is { CanFocus: false })
  357. {
  358. Debug.WriteLine ($@"WARNING: Attempt to FocusChanging where SuperView.CanFocus == false. {this}");
  359. return (false, false);
  360. }
  361. if (!CanBeVisible (this) || !Enabled)
  362. {
  363. return (false, false);
  364. }
  365. if (!CanFocus)
  366. {
  367. return (false, false);
  368. }
  369. bool previousValue = HasFocus;
  370. bool cancelled = NotifyFocusChanging (false, true, previousFocusedView, this);
  371. if (cancelled)
  372. {
  373. return (false, true);
  374. }
  375. // Make sure superviews up the superview hierarchy have focus.
  376. // Any of them may cancel gaining focus. In which case we need to back out.
  377. if (superViewOrParent is { HasFocus: false } sv)
  378. {
  379. (bool focusSet, bool svCancelled) = sv.SetHasFocusTrue (previousFocusedView, true);
  380. if (!focusSet)
  381. {
  382. return (false, svCancelled);
  383. }
  384. }
  385. if (_hasFocus)
  386. {
  387. // Something else beat us to the change (likely a FocusChanged handler).
  388. return (true, false);
  389. }
  390. // By setting _hasFocus to true we definitively change HasFocus for this view.
  391. // Get whatever peer has focus, if any
  392. View? focusedPeer = superViewOrParent?.Focused;
  393. _hasFocus = true;
  394. // Ensure that the peer loses focus
  395. focusedPeer?.SetHasFocusFalse (this, true);
  396. if (!traversingUp)
  397. {
  398. // Restore focus to the previously focused subview
  399. if (!RestoreFocus ())
  400. {
  401. // Couldn't restore focus, so use Advance to navigate to the next focusable subview
  402. if (!AdvanceFocus (NavigationDirection.Forward, null))
  403. {
  404. // Couldn't advance, so we're the most focused view in the application
  405. }
  406. }
  407. }
  408. if (previousFocusedView is { HasFocus: true } && Subviews.Contains (previousFocusedView))
  409. {
  410. previousFocusedView.SetHasFocusFalse (this);
  411. }
  412. if (previousFocusedView is { HasFocus: true })
  413. {
  414. if (previousFocusedView.SuperView is Adornment a)
  415. {
  416. previousFocusedView.SetHasFocusFalse (this);
  417. }
  418. }
  419. _previouslyFocused = null;
  420. Application.Navigation?.SetFocused (this);
  421. if (Arrangement.HasFlag (ViewArrangement.Overlapped))
  422. {
  423. SuperView?.MoveSubviewToEnd (this);
  424. }
  425. NotifyFocusChanged (HasFocus, previousFocusedView, this);
  426. // Post-conditions - prove correctness
  427. if (HasFocus == previousValue)
  428. {
  429. throw new InvalidOperationException ("NotifyFocusChanging was not cancelled and the HasFocus value did not change.");
  430. }
  431. return (true, false);
  432. }
  433. private bool NotifyFocusChanging (bool currentHasFocus, bool newHasFocus, View? currentFocused, View? newFocused)
  434. {
  435. // Call the virtual method
  436. if (OnHasFocusChanging (currentHasFocus, newHasFocus, currentFocused, newFocused))
  437. {
  438. // The event was cancelled
  439. return true;
  440. }
  441. var args = new HasFocusEventArgs (currentHasFocus, newHasFocus, currentFocused, newFocused);
  442. HasFocusChanging?.Invoke (this, args);
  443. if (args.Cancel)
  444. {
  445. // The event was cancelled
  446. return true;
  447. }
  448. return false;
  449. }
  450. /// <summary>
  451. /// Invoked when <see cref="View.HasFocus"/> is about to change. This method is called before the
  452. /// <see cref="HasFocusChanging"/> event is raised.
  453. /// </summary>
  454. /// <remarks>
  455. /// <para>
  456. /// Use <see cref="OnHasFocusChanged"/> to be notified after the focus has changed.
  457. /// </para>
  458. /// </remarks>
  459. /// <param name="currentHasFocus">The current value of <see cref="View.HasFocus"/>.</param>
  460. /// <param name="newHasFocus">The value <see cref="View.HasFocus"/> will have if the focus change happens.</param>
  461. /// <param name="currentFocused">The view that is currently Focused. May be <see langword="null"/>.</param>
  462. /// <param name="newFocused">The view that will be focused. May be <see langword="null"/>.</param>
  463. /// <returns>
  464. /// <see langword="true"/>, if the change to <see cref="View.HasFocus"/> is to be cancelled, <see langword="false"/>
  465. /// otherwise.
  466. /// </returns>
  467. protected virtual bool OnHasFocusChanging (bool currentHasFocus, bool newHasFocus, View? currentFocused, View? newFocused) { return false; }
  468. /// <summary>
  469. /// Raised when <see cref="View.HasFocus"/> is about to change.
  470. /// </summary>
  471. /// <remarks>
  472. /// <para>
  473. /// Cancel the event to prevent the focus from changing.
  474. /// </para>
  475. /// <para>
  476. /// Use <see cref="HasFocusChanged"/> to be notified after the focus has changed.
  477. /// </para>
  478. /// </remarks>
  479. public event EventHandler<HasFocusEventArgs>? HasFocusChanging;
  480. /// <summary>
  481. /// Called when this view should stop being focused.
  482. /// </summary>
  483. /// <param name="newFocusedView">
  484. /// The new focused view. If <see langword="null"/> it is not known which view will be
  485. /// focused.
  486. /// </param>
  487. /// <param name="traversingDown">
  488. /// Set to true to indicate method is being called recurively, traversing down the focus
  489. /// chain.
  490. /// </param>
  491. /// <exception cref="InvalidOperationException"></exception>
  492. private void SetHasFocusFalse (View? newFocusedView, bool traversingDown = false)
  493. {
  494. // Pre-conditions
  495. if (!_hasFocus)
  496. {
  497. throw new InvalidOperationException ("SetHasFocusFalse should not be called if the view does not have focus.");
  498. }
  499. var thisAsAdornment = this as Adornment;
  500. View? superViewOrParent = thisAsAdornment?.Parent ?? SuperView;
  501. // If newFocusedVew is null, we need to find the view that should get focus, and SetFocus on it.
  502. if (!traversingDown && newFocusedView is null)
  503. {
  504. if (superViewOrParent?._previouslyFocused is { })
  505. {
  506. Debug.Assert (!superViewOrParent._previouslyFocused.WasDisposed);
  507. if (superViewOrParent._previouslyFocused != this)
  508. {
  509. superViewOrParent?._previouslyFocused?.SetFocus ();
  510. // The above will cause SetHasFocusFalse, so we can return
  511. return;
  512. }
  513. }
  514. if (superViewOrParent is { })
  515. {
  516. if (superViewOrParent.AdvanceFocus (NavigationDirection.Forward, TabStop))
  517. {
  518. // The above will cause SetHasFocusFalse, so we can return
  519. return;
  520. }
  521. newFocusedView = superViewOrParent;
  522. }
  523. if (Application.Navigation is { } && Application.Current is { })
  524. {
  525. // Temporarily ensure this view can't get focus
  526. bool prevCanFocus = _canFocus;
  527. _canFocus = false;
  528. bool restoredFocus = Application.Current!.RestoreFocus ();
  529. _canFocus = prevCanFocus;
  530. if (restoredFocus)
  531. {
  532. // The above caused SetHasFocusFalse, so we can return
  533. return;
  534. }
  535. }
  536. // No other focusable view to be found. Just "leave" us...
  537. }
  538. // Before we can leave focus, we need to make sure that all views down the subview-hierarchy have left focus.
  539. View? mostFocused = MostFocused;
  540. if (mostFocused is { } && (newFocusedView is null || mostFocused != newFocusedView))
  541. {
  542. // Start at the bottom and work our way up to us
  543. View? bottom = mostFocused;
  544. while (bottom is { } && bottom != this)
  545. {
  546. if (bottom.HasFocus)
  547. {
  548. bottom.SetHasFocusFalse (newFocusedView, true);
  549. }
  550. bottom = bottom.SuperView;
  551. }
  552. if (bottom == this && bottom.SuperView is Adornment a)
  553. {
  554. a.SetHasFocusFalse (newFocusedView, true);
  555. }
  556. }
  557. if (superViewOrParent is { })
  558. {
  559. superViewOrParent._previouslyFocused = this;
  560. }
  561. bool previousValue = HasFocus;
  562. // Note, can't be cancelled.
  563. NotifyFocusChanging (HasFocus, !HasFocus, newFocusedView, this);
  564. // Get whatever peer has focus, if any so we can update our superview's _previouslyMostFocused
  565. View? focusedPeer = superViewOrParent?.Focused;
  566. // Set HasFocus false
  567. _hasFocus = false;
  568. if (Application.Navigation is { })
  569. {
  570. View? appFocused = Application.Navigation.GetFocused ();
  571. if (appFocused is { } || appFocused == this)
  572. {
  573. Application.Navigation.SetFocused (newFocusedView ?? superViewOrParent);
  574. }
  575. }
  576. NotifyFocusChanged (HasFocus, this, newFocusedView);
  577. if (_hasFocus)
  578. {
  579. // Notify caused HasFocus to change to true.
  580. return;
  581. }
  582. // Post-conditions - prove correctness
  583. if (HasFocus == previousValue)
  584. {
  585. throw new InvalidOperationException ("SetHasFocusFalse and the HasFocus value did not change.");
  586. }
  587. SetNeedsDisplay ();
  588. }
  589. private void NotifyFocusChanged (bool newHasFocus, View? previousFocusedView, View? focusedVew)
  590. {
  591. // Call the virtual method
  592. OnHasFocusChanged (newHasFocus, previousFocusedView, focusedVew);
  593. // Raise the event
  594. var args = new HasFocusEventArgs (newHasFocus, newHasFocus, previousFocusedView, focusedVew);
  595. HasFocusChanged?.Invoke (this, args);
  596. }
  597. /// <summary>
  598. /// Invoked after <see cref="HasFocus"/> has changed. This method is called before the <see cref="HasFocusChanged"/>
  599. /// event is raised.
  600. /// </summary>
  601. /// <remarks>
  602. /// <para>
  603. /// This event cannot be cancelled.
  604. /// </para>
  605. /// </remarks>
  606. /// <param name="newHasFocus">The new value of <see cref="View.HasFocus"/>.</param>
  607. /// <param name="previousFocusedView"></param>
  608. /// <param name="focusedVew">The view that is now focused. May be <see langword="null"/></param>
  609. protected virtual void OnHasFocusChanged (bool newHasFocus, View? previousFocusedView, View? focusedVew) { }
  610. /// <summary>Raised after <see cref="HasFocus"/> has changed.</summary>
  611. /// <remarks>
  612. /// <para>
  613. /// This event cannot be cancelled.
  614. /// </para>
  615. /// </remarks>
  616. public event EventHandler<HasFocusEventArgs>? HasFocusChanged;
  617. #endregion HasFocus
  618. #region Tab/Focus Handling
  619. /// <summary>
  620. /// 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
  621. /// Adornments are returned.
  622. /// </summary>
  623. /// <param name="direction"></param>
  624. /// <param name="behavior"></param>
  625. /// <returns></returns>
  626. internal View [] GetFocusChain (NavigationDirection direction, TabBehavior? behavior)
  627. {
  628. IEnumerable<View>? filteredSubviews;
  629. if (behavior.HasValue)
  630. {
  631. filteredSubviews = _subviews?.Where (v => v.TabStop == behavior && v is { CanFocus: true, Visible: true, Enabled: true });
  632. }
  633. else
  634. {
  635. filteredSubviews = _subviews?.Where (v => v is { CanFocus: true, Visible: true, Enabled: true });
  636. }
  637. // How about in Adornments?
  638. if (Padding is { CanFocus: true, Visible: true, Enabled: true } && Padding.TabStop == behavior)
  639. {
  640. filteredSubviews = filteredSubviews?.Append (Padding);
  641. }
  642. if (Border is { CanFocus: true, Visible: true, Enabled: true } && Border.TabStop == behavior)
  643. {
  644. filteredSubviews = filteredSubviews?.Append (Border);
  645. }
  646. if (Margin is { CanFocus: true, Visible: true, Enabled: true } && Margin.TabStop == behavior)
  647. {
  648. filteredSubviews = filteredSubviews?.Append (Margin);
  649. }
  650. if (direction == NavigationDirection.Backward)
  651. {
  652. filteredSubviews = filteredSubviews?.Reverse ();
  653. }
  654. return filteredSubviews?.ToArray () ?? Array.Empty<View> ();
  655. }
  656. private TabBehavior? _tabStop;
  657. /// <summary>
  658. /// Gets or sets the behavior of <see cref="AdvanceFocus"/> for keyboard navigation.
  659. /// </summary>
  660. /// <remarks>
  661. /// <para>
  662. /// If <see langword="null"/> the tab stop has not been set and setting <see cref="CanFocus"/> to true will set it
  663. /// to
  664. /// <see cref="TabBehavior.TabStop"/>.
  665. /// </para>
  666. /// <para>
  667. /// TabStop is independent of <see cref="CanFocus"/>. If <see cref="CanFocus"/> is <see langword="false"/>, the
  668. /// view will not gain
  669. /// focus even if this property is set and vice-versa.
  670. /// </para>
  671. /// <para>
  672. /// The default <see cref="TabBehavior.TabStop"/> keys are <see cref="Application.NextTabKey"/> (<c>Key.Tab</c>)
  673. /// and <see cref="Application.PrevTabKey"/> (<c>Key>Tab.WithShift</c>).
  674. /// </para>
  675. /// <para>
  676. /// The default <see cref="TabBehavior.TabGroup"/> keys are <see cref="Application.NextTabGroupKey"/> (
  677. /// <c>Key.F6</c>) and <see cref="Application.PrevTabGroupKey"/> (<c>Key>Key.F6.WithShift</c>).
  678. /// </para>
  679. /// </remarks>
  680. public TabBehavior? TabStop
  681. {
  682. get => _tabStop;
  683. set
  684. {
  685. if (_tabStop is { } && _tabStop == value)
  686. {
  687. return;
  688. }
  689. _tabStop = value;
  690. }
  691. }
  692. #endregion Tab/Focus Handling
  693. }