View.Navigation.cs 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959
  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. return true;
  307. }
  308. }
  309. var index = GetScopedTabIndexes (behavior, direction);
  310. if (index.Length == 0)
  311. {
  312. return false;
  313. }
  314. var focusedIndex = index.IndexOf (Focused);
  315. int next = 0;
  316. if (focusedIndex < index.Length - 1)
  317. {
  318. next = focusedIndex + 1;
  319. }
  320. else
  321. {
  322. if (behavior == TabBehavior.TabGroup && behavior == TabStop && SuperView?.TabStop == TabBehavior.TabGroup)
  323. {
  324. // Go up the hierarchy and leave
  325. Focused.SetHasFocus (false, this);
  326. // TODO: Should we check the return value of SetHasFocus?
  327. return false;
  328. }
  329. }
  330. View view = index [next];
  331. if (view.HasFocus)
  332. {
  333. return true;
  334. }
  335. // The subview does not have focus, but at least one other that can. Can this one be focused?
  336. if (view.CanFocus && view.Visible && view.Enabled)
  337. {
  338. // Make Focused Leave
  339. Focused.SetHasFocus (false, view);
  340. view.FocusDeepest (TabBehavior.TabStop, direction);
  341. return true;
  342. }
  343. if (Focused is { })
  344. {
  345. // Leave
  346. Focused.SetHasFocus (false, this);
  347. // Signal that nothing is focused, and callers should try a peer-subview
  348. Focused = null;
  349. }
  350. return false;
  351. }
  352. /// <summary>
  353. /// INTERNAL API to restore focus to the subview that had focus before this view lost focused.
  354. /// </summary>
  355. /// <returns>
  356. /// Returns true if focus was restored to a subview, false otherwise.
  357. /// </returns>
  358. internal bool RestoreFocus (TabBehavior? behavior)
  359. {
  360. if (Focused is null && _subviews?.Count > 0)
  361. {
  362. // TODO: Find the previous focused view and set focus to it
  363. if (PreviouslyMostFocused is { } && PreviouslyMostFocused.TabStop == behavior)
  364. {
  365. SetFocus (PreviouslyMostFocused);
  366. return true;
  367. }
  368. return true;
  369. }
  370. return false;
  371. }
  372. /// <summary>
  373. /// Internal API that causes <paramref name="viewToEnterFocus"/> to enter focus.
  374. /// <paramref name="viewToEnterFocus"/> does not need to be a subview.
  375. /// Recursively sets focus DOWN in the view hierarchy.
  376. /// </summary>
  377. /// <param name="viewToEnterFocus"></param>
  378. private void SetFocus (View viewToEnterFocus)
  379. {
  380. if (viewToEnterFocus is null)
  381. {
  382. return;
  383. }
  384. if (!viewToEnterFocus.CanFocus || !viewToEnterFocus.Visible || !viewToEnterFocus.Enabled)
  385. {
  386. return;
  387. }
  388. // If viewToEnterFocus is already the focused view, don't do anything
  389. if (Focused?._hasFocus == true && Focused == viewToEnterFocus)
  390. {
  391. return;
  392. }
  393. // If a subview has focus and viewToEnterFocus is the focused view's superview OR viewToEnterFocus is this view,
  394. // then make viewToEnterFocus.HasFocus = true and return
  395. if ((Focused?._hasFocus == true && Focused?.SuperView == viewToEnterFocus) || viewToEnterFocus == this)
  396. {
  397. if (!viewToEnterFocus._hasFocus)
  398. {
  399. viewToEnterFocus._hasFocus = true;
  400. }
  401. return;
  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 down the view hierarchy
  424. if (SuperView is { })
  425. {
  426. SuperView.SetFocus (this);
  427. }
  428. else
  429. {
  430. // If there is no SuperView, then this is a top-level view
  431. SetFocus (this);
  432. }
  433. }
  434. #if AUTO_CANFOCUS
  435. // 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.
  436. // Set to true in Add() to indicate that the view being added to a SuperView has CanFocus=true.
  437. // Makes it so CanFocus will update the SuperView's CanFocus property.
  438. internal bool _addingViewSoCanFocusAlsoUpdatesSuperView;
  439. // 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
  440. private bool _oldCanFocus;
  441. #endif
  442. private bool _canFocus;
  443. /// <summary>Gets or sets a value indicating whether this <see cref="View"/> can be focused.</summary>
  444. /// <remarks>
  445. /// <para>
  446. /// <see cref="SuperView"/> must also have <see cref="CanFocus"/> set to <see langword="true"/>.
  447. /// </para>
  448. /// <para>
  449. /// When set to <see langword="false"/>, if an attempt is made to make this view focused, the focus will be set to
  450. /// the next focusable view.
  451. /// </para>
  452. /// <para>
  453. /// When set to <see langword="false"/>, the <see cref="TabIndex"/> will be set to -1.
  454. /// </para>
  455. /// <para>
  456. /// When set to <see langword="false"/>, the values of <see cref="CanFocus"/> and <see cref="TabIndex"/> for all
  457. /// subviews will be cached so that when <see cref="CanFocus"/> is set back to <see langword="true"/>, the subviews
  458. /// will be restored to their previous values.
  459. /// </para>
  460. /// <para>
  461. /// Changing this property to <see langword="true"/> will cause <see cref="TabStop"/> to be set to
  462. /// <see cref="TabBehavior.TabStop"/>" as a convenience. Changing this property to
  463. /// <see langword="false"/> will have no effect on <see cref="TabStop"/>.
  464. /// </para>
  465. /// </remarks>
  466. public bool CanFocus
  467. {
  468. get => _canFocus;
  469. set
  470. {
  471. #if AUTO_CANFOCUS
  472. if (!_addingViewSoCanFocusAlsoUpdatesSuperView && IsInitialized && SuperView?.CanFocus == false && value)
  473. {
  474. throw new InvalidOperationException ("Cannot set CanFocus to true if the SuperView CanFocus is false!");
  475. }
  476. #endif
  477. if (_canFocus == value)
  478. {
  479. return;
  480. }
  481. _canFocus = value;
  482. #if AUTO_CANFOCUS
  483. switch (_canFocus)
  484. {
  485. case false when _tabIndex > -1:
  486. // BUGBUG: This is a poor API design. Automatic behavior like this is non-obvious and should be avoided. Callers should adjust TabIndex explicitly.
  487. //TabIndex = -1;
  488. break;
  489. case true when SuperView?.CanFocus == false && _addingViewSoCanFocusAlsoUpdatesSuperView:
  490. SuperView.CanFocus = true;
  491. break;
  492. }
  493. #endif
  494. if (TabStop is null && _canFocus)
  495. {
  496. TabStop = TabBehavior.TabStop;
  497. }
  498. if (!_canFocus && SuperView?.Focused == this)
  499. {
  500. SuperView.Focused = null;
  501. }
  502. if (!_canFocus && HasFocus)
  503. {
  504. SetHasFocus (false, this);
  505. SuperView?.RestoreFocus (null);
  506. // If EnsureFocus () didn't set focus to a view, focus the next focusable view in the application
  507. if (SuperView is { Focused: null })
  508. {
  509. SuperView.AdvanceFocus (NavigationDirection.Forward, null);
  510. if (SuperView.Focused is null && Application.Current is { })
  511. {
  512. Application.Current.AdvanceFocus (NavigationDirection.Forward, null);
  513. }
  514. ApplicationOverlapped.BringOverlappedTopToFront ();
  515. }
  516. }
  517. if (_subviews is { } && IsInitialized)
  518. {
  519. #if AUTO_CANFOCUS
  520. // Change the CanFocus of all subviews to the same value as this view
  521. // if the CanFocus of the subview is different from the value being set
  522. foreach (View view in _subviews)
  523. {
  524. if (view.CanFocus != value)
  525. {
  526. if (!value)
  527. {
  528. // Cache the old CanFocus and TabIndex so that they can be restored when CanFocus is changed back to true
  529. view._oldCanFocus = view.CanFocus;
  530. view._oldTabIndex = view._tabIndex;
  531. view.CanFocus = false;
  532. //view._tabIndex = -1;
  533. }
  534. else
  535. {
  536. if (_addingViewSoCanFocusAlsoUpdatesSuperView)
  537. {
  538. view._addingViewSoCanFocusAlsoUpdatesSuperView = true;
  539. }
  540. // Restore the old CanFocus and TabIndex to the values they held before CanFocus was set to false
  541. view.CanFocus = view._oldCanFocus;
  542. view._tabIndex = view._oldTabIndex;
  543. view._addingViewSoCanFocusAlsoUpdatesSuperView = false;
  544. }
  545. }
  546. }
  547. #endif
  548. if (this is Toplevel && Application.Current!.Focused != this)
  549. {
  550. ApplicationOverlapped.BringOverlappedTopToFront ();
  551. }
  552. }
  553. OnCanFocusChanged ();
  554. SetNeedsDisplay ();
  555. }
  556. }
  557. /// <summary>Raised when <see cref="CanFocus"/> has been changed.</summary>
  558. /// <remarks>
  559. /// Raised by the <see cref="OnCanFocusChanged"/> virtual method.
  560. /// </remarks>
  561. public event EventHandler CanFocusChanged;
  562. /// <summary>Returns the currently focused Subview inside this view, or <see langword="null"/> if nothing is focused.</summary>
  563. /// <value>The currently focused Subview.</value>
  564. [CanBeNull]
  565. public View Focused { get; private set; }
  566. /// <summary>
  567. /// Focuses the deepest focusable view in <see cref="View.TabIndexes"/> if one exists. If there are no views in
  568. /// <see cref="View.TabIndexes"/> then the focus is set to the view itself.
  569. /// </summary>
  570. /// <param name="behavior"></param>
  571. /// <param name="direction"></param>
  572. public void FocusDeepest (TabBehavior? behavior, NavigationDirection direction)
  573. {
  574. if (!CanBeVisible (this))
  575. {
  576. return;
  577. }
  578. //View deepest = FindDeepestFocusableView (behavior, direction);
  579. //if (deepest is { })
  580. //{
  581. // deepest.SetFocus ();
  582. //}
  583. if (_tabIndexes is null)
  584. {
  585. SuperView?.SetFocus (this);
  586. return;
  587. }
  588. SetFocus ();
  589. foreach (View view in _tabIndexes)
  590. {
  591. if (view.CanFocus && (behavior is null || view.TabStop == behavior) && view.Visible && view.Enabled)
  592. {
  593. SetFocus (view);
  594. return;
  595. }
  596. }
  597. }
  598. [CanBeNull]
  599. private View FindDeepestFocusableView (TabBehavior? behavior, NavigationDirection direction)
  600. {
  601. var indicies = GetScopedTabIndexes (behavior, direction);
  602. foreach (View v in indicies)
  603. {
  604. if (v.TabIndexes.Count == 0)
  605. {
  606. return v;
  607. }
  608. return v.FindDeepestFocusableView (behavior, direction);
  609. }
  610. return null;
  611. }
  612. /// <summary>Returns a value indicating if this View is currently on Top (Active)</summary>
  613. public bool IsCurrentTop => Application.Current == this;
  614. /// <summary>
  615. /// Returns the most focused Subview in the chain of subviews (the leaf view that has the focus), or
  616. /// <see langword="null"/> if nothing is focused.
  617. /// </summary>
  618. /// <value>The most focused Subview.</value>
  619. public View MostFocused
  620. {
  621. get
  622. {
  623. if (Focused is null)
  624. {
  625. return null;
  626. }
  627. View most = Focused.MostFocused;
  628. if (most is { })
  629. {
  630. return most;
  631. }
  632. return Focused;
  633. }
  634. }
  635. /// <summary>Invoked when the <see cref="CanFocus"/> property from a view is changed.</summary>
  636. /// <remarks>
  637. /// Raises the <see cref="CanFocusChanged"/> event.
  638. /// </remarks>
  639. public virtual void OnCanFocusChanged () { CanFocusChanged?.Invoke (this, EventArgs.Empty); }
  640. #region Tab/Focus Handling
  641. #nullable enable
  642. private List<View>? _tabIndexes;
  643. // TODO: This should be a get-only property?
  644. // BUGBUG: This returns an AsReadOnly list, but isn't declared as such.
  645. /// <summary>Gets a list of the subviews that are a <see cref="TabStop"/>.</summary>
  646. /// <value>The tabIndexes.</value>
  647. public IList<View> TabIndexes => _tabIndexes?.AsReadOnly () ?? _empty;
  648. /// <summary>
  649. /// Gets TabIndexes that are scoped to the specified behavior and direction. If behavior is null, all TabIndexes are returned.
  650. /// </summary>
  651. /// <param name="behavior"></param>
  652. /// <param name="direction"></param>
  653. /// <returns></returns>GetScopedTabIndexes
  654. private View [] GetScopedTabIndexes (TabBehavior? behavior, NavigationDirection direction)
  655. {
  656. IEnumerable<View>? indicies;
  657. if (behavior.HasValue)
  658. {
  659. indicies = _tabIndexes?.Where (v => v.TabStop == behavior && v is { CanFocus: true, Visible: true, Enabled: true });
  660. }
  661. else
  662. {
  663. indicies = _tabIndexes?.Where (v => v is { CanFocus: true, Visible: true, Enabled: true });
  664. }
  665. if (direction == NavigationDirection.Backward)
  666. {
  667. indicies = indicies?.Reverse ();
  668. }
  669. return indicies?.ToArray () ?? Array.Empty<View> ();
  670. }
  671. private int? _tabIndex; // null indicates the view has not yet been added to TabIndexes
  672. private int? _oldTabIndex;
  673. /// <summary>
  674. /// Indicates the order of the current <see cref="View"/> in <see cref="TabIndexes"/> list.
  675. /// </summary>
  676. /// <remarks>
  677. /// <para>
  678. /// If <see langword="null"/>, the view is not part of the tab order.
  679. /// </para>
  680. /// <para>
  681. /// On set, if <see cref="SuperView"/> is <see langword="null"/> or has not TabStops, <see cref="TabIndex"/> will
  682. /// be set to 0.
  683. /// </para>
  684. /// <para>
  685. /// On set, if <see cref="SuperView"/> has only one TabStop, <see cref="TabIndex"/> will be set to 0.
  686. /// </para>
  687. /// <para>
  688. /// See also <seealso cref="TabStop"/>.
  689. /// </para>
  690. /// </remarks>
  691. public int? TabIndex
  692. {
  693. get => _tabIndex;
  694. // TOOD: This should be a get-only property. Introduce SetTabIndex (int value) (or similar).
  695. set
  696. {
  697. // Once a view is in the tab order, it should not be removed from the tab order; set TabStop to NoStop instead.
  698. Debug.Assert (value >= 0);
  699. Debug.Assert (value is { });
  700. if (SuperView?._tabIndexes is null || SuperView?._tabIndexes.Count == 1)
  701. {
  702. // BUGBUG: Property setters should set the property to the value passed in and not have side effects.
  703. _tabIndex = 0;
  704. return;
  705. }
  706. if (_tabIndex == value && TabIndexes.IndexOf (this) == value)
  707. {
  708. return;
  709. }
  710. _tabIndex = value > SuperView!.TabIndexes.Count - 1 ? SuperView._tabIndexes.Count - 1 :
  711. value < 0 ? 0 : value;
  712. _tabIndex = GetGreatestTabIndexInSuperView ((int)_tabIndex);
  713. if (SuperView._tabIndexes.IndexOf (this) != _tabIndex)
  714. {
  715. // BUGBUG: we have to use _tabIndexes and not TabIndexes because TabIndexes returns is a read-only version of _tabIndexes
  716. SuperView._tabIndexes.Remove (this);
  717. SuperView._tabIndexes.Insert ((int)_tabIndex, this);
  718. UpdatePeerTabIndexes ();
  719. }
  720. return;
  721. // Updates the <see cref="TabIndex"/>s of the views in the <see cref="SuperView"/>'s to match their order in <see cref="TabIndexes"/>.
  722. void UpdatePeerTabIndexes ()
  723. {
  724. if (SuperView is null)
  725. {
  726. return;
  727. }
  728. var i = 0;
  729. foreach (View superViewTabStop in SuperView._tabIndexes)
  730. {
  731. if (superViewTabStop._tabIndex is null)
  732. {
  733. continue;
  734. }
  735. superViewTabStop._tabIndex = i;
  736. i++;
  737. }
  738. }
  739. }
  740. }
  741. /// <summary>
  742. /// Gets the greatest <see cref="TabIndex"/> of the <see cref="SuperView"/>'s <see cref="TabIndexes"/> that is less
  743. /// than or equal to <paramref name="idx"/>.
  744. /// </summary>
  745. /// <param name="idx"></param>
  746. /// <returns>The minimum of <paramref name="idx"/> and the <see cref="SuperView"/>'s <see cref="TabIndexes"/>.</returns>
  747. private int GetGreatestTabIndexInSuperView (int idx)
  748. {
  749. if (SuperView is null)
  750. {
  751. return 0;
  752. }
  753. var i = 0;
  754. foreach (View superViewTabStop in SuperView._tabIndexes)
  755. {
  756. if (superViewTabStop._tabIndex is null || superViewTabStop == this)
  757. {
  758. continue;
  759. }
  760. i++;
  761. }
  762. return Math.Min (i, idx);
  763. }
  764. private TabBehavior? _tabStop;
  765. /// <summary>
  766. /// Gets or sets the behavior of <see cref="AdvanceFocus"/> for keyboard navigation.
  767. /// </summary>
  768. /// <remarks>
  769. /// <para>
  770. /// If <see langword="null"/> the tab stop has not been set and setting <see cref="CanFocus"/> to true will set it
  771. /// to
  772. /// <see cref="TabBehavior.TabStop"/>.
  773. /// </para>
  774. /// <para>
  775. /// TabStop is independent of <see cref="CanFocus"/>. If <see cref="CanFocus"/> is <see langword="false"/>, the
  776. /// view will not gain
  777. /// focus even if this property is set and vice-versa.
  778. /// </para>
  779. /// <para>
  780. /// The default <see cref="TabBehavior.TabStop"/> keys are <c>Key.Tab</c> and <c>Key>Tab.WithShift</c>.
  781. /// </para>
  782. /// <para>
  783. /// The default <see cref="TabBehavior.TabGroup"/> keys are <c>Key.Tab.WithCtrl</c> and <c>Key>Key.Tab.WithCtrl.WithShift</c>.
  784. /// </para>
  785. /// </remarks>
  786. public TabBehavior? TabStop
  787. {
  788. get => _tabStop;
  789. set
  790. {
  791. if (_tabStop == value)
  792. {
  793. return;
  794. }
  795. Debug.Assert (value is { });
  796. if (_tabStop is null && TabIndex is null)
  797. {
  798. // This view has not yet been added to TabIndexes (TabStop has not been set previously).
  799. TabIndex = GetGreatestTabIndexInSuperView (SuperView is { } ? SuperView._tabIndexes.Count : 0);
  800. }
  801. _tabStop = value;
  802. }
  803. }
  804. #endregion Tab/Focus Handling
  805. }