View.Navigation.cs 34 KB

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