View.Navigation.cs 38 KB

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