View.Navigation.cs 33 KB

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