View.Navigation.cs 35 KB

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