View.Navigation.cs 33 KB

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