View.Navigation.cs 29 KB

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