View.Navigation.cs 34 KB

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