View.Navigation.cs 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020
  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. internal void RaiseFocusedChanged (View? previousFocused, View? focused)
  273. {
  274. //Logging.Trace($"RaiseFocusedChanged: {focused.Title}");
  275. OnFocusedChanged (previousFocused, focused);
  276. FocusedChanged?.Invoke (this, new HasFocusEventArgs (true, true, previousFocused, focused));
  277. }
  278. /// <summary>
  279. /// Called when the focused view has changed.
  280. /// </summary>
  281. /// <param name="previousFocused"></param>
  282. /// <param name="focused"></param>
  283. protected virtual void OnFocusedChanged (View? previousFocused, View? focused) { }
  284. /// <summary>
  285. /// Raised when the focused view has changed.
  286. /// </summary>
  287. public event EventHandler<HasFocusEventArgs>? FocusedChanged;
  288. /// <summary>Returns a value indicating if this View is currently on Top (Active)</summary>
  289. public bool IsCurrentTop => Application.Top == this;
  290. /// <summary>
  291. /// Returns the most focused SubView down the subview-hierarchy.
  292. /// </summary>
  293. /// <value>The most focused SubView, or <see langword="null"/> if no SubView is focused.</value>
  294. public View? MostFocused
  295. {
  296. get
  297. {
  298. // TODO: Remove this API. It's duplicative of Application.Navigation.GetFocused.
  299. if (Focused is null)
  300. {
  301. return null;
  302. }
  303. View? most = Focused.MostFocused;
  304. if (most is { })
  305. {
  306. return most;
  307. }
  308. return Focused;
  309. }
  310. }
  311. /// <summary>Invoked when the <see cref="CanFocus"/> property from a view is changed.</summary>
  312. /// <remarks>
  313. /// Raises the <see cref="CanFocusChanged"/> event.
  314. /// </remarks>
  315. public virtual void OnCanFocusChanged () { CanFocusChanged?.Invoke (this, EventArgs.Empty); }
  316. /// <summary>
  317. /// INTERNAL API to restore focus to the subview that had focus before this view lost focus.
  318. /// </summary>
  319. /// <returns>
  320. /// Returns true if focus was restored to a subview, false otherwise.
  321. /// </returns>
  322. internal bool RestoreFocus ()
  323. {
  324. // Ignore TabStop
  325. View [] indicies = GetFocusChain (NavigationDirection.Forward, null);
  326. if (Focused is null && _previouslyFocused is { } && indicies.Contains (_previouslyFocused))
  327. {
  328. if (_previouslyFocused.SetFocus ())
  329. {
  330. return true;
  331. }
  332. _previouslyFocused = null;
  333. }
  334. return false;
  335. }
  336. /// <summary>
  337. /// Clears any focus state (e.g. the previously focused subview) from this view.
  338. /// </summary>
  339. public void ClearFocus ()
  340. {
  341. _previouslyFocused = null;
  342. }
  343. private View? FindDeepestFocusableView (NavigationDirection direction, TabBehavior? behavior)
  344. {
  345. View [] indicies = GetFocusChain (direction, behavior);
  346. foreach (View v in indicies)
  347. {
  348. return v.FindDeepestFocusableView (direction, behavior);
  349. }
  350. return null;
  351. }
  352. #region HasFocus
  353. // Backs `HasFocus` and is the ultimate source of truth whether a View has focus or not.
  354. private bool _hasFocus;
  355. /// <summary>
  356. /// Gets or sets whether this view has focus.
  357. /// </summary>
  358. /// <remarks>
  359. /// <para>
  360. /// See the View Navigation Deep Dive for more information:
  361. /// <see href="https://gui-cs.github.io/Terminal.GuiV2Docs/docs/navigation.html"/>
  362. /// </para>
  363. /// <para>
  364. /// Only Views that are visible, enabled, and have <see cref="CanFocus"/> set to <see langword="true"/> are
  365. /// focusable. If
  366. /// these conditions are not met when this property is set to <see langword="true"/> <see cref="HasFocus"/> will
  367. /// not change.
  368. /// </para>
  369. /// <para>
  370. /// Setting this property causes the <see cref="OnHasFocusChanging"/> and <see cref="OnHasFocusChanged"/> virtual
  371. /// methods (and <see cref="HasFocusChanging"/> and
  372. /// <see cref="HasFocusChanged"/> events to be raised). If the event is cancelled, <see cref="HasFocus"/> will not
  373. /// be changed.
  374. /// </para>
  375. /// <para>
  376. /// Setting this property to <see langword="true"/> will recursively set <see cref="HasFocus"/> to
  377. /// <see langword="true"/> for all SuperViews up the hierarchy.
  378. /// </para>
  379. /// <para>
  380. /// Setting this property to <see langword="true"/> will cause the subview furthest down the hierarchy that is
  381. /// focusable to also gain focus (as long as <see cref="TabStop"/>
  382. /// </para>
  383. /// <para>
  384. /// Setting this property to <see langword="false"/> will cause <see cref="AdvanceFocus"/> to set
  385. /// the focus on the next view to be focused.
  386. /// </para>
  387. /// </remarks>
  388. public bool HasFocus
  389. {
  390. set
  391. {
  392. if (HasFocus == value)
  393. {
  394. return;
  395. }
  396. if (value)
  397. {
  398. // NOTE: If Application.Navigation is null, we pass null to FocusChanging. For unit tests.
  399. (bool focusSet, bool _) = SetHasFocusTrue (Application.Navigation?.GetFocused ());
  400. if (focusSet)
  401. {
  402. // The change happened
  403. // HasFocus is now true
  404. }
  405. }
  406. else
  407. {
  408. SetHasFocusFalse (null);
  409. Debug.Assert (!_hasFocus);
  410. if (_hasFocus)
  411. {
  412. // force it.
  413. _hasFocus = false;
  414. }
  415. }
  416. }
  417. get => _hasFocus;
  418. }
  419. /// <summary>
  420. /// Causes this view to be focused. Calling this method has the same effect as setting <see cref="HasFocus"/> to
  421. /// <see langword="true"/> but with the added benefit of returning a value indicating whether the focus was set.
  422. /// </summary>
  423. /// <remarks>
  424. /// <para>
  425. /// See the View Navigation Deep Dive for more information:
  426. /// <see href="https://gui-cs.github.io/Terminal.GuiV2Docs/docs/navigation.html"/>
  427. /// </para>
  428. /// </remarks>
  429. /// <returns><see langword="true"/> if the focus changed; <see langword="true"/> false otherwise.</returns>
  430. public bool SetFocus ()
  431. {
  432. (bool focusSet, bool _) = SetHasFocusTrue (Application.Navigation?.GetFocused ());
  433. return focusSet;
  434. }
  435. /// <summary>
  436. /// A cache of the subview that was focused when this view last lost focus. This is used by <see cref="RestoreFocus"/>.
  437. /// </summary>
  438. private View? _previouslyFocused;
  439. /// <summary>
  440. /// INTERNAL: Called when focus is going to change to this view. This method is called by <see cref="SetFocus"/> and
  441. /// other methods that
  442. /// set or remove focus from a view.
  443. /// </summary>
  444. /// <param name="currentFocusedView">
  445. /// The currently focused view. If <see langword="null"/> there is no previously focused
  446. /// view.
  447. /// </param>
  448. /// <param name="traversingUp"></param>
  449. /// <returns><see langword="true"/> if <see cref="HasFocus"/> was changed to <see langword="true"/>.</returns>
  450. /// <exception cref="InvalidOperationException"></exception>
  451. private (bool focusSet, bool cancelled) SetHasFocusTrue (View? currentFocusedView, bool traversingUp = false)
  452. {
  453. Debug.Assert (SuperView is null || View.IsInHierarchy (SuperView, this));
  454. // Pre-conditions
  455. if (_hasFocus)
  456. {
  457. return (false, false);
  458. }
  459. if (currentFocusedView is { HasFocus: false })
  460. {
  461. throw new ArgumentException ("SetHasFocusTrue: currentFocusedView must HasFocus.");
  462. }
  463. var thisAsAdornment = this as Adornment;
  464. View? superViewOrParent = thisAsAdornment?.Parent ?? SuperView;
  465. if (CanFocus && superViewOrParent is { CanFocus: false })
  466. {
  467. Debug.WriteLine ($@"WARNING: Attempt to FocusChanging where SuperView.CanFocus == false. {this}");
  468. return (false, false);
  469. }
  470. if (!CanBeVisible (this) || !Enabled)
  471. {
  472. return (false, false);
  473. }
  474. if (!CanFocus)
  475. {
  476. return (false, false);
  477. }
  478. bool previousValue = HasFocus;
  479. bool cancelled = RaiseFocusChanging (false, true, currentFocusedView, this);
  480. if (cancelled)
  481. {
  482. return (false, true);
  483. }
  484. // Make sure superviews up the superview hierarchy have focus.
  485. // Any of them may cancel gaining focus. In which case we need to back out.
  486. if (superViewOrParent is { HasFocus: false } sv)
  487. {
  488. (bool focusSet, bool svCancelled) = sv.SetHasFocusTrue (currentFocusedView, true);
  489. if (!focusSet)
  490. {
  491. return (false, svCancelled);
  492. }
  493. }
  494. if (_hasFocus)
  495. {
  496. // Something else beat us to the change (likely a FocusChanged handler).
  497. return (true, false);
  498. }
  499. // By setting _hasFocus to true we definitively change HasFocus for this view.
  500. // Get whatever peer has focus, if any
  501. View? focusedPeer = superViewOrParent?.Focused;
  502. _hasFocus = true;
  503. // Ensure that the peer loses focus
  504. focusedPeer?.SetHasFocusFalse (this, true);
  505. if (!traversingUp)
  506. {
  507. // Restore focus to the previously focused subview, if any
  508. if (!RestoreFocus ())
  509. {
  510. // Couldn't restore focus, so use Advance to navigate to the next focusable subview, if any
  511. AdvanceFocus (NavigationDirection.Forward, null);
  512. }
  513. }
  514. // Now make sure the old focused view loses focus
  515. if (currentFocusedView is { HasFocus: true } && GetFocusChain (NavigationDirection.Forward, TabStop).Contains (currentFocusedView))
  516. {
  517. currentFocusedView.SetHasFocusFalse (this);
  518. }
  519. if (_previouslyFocused is { })
  520. {
  521. _previouslyFocused = null;
  522. }
  523. if (Arrangement.HasFlag (ViewArrangement.Overlapped))
  524. {
  525. SuperView?.MoveSubViewToEnd (this);
  526. }
  527. // Focus work is done. Notify.
  528. RaiseFocusChanged (HasFocus, currentFocusedView, this);
  529. SetNeedsDraw ();
  530. // Post-conditions - prove correctness
  531. if (HasFocus == previousValue)
  532. {
  533. throw new InvalidOperationException ("NotifyFocusChanging was not cancelled and the HasFocus value did not change.");
  534. }
  535. return (true, false);
  536. }
  537. private bool RaiseFocusChanging (bool currentHasFocus, bool newHasFocus, View? currentFocused, View? newFocused)
  538. {
  539. Debug.Assert (currentFocused is null || currentFocused is { HasFocus: true });
  540. Debug.Assert (newFocused is null || newFocused is { CanFocus: true });
  541. // Call the virtual method
  542. if (OnHasFocusChanging (currentHasFocus, newHasFocus, currentFocused, newFocused))
  543. {
  544. // The event was cancelled
  545. return true;
  546. }
  547. var args = new HasFocusEventArgs (currentHasFocus, newHasFocus, currentFocused, newFocused);
  548. HasFocusChanging?.Invoke (this, args);
  549. if (args.Cancel)
  550. {
  551. // The event was cancelled
  552. return true;
  553. }
  554. View? appFocused = Application.Navigation?.GetFocused ();
  555. if (appFocused == currentFocused)
  556. {
  557. if (newFocused is { HasFocus: true })
  558. {
  559. Application.Navigation?.SetFocused (newFocused);
  560. }
  561. else
  562. {
  563. Application.Navigation?.SetFocused (null);
  564. }
  565. }
  566. return false;
  567. }
  568. /// <summary>
  569. /// Invoked when <see cref="View.HasFocus"/> is about to change. This method is called before the
  570. /// <see cref="HasFocusChanging"/> event is raised.
  571. /// </summary>
  572. /// <remarks>
  573. /// <para>
  574. /// Use <see cref="OnHasFocusChanged"/> to be notified after the focus has changed.
  575. /// </para>
  576. /// </remarks>
  577. /// <param name="currentHasFocus">The current value of <see cref="View.HasFocus"/>.</param>
  578. /// <param name="newHasFocus">The value <see cref="View.HasFocus"/> will have if the focus change happens.</param>
  579. /// <param name="currentFocused">The view that is currently Focused. May be <see langword="null"/>.</param>
  580. /// <param name="newFocused">The view that will be focused. May be <see langword="null"/>.</param>
  581. /// <returns>
  582. /// <see langword="true"/>, if the change to <see cref="View.HasFocus"/> is to be cancelled, <see langword="false"/>
  583. /// otherwise.
  584. /// </returns>
  585. protected virtual bool OnHasFocusChanging (bool currentHasFocus, bool newHasFocus, View? currentFocused, View? newFocused) { return false; }
  586. /// <summary>
  587. /// Raised when <see cref="View.HasFocus"/> is about to change.
  588. /// </summary>
  589. /// <remarks>
  590. /// <para>
  591. /// Cancel the event to prevent the focus from changing.
  592. /// </para>
  593. /// <para>
  594. /// Use <see cref="HasFocusChanged"/> to be notified after the focus has changed.
  595. /// </para>
  596. /// </remarks>
  597. public event EventHandler<HasFocusEventArgs>? HasFocusChanging;
  598. /// <summary>
  599. /// Called when this view should stop being focused.
  600. /// </summary>
  601. /// <param name="newFocusedView">
  602. /// The new focused view. If <see langword="null"/> it is not known which view will be
  603. /// focused.
  604. /// </param>
  605. /// <param name="traversingDown">
  606. /// Set to true to traverse down the focus
  607. /// chain only. If false, the method will attempt to AdvanceFocus on the superview or restorefocus on
  608. /// Application.Navigation.GetFocused().
  609. /// </param>
  610. /// <exception cref="InvalidOperationException"></exception>
  611. private void SetHasFocusFalse (View? newFocusedView, bool traversingDown = false)
  612. {
  613. // Pre-conditions
  614. if (!_hasFocus)
  615. {
  616. throw new InvalidOperationException ("SetHasFocusFalse should not be called if the view does not have focus.");
  617. }
  618. if (newFocusedView is { HasFocus: false })
  619. {
  620. throw new InvalidOperationException ("SetHasFocusFalse new focused view does not have focus.");
  621. }
  622. var thisAsAdornment = this as Adornment;
  623. View? superViewOrParent = thisAsAdornment?.Parent ?? SuperView;
  624. // If newFocusedVew is null, we need to find the view that should get focus, and SetFocus on it.
  625. if (!traversingDown && newFocusedView is null)
  626. {
  627. // Restore focus?
  628. if (superViewOrParent?._previouslyFocused is { CanFocus: true })
  629. {
  630. // TODO: Why don't we call RestoreFocus here?
  631. if (superViewOrParent._previouslyFocused != this && superViewOrParent._previouslyFocused.SetFocus ())
  632. {
  633. // The above will cause SetHasFocusFalse, so we can return
  634. Debug.Assert (!_hasFocus);
  635. return;
  636. }
  637. }
  638. // AdvanceFocus?
  639. if (superViewOrParent is { CanFocus: true })
  640. {
  641. if (superViewOrParent.AdvanceFocus (NavigationDirection.Forward, TabStop))
  642. {
  643. // The above might have SetHasFocusFalse, so we can return
  644. if (!_hasFocus)
  645. {
  646. return;
  647. }
  648. }
  649. if (superViewOrParent is { HasFocus: true, CanFocus: true })
  650. {
  651. newFocusedView = superViewOrParent;
  652. }
  653. }
  654. // Application.Navigation.GetFocused?
  655. View? applicationFocused = Application.Navigation?.GetFocused ();
  656. if (newFocusedView is null && applicationFocused != this && applicationFocused is { CanFocus: true })
  657. {
  658. // Temporarily ensure this view can't get focus
  659. bool prevCanFocus = _canFocus;
  660. _canFocus = false;
  661. bool restoredFocus = applicationFocused!.RestoreFocus ();
  662. _canFocus = prevCanFocus;
  663. if (restoredFocus)
  664. {
  665. // The above caused SetHasFocusFalse, so we can return
  666. Debug.Assert (!_hasFocus);
  667. return;
  668. }
  669. }
  670. // Application.Top?
  671. if (newFocusedView is null && Application.Top is { CanFocus: true, HasFocus: false })
  672. {
  673. // Temporarily ensure this view can't get focus
  674. bool prevCanFocus = _canFocus;
  675. _canFocus = false;
  676. bool restoredFocus = Application.Top.RestoreFocus ();
  677. _canFocus = prevCanFocus;
  678. if (Application.Top is { CanFocus: true, HasFocus: true })
  679. {
  680. newFocusedView = Application.Top;
  681. }
  682. else if (restoredFocus)
  683. {
  684. // The above caused SetHasFocusFalse, so we can return
  685. Debug.Assert (!_hasFocus);
  686. return;
  687. }
  688. }
  689. // No other focusable view to be found. Just "leave" us...
  690. }
  691. Debug.Assert (_hasFocus);
  692. // Before we can leave focus, we need to make sure that all views down the subview-hierarchy have left focus.
  693. View? mostFocused = MostFocused;
  694. if (mostFocused is { } && (newFocusedView is null || mostFocused != newFocusedView))
  695. {
  696. // Start at the bottom and work our way up to us
  697. View? bottom = mostFocused;
  698. while (bottom is { } && bottom != this)
  699. {
  700. if (bottom.HasFocus)
  701. {
  702. bottom.SetHasFocusFalse (newFocusedView, true);
  703. Debug.Assert (_hasFocus);
  704. }
  705. bottom = bottom.SuperView;
  706. }
  707. Debug.Assert (_hasFocus);
  708. }
  709. if (superViewOrParent is { })
  710. {
  711. superViewOrParent._previouslyFocused = this;
  712. }
  713. bool previousValue = HasFocus;
  714. Debug.Assert (_hasFocus);
  715. // Note, can't be cancelled.
  716. RaiseFocusChanging (HasFocus, !HasFocus, this, newFocusedView);
  717. // Even though the change can't be cancelled, some listener may have changed the focus to another view.
  718. if (!_hasFocus)
  719. {
  720. // Notify caused HasFocus to change to false.
  721. return;
  722. }
  723. // Get whatever peer has focus, if any so we can update our superview's _previouslyMostFocused
  724. View? focusedPeer = superViewOrParent?.Focused;
  725. // Set HasFocus false
  726. _hasFocus = false;
  727. RaiseFocusChanged (HasFocus, this, newFocusedView);
  728. if (_hasFocus)
  729. {
  730. // Notify caused HasFocus to change to true.
  731. return;
  732. }
  733. // Post-conditions - prove correctness
  734. if (HasFocus == previousValue)
  735. {
  736. throw new InvalidOperationException ("SetHasFocusFalse and the HasFocus value did not change.");
  737. }
  738. SetNeedsDraw ();
  739. }
  740. private void RaiseFocusChanged (bool newHasFocus, View? previousFocusedView, View? focusedView)
  741. {
  742. // If we are the most focused view, we need to set the focused view in Application.Navigation
  743. if (newHasFocus && focusedView?.Focused is null)
  744. {
  745. Application.Navigation?.SetFocused (focusedView);
  746. }
  747. // Call the virtual method
  748. OnHasFocusChanged (newHasFocus, previousFocusedView, focusedView);
  749. // Raise the event
  750. var args = new HasFocusEventArgs (newHasFocus, newHasFocus, previousFocusedView, focusedView);
  751. HasFocusChanged?.Invoke (this, args);
  752. if (newHasFocus || focusedView is null)
  753. {
  754. SuperView?.RaiseFocusedChanged (previousFocusedView, focusedView);
  755. }
  756. }
  757. /// <summary>
  758. /// Invoked after <see cref="HasFocus"/> has changed. This method is called before the <see cref="HasFocusChanged"/>
  759. /// event is raised.
  760. /// </summary>
  761. /// <remarks>
  762. /// <para>
  763. /// This event cannot be cancelled.
  764. /// </para>
  765. /// </remarks>
  766. /// <param name="newHasFocus">The new value of <see cref="View.HasFocus"/>.</param>
  767. /// <param name="previousFocusedView"></param>
  768. /// <param name="focusedView">The view that is now focused. May be <see langword="null"/></param>
  769. protected virtual void OnHasFocusChanged (bool newHasFocus, View? previousFocusedView, View? focusedView) { }
  770. /// <summary>Raised after <see cref="HasFocus"/> has changed.</summary>
  771. /// <remarks>
  772. /// <para>
  773. /// This event cannot be cancelled.
  774. /// </para>
  775. /// </remarks>
  776. public event EventHandler<HasFocusEventArgs>? HasFocusChanged;
  777. #endregion HasFocus
  778. #region Tab/Focus Handling
  779. /// <summary>
  780. /// Gets the subviews and Adornments of this view that are scoped to the specified behavior and direction. If behavior
  781. /// is null, all focusable subviews and
  782. /// Adornments are returned.
  783. /// </summary>
  784. /// <param name="direction"></param>
  785. /// <param name="behavior"></param>
  786. /// <returns></returns>
  787. internal View [] GetFocusChain (NavigationDirection direction, TabBehavior? behavior)
  788. {
  789. IEnumerable<View>? filteredSubViews;
  790. if (behavior.HasValue)
  791. {
  792. filteredSubViews = InternalSubViews?.Where (v => v.TabStop == behavior && v is { CanFocus: true, Visible: true, Enabled: true });
  793. }
  794. else
  795. {
  796. filteredSubViews = InternalSubViews?.Where (v => v is { CanFocus: true, Visible: true, Enabled: true });
  797. }
  798. // How about in Adornments?
  799. if (Padding is { CanFocus: true, Visible: true, Enabled: true } && Padding.TabStop == behavior)
  800. {
  801. filteredSubViews = filteredSubViews?.Append (Padding);
  802. }
  803. if (Border is { CanFocus: true, Visible: true, Enabled: true } && Border.TabStop == behavior)
  804. {
  805. filteredSubViews = filteredSubViews?.Append (Border);
  806. }
  807. if (Margin is { CanFocus: true, Visible: true, Enabled: true } && Margin.TabStop == behavior)
  808. {
  809. filteredSubViews = filteredSubViews?.Append (Margin);
  810. }
  811. if (direction == NavigationDirection.Backward)
  812. {
  813. filteredSubViews = filteredSubViews?.Reverse ();
  814. }
  815. return filteredSubViews?.ToArray () ?? Array.Empty<View> ();
  816. }
  817. private TabBehavior? _tabStop;
  818. /// <summary>
  819. /// Gets or sets the behavior of <see cref="AdvanceFocus"/> for keyboard navigation.
  820. /// </summary>
  821. /// <remarks>
  822. /// <remarks>
  823. /// <para>
  824. /// See the View Navigation Deep Dive for more information:
  825. /// <see href="https://gui-cs.github.io/Terminal.GuiV2Docs/docs/navigation.html"/>
  826. /// </para>
  827. /// </remarks>
  828. /// ///
  829. /// <para>
  830. /// If <see langword="null"/> the tab stop has not been set and setting <see cref="CanFocus"/> to true will set it
  831. /// to
  832. /// <see cref="TabBehavior.TabStop"/>.
  833. /// </para>
  834. /// <para>
  835. /// TabStop is independent of <see cref="CanFocus"/>. If <see cref="CanFocus"/> is <see langword="false"/>, the
  836. /// view will not gain
  837. /// focus even if this property is set and vice versa.
  838. /// </para>
  839. /// <para>
  840. /// The default <see cref="TabBehavior.TabStop"/> keys are <see cref="Application.NextTabKey"/> (<c>Key.Tab</c>)
  841. /// and <see cref="Application.PrevTabKey"/> (<c>Key>Tab.WithShift</c>).
  842. /// </para>
  843. /// <para>
  844. /// The default <see cref="TabBehavior.TabGroup"/> keys are <see cref="Application.NextTabGroupKey"/> (
  845. /// <c>Key.F6</c>) and <see cref="Application.PrevTabGroupKey"/> (<c>Key>Key.F6.WithShift</c>).
  846. /// </para>
  847. /// </remarks>
  848. public TabBehavior? TabStop
  849. {
  850. get => _tabStop;
  851. set
  852. {
  853. if (_tabStop is { } && _tabStop == value)
  854. {
  855. return;
  856. }
  857. _tabStop = value;
  858. }
  859. }
  860. #endregion Tab/Focus Handling
  861. }