View.Navigation.cs 30 KB

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