View.Navigation.cs 32 KB

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