View.Navigation.cs 33 KB

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