View.Navigation.cs 32 KB

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