View.Navigation.cs 32 KB

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