View.Navigation.cs 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960
  1. using System.Diagnostics;
  2. using static Terminal.Gui.FakeDriver;
  3. namespace Terminal.Gui;
  4. public partial class View // Focus and cross-view navigation management (TabStop, TabIndex, etc...)
  5. {
  6. #region HasFocus
  7. // Backs `HasFocus` and is the ultimate source of truth whether a View has focus or not.
  8. private bool _hasFocus;
  9. /// <summary>
  10. /// Gets or sets whether this view has focus.
  11. /// </summary>
  12. /// <remarks>
  13. /// <para>
  14. /// Only Views that are visible, enabled, and have <see cref="CanFocus"/> set to <see langword="true"/> are focusable. If
  15. /// these conditions are not met when this property is set to <see langword="true"/> <see cref="HasFocus"/> will not change.
  16. /// </para>
  17. /// <para>
  18. /// Setting this property causes the <see cref="OnEnter"/> and <see cref="OnLeave"/> virtual methods (and <see cref="Enter"/> and
  19. /// <see cref="Leave"/> events to be raised). If the event is cancelled, <see cref="HasFocus"/> will not be changed.
  20. /// </para>
  21. /// <para>
  22. /// Setting this property to <see langword="true"/> will recursively set <see cref="HasFocus"/> to
  23. /// <see langword="true"/> for all SuperViews up the hierarchy.
  24. /// </para>
  25. /// <para>
  26. /// Setting this property to <see langword="true"/> will cause the subview furthest down the hierarchy that is
  27. /// focusable to also gain focus (as long as <see cref="TabStop"/>
  28. /// </para>
  29. /// <para>
  30. /// Setting this property to <see langword="false"/> will cause <see cref="ApplicationNavigation.MoveNextView"/> to set
  31. /// the focus on the next view to be focused.
  32. /// </para>
  33. /// </remarks>
  34. public bool HasFocus
  35. {
  36. set
  37. {
  38. if (HasFocus != value)
  39. {
  40. if (value)
  41. {
  42. if (EnterFocus (Application.Navigation?.GetFocused ()))
  43. {
  44. // The change happened
  45. // HasFocus is now true
  46. }
  47. }
  48. else
  49. {
  50. LeaveFocus (null);
  51. }
  52. }
  53. }
  54. get => _hasFocus;
  55. }
  56. /// <summary>
  57. /// Causes this view to be focused. Calling this method has the same effect as setting <see cref="HasFocus"/> to
  58. /// <see langword="true"/> but with the added benefit of returning a value indicating whether the focus was set.
  59. /// </summary>
  60. public bool SetFocus ()
  61. {
  62. return EnterFocus (Application.Navigation?.GetFocused ());
  63. }
  64. /// <summary>
  65. /// Called when view is entering focus. This method is called by <see cref="SetHasFocus"/> and other methods that
  66. /// set or remove focus from a view.
  67. /// </summary>
  68. /// <param name="leavingView">The previously focused view. If <see langword="null"/> there is no previously focused view.</param>
  69. /// <param name="traversingUp"></param>
  70. /// <returns><see langword="true"/> if <see cref="HasFocus"/> was changed to <see langword="true"/>.</returns>
  71. /// <exception cref="InvalidOperationException"></exception>
  72. private bool EnterFocus ([CanBeNull] View leavingView, bool traversingUp = false)
  73. {
  74. Debug.Assert (ApplicationNavigation.IsInHierarchy (SuperView, this));
  75. // Pre-conditions
  76. if (_hasFocus)
  77. {
  78. throw new InvalidOperationException ($"EnterFocus should not be called if the view already has focus.");
  79. }
  80. if (CanFocus && SuperView?.CanFocus == false)
  81. {
  82. throw new InvalidOperationException ($"It is not possible to EnterFocus if the View's SuperView has CanFocus = false.");
  83. }
  84. if (!CanBeVisible (this) || !Enabled)
  85. {
  86. return false;
  87. }
  88. if (!CanFocus)
  89. {
  90. return false;
  91. }
  92. bool previousValue = HasFocus;
  93. if (!traversingUp)
  94. {
  95. // Call the virtual method
  96. if (OnEnter (leavingView))
  97. {
  98. // The event was cancelled
  99. return false;
  100. }
  101. var args = new FocusEventArgs (leavingView, this);
  102. Enter?.Invoke (this, args);
  103. if (args.Cancel)
  104. {
  105. // The event was cancelled
  106. return false;
  107. }
  108. // If we're here, we can be focused. But we may have subviews.
  109. // Restore focus to the previously most focused subview in the subview-hierarchy
  110. if (RestoreFocus (TabStop))
  111. {
  112. // A subview was focused. We're done because the subview has focus and it recursed up the superview hierarchy.
  113. return true;
  114. }
  115. // Couldn't restore focus, so use Advance to navigate to the next focusable subview
  116. if (AdvanceFocus (NavigationDirection.Forward, TabStop))
  117. {
  118. // A subview was focused. We're done because the subview has focus and it recursed up the superview hierarchy.
  119. return true;
  120. }
  121. }
  122. // If we're here, we're the most-focusable view in the application OR we're traversing up the superview hierarchy.
  123. // If we previously had a subview with focus (`Focused = subview`), we need to make sure that all subviews down the `subview`-hierarchy LeaveFocus.
  124. if (Focused is { })
  125. {
  126. // LeaveFocus will recurse down the subview hierarchy and will also set PreviouslyMostFocused
  127. Focused.LeaveFocus (this);
  128. Focused = null;
  129. }
  130. // We need to ensure all superviews up the superview hierarchy have focus.
  131. // Any of them may cancel gaining focus. In which case we need to back out.
  132. if (SuperView is { HasFocus: false } sv)
  133. {
  134. // Tell EnterFocus that we're traversing up the superview hierarchy
  135. if (!sv.EnterFocus (leavingView, traversingUp))
  136. {
  137. // The change was cancelled
  138. return false;
  139. }
  140. }
  141. // If we're here, we're the most-focusable view in the application and all superviews up the superview hierarchy have focus.
  142. // By setting _hasFocus to true we definitively change HasFocus for this view.
  143. _hasFocus = true;
  144. // We're the most focused view in the application, we need to set the focused view to this view.
  145. Application.Navigation?.SetFocused (this);
  146. // Post-conditions - prove correctness
  147. if (HasFocus == previousValue)
  148. {
  149. throw new InvalidOperationException ($"EnterFocus was not cancelled and the HasFocus value did not change.");
  150. }
  151. SetNeedsDisplay ();
  152. return true;
  153. }
  154. /// <summary>Virtual method invoked when this view is gaining focus (entering).</summary>
  155. /// <param name="leavingView">The view that is leaving focus.</param>
  156. /// <returns> <see langword="true"/>, if the event is to be cancelled, <see langword="false"/> otherwise.</returns>
  157. protected virtual bool OnEnter ([CanBeNull] View leavingView)
  158. {
  159. return false;
  160. }
  161. /// <summary>Raised when the view is gaining (entering) focus. Can be cancelled.</summary>
  162. /// <remarks>
  163. /// Raised by <see cref="EnterFocus"/>.
  164. /// </remarks>
  165. public event EventHandler<FocusEventArgs> Enter;
  166. /// <summary>
  167. /// Called when view is losing focus.
  168. /// </summary>
  169. /// <param name="enteringView">The previously focused view. If <see langword="null"/> there is no previously focused view.</param>
  170. /// <returns><see langword="true"/> if <see cref="HasFocus"/> was changed.</returns>
  171. /// <exception cref="InvalidOperationException"></exception>
  172. private void LeaveFocus ([CanBeNull] View enteringView)
  173. {
  174. // Pre-conditions
  175. if (_hasFocus)
  176. {
  177. throw new InvalidOperationException ($"LeaveFocus should not be called if the view does not have focus.");
  178. }
  179. // If enteringView is null, we need to find the view that should get focus, and SetFocus on it.
  180. if (enteringView is null)
  181. {
  182. if (SuperView?.PreviouslyMostFocused != this)
  183. {
  184. SuperView?.PreviouslyMostFocused?.SetFocus ();
  185. // The above will cause LeaveFocus, so we can return
  186. return;
  187. }
  188. else
  189. {
  190. // Temporarily ensure this view can't get focus
  191. bool prevCanFocus = _canFocus;
  192. _canFocus = false;
  193. ApplicationNavigation.MoveNextView ();
  194. _canFocus = prevCanFocus;
  195. // The above will cause LeaveFocus, so we can return
  196. return;
  197. }
  198. }
  199. // Before we can leave focus, we need to make sure that all views down the subview-hierarchy have left focus.
  200. if (Application.Navigation?.GetFocused () != this)
  201. {
  202. // Save the most focused view in the subview-hierarchy
  203. View originalBottom = Application.Navigation?.GetFocused ();
  204. // Start at the bottom and work our way up to us
  205. View bottom = originalBottom;
  206. while (bottom is { } && bottom != this)
  207. {
  208. if (bottom.HasFocus)
  209. {
  210. bottom.LeaveFocus (enteringView);
  211. return ;
  212. }
  213. bottom = bottom.SuperView;
  214. }
  215. PreviouslyMostFocused = originalBottom;
  216. }
  217. bool previousValue = HasFocus;
  218. // Call the virtual method - NOTE: Leave cannot be cancelled
  219. OnLeave (enteringView);
  220. var args = new FocusEventArgs (enteringView, this);
  221. Leave?.Invoke (this, args);
  222. Focused = null;
  223. _hasFocus = false;
  224. if (Application.Navigation?.GetFocused () != this)
  225. {
  226. PreviouslyMostFocused = null;
  227. if (SuperView is { })
  228. {
  229. SuperView.Focused = null;
  230. SuperView.PreviouslyMostFocused = this;
  231. }
  232. }
  233. // Post-conditions - prove correctness
  234. if (HasFocus == previousValue)
  235. {
  236. throw new InvalidOperationException ($"LeaveFocus and the HasFocus value did not change.");
  237. }
  238. SetNeedsDisplay ();
  239. }
  240. /// <summary>
  241. /// Caches the most focused subview when this view is losing focus. This is used by <see cref="RestoreFocus"/>.
  242. /// </summary>
  243. [CanBeNull]
  244. internal View PreviouslyMostFocused { get; set; }
  245. /// <summary>Virtual method invoked when this view is losing focus (leaving).</summary>
  246. /// <param name="enteringView">The view that is gaining focus.</param>
  247. protected virtual void OnLeave ([CanBeNull] View enteringView)
  248. {
  249. return;
  250. }
  251. /// <summary>Raised when the view is gaining (entering) focus. Can NOT be cancelled.</summary>
  252. /// <remarks>
  253. /// Raised by <see cref="LeaveFocus"/>.
  254. /// </remarks>
  255. public event EventHandler<FocusEventArgs> Leave;
  256. #endregion HasFocus
  257. /// <summary>
  258. /// Advances the focus to the next or previous view in <see cref="View.TabIndexes"/>, based on
  259. /// <paramref name="direction"/>.
  260. /// itself.
  261. /// </summary>
  262. /// <remarks>
  263. /// <para>
  264. /// If there is no next/previous view, the focus is set to the view itself.
  265. /// </para>
  266. /// </remarks>
  267. /// <param name="direction"></param>
  268. /// <param name="behavior"></param>
  269. /// <returns>
  270. /// <see langword="true"/> if focus was changed to another subview (or stayed on this one), <see langword="false"/>
  271. /// otherwise.
  272. /// </returns>
  273. public bool AdvanceFocus (NavigationDirection direction, TabBehavior? behavior)
  274. {
  275. if (!CanBeVisible (this)) // TODO: is this check needed?
  276. {
  277. return false;
  278. }
  279. if (TabIndexes is null || TabIndexes.Count == 0)
  280. {
  281. return false;
  282. }
  283. if (Focused is null)
  284. {
  285. FocusDeepest (behavior, direction);
  286. return Focused is { };
  287. }
  288. if (Focused is { })
  289. {
  290. if (Focused.AdvanceFocus (direction, behavior))
  291. {
  292. // TODO: Temporary hack to make Application.Navigation.FocusChanged work
  293. if (Focused.Focused is null)
  294. {
  295. Application.Navigation?.SetFocused (Focused);
  296. }
  297. return true;
  298. }
  299. }
  300. var index = GetScopedTabIndexes (behavior, direction);
  301. if (index.Length == 0)
  302. {
  303. return false;
  304. }
  305. var focusedIndex = index.IndexOf (Focused);
  306. int next = 0;
  307. if (focusedIndex < index.Length - 1)
  308. {
  309. next = focusedIndex + 1;
  310. }
  311. else
  312. {
  313. if (behavior == TabBehavior.TabGroup && behavior == TabStop && SuperView?.TabStop == TabBehavior.TabGroup)
  314. {
  315. // Go down the subview-hierarchy and leave
  316. // BUGBUG: This doesn't seem right
  317. Focused.HasFocus = false;
  318. // TODO: Should we check the return value of SetHasFocus?
  319. return false;
  320. }
  321. }
  322. View view = index [next];
  323. if (view.HasFocus)
  324. {
  325. return true;
  326. }
  327. // The subview does not have focus, but at least one other that can. Can this one be focused?
  328. if (view.CanFocus && view.Visible && view.Enabled)
  329. {
  330. // Make Focused Leave
  331. // BUGBUG: This doesn't seem right
  332. Focused.HasFocus = false;
  333. view.FocusDeepest (TabBehavior.TabStop, direction);
  334. // TODO: Temporary hack to make Application.Navigation.FocusChanged work
  335. if (view.Focused is null)
  336. {
  337. Application.Navigation?.SetFocused (view);
  338. }
  339. return true;
  340. }
  341. if (Focused is { })
  342. {
  343. // Leave
  344. // BUGBUG: This doesn't seem right
  345. Focused.HasFocus = false;
  346. // Signal that nothing is focused, and callers should try a peer-subview
  347. Focused = null;
  348. }
  349. return false;
  350. }
  351. /// <summary>
  352. /// INTERNAL API to restore focus to the subview that had focus before this view lost focus.
  353. /// </summary>
  354. /// <returns>
  355. /// Returns true if focus was restored to a subview, false otherwise.
  356. /// </returns>
  357. internal bool RestoreFocus (TabBehavior? behavior)
  358. {
  359. if (Focused is null && _subviews?.Count > 0)
  360. {
  361. // TODO: Find the previous focused view and set focus to it
  362. if (PreviouslyMostFocused is { } && PreviouslyMostFocused.TabStop == behavior)
  363. {
  364. return PreviouslyMostFocused.SetFocus ();
  365. }
  366. return true;
  367. }
  368. return false;
  369. }
  370. ///// <summary>
  371. ///// Internal API that causes <paramref name="viewToEnterFocus"/> to enter focus.
  372. ///// <paramref name="viewToEnterFocus"/> must be a subview.
  373. ///// Recursively sets focus up the superview hierarchy.
  374. ///// </summary>
  375. ///// <param name="viewToEnterFocus"></param>
  376. ///// <returns><see langword="true"/> if <paramref name="viewToEnterFocus"/> got focus.</returns>
  377. //private bool SetFocus (View viewToEnterFocus)
  378. //{
  379. // if (viewToEnterFocus is null)
  380. // {
  381. // return false;
  382. // }
  383. // if (!viewToEnterFocus.CanFocus || !viewToEnterFocus.Visible || !viewToEnterFocus.Enabled)
  384. // {
  385. // return false;
  386. // }
  387. // // If viewToEnterFocus is already the focused view, don't do anything
  388. // if (Focused?._hasFocus == true && Focused == viewToEnterFocus)
  389. // {
  390. // return false;
  391. // }
  392. // // If a subview has focus and viewToEnterFocus is the focused view's superview OR viewToEnterFocus is this view,
  393. // // then make viewToEnterFocus.HasFocus = true and return
  394. // if ((Focused?._hasFocus == true && Focused?.SuperView == viewToEnterFocus) || viewToEnterFocus == this)
  395. // {
  396. // if (!viewToEnterFocus._hasFocus)
  397. // {
  398. // viewToEnterFocus._hasFocus = true;
  399. // }
  400. // // viewToEnterFocus is already focused
  401. // return true;
  402. // }
  403. // // Make sure that viewToEnterFocus is a subview of this view
  404. // View c;
  405. // for (c = viewToEnterFocus._superView; c != null; c = c._superView)
  406. // {
  407. // if (c == this)
  408. // {
  409. // break;
  410. // }
  411. // }
  412. // if (c is null)
  413. // {
  414. // throw new ArgumentException (@$"The specified view {viewToEnterFocus} is not part of the hierarchy of {this}.");
  415. // }
  416. // // If a subview has focus, make it leave focus. This will leave focus up the hierarchy.
  417. // Focused?.SetHasFocus (false, viewToEnterFocus);
  418. // // make viewToEnterFocus Focused and enter focus
  419. // View f = Focused;
  420. // Focused = viewToEnterFocus;
  421. // Focused?.SetHasFocus (true, f, true);
  422. // Focused?.FocusDeepest (null, NavigationDirection.Forward);
  423. // // Recursively set focus up the superview hierarchy
  424. // if (SuperView is { })
  425. // {
  426. // // BUGBUG: If focus is cancelled at any point, we should stop and restore focus to the previous focused view
  427. // SuperView.SetFocus (this);
  428. // }
  429. // else
  430. // {
  431. // // BUGBUG: this makes no sense in the new design
  432. // // If there is no SuperView, then this is a top-level view
  433. // SetFocus (this);
  434. // }
  435. // // TODO: Temporary hack to make Application.Navigation.FocusChanged work
  436. // if (HasFocus && Focused.Focused is null)
  437. // {
  438. // Application.Navigation?.SetFocused (Focused);
  439. // }
  440. // // TODO: This is a temporary hack to make overlapped non-Toplevels have a zorder. See also: View.OnDrawContent.
  441. // if (viewToEnterFocus is { } && (viewToEnterFocus.TabStop == TabBehavior.TabGroup && viewToEnterFocus.Arrangement.HasFlag (ViewArrangement.Overlapped)))
  442. // {
  443. // viewToEnterFocus.TabIndex = 0;
  444. // }
  445. // return true;
  446. //}
  447. #if AUTO_CANFOCUS
  448. // BUGBUG: This is a poor API design. Automatic behavior like this is non-obvious and should be avoided. Instead, callers to Add should be explicit about what they want.
  449. // Set to true in Add() to indicate that the view being added to a SuperView has CanFocus=true.
  450. // Makes it so CanFocus will update the SuperView's CanFocus property.
  451. internal bool _addingViewSoCanFocusAlsoUpdatesSuperView;
  452. // Used to cache CanFocus on subviews when CanFocus is set to false so that it can be restored when CanFocus is changed back to true
  453. private bool _oldCanFocus;
  454. #endif
  455. private bool _canFocus;
  456. /// <summary>Gets or sets a value indicating whether this <see cref="View"/> can be focused.</summary>
  457. /// <remarks>
  458. /// <para>
  459. /// <see cref="SuperView"/> must also have <see cref="CanFocus"/> set to <see langword="true"/>.
  460. /// </para>
  461. /// <para>
  462. /// When set to <see langword="false"/>, if an attempt is made to make this view focused, the focus will be set to
  463. /// the next focusable view.
  464. /// </para>
  465. /// <para>
  466. /// When set to <see langword="false"/>, the <see cref="TabIndex"/> will be set to -1.
  467. /// </para>
  468. /// <para>
  469. /// When set to <see langword="false"/>, the values of <see cref="CanFocus"/> and <see cref="TabIndex"/> for all
  470. /// subviews will be cached so that when <see cref="CanFocus"/> is set back to <see langword="true"/>, the subviews
  471. /// will be restored to their previous values.
  472. /// </para>
  473. /// <para>
  474. /// Changing this property to <see langword="true"/> will cause <see cref="TabStop"/> to be set to
  475. /// <see cref="TabBehavior.TabStop"/>" as a convenience. Changing this property to
  476. /// <see langword="false"/> will have no effect on <see cref="TabStop"/>.
  477. /// </para>
  478. /// </remarks>
  479. public bool CanFocus
  480. {
  481. get => _canFocus;
  482. set
  483. {
  484. #if AUTO_CANFOCUS
  485. if (!_addingViewSoCanFocusAlsoUpdatesSuperView && IsInitialized && SuperView?.CanFocus == false && value)
  486. {
  487. throw new InvalidOperationException ("Cannot set CanFocus to true if the SuperView CanFocus is false!");
  488. }
  489. #endif
  490. if (_canFocus == value)
  491. {
  492. return;
  493. }
  494. _canFocus = value;
  495. #if AUTO_CANFOCUS
  496. switch (_canFocus)
  497. {
  498. case false when _tabIndex > -1:
  499. // BUGBUG: This is a poor API design. Automatic behavior like this is non-obvious and should be avoided. Callers should adjust TabIndex explicitly.
  500. //TabIndex = -1;
  501. break;
  502. case true when SuperView?.CanFocus == false && _addingViewSoCanFocusAlsoUpdatesSuperView:
  503. SuperView.CanFocus = true;
  504. break;
  505. }
  506. #endif
  507. if (TabStop is null && _canFocus)
  508. {
  509. TabStop = TabBehavior.TabStop;
  510. }
  511. if (!_canFocus && SuperView?.Focused == this)
  512. {
  513. SuperView.Focused = null;
  514. }
  515. if (!_canFocus && HasFocus)
  516. {
  517. HasFocus = false;
  518. SuperView?.RestoreFocus (null);
  519. // If EnsureFocus () didn't set focus to a view, focus the next focusable view in the application
  520. if (SuperView is { Focused: null })
  521. {
  522. SuperView.AdvanceFocus (NavigationDirection.Forward, null);
  523. if (SuperView.Focused is null && Application.Current is { })
  524. {
  525. Application.Current.AdvanceFocus (NavigationDirection.Forward, null);
  526. }
  527. ApplicationOverlapped.BringOverlappedTopToFront ();
  528. }
  529. }
  530. if (_subviews is { } && IsInitialized)
  531. {
  532. #if AUTO_CANFOCUS
  533. // Change the CanFocus of all subviews to the same value as this view
  534. // if the CanFocus of the subview is different from the value being set
  535. foreach (View view in _subviews)
  536. {
  537. if (view.CanFocus != value)
  538. {
  539. if (!value)
  540. {
  541. // Cache the old CanFocus and TabIndex so that they can be restored when CanFocus is changed back to true
  542. view._oldCanFocus = view.CanFocus;
  543. view._oldTabIndex = view._tabIndex;
  544. view.CanFocus = false;
  545. //view._tabIndex = -1;
  546. }
  547. else
  548. {
  549. if (_addingViewSoCanFocusAlsoUpdatesSuperView)
  550. {
  551. view._addingViewSoCanFocusAlsoUpdatesSuperView = true;
  552. }
  553. // Restore the old CanFocus and TabIndex to the values they held before CanFocus was set to false
  554. view.CanFocus = view._oldCanFocus;
  555. view._tabIndex = view._oldTabIndex;
  556. view._addingViewSoCanFocusAlsoUpdatesSuperView = false;
  557. }
  558. }
  559. }
  560. #endif
  561. if (this is Toplevel && Application.Current!.Focused != this)
  562. {
  563. ApplicationOverlapped.BringOverlappedTopToFront ();
  564. }
  565. }
  566. OnCanFocusChanged ();
  567. SetNeedsDisplay ();
  568. }
  569. }
  570. /// <summary>Raised when <see cref="CanFocus"/> has been changed.</summary>
  571. /// <remarks>
  572. /// Raised by the <see cref="OnCanFocusChanged"/> virtual method.
  573. /// </remarks>
  574. public event EventHandler CanFocusChanged;
  575. /// <summary>Returns the currently focused Subview inside this view, or <see langword="null"/> if nothing is focused.</summary>
  576. /// <value>The currently focused Subview.</value>
  577. [CanBeNull]
  578. public View Focused { get; private set; }
  579. /// <summary>
  580. /// Focuses the deepest focusable view in <see cref="View.TabIndexes"/> if one exists. If there are no views in
  581. /// <see cref="View.TabIndexes"/> then the focus is set to the view itself.
  582. /// </summary>
  583. /// <param name="behavior"></param>
  584. /// <param name="direction"></param>
  585. public void FocusDeepest (TabBehavior? behavior, NavigationDirection direction)
  586. {
  587. if (!CanBeVisible (this))
  588. {
  589. return;
  590. }
  591. View deepest = FindDeepestFocusableView (behavior, direction);
  592. if (deepest is { })
  593. {
  594. deepest.SetFocus ();
  595. }
  596. }
  597. [CanBeNull]
  598. private View FindDeepestFocusableView (TabBehavior? behavior, NavigationDirection direction)
  599. {
  600. var indicies = GetScopedTabIndexes (behavior, direction);
  601. foreach (View v in indicies)
  602. {
  603. if (v.TabIndexes.Count == 0)
  604. {
  605. return v;
  606. }
  607. return v.FindDeepestFocusableView (behavior, direction);
  608. }
  609. return null;
  610. }
  611. /// <summary>Returns a value indicating if this View is currently on Top (Active)</summary>
  612. public bool IsCurrentTop => Application.Current == this;
  613. /// <summary>
  614. /// Returns the most focused Subview in the chain of subviews (the leaf view that has the focus), or
  615. /// <see langword="null"/> if nothing is focused.
  616. /// </summary>
  617. /// <value>The most focused Subview.</value>
  618. public View MostFocused
  619. {
  620. get
  621. {
  622. if (Focused is null)
  623. {
  624. return null;
  625. }
  626. View most = Focused.MostFocused;
  627. if (most is { })
  628. {
  629. return most;
  630. }
  631. return Focused;
  632. }
  633. }
  634. /// <summary>Invoked when the <see cref="CanFocus"/> property from a view is changed.</summary>
  635. /// <remarks>
  636. /// Raises the <see cref="CanFocusChanged"/> event.
  637. /// </remarks>
  638. public virtual void OnCanFocusChanged () { CanFocusChanged?.Invoke (this, EventArgs.Empty); }
  639. #region Tab/Focus Handling
  640. #nullable enable
  641. private List<View>? _tabIndexes;
  642. // TODO: This should be a get-only property?
  643. // BUGBUG: This returns an AsReadOnly list, but isn't declared as such.
  644. /// <summary>Gets a list of the subviews that are a <see cref="TabStop"/>.</summary>
  645. /// <value>The tabIndexes.</value>
  646. public IList<View> TabIndexes => _tabIndexes?.AsReadOnly () ?? _empty;
  647. /// <summary>
  648. /// Gets TabIndexes that are scoped to the specified behavior and direction. If behavior is null, all TabIndexes are returned.
  649. /// </summary>
  650. /// <param name="behavior"></param>
  651. /// <param name="direction"></param>
  652. /// <returns></returns>GetScopedTabIndexes
  653. private View [] GetScopedTabIndexes (TabBehavior? behavior, NavigationDirection direction)
  654. {
  655. IEnumerable<View>? indicies;
  656. if (behavior.HasValue)
  657. {
  658. indicies = _tabIndexes?.Where (v => v.TabStop == behavior && v is { CanFocus: true, Visible: true, Enabled: true });
  659. }
  660. else
  661. {
  662. indicies = _tabIndexes?.Where (v => v is { CanFocus: true, Visible: true, Enabled: true });
  663. }
  664. if (direction == NavigationDirection.Backward)
  665. {
  666. indicies = indicies?.Reverse ();
  667. }
  668. return indicies?.ToArray () ?? Array.Empty<View> ();
  669. }
  670. private int? _tabIndex; // null indicates the view has not yet been added to TabIndexes
  671. private int? _oldTabIndex;
  672. /// <summary>
  673. /// Indicates the order of the current <see cref="View"/> in <see cref="TabIndexes"/> list.
  674. /// </summary>
  675. /// <remarks>
  676. /// <para>
  677. /// If <see langword="null"/>, the view is not part of the tab order.
  678. /// </para>
  679. /// <para>
  680. /// On set, if <see cref="SuperView"/> is <see langword="null"/> or has not TabStops, <see cref="TabIndex"/> will
  681. /// be set to 0.
  682. /// </para>
  683. /// <para>
  684. /// On set, if <see cref="SuperView"/> has only one TabStop, <see cref="TabIndex"/> will be set to 0.
  685. /// </para>
  686. /// <para>
  687. /// See also <seealso cref="TabStop"/>.
  688. /// </para>
  689. /// </remarks>
  690. public int? TabIndex
  691. {
  692. get => _tabIndex;
  693. // TOOD: This should be a get-only property. Introduce SetTabIndex (int value) (or similar).
  694. set
  695. {
  696. // Once a view is in the tab order, it should not be removed from the tab order; set TabStop to NoStop instead.
  697. Debug.Assert (value >= 0);
  698. Debug.Assert (value is { });
  699. if (SuperView?._tabIndexes is null || SuperView?._tabIndexes.Count == 1)
  700. {
  701. // BUGBUG: Property setters should set the property to the value passed in and not have side effects.
  702. _tabIndex = 0;
  703. return;
  704. }
  705. if (_tabIndex == value && TabIndexes.IndexOf (this) == value)
  706. {
  707. return;
  708. }
  709. _tabIndex = value > SuperView!.TabIndexes.Count - 1 ? SuperView._tabIndexes.Count - 1 :
  710. value < 0 ? 0 : value;
  711. _tabIndex = GetGreatestTabIndexInSuperView ((int)_tabIndex);
  712. if (SuperView._tabIndexes.IndexOf (this) != _tabIndex)
  713. {
  714. // BUGBUG: we have to use _tabIndexes and not TabIndexes because TabIndexes returns is a read-only version of _tabIndexes
  715. SuperView._tabIndexes.Remove (this);
  716. SuperView._tabIndexes.Insert ((int)_tabIndex, this);
  717. UpdatePeerTabIndexes ();
  718. }
  719. return;
  720. // Updates the <see cref="TabIndex"/>s of the views in the <see cref="SuperView"/>'s to match their order in <see cref="TabIndexes"/>.
  721. void UpdatePeerTabIndexes ()
  722. {
  723. if (SuperView is null)
  724. {
  725. return;
  726. }
  727. var i = 0;
  728. foreach (View superViewTabStop in SuperView._tabIndexes)
  729. {
  730. if (superViewTabStop._tabIndex is null)
  731. {
  732. continue;
  733. }
  734. superViewTabStop._tabIndex = i;
  735. i++;
  736. }
  737. }
  738. }
  739. }
  740. /// <summary>
  741. /// Gets the greatest <see cref="TabIndex"/> of the <see cref="SuperView"/>'s <see cref="TabIndexes"/> that is less
  742. /// than or equal to <paramref name="idx"/>.
  743. /// </summary>
  744. /// <param name="idx"></param>
  745. /// <returns>The minimum of <paramref name="idx"/> and the <see cref="SuperView"/>'s <see cref="TabIndexes"/>.</returns>
  746. private int GetGreatestTabIndexInSuperView (int idx)
  747. {
  748. if (SuperView is null)
  749. {
  750. return 0;
  751. }
  752. var i = 0;
  753. foreach (View superViewTabStop in SuperView._tabIndexes)
  754. {
  755. if (superViewTabStop._tabIndex is null || superViewTabStop == this)
  756. {
  757. continue;
  758. }
  759. i++;
  760. }
  761. return Math.Min (i, idx);
  762. }
  763. private TabBehavior? _tabStop;
  764. /// <summary>
  765. /// Gets or sets the behavior of <see cref="AdvanceFocus"/> for keyboard navigation.
  766. /// </summary>
  767. /// <remarks>
  768. /// <para>
  769. /// If <see langword="null"/> the tab stop has not been set and setting <see cref="CanFocus"/> to true will set it
  770. /// to
  771. /// <see cref="TabBehavior.TabStop"/>.
  772. /// </para>
  773. /// <para>
  774. /// TabStop is independent of <see cref="CanFocus"/>. If <see cref="CanFocus"/> is <see langword="false"/>, the
  775. /// view will not gain
  776. /// focus even if this property is set and vice-versa.
  777. /// </para>
  778. /// <para>
  779. /// The default <see cref="TabBehavior.TabStop"/> keys are <see cref="Application.NextTabKey"/> (<c>Key.Tab</c>) and <see cref="Application.PrevTabKey"/> (<c>Key>Tab.WithShift</c>).
  780. /// </para>
  781. /// <para>
  782. /// The default <see cref="TabBehavior.TabGroup"/> keys are <see cref="Application.NextTabGroupKey"/> (<c>Key.F6</c>) and <see cref="Application.PrevTabGroupKey"/> (<c>Key>Key.F6.WithShift</c>).
  783. /// </para>
  784. /// </remarks>
  785. public TabBehavior? TabStop
  786. {
  787. get => _tabStop;
  788. set
  789. {
  790. if (_tabStop == value)
  791. {
  792. return;
  793. }
  794. Debug.Assert (value is { });
  795. if (_tabStop is null && TabIndex is null)
  796. {
  797. // This view has not yet been added to TabIndexes (TabStop has not been set previously).
  798. TabIndex = GetGreatestTabIndexInSuperView (SuperView is { } ? SuperView._tabIndexes.Count : 0);
  799. }
  800. _tabStop = value;
  801. }
  802. }
  803. #endregion Tab/Focus Handling
  804. }