View.Navigation.cs 36 KB

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