View.Navigation.cs 38 KB

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