View.Navigation.cs 38 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088
  1. using System.Diagnostics;
  2. namespace Terminal.Gui.ViewBase;
  3. public partial class View // Focus and cross-view navigation management (TabStop, TabIndex, etc...)
  4. {
  5. private bool _canFocus;
  6. /// <summary>
  7. /// Advances the focus to the next or previous view in the focus chain, based on
  8. /// <paramref name="direction"/>.
  9. /// itself.
  10. /// </summary>
  11. /// <remarks>
  12. /// <para>
  13. /// If there is no next/previous view to advance to, the focus is set to the view itself.
  14. /// </para>
  15. /// <para>
  16. /// See the View Navigation Deep Dive for more information:
  17. /// <see href="https://gui-cs.github.io/Terminal.Gui/docs/navigation.html"/>
  18. /// </para>
  19. /// </remarks>
  20. /// <param name="direction"></param>
  21. /// <param name="behavior"></param>
  22. /// <returns>
  23. /// <see langword="true"/> if focus was changed to another subview (or stayed on this one), <see langword="false"/>
  24. /// otherwise.
  25. /// </returns>
  26. public bool AdvanceFocus (NavigationDirection direction, TabBehavior? behavior)
  27. {
  28. //Logging.Trace ($"{Id} - {direction} {behavior}");
  29. if (!CanBeVisible (this)) // TODO: is this check needed?
  30. {
  31. return false;
  32. }
  33. if (RaiseAdvancingFocus (direction, behavior))
  34. {
  35. return true;
  36. }
  37. View? focused = Focused;
  38. if (focused is { } && focused.AdvanceFocus (direction, behavior))
  39. {
  40. return true;
  41. }
  42. // AdvanceFocus did not advance - do we wrap, or move up to the superview?
  43. View [] focusChain = GetFocusChain (direction, behavior);
  44. if (focusChain.Length == 0)
  45. {
  46. return false;
  47. }
  48. // Special case TabGroup
  49. if (behavior == TabBehavior.TabGroup)
  50. {
  51. if (direction == NavigationDirection.Forward && focused == focusChain [^1] && SuperView is null)
  52. {
  53. // We're at the top of the focus chain. Go back down the focus chain and focus the first TabGroup
  54. if (AdvanceFocusChain ())
  55. {
  56. return true;
  57. }
  58. }
  59. if (direction == NavigationDirection.Backward && focused == focusChain [0] && SuperView is null)
  60. {
  61. // We're at the bottom of the focus chain
  62. if (AdvanceFocusChain ())
  63. {
  64. return true;
  65. }
  66. }
  67. }
  68. int focusedIndex = focusChain.IndexOf (Focused); // Will return -1 if Focused can't be found or is null
  69. var next = 0; // Assume we wrap to start of the focus chain
  70. if (focusedIndex < focusChain.Length - 1)
  71. {
  72. // We're moving w/in the subviews
  73. next = focusedIndex + 1;
  74. }
  75. else
  76. {
  77. // Determine if focus should remain in this focus chain, or move to the superview's focus chain
  78. if (SuperView is { })
  79. {
  80. // If we are TabStop, and we have at least one other focusable peer, move to the SuperView's chain
  81. if (TabStop == TabBehavior.TabStop && SuperView is { } && ShouldBubbleUpForWrapping (SuperView, direction, behavior))
  82. {
  83. return false;
  84. }
  85. // TabGroup is special-cased.
  86. if (focused?.TabStop == TabBehavior.TabGroup)
  87. {
  88. if (SuperView?.GetFocusChain (direction, TabBehavior.TabGroup)?.Length > 0)
  89. {
  90. // Our superview has a TabGroup subview; signal we couldn't move so we nav out to it
  91. return false;
  92. }
  93. }
  94. }
  95. }
  96. View view = focusChain [next];
  97. if (view.HasFocus)
  98. {
  99. // We could not advance
  100. if (view != this)
  101. {
  102. // Tell it to try the other way.
  103. return view.RaiseAdvancingFocus (
  104. direction == NavigationDirection.Forward ? NavigationDirection.Backward : NavigationDirection.Forward,
  105. behavior);
  106. }
  107. return view == this;
  108. }
  109. // The subview does not have focus, but at least one other that can. Can this one be focused?
  110. (bool focusSet, bool _) = view.SetHasFocusTrue (Focused);
  111. return focusSet;
  112. bool AdvanceFocusChain ()
  113. {
  114. if (focusChain.Length > 0)
  115. {
  116. // Get the index of the currently focused view
  117. int focusedTabGroupIndex = focusChain.IndexOf (Focused); // Will return -1 if Focused can't be found or is null
  118. if (focusedTabGroupIndex + 1 > focusChain.Length - 1)
  119. {
  120. focusedTabGroupIndex = 0;
  121. }
  122. else
  123. {
  124. focusedTabGroupIndex++;
  125. }
  126. View [] subViews = focusChain [focusedTabGroupIndex].GetFocusChain (NavigationDirection.Forward, TabBehavior.TabStop);
  127. if (subViews.Length > 0)
  128. {
  129. if (focusChain [focusedTabGroupIndex]._previouslyFocused is { }
  130. && subViews.Any (v => v == focusChain [focusedTabGroupIndex]._previouslyFocused))
  131. {
  132. if (focusChain [focusedTabGroupIndex]._previouslyFocused!.SetFocus ())
  133. {
  134. return true;
  135. }
  136. }
  137. // We have a subview that can be focused
  138. if (subViews [0].SetFocus ())
  139. {
  140. return true;
  141. }
  142. }
  143. }
  144. return false;
  145. }
  146. }
  147. /// <summary>
  148. /// Determines if focus should bubble up to a SuperView when wrapping would occur.
  149. /// Iteratively checks up the SuperView hierarchy to see if there are any focusable peers at any level.
  150. /// </summary>
  151. /// <param name="view">The SuperView to check.</param>
  152. /// <param name="direction">The navigation direction.</param>
  153. /// <param name="behavior">The tab behavior to filter by.</param>
  154. /// <returns>
  155. /// <see langword="true"/> if there are focusable peers at this level or any ancestor level,
  156. /// <see langword="false"/> otherwise.
  157. /// </returns>
  158. private bool ShouldBubbleUpForWrapping (View? view, NavigationDirection direction, TabBehavior? behavior)
  159. {
  160. View? currentView = view;
  161. while (currentView is { })
  162. {
  163. // If this parent has multiple focusable children, we should bubble up
  164. View [] chain = currentView.GetFocusChain (direction, behavior);
  165. if (chain.Length > 1)
  166. {
  167. return true;
  168. }
  169. // If parent has only 1 child but parent is also TabStop with a SuperView, continue checking up the hierarchy
  170. if (currentView.TabStop == TabBehavior.TabStop && currentView.SuperView is { })
  171. {
  172. currentView = currentView.SuperView;
  173. }
  174. else
  175. {
  176. break;
  177. }
  178. }
  179. return false;
  180. }
  181. private bool RaiseAdvancingFocus (NavigationDirection direction, TabBehavior? behavior)
  182. {
  183. // Call the virtual method
  184. if (OnAdvancingFocus (direction, behavior))
  185. {
  186. // The event was cancelled
  187. return true;
  188. }
  189. var args = new AdvanceFocusEventArgs (direction, behavior);
  190. AdvancingFocus?.Invoke (this, args);
  191. if (args.Cancel)
  192. {
  193. // The event was cancelled
  194. return true;
  195. }
  196. return false;
  197. }
  198. /// <summary>
  199. /// Called when <see cref="View.AdvanceFocus"/> is about to advance focus.
  200. /// </summary>
  201. /// <remarks>
  202. /// <para>
  203. /// If a view cancels the event and the focus could not otherwise advance, the Navigation direction will be
  204. /// reversed and the event will be raised again.
  205. /// </para>
  206. /// </remarks>
  207. /// <returns>
  208. /// <see langword="true"/>, if the focus advance is to be cancelled, <see langword="false"/>
  209. /// otherwise.
  210. /// </returns>
  211. protected virtual bool OnAdvancingFocus (NavigationDirection direction, TabBehavior? behavior) { return false; }
  212. /// <summary>
  213. /// Raised when <see cref="View.AdvanceFocus"/> is about to advance focus.
  214. /// </summary>
  215. /// <remarks>
  216. /// <para>
  217. /// Cancel the event to prevent the focus from advancing.
  218. /// </para>
  219. /// <para>
  220. /// If a view cancels the event and the focus could not otherwise advance, the Navigation direction will be
  221. /// reversed and the event will be raised again.
  222. /// </para>
  223. /// </remarks>
  224. public event EventHandler<AdvanceFocusEventArgs>? AdvancingFocus;
  225. /// <summary>Gets or sets a value indicating whether this <see cref="View"/> can be focused.</summary>
  226. /// <remarks>
  227. /// <para>
  228. /// See the View Navigation Deep Dive for more information:
  229. /// <see href="https://gui-cs.github.io/Terminal.Gui/docs/navigation.html"/>
  230. /// </para>
  231. /// <para>
  232. /// <see cref="SuperView"/> must also have <see cref="CanFocus"/> set to <see langword="true"/>.
  233. /// </para>
  234. /// <para>
  235. /// When set to <see langword="false"/>, if an attempt is made to make this view focused, the focus will be set to
  236. /// the next focusable view.
  237. /// </para>
  238. /// <para>
  239. /// When set to <see langword="false"/>, the value of <see cref="CanFocus"/> for all
  240. /// subviews will be cached so that when <see cref="CanFocus"/> is set back to <see langword="true"/>, the subviews
  241. /// will be restored to their previous values.
  242. /// </para>
  243. /// <para>
  244. /// Changing this property to <see langword="true"/> will cause <see cref="TabStop"/> to be set to
  245. /// <see cref="TabBehavior.TabStop"/>" as a convenience. Changing this property to
  246. /// <see langword="false"/> will have no effect on <see cref="TabStop"/>.
  247. /// </para>
  248. /// </remarks>
  249. public bool CanFocus
  250. {
  251. get => _canFocus;
  252. set
  253. {
  254. if (_canFocus == value)
  255. {
  256. return;
  257. }
  258. _canFocus = value;
  259. if (TabStop is null && _canFocus)
  260. {
  261. TabStop = TabBehavior.TabStop;
  262. }
  263. if (!_canFocus && HasFocus)
  264. {
  265. // If CanFocus is set to false and this view has focus, make it leave focus
  266. // Set transversing down so we don't go back up the hierarchy...
  267. SetHasFocusFalse (null);
  268. }
  269. if (_canFocus && !HasFocus && Visible && SuperView is { Focused: null })
  270. {
  271. // If CanFocus is set to true and this view does not have focus, make it enter focus
  272. SetFocus ();
  273. }
  274. OnCanFocusChanged ();
  275. }
  276. }
  277. /// <summary>Raised when <see cref="CanFocus"/> has been changed.</summary>
  278. /// <remarks>
  279. /// Raised by the <see cref="OnCanFocusChanged"/> virtual method.
  280. /// </remarks>
  281. public event EventHandler? CanFocusChanged;
  282. /// <summary>
  283. /// Focuses the deepest focusable SubView if one exists. If there are no focusable SubViews then the focus is set to
  284. /// the view itself.
  285. /// </summary>
  286. /// <param name="direction"></param>
  287. /// <param name="behavior"></param>
  288. /// <returns><see langword="true"/> if a subview other than this was focused.</returns>
  289. public bool FocusDeepest (NavigationDirection direction, TabBehavior? behavior)
  290. {
  291. View? deepest = FindDeepestFocusableView (direction, behavior);
  292. if (deepest is { })
  293. {
  294. return deepest.SetFocus ();
  295. }
  296. return SetFocus ();
  297. }
  298. /// <summary>Gets the currently focused SubView or Adornment of this view, or <see langword="null"/> if nothing is focused.</summary>
  299. public View? Focused
  300. {
  301. get
  302. {
  303. View? focused = SubViews.FirstOrDefault (v => v.HasFocus);
  304. if (focused is { })
  305. {
  306. return focused;
  307. }
  308. // How about in Adornments?
  309. if (Margin is { HasFocus: true })
  310. {
  311. return Margin;
  312. }
  313. if (Border is { HasFocus: true })
  314. {
  315. return Border;
  316. }
  317. if (Padding is { HasFocus: true })
  318. {
  319. return Padding;
  320. }
  321. return null;
  322. }
  323. }
  324. internal void RaiseFocusedChanged (View? previousFocused, View? focused)
  325. {
  326. //Logging.Trace($"RaiseFocusedChanged: {focused.Title}");
  327. OnFocusedChanged (previousFocused, focused);
  328. FocusedChanged?.Invoke (this, new (true, true, previousFocused, focused));
  329. }
  330. /// <summary>
  331. /// Called when the focused view has changed.
  332. /// </summary>
  333. /// <param name="previousFocused"></param>
  334. /// <param name="focused"></param>
  335. protected virtual void OnFocusedChanged (View? previousFocused, View? focused) { }
  336. /// <summary>
  337. /// Raised when the focused view has changed.
  338. /// </summary>
  339. public event EventHandler<HasFocusEventArgs>? FocusedChanged;
  340. /// <summary>Returns a value indicating if this View is currently on Top (Active)</summary>
  341. public bool IsCurrentTop => App?.TopRunnableView == this;
  342. /// <summary>
  343. /// Returns the most focused SubView down the subview-hierarchy.
  344. /// </summary>
  345. /// <value>The most focused SubView, or <see langword="null"/> if no SubView is focused.</value>
  346. public View? MostFocused
  347. {
  348. get
  349. {
  350. // TODO: Remove this API. It's duplicative of Application.Navigation.GetFocused.
  351. if (Focused is null)
  352. {
  353. return null;
  354. }
  355. View? most = Focused.MostFocused;
  356. if (most is { })
  357. {
  358. return most;
  359. }
  360. return Focused;
  361. }
  362. }
  363. /// <summary>Invoked when the <see cref="CanFocus"/> property from a view is changed.</summary>
  364. /// <remarks>
  365. /// Raises the <see cref="CanFocusChanged"/> event.
  366. /// </remarks>
  367. public virtual void OnCanFocusChanged () { CanFocusChanged?.Invoke (this, EventArgs.Empty); }
  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 ()
  375. {
  376. // Ignore TabStop
  377. View [] indicies = GetFocusChain (NavigationDirection.Forward, null);
  378. if (Focused is null && _previouslyFocused is { } && indicies.Contains (_previouslyFocused))
  379. {
  380. if (_previouslyFocused.SetFocus ())
  381. {
  382. return true;
  383. }
  384. _previouslyFocused = null;
  385. }
  386. return false;
  387. }
  388. /// <summary>
  389. /// Clears any focus state (e.g. the previously focused subview) from this view.
  390. /// </summary>
  391. public void ClearFocus () { _previouslyFocused = null; }
  392. private View? FindDeepestFocusableView (NavigationDirection direction, TabBehavior? behavior)
  393. {
  394. View [] indicies = GetFocusChain (direction, behavior);
  395. foreach (View v in indicies)
  396. {
  397. return v.FindDeepestFocusableView (direction, behavior);
  398. }
  399. return null;
  400. }
  401. #region HasFocus
  402. // Backs `HasFocus` and is the ultimate source of truth whether a View has focus or not.
  403. private bool _hasFocus;
  404. /// <summary>
  405. /// Gets or sets whether this view has focus.
  406. /// </summary>
  407. /// <remarks>
  408. /// <para>
  409. /// See the View Navigation Deep Dive for more information:
  410. /// <see href="https://gui-cs.github.io/Terminal.Gui/docs/navigation.html"/>
  411. /// </para>
  412. /// <para>
  413. /// Only Views that are visible, enabled, and have <see cref="CanFocus"/> set to <see langword="true"/> are
  414. /// focusable. If
  415. /// these conditions are not met when this property is set to <see langword="true"/> <see cref="HasFocus"/> will
  416. /// not change.
  417. /// </para>
  418. /// <para>
  419. /// Setting this property causes the <see cref="OnHasFocusChanging"/> and <see cref="OnHasFocusChanged"/> virtual
  420. /// methods (and <see cref="HasFocusChanging"/> and
  421. /// <see cref="HasFocusChanged"/> events to be raised). If the event is cancelled, <see cref="HasFocus"/> will not
  422. /// be changed.
  423. /// </para>
  424. /// <para>
  425. /// Setting this property to <see langword="true"/> will recursively set <see cref="HasFocus"/> to
  426. /// <see langword="true"/> for all SuperViews up the hierarchy.
  427. /// </para>
  428. /// <para>
  429. /// Setting this property to <see langword="true"/> will cause the subview furthest down the hierarchy that is
  430. /// focusable to also gain focus (as long as <see cref="TabStop"/>
  431. /// </para>
  432. /// <para>
  433. /// Setting this property to <see langword="false"/> will cause <see cref="AdvanceFocus"/> to set
  434. /// the focus on the next view to be focused.
  435. /// </para>
  436. /// </remarks>
  437. public bool HasFocus
  438. {
  439. set
  440. {
  441. if (HasFocus == value)
  442. {
  443. return;
  444. }
  445. if (value)
  446. {
  447. // NOTE: If Application.Navigation is null, we pass null to FocusChanging. For unit tests.
  448. (bool focusSet, bool _) = SetHasFocusTrue (App?.Navigation?.GetFocused ());
  449. if (focusSet)
  450. {
  451. // The change happened
  452. // HasFocus is now true
  453. }
  454. }
  455. else
  456. {
  457. SetHasFocusFalse (null);
  458. Debug.Assert (!_hasFocus);
  459. if (_hasFocus)
  460. {
  461. // force it.
  462. _hasFocus = false;
  463. }
  464. }
  465. }
  466. get => _hasFocus;
  467. }
  468. /// <summary>
  469. /// Causes this view to be focused. Calling this method has the same effect as setting <see cref="HasFocus"/> to
  470. /// <see langword="true"/> but with the added benefit of returning a value indicating whether the focus was set.
  471. /// </summary>
  472. /// <remarks>
  473. /// <para>
  474. /// See the View Navigation Deep Dive for more information:
  475. /// <see href="https://gui-cs.github.io/Terminal.Gui/docs/navigation.html"/>
  476. /// </para>
  477. /// </remarks>
  478. /// <returns><see langword="true"/> if the focus changed; <see langword="true"/> false otherwise.</returns>
  479. public bool SetFocus ()
  480. {
  481. (bool focusSet, bool _) = SetHasFocusTrue (App?.Navigation?.GetFocused ());
  482. return focusSet;
  483. }
  484. /// <summary>
  485. /// A cache of the subview that was focused when this view last lost focus. This is used by <see cref="RestoreFocus"/>.
  486. /// </summary>
  487. private View? _previouslyFocused;
  488. /// <summary>
  489. /// INTERNAL: Called when focus is going to change to this view. This method is called by <see cref="SetFocus"/> and
  490. /// other methods that
  491. /// set or remove focus from a view.
  492. /// </summary>
  493. /// <param name="currentFocusedView">
  494. /// The currently focused view. If <see langword="null"/> there is no previously focused
  495. /// view.
  496. /// </param>
  497. /// <param name="traversingUp"></param>
  498. /// <returns><see langword="true"/> if <see cref="HasFocus"/> was changed to <see langword="true"/>.</returns>
  499. /// <exception cref="InvalidOperationException"></exception>
  500. private (bool focusSet, bool cancelled) SetHasFocusTrue (View? currentFocusedView, bool traversingUp = false)
  501. {
  502. Debug.Assert (SuperView is null || IsInHierarchy (SuperView, this));
  503. //Logging.Trace ($"{Id} - {currentFocusedView?.Id} -> {Id}");
  504. // Pre-conditions
  505. if (_hasFocus)
  506. {
  507. //// See https://github.com/gui-cs/Terminal.Gui/pull/4013#issuecomment-2823934197
  508. //if (Application.Navigation is { } && (Application.Navigation.GetFocused () == this || Application.Navigation.GetFocused () == MostFocused))
  509. //{
  510. // throw new InvalidOperationException (@"Do not SetFocus on a view that is already MostFocused.");
  511. //}
  512. return (false, false);
  513. }
  514. if (currentFocusedView is { HasFocus: false })
  515. {
  516. throw new ArgumentException ("SetHasFocusTrue: currentFocusedView must HasFocus.");
  517. }
  518. var thisAsAdornment = this as Adornment;
  519. View? superViewOrParent = thisAsAdornment?.Parent ?? SuperView;
  520. if (CanFocus && superViewOrParent is { CanFocus: false })
  521. {
  522. Logging.Warning ($@"Attempt to FocusChanging where SuperView.CanFocus == false. {this}");
  523. return (false, false);
  524. }
  525. if (!CanBeVisible (this) || !Enabled)
  526. {
  527. return (false, false);
  528. }
  529. if (!CanFocus)
  530. {
  531. return (false, false);
  532. }
  533. bool previousValue = HasFocus;
  534. bool cancelled = RaiseFocusChanging (false, true, currentFocusedView, this);
  535. if (cancelled)
  536. {
  537. return (false, true);
  538. }
  539. // Make sure superviews up the superview hierarchy have focus.
  540. // Any of them may cancel gaining focus. In which case we need to back out.
  541. if (superViewOrParent is { HasFocus: false } sv)
  542. {
  543. (bool focusSet, bool svCancelled) = sv.SetHasFocusTrue (currentFocusedView, true);
  544. if (!focusSet)
  545. {
  546. return (false, svCancelled);
  547. }
  548. }
  549. if (_hasFocus)
  550. {
  551. // Something else beat us to the change (likely a FocusChanged handler).
  552. return (true, false);
  553. }
  554. // By setting _hasFocus to true we definitively change HasFocus for this view.
  555. // Get whatever peer has focus, if any
  556. View? focusedPeer = superViewOrParent?.Focused;
  557. _hasFocus = true;
  558. // Ensure that the peer loses focus
  559. focusedPeer?.SetHasFocusFalse (this, true);
  560. if (!traversingUp)
  561. {
  562. // Restore focus to the previously focused subview, if any
  563. if (!RestoreFocus ())
  564. {
  565. // Couldn't restore focus, so use Advance to navigate to the next focusable subview, if any
  566. AdvanceFocus (NavigationDirection.Forward, null);
  567. }
  568. }
  569. // Now make sure the old focused view loses focus
  570. if (currentFocusedView is { HasFocus: true } && GetFocusChain (NavigationDirection.Forward, TabStop).Contains (currentFocusedView))
  571. {
  572. currentFocusedView.SetHasFocusFalse (this);
  573. }
  574. if (_previouslyFocused is { })
  575. {
  576. _previouslyFocused = null;
  577. }
  578. if (Arrangement.HasFlag (ViewArrangement.Overlapped))
  579. {
  580. SuperView?.MoveSubViewToEnd (this);
  581. }
  582. // Focus work is done. Notify.
  583. RaiseFocusChanged (HasFocus, currentFocusedView, this);
  584. SetNeedsDraw ();
  585. // Post-conditions - prove correctness
  586. if (HasFocus == previousValue)
  587. {
  588. throw new InvalidOperationException ("NotifyFocusChanging was not cancelled and the HasFocus value did not change.");
  589. }
  590. return (true, false);
  591. }
  592. // TODO: CWP: FocusChanging should use an event arg type derived from ResultEventArgs<bool> so that its more obvious
  593. // TODO: the result can be changed.
  594. private bool RaiseFocusChanging (bool currentHasFocus, bool newHasFocus, View? currentFocused, View? newFocused)
  595. {
  596. Debug.Assert (currentFocused is null || currentFocused is { HasFocus: true });
  597. Debug.Assert (newFocused is null || newFocused is { CanFocus: true });
  598. // Call the virtual method
  599. if (OnHasFocusChanging (currentHasFocus, newHasFocus, currentFocused, newFocused))
  600. {
  601. // The event was cancelled
  602. return true;
  603. }
  604. var args = new HasFocusEventArgs (currentHasFocus, newHasFocus, currentFocused, newFocused);
  605. HasFocusChanging?.Invoke (this, args);
  606. if (args.Cancel)
  607. {
  608. // The event was cancelled
  609. return true;
  610. }
  611. View? appFocused = App?.Navigation?.GetFocused ();
  612. if (appFocused == currentFocused)
  613. {
  614. if (newFocused is { HasFocus: true })
  615. {
  616. App?.Navigation?.SetFocused (newFocused);
  617. }
  618. else
  619. {
  620. App?.Navigation?.SetFocused (null);
  621. }
  622. }
  623. return false;
  624. }
  625. /// <summary>
  626. /// Invoked when <see cref="View.HasFocus"/> is about to change. This method is called before the
  627. /// <see cref="HasFocusChanging"/> event is raised.
  628. /// </summary>
  629. /// <remarks>
  630. /// <para>
  631. /// Use <see cref="OnHasFocusChanged"/> to be notified after the focus has changed.
  632. /// </para>
  633. /// </remarks>
  634. /// <param name="currentHasFocus">The current value of <see cref="View.HasFocus"/>.</param>
  635. /// <param name="newHasFocus">The value <see cref="View.HasFocus"/> will have if the focus change happens.</param>
  636. /// <param name="currentFocused">The view that is currently Focused. May be <see langword="null"/>.</param>
  637. /// <param name="newFocused">The view that will be focused. May be <see langword="null"/>.</param>
  638. /// <returns>
  639. /// <see langword="true"/>, if the change to <see cref="View.HasFocus"/> is to be cancelled, <see langword="false"/>
  640. /// otherwise.
  641. /// </returns>
  642. protected virtual bool OnHasFocusChanging (bool currentHasFocus, bool newHasFocus, View? currentFocused, View? newFocused) { return false; }
  643. /// <summary>
  644. /// Raised when <see cref="View.HasFocus"/> is about to change.
  645. /// </summary>
  646. /// <remarks>
  647. /// <para>
  648. /// Cancel the event to prevent the focus from changing.
  649. /// </para>
  650. /// <para>
  651. /// Use <see cref="HasFocusChanged"/> to be notified after the focus has changed.
  652. /// </para>
  653. /// </remarks>
  654. public event EventHandler<HasFocusEventArgs>? HasFocusChanging;
  655. /// <summary>
  656. /// Called when this view should stop being focused.
  657. /// </summary>
  658. /// <param name="newFocusedView">
  659. /// The new focused view. If <see langword="null"/> it is not known which view will be
  660. /// focused.
  661. /// </param>
  662. /// <param name="traversingDown">
  663. /// Set to true to traverse down the focus
  664. /// chain only. If false, the method will attempt to AdvanceFocus on the superview or restorefocus on
  665. /// Application.Navigation.GetFocused().
  666. /// </param>
  667. /// <exception cref="InvalidOperationException"></exception>
  668. private void SetHasFocusFalse (View? newFocusedView, bool traversingDown = false)
  669. {
  670. // Pre-conditions
  671. if (!_hasFocus)
  672. {
  673. throw new InvalidOperationException ("SetHasFocusFalse should not be called if the view does not have focus.");
  674. }
  675. if (newFocusedView is { HasFocus: false })
  676. {
  677. throw new InvalidOperationException ("SetHasFocusFalse new focused view does not have focus.");
  678. }
  679. var thisAsAdornment = this as Adornment;
  680. View? superViewOrParent = thisAsAdornment?.Parent ?? SuperView;
  681. // If newFocusedVew is null, we need to find the view that should get focus, and SetFocus on it.
  682. if (!traversingDown && newFocusedView is null)
  683. {
  684. // Restore focus?
  685. if (superViewOrParent?._previouslyFocused is { CanFocus: true })
  686. {
  687. // TODO: Why don't we call RestoreFocus here?
  688. if (superViewOrParent._previouslyFocused != this && superViewOrParent._previouslyFocused.SetFocus ())
  689. {
  690. // The above will cause SetHasFocusFalse, so we can return
  691. Debug.Assert (!_hasFocus);
  692. return;
  693. }
  694. }
  695. // AdvanceFocus?
  696. if (superViewOrParent is { CanFocus: true })
  697. {
  698. if (superViewOrParent.AdvanceFocus (NavigationDirection.Forward, TabStop))
  699. {
  700. // The above might have SetHasFocusFalse, so we can return
  701. if (!_hasFocus)
  702. {
  703. return;
  704. }
  705. }
  706. if (superViewOrParent is { HasFocus: true, CanFocus: true })
  707. {
  708. newFocusedView = superViewOrParent;
  709. }
  710. }
  711. // Application.Navigation.GetFocused?
  712. View? applicationFocused = App?.Navigation?.GetFocused ();
  713. if (newFocusedView is null && applicationFocused != this && applicationFocused is { CanFocus: true })
  714. {
  715. // Temporarily ensure this view can't get focus
  716. bool prevCanFocus = _canFocus;
  717. _canFocus = false;
  718. bool restoredFocus = applicationFocused!.RestoreFocus ();
  719. _canFocus = prevCanFocus;
  720. if (restoredFocus)
  721. {
  722. // The above caused SetHasFocusFalse, so we can return
  723. Debug.Assert (!_hasFocus);
  724. return;
  725. }
  726. }
  727. // Application.TopRunnable?
  728. if (newFocusedView is null && App?.TopRunnableView is { CanFocus: true, HasFocus: false })
  729. {
  730. // Temporarily ensure this view can't get focus
  731. bool prevCanFocus = _canFocus;
  732. _canFocus = false;
  733. bool restoredFocus = App?.TopRunnableView.RestoreFocus () ?? false;
  734. _canFocus = prevCanFocus;
  735. if (App?.TopRunnableView is { CanFocus: true, HasFocus: true })
  736. {
  737. newFocusedView = App?.TopRunnableView;
  738. }
  739. else if (restoredFocus)
  740. {
  741. // The above caused SetHasFocusFalse, so we can return
  742. Debug.Assert (!_hasFocus);
  743. return;
  744. }
  745. }
  746. // No other focusable view to be found. Just "leave" us...
  747. }
  748. Debug.Assert (_hasFocus);
  749. // Before we can leave focus, we need to make sure that all views down the subview-hierarchy have left focus.
  750. View? mostFocused = MostFocused;
  751. if (mostFocused is { } && (newFocusedView is null || mostFocused != newFocusedView))
  752. {
  753. // Start at the bottom and work our way up to us
  754. View? bottom = mostFocused;
  755. while (bottom is { } && bottom != this)
  756. {
  757. if (bottom.HasFocus)
  758. {
  759. bottom.SetHasFocusFalse (newFocusedView, true);
  760. Debug.Assert (_hasFocus);
  761. }
  762. bottom = bottom.SuperView;
  763. }
  764. Debug.Assert (_hasFocus);
  765. }
  766. if (superViewOrParent is { })
  767. {
  768. superViewOrParent._previouslyFocused = this;
  769. }
  770. bool previousValue = HasFocus;
  771. Debug.Assert (_hasFocus);
  772. // Note, can't be cancelled.
  773. RaiseFocusChanging (HasFocus, !HasFocus, this, newFocusedView);
  774. // Even though the change can't be cancelled, some listener may have changed the focus to another view.
  775. if (!_hasFocus)
  776. {
  777. // Notify caused HasFocus to change to false.
  778. return;
  779. }
  780. // Get whatever peer has focus, if any so we can update our superview's _previouslyMostFocused
  781. View? focusedPeer = superViewOrParent?.Focused;
  782. // Set HasFocus false
  783. _hasFocus = false;
  784. RaiseFocusChanged (HasFocus, this, newFocusedView);
  785. if (_hasFocus)
  786. {
  787. // Notify caused HasFocus to change to true.
  788. return;
  789. }
  790. // Post-conditions - prove correctness
  791. if (HasFocus == previousValue)
  792. {
  793. throw new InvalidOperationException ("SetHasFocusFalse and the HasFocus value did not change.");
  794. }
  795. SetNeedsDraw ();
  796. }
  797. // TODO: CWP: FocusChanged should not be using event args derived from CancelEventArgs, as it is not cancellable.
  798. private void RaiseFocusChanged (bool newHasFocus, View? previousFocusedView, View? focusedView)
  799. {
  800. // If we are the most focused view, we need to set the focused view in Application.Navigation
  801. if (newHasFocus && focusedView?.Focused is null)
  802. {
  803. App?.Navigation?.SetFocused (focusedView);
  804. }
  805. // Call the virtual method
  806. OnHasFocusChanged (newHasFocus, previousFocusedView, focusedView);
  807. // Raise the event
  808. var args = new HasFocusEventArgs (newHasFocus, newHasFocus, previousFocusedView, focusedView);
  809. HasFocusChanged?.Invoke (this, args);
  810. if (newHasFocus || focusedView is null)
  811. {
  812. SuperView?.RaiseFocusedChanged (previousFocusedView, focusedView);
  813. }
  814. }
  815. /// <summary>
  816. /// Invoked after <see cref="HasFocus"/> has changed. This method is called before the <see cref="HasFocusChanged"/>
  817. /// event is raised.
  818. /// </summary>
  819. /// <remarks>
  820. /// <para>
  821. /// This event cannot be cancelled.
  822. /// </para>
  823. /// </remarks>
  824. /// <param name="newHasFocus">The new value of <see cref="View.HasFocus"/>.</param>
  825. /// <param name="previousFocusedView"></param>
  826. /// <param name="focusedView">The view that is now focused. May be <see langword="null"/></param>
  827. protected virtual void OnHasFocusChanged (bool newHasFocus, View? previousFocusedView, View? focusedView) { }
  828. /// <summary>Raised after <see cref="HasFocus"/> has changed.</summary>
  829. /// <remarks>
  830. /// <para>
  831. /// This event cannot be cancelled.
  832. /// </para>
  833. /// </remarks>
  834. public event EventHandler<HasFocusEventArgs>? HasFocusChanged;
  835. #endregion HasFocus
  836. #region Tab/Focus Handling
  837. /// <summary>
  838. /// Gets the subviews and Adornments of this view that are scoped to the specified behavior and direction. If behavior
  839. /// is null, all focusable subviews and
  840. /// Adornments are returned.
  841. /// </summary>
  842. /// <param name="direction"></param>
  843. /// <param name="behavior"></param>
  844. /// <returns></returns>
  845. internal View [] GetFocusChain (NavigationDirection direction, TabBehavior? behavior)
  846. {
  847. IEnumerable<View>? filteredSubViews;
  848. if (behavior.HasValue)
  849. {
  850. filteredSubViews = InternalSubViews?.Where (v => v.TabStop == behavior && v is { CanFocus: true, Visible: true, Enabled: true });
  851. }
  852. else
  853. {
  854. filteredSubViews = InternalSubViews?.Where (v => v is { CanFocus: true, Visible: true, Enabled: true });
  855. }
  856. // How about in Adornments?
  857. if (Padding is { CanFocus: true, Visible: true, Enabled: true } && Padding.TabStop == behavior)
  858. {
  859. filteredSubViews = filteredSubViews?.Append (Padding);
  860. }
  861. if (Border is { CanFocus: true, Visible: true, Enabled: true } && Border.TabStop == behavior)
  862. {
  863. filteredSubViews = filteredSubViews?.Append (Border);
  864. }
  865. if (Margin is { CanFocus: true, Visible: true, Enabled: true } && Margin.TabStop == behavior)
  866. {
  867. filteredSubViews = filteredSubViews?.Append (Margin);
  868. }
  869. if (direction == NavigationDirection.Backward)
  870. {
  871. filteredSubViews = filteredSubViews?.Reverse ();
  872. }
  873. return filteredSubViews?.ToArray () ?? Array.Empty<View> ();
  874. }
  875. private TabBehavior? _tabStop;
  876. /// <summary>
  877. /// Gets or sets the behavior of <see cref="AdvanceFocus"/> for keyboard navigation.
  878. /// </summary>
  879. /// <remarks>
  880. /// <remarks>
  881. /// <para>
  882. /// See the View Navigation Deep Dive for more information:
  883. /// <see href="https://gui-cs.github.io/Terminal.Gui/docs/navigation.html"/>
  884. /// </para>
  885. /// </remarks>
  886. /// ///
  887. /// <para>
  888. /// If <see langword="null"/> the tab stop has not been set and setting <see cref="CanFocus"/> to true will set it
  889. /// to
  890. /// <see cref="TabBehavior.TabStop"/>.
  891. /// </para>
  892. /// <para>
  893. /// TabStop is independent of <see cref="CanFocus"/>. If <see cref="CanFocus"/> is <see langword="false"/>, the
  894. /// view will not gain
  895. /// focus even if this property is set and vice versa.
  896. /// </para>
  897. /// <para>
  898. /// The default <see cref="TabBehavior.TabStop"/> keys are <see cref="Application.NextTabKey"/> (<c>Key.Tab</c>)
  899. /// and <see cref="Application.PrevTabKey"/> (<c>Key>Tab.WithShift</c>).
  900. /// </para>
  901. /// <para>
  902. /// The default <see cref="TabBehavior.TabGroup"/> keys are <see cref="Application.NextTabGroupKey"/> (
  903. /// <c>Key.F6</c>) and <see cref="Application.PrevTabGroupKey"/> (<c>Key>Key.F6.WithShift</c>).
  904. /// </para>
  905. /// </remarks>
  906. public TabBehavior? TabStop
  907. {
  908. get => _tabStop;
  909. set
  910. {
  911. if (_tabStop is { } && _tabStop == value)
  912. {
  913. return;
  914. }
  915. _tabStop = value;
  916. }
  917. }
  918. #endregion Tab/Focus Handling
  919. }