View.Navigation.cs 36 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027
  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.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. // TODO: CWP: FocusChanging should use an event arg type derived from ResultEventArgs<bool> so that its more obvious
  540. // TODO: the result can be changed.
  541. private bool RaiseFocusChanging (bool currentHasFocus, bool newHasFocus, View? currentFocused, View? newFocused)
  542. {
  543. Debug.Assert (currentFocused is null || currentFocused is { HasFocus: true });
  544. Debug.Assert (newFocused is null || newFocused is { CanFocus: true });
  545. // Call the virtual method
  546. if (OnHasFocusChanging (currentHasFocus, newHasFocus, currentFocused, newFocused))
  547. {
  548. // The event was cancelled
  549. return true;
  550. }
  551. var args = new HasFocusEventArgs (currentHasFocus, newHasFocus, currentFocused, newFocused);
  552. HasFocusChanging?.Invoke (this, args);
  553. if (args.Cancel)
  554. {
  555. // The event was cancelled
  556. return true;
  557. }
  558. View? appFocused = Application.Navigation?.GetFocused ();
  559. if (appFocused == currentFocused)
  560. {
  561. if (newFocused is { HasFocus: true })
  562. {
  563. Application.Navigation?.SetFocused (newFocused);
  564. }
  565. else
  566. {
  567. Application.Navigation?.SetFocused (null);
  568. }
  569. }
  570. return false;
  571. }
  572. /// <summary>
  573. /// Invoked when <see cref="View.HasFocus"/> is about to change. This method is called before the
  574. /// <see cref="HasFocusChanging"/> event is raised.
  575. /// </summary>
  576. /// <remarks>
  577. /// <para>
  578. /// Use <see cref="OnHasFocusChanged"/> to be notified after the focus has changed.
  579. /// </para>
  580. /// </remarks>
  581. /// <param name="currentHasFocus">The current value of <see cref="View.HasFocus"/>.</param>
  582. /// <param name="newHasFocus">The value <see cref="View.HasFocus"/> will have if the focus change happens.</param>
  583. /// <param name="currentFocused">The view that is currently Focused. May be <see langword="null"/>.</param>
  584. /// <param name="newFocused">The view that will be focused. May be <see langword="null"/>.</param>
  585. /// <returns>
  586. /// <see langword="true"/>, if the change to <see cref="View.HasFocus"/> is to be cancelled, <see langword="false"/>
  587. /// otherwise.
  588. /// </returns>
  589. protected virtual bool OnHasFocusChanging (bool currentHasFocus, bool newHasFocus, View? currentFocused, View? newFocused) { return false; }
  590. /// <summary>
  591. /// Raised when <see cref="View.HasFocus"/> is about to change.
  592. /// </summary>
  593. /// <remarks>
  594. /// <para>
  595. /// Cancel the event to prevent the focus from changing.
  596. /// </para>
  597. /// <para>
  598. /// Use <see cref="HasFocusChanged"/> to be notified after the focus has changed.
  599. /// </para>
  600. /// </remarks>
  601. public event EventHandler<HasFocusEventArgs>? HasFocusChanging;
  602. /// <summary>
  603. /// Called when this view should stop being focused.
  604. /// </summary>
  605. /// <param name="newFocusedView">
  606. /// The new focused view. If <see langword="null"/> it is not known which view will be
  607. /// focused.
  608. /// </param>
  609. /// <param name="traversingDown">
  610. /// Set to true to traverse down the focus
  611. /// chain only. If false, the method will attempt to AdvanceFocus on the superview or restorefocus on
  612. /// Application.Navigation.GetFocused().
  613. /// </param>
  614. /// <exception cref="InvalidOperationException"></exception>
  615. private void SetHasFocusFalse (View? newFocusedView, bool traversingDown = false)
  616. {
  617. // Pre-conditions
  618. if (!_hasFocus)
  619. {
  620. throw new InvalidOperationException ("SetHasFocusFalse should not be called if the view does not have focus.");
  621. }
  622. if (newFocusedView is { HasFocus: false })
  623. {
  624. throw new InvalidOperationException ("SetHasFocusFalse new focused view does not have focus.");
  625. }
  626. var thisAsAdornment = this as Adornment;
  627. View? superViewOrParent = thisAsAdornment?.Parent ?? SuperView;
  628. // If newFocusedVew is null, we need to find the view that should get focus, and SetFocus on it.
  629. if (!traversingDown && newFocusedView is null)
  630. {
  631. // Restore focus?
  632. if (superViewOrParent?._previouslyFocused is { CanFocus: true })
  633. {
  634. // TODO: Why don't we call RestoreFocus here?
  635. if (superViewOrParent._previouslyFocused != this && superViewOrParent._previouslyFocused.SetFocus ())
  636. {
  637. // The above will cause SetHasFocusFalse, so we can return
  638. Debug.Assert (!_hasFocus);
  639. return;
  640. }
  641. }
  642. // AdvanceFocus?
  643. if (superViewOrParent is { CanFocus: true })
  644. {
  645. if (superViewOrParent.AdvanceFocus (NavigationDirection.Forward, TabStop))
  646. {
  647. // The above might have SetHasFocusFalse, so we can return
  648. if (!_hasFocus)
  649. {
  650. return;
  651. }
  652. }
  653. if (superViewOrParent is { HasFocus: true, CanFocus: true })
  654. {
  655. newFocusedView = superViewOrParent;
  656. }
  657. }
  658. // Application.Navigation.GetFocused?
  659. View? applicationFocused = Application.Navigation?.GetFocused ();
  660. if (newFocusedView is null && applicationFocused != this && applicationFocused is { CanFocus: true })
  661. {
  662. // Temporarily ensure this view can't get focus
  663. bool prevCanFocus = _canFocus;
  664. _canFocus = false;
  665. bool restoredFocus = applicationFocused!.RestoreFocus ();
  666. _canFocus = prevCanFocus;
  667. if (restoredFocus)
  668. {
  669. // The above caused SetHasFocusFalse, so we can return
  670. Debug.Assert (!_hasFocus);
  671. return;
  672. }
  673. }
  674. // Application.Top?
  675. if (newFocusedView is null && Application.Top is { CanFocus: true, HasFocus: false })
  676. {
  677. // Temporarily ensure this view can't get focus
  678. bool prevCanFocus = _canFocus;
  679. _canFocus = false;
  680. bool restoredFocus = Application.Top.RestoreFocus ();
  681. _canFocus = prevCanFocus;
  682. if (Application.Top is { CanFocus: true, HasFocus: true })
  683. {
  684. newFocusedView = Application.Top;
  685. }
  686. else if (restoredFocus)
  687. {
  688. // The above caused SetHasFocusFalse, so we can return
  689. Debug.Assert (!_hasFocus);
  690. return;
  691. }
  692. }
  693. // No other focusable view to be found. Just "leave" us...
  694. }
  695. Debug.Assert (_hasFocus);
  696. // Before we can leave focus, we need to make sure that all views down the subview-hierarchy have left focus.
  697. View? mostFocused = MostFocused;
  698. if (mostFocused is { } && (newFocusedView is null || mostFocused != newFocusedView))
  699. {
  700. // Start at the bottom and work our way up to us
  701. View? bottom = mostFocused;
  702. while (bottom is { } && bottom != this)
  703. {
  704. if (bottom.HasFocus)
  705. {
  706. bottom.SetHasFocusFalse (newFocusedView, true);
  707. Debug.Assert (_hasFocus);
  708. }
  709. bottom = bottom.SuperView;
  710. }
  711. Debug.Assert (_hasFocus);
  712. }
  713. if (superViewOrParent is { })
  714. {
  715. superViewOrParent._previouslyFocused = this;
  716. }
  717. bool previousValue = HasFocus;
  718. Debug.Assert (_hasFocus);
  719. // Note, can't be cancelled.
  720. RaiseFocusChanging (HasFocus, !HasFocus, this, newFocusedView);
  721. // Even though the change can't be cancelled, some listener may have changed the focus to another view.
  722. if (!_hasFocus)
  723. {
  724. // Notify caused HasFocus to change to false.
  725. return;
  726. }
  727. // Get whatever peer has focus, if any so we can update our superview's _previouslyMostFocused
  728. View? focusedPeer = superViewOrParent?.Focused;
  729. // Set HasFocus false
  730. _hasFocus = false;
  731. RaiseFocusChanged (HasFocus, this, newFocusedView);
  732. if (_hasFocus)
  733. {
  734. // Notify caused HasFocus to change to true.
  735. return;
  736. }
  737. // Post-conditions - prove correctness
  738. if (HasFocus == previousValue)
  739. {
  740. throw new InvalidOperationException ("SetHasFocusFalse and the HasFocus value did not change.");
  741. }
  742. SetNeedsDraw ();
  743. }
  744. // TODO: CWP: FocusChanged should not be using event args derived from CancelEventArgs, as it is not cancellable.
  745. private void RaiseFocusChanged (bool newHasFocus, View? previousFocusedView, View? focusedView)
  746. {
  747. // If we are the most focused view, we need to set the focused view in Application.Navigation
  748. if (newHasFocus && focusedView?.Focused is null)
  749. {
  750. Application.Navigation?.SetFocused (focusedView);
  751. }
  752. // Call the virtual method
  753. OnHasFocusChanged (newHasFocus, previousFocusedView, focusedView);
  754. // Raise the event
  755. var args = new HasFocusEventArgs (newHasFocus, newHasFocus, previousFocusedView, focusedView);
  756. HasFocusChanged?.Invoke (this, args);
  757. if (newHasFocus || focusedView is null)
  758. {
  759. SuperView?.RaiseFocusedChanged (previousFocusedView, focusedView);
  760. }
  761. }
  762. /// <summary>
  763. /// Invoked after <see cref="HasFocus"/> has changed. This method is called before the <see cref="HasFocusChanged"/>
  764. /// event is raised.
  765. /// </summary>
  766. /// <remarks>
  767. /// <para>
  768. /// This event cannot be cancelled.
  769. /// </para>
  770. /// </remarks>
  771. /// <param name="newHasFocus">The new value of <see cref="View.HasFocus"/>.</param>
  772. /// <param name="previousFocusedView"></param>
  773. /// <param name="focusedView">The view that is now focused. May be <see langword="null"/></param>
  774. protected virtual void OnHasFocusChanged (bool newHasFocus, View? previousFocusedView, View? focusedView) { }
  775. /// <summary>Raised after <see cref="HasFocus"/> has changed.</summary>
  776. /// <remarks>
  777. /// <para>
  778. /// This event cannot be cancelled.
  779. /// </para>
  780. /// </remarks>
  781. public event EventHandler<HasFocusEventArgs>? HasFocusChanged;
  782. #endregion HasFocus
  783. #region Tab/Focus Handling
  784. /// <summary>
  785. /// Gets the subviews and Adornments of this view that are scoped to the specified behavior and direction. If behavior
  786. /// is null, all focusable subviews and
  787. /// Adornments are returned.
  788. /// </summary>
  789. /// <param name="direction"></param>
  790. /// <param name="behavior"></param>
  791. /// <returns></returns>
  792. internal View [] GetFocusChain (NavigationDirection direction, TabBehavior? behavior)
  793. {
  794. IEnumerable<View>? filteredSubViews;
  795. if (behavior.HasValue)
  796. {
  797. filteredSubViews = InternalSubViews?.Where (v => v.TabStop == behavior && v is { CanFocus: true, Visible: true, Enabled: true });
  798. }
  799. else
  800. {
  801. filteredSubViews = InternalSubViews?.Where (v => v is { CanFocus: true, Visible: true, Enabled: true });
  802. }
  803. // How about in Adornments?
  804. if (Padding is { CanFocus: true, Visible: true, Enabled: true } && Padding.TabStop == behavior)
  805. {
  806. filteredSubViews = filteredSubViews?.Append (Padding);
  807. }
  808. if (Border is { CanFocus: true, Visible: true, Enabled: true } && Border.TabStop == behavior)
  809. {
  810. filteredSubViews = filteredSubViews?.Append (Border);
  811. }
  812. if (Margin is { CanFocus: true, Visible: true, Enabled: true } && Margin.TabStop == behavior)
  813. {
  814. filteredSubViews = filteredSubViews?.Append (Margin);
  815. }
  816. if (direction == NavigationDirection.Backward)
  817. {
  818. filteredSubViews = filteredSubViews?.Reverse ();
  819. }
  820. return filteredSubViews?.ToArray () ?? Array.Empty<View> ();
  821. }
  822. private TabBehavior? _tabStop;
  823. /// <summary>
  824. /// Gets or sets the behavior of <see cref="AdvanceFocus"/> for keyboard navigation.
  825. /// </summary>
  826. /// <remarks>
  827. /// <remarks>
  828. /// <para>
  829. /// See the View Navigation Deep Dive for more information:
  830. /// <see href="https://gui-cs.github.io/Terminal.GuiV2Docs/docs/navigation.html"/>
  831. /// </para>
  832. /// </remarks>
  833. /// ///
  834. /// <para>
  835. /// If <see langword="null"/> the tab stop has not been set and setting <see cref="CanFocus"/> to true will set it
  836. /// to
  837. /// <see cref="TabBehavior.TabStop"/>.
  838. /// </para>
  839. /// <para>
  840. /// TabStop is independent of <see cref="CanFocus"/>. If <see cref="CanFocus"/> is <see langword="false"/>, the
  841. /// view will not gain
  842. /// focus even if this property is set and vice versa.
  843. /// </para>
  844. /// <para>
  845. /// The default <see cref="TabBehavior.TabStop"/> keys are <see cref="Application.NextTabKey"/> (<c>Key.Tab</c>)
  846. /// and <see cref="Application.PrevTabKey"/> (<c>Key>Tab.WithShift</c>).
  847. /// </para>
  848. /// <para>
  849. /// The default <see cref="TabBehavior.TabGroup"/> keys are <see cref="Application.NextTabGroupKey"/> (
  850. /// <c>Key.F6</c>) and <see cref="Application.PrevTabGroupKey"/> (<c>Key>Key.F6.WithShift</c>).
  851. /// </para>
  852. /// </remarks>
  853. public TabBehavior? TabStop
  854. {
  855. get => _tabStop;
  856. set
  857. {
  858. if (_tabStop is { } && _tabStop == value)
  859. {
  860. return;
  861. }
  862. _tabStop = value;
  863. }
  864. }
  865. #endregion Tab/Focus Handling
  866. }