From 99905032960ac15a4094b655d2119cbe130e1d2c Mon Sep 17 00:00:00 2001 From: Tig Date: Thu, 1 Aug 2024 16:38:30 -0600 Subject: [PATCH] WIP: Focus re-design --- .../Application/Application.Navigation.cs | 31 +- .../View/Navigation/FocusEventArgs.cs | 14 +- Terminal.Gui/View/View.Navigation.cs | 724 ++++++++++-------- Terminal.Gui/View/View.cs | 5 + docfx/docs/navigation.md | 1 + 5 files changed, 440 insertions(+), 335 deletions(-) diff --git a/Terminal.Gui/Application/Application.Navigation.cs b/Terminal.Gui/Application/Application.Navigation.cs index fec0c5266..b51d56b6e 100644 --- a/Terminal.Gui/Application/Application.Navigation.cs +++ b/Terminal.Gui/Application/Application.Navigation.cs @@ -13,27 +13,32 @@ public static class ApplicationNavigation private static View? _focused = null; /// - /// Gets or sets the most focused in the application. + /// Gets the most focused in the application, if there is one. + /// + public static View? GetFocused () { return _focused; } + + /// + /// INTERNAL method to record the most focused in the application. /// /// - /// When set, raises . + /// Raises . /// - public static View? Focused + internal static void SetFocused (View? value) { - get => _focused; - set + if (_focused == value) { - if (_focused == value) - { - return; - } - - _focused = value; - - FocusedChanged?.Invoke (null, EventArgs.Empty); + return; } + + _focused = value; + + FocusedChanged?.Invoke (null, EventArgs.Empty); + + return; } + // TODO: Support Application canceling the HasFocus change + /// /// Gets whether is in the Subview hierarchy of . /// diff --git a/Terminal.Gui/View/Navigation/FocusEventArgs.cs b/Terminal.Gui/View/Navigation/FocusEventArgs.cs index 6d8d28267..2af837d14 100644 --- a/Terminal.Gui/View/Navigation/FocusEventArgs.cs +++ b/Terminal.Gui/View/Navigation/FocusEventArgs.cs @@ -1,9 +1,9 @@ namespace Terminal.Gui; -/// Defines the event arguments for +/// Defines the event arguments for public class FocusEventArgs : EventArgs { - /// Constructs. + /// Initializes a new instance. /// The view that is losing focus. /// The view that is gaining focus. public FocusEventArgs (View leaving, View entering) { @@ -12,16 +12,14 @@ public class FocusEventArgs : EventArgs } /// - /// Indicates if the current focus event has already been processed and the driver should stop notifying any other - /// event subscriber. It's important to set this value to true specially when updating any View's layout from inside the - /// subscriber method. + /// Gets or sets whether the event should be canceled. Set to to prevent the focus change. /// - public bool Handled { get; set; } + public bool Cancel { get; set; } - /// Indicates the view that is losing focus. + /// Gets or sets the view that is losing focus. public View Leaving { get; set; } - /// Indicates the view that is gaining focus. + /// Gets or sets the view that is gaining focus. public View Entering { get; set; } } diff --git a/Terminal.Gui/View/View.Navigation.cs b/Terminal.Gui/View/View.Navigation.cs index ded4e4395..afa8498df 100644 --- a/Terminal.Gui/View/View.Navigation.cs +++ b/Terminal.Gui/View/View.Navigation.cs @@ -5,8 +5,313 @@ namespace Terminal.Gui; public partial class View // Focus and cross-view navigation management (TabStop, TabIndex, etc...) { + #region HasFocus - private NavigationDirection _focusDirection; + // Backs `HasFocus` and is the ultimate source of truth whether a View has focus or not. + private bool _hasFocus; + + /// + /// Gets or sets whether this view has focus. + /// + /// + /// + /// Only Views that are visible, enabled, and have set to are focusable. If + /// these conditions are not met when this property is set to will not change. + /// + /// + /// Setting this property causes the and virtual methods (and and + /// events to be raised). If the event is cancelled, will not be changed. + /// + /// + /// Setting this property to will recursively set to + /// for all SuperViews up the hierarchy. + /// + /// + /// Setting this property to will cause the subview furthest down the hierarchy that is + /// focusable to also gain focus (as long as + /// + /// + /// Setting this property to will recursively set to + /// for any focused subviews. + /// + /// + public bool HasFocus + { + set => SetHasFocus (value, this); + get => _hasFocus; + } + + /// + /// Causes this view to be focused. Calling this method has the same effect as setting to + /// . + /// + public void SetFocus () + { + HasFocus = true; + } + + /// + /// Internal API that sets . This method is called by `HasFocus_set` and other methods that + /// need to set or remove focus from a view. + /// + /// The new setting for . + /// The view that will be gaining or losing focus. + /// + /// If is and there is a focused subview ( + /// is not ), + /// this method will recursively remove focus from any focused subviews of . + /// + private bool SetHasFocus (bool newHasFocus, View view) + { + if (HasFocus != newHasFocus) + { + if (newHasFocus) + { + Debug.Assert (view is null || SuperView is null || ApplicationNavigation.IsInHierarchy (SuperView, view)); + + if (OnEnter (view)) + { + // The change happened + // HasFocus is now true + } + else + { + // The event was cancelled or view is not focusable + return false; + } + } + else + { + if (OnLeave (view)) + { + // The change happened + // HasFocus is now false + } + else + { + // The event was cancelled or view was not focused + return false; + } + } + + SetNeedsDisplay (); + } + + return true; + } + + /// + /// Called when view is entering focus. This method is called by and other methods that + /// set or remove focus from a view. + /// + /// The previously focused view. If there is no previously focused view. + /// if was changed to . + /// + private bool EnterFocus ([CanBeNull] View leavingView) + { + // Pre-conditions + if (_hasFocus) + { + throw new InvalidOperationException ($"EnterFocus should not be called if the view already has focus."); + } + + if (CanFocus && SuperView?.CanFocus == false) + { + throw new InvalidOperationException ($"It is not possible to EnterFocus if the View's SuperView has CanFocus = false."); + } + + if (!CanBeVisible (this) || !Enabled) + { + return false; + } + + if (!CanFocus) + { + return false; + } + + // Verify all views up the superview-hierarchy are focusable. + if (SuperView is { }) + { + View super = SuperView; + + while (super is { }) + { + // TODO: Check Visible & Enabled too! + if (!super.CanFocus) + { + return false; + } + super = super.SuperView; + } + } + + bool previousValue = HasFocus; + + // Call the virtual method + if (OnEnter (leavingView)) + { + // The event was cancelled + return false; + } + + var args = new FocusEventArgs (leavingView, this); + Enter?.Invoke (this, args); + if (args.Cancel) + { + // The event was cancelled + return false; + } + + // Now, these things need to be true for us to set _hasFocus to true: + // All views down v's view-hierarchy need to gain focus, if they don't already have it. + // Any of them may cancel gaining focus, so we need to do that first. + + _hasFocus = true; + + // By setting _hasFocus to true we've definitively changed HasFocus for this view + + if (SuperView is { }) + { + SuperView.Focused = this; + } + + if (!RestoreFocus (TabStop)) + { + // Couldn't restore focus, so use Advance to navigate + if (!AdvanceFocus (NavigationDirection.Forward, TabStop)) + { + // Couldn't advance, so we're the most-focusable view in the application + ApplicationNavigation.SetFocused (this); + } + } + + // All views down the superview-hierarchy need to have HasFocus == true + + // Post-conditions - prove correctness + if (HasFocus == previousValue) + { + throw new InvalidOperationException ($"EnterFocus was not cancelled and the HasFocus value did not change."); + } + return true; + } + + /// Virtual method invoked when this view is gaining focus (entering). + /// The view that is leaving focus. + /// , if the event is to be cancelled, otherwise. + protected virtual bool OnEnter ([CanBeNull] View leavingView) + { + return false; + } + + /// Raised when the view is gaining (entering) focus. Can be cancelled. + /// + /// Raised by . + /// + public event EventHandler Enter; + + /// + /// Called when view is entering focus. This method is called by and other methods that + /// set or remove focus from a view. + /// + /// The previously focused view. If there is no previously focused view. + /// if was changed. + /// + private bool LeaveFocus ([CanBeNull] View enteringView) + { + // Pre-conditions + if (_hasFocus) + { + throw new InvalidOperationException ($"LeaveFocus should not be called if the view does not have focus."); + } + + // Before we can leave focus, we need to make sure that all views down the subview-hierarchy have left focus. + // Any of them may cancel losing focus, so we need to do that first. + if (ApplicationNavigation.GetFocused () != this) + { + // Save the most focused view in the subview-hierarchy + View originalBottom = ApplicationNavigation.GetFocused (); + // Start at the bottom and work our way up to us + View bottom = originalBottom; + + while (bottom is { } && bottom != this) + { + if (bottom.HasFocus && !bottom.SetHasFocus (false, enteringView)) + { + // The change was cancelled + return false; + } + bottom = bottom.SuperView; + } + + PreviouslyMostFocused = originalBottom; + } + + bool previousValue = HasFocus; + + // Call the virtual method + if (OnLeave (enteringView)) + { + // The event was cancelled + return false; + } + + var args = new FocusEventArgs (enteringView, this); + Leave?.Invoke (this, args); + if (args.Cancel) + { + // The event was cancelled + return false; + } + + Focused = null; + + if (SuperView is { }) + { + SuperView.Focused = null; + } + + _hasFocus = false; + + if (ApplicationNavigation.GetFocused () != this) + { + PreviouslyMostFocused = null; + + if (SuperView is { }) + { + SuperView.PreviouslyMostFocused = this; + } + } + + // Post-conditions - prove correctness + if (HasFocus == previousValue) + { + throw new InvalidOperationException ($"LeaveFocus was not cancelled and the HasFocus value did not change."); + } + return true; + } + + /// + /// Caches the most focused subview when this view is losing focus. This is used by . + /// + [CanBeNull] + internal View PreviouslyMostFocused { get; set; } + + /// Virtual method invoked when this view is losing focus (leaving). + /// The view that is gaining focus. + /// , if the event is to be cancelled, otherwise. + protected virtual bool OnLeave ([CanBeNull] View enteringView) + { + return false; + } + + /// Raised when the view is gaining (entering) focus. Can be cancelled. + /// + /// Raised by . + /// + public event EventHandler Leave; + + #endregion HasFocus /// /// Advances the focus to the next or previous view in , based on @@ -19,20 +324,18 @@ public partial class View // Focus and cross-view navigation management (TabStop /// /// /// - /// If will advance into ... + /// /// /// if focus was changed to another subview (or stayed on this one), /// otherwise. /// public bool AdvanceFocus (NavigationDirection direction, TabBehavior? behavior) { - if (!CanBeVisible (this)) + if (!CanBeVisible (this)) // TODO: is this check needed? { return false; } - FocusDirection = direction; - if (TabIndexes is null || TabIndexes.Count == 0) { return false; @@ -71,40 +374,13 @@ public partial class View // Focus and cross-view navigation management (TabStop { if (behavior == TabBehavior.TabGroup && behavior == TabStop && SuperView?.TabStop == TabBehavior.TabGroup) { - // Go up the hierarchy - // Leave + // Go up the hierarchy and leave Focused.SetHasFocus (false, this); - // Signal that nothing is focused, and callers should try a peer-subview - Focused = null; + // TODO: Should we check the return value of SetHasFocus? return false; } - - //Focused.RestoreFocus (TabBehavior.TabStop); - - //if (Focused is { }) - //{ - // return true; - //} - - // Wrap around - //if (SuperView is {}) - //{ - // if (direction == NavigationDirection.Forward) - // { - // return false; - // } - // else - // { - // return false; - - // //SuperView.FocusFirst (groupOnly); - // } - // return true; - //} - //next = index.Length - 1; - } View view = index [next]; @@ -137,6 +413,104 @@ public partial class View // Focus and cross-view navigation management (TabStop return false; } + + /// + /// INTERNAL API to restore focus to the subview that had focus before this view lost focused. + /// + /// + /// Returns true if focus was restored to a subview, false otherwise. + /// + internal bool RestoreFocus (TabBehavior? behavior) + { + if (Focused is null && _subviews?.Count > 0) + { + // TODO: Find the previous focused view and set focus to it + if (PreviouslyMostFocused is { } && PreviouslyMostFocused.TabStop == behavior) + { + SetFocus (PreviouslyMostFocused); + + return true; + } + return true; + } + + return false; + } + + /// + /// Internal API that causes to enter focus. + /// does not need to be a subview. + /// Recursively sets focus DOWN in the view hierarchy. + /// + /// + private void SetFocus (View viewToEnterFocus) + { + if (viewToEnterFocus is null) + { + return; + } + + if (!viewToEnterFocus.CanFocus || !viewToEnterFocus.Visible || !viewToEnterFocus.Enabled) + { + return; + } + + // If viewToEnterFocus is already the focused view, don't do anything + if (Focused?._hasFocus == true && Focused == viewToEnterFocus) + { + return; + } + + // If a subview has focus and viewToEnterFocus is the focused view's superview OR viewToEnterFocus is this view, + // then make viewToEnterFocus.HasFocus = true and return + if ((Focused?._hasFocus == true && Focused?.SuperView == viewToEnterFocus) || viewToEnterFocus == this) + { + if (!viewToEnterFocus._hasFocus) + { + viewToEnterFocus._hasFocus = true; + } + + return; + } + + // Make sure that viewToEnterFocus is a subview of this view + View c; + + for (c = viewToEnterFocus._superView; c != null; c = c._superView) + { + if (c == this) + { + break; + } + } + + if (c is null) + { + throw new ArgumentException (@$"The specified view {viewToEnterFocus} is not part of the hierarchy of {this}."); + } + + // If a subview has focus, make it leave focus. This will leave focus up the hierarchy. + Focused?.SetHasFocus (false, viewToEnterFocus); + + // make viewToEnterFocus Focused and enter focus + View f = Focused; + Focused = viewToEnterFocus; + Focused?.SetHasFocus (true, f, true); + Focused?.FocusDeepest (null, NavigationDirection.Forward); + + // Recursively set focus down the view hierarchy + if (SuperView is { }) + { + SuperView.SetFocus (this); + } + else + { + // If there is no SuperView, then this is a top-level view + SetFocus (this); + } + } + + #if AUTO_CANFOCUS // 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. // Set to true in Add() to indicate that the view being added to a SuperView has CanFocus=true. @@ -286,14 +660,9 @@ public partial class View // Focus and cross-view navigation management (TabStop /// public event EventHandler CanFocusChanged; - /// Raised when the view is gaining (entering) focus. Can be cancelled. - /// - /// Raised by the virtual method. - /// - public event EventHandler Enter; - /// Returns the currently focused Subview inside this view, or if nothing is focused. /// The currently focused Subview. + [CanBeNull] public View Focused { get; private set; } /// @@ -354,38 +723,9 @@ public partial class View // Focus and cross-view navigation management (TabStop return null; } - private bool _hasFocus; - - /// - /// Gets or sets whether this view has focus. - /// - /// - /// - /// Causes the and virtual methods (and and - /// events to be raised) when the value changes. - /// - /// - /// Setting this property to will recursively set to - /// - /// for any focused subviews. - /// - /// - public bool HasFocus - { - // Force the specified view to have focus - set => SetHasFocus (value, this, true); - get => _hasFocus; - } - /// Returns a value indicating if this View is currently on Top (Active) public bool IsCurrentTop => Application.Current == this; - /// Raised when the view is losing (leaving) focus. Can be cancelled. - /// - /// Raised by the virtual method. - /// - public event EventHandler Leave; - /// /// Returns the most focused Subview in the chain of subviews (the leaf view that has the focus), or /// if nothing is focused. @@ -416,251 +756,7 @@ public partial class View // Focus and cross-view navigation management (TabStop /// Raises the event. /// public virtual void OnCanFocusChanged () { CanFocusChanged?.Invoke (this, EventArgs.Empty); } - - // BUGBUG: The focus API is poorly defined and implemented. It deeply intertwines the view hierarchy with the tab order. - - /// Invoked when this view is gaining focus (entering). - /// The view that is leaving focus. - /// , if the event was handled, otherwise. - /// - /// - /// Overrides must call the base class method to ensure that the event is raised. If the event - /// is handled, the method should return . - /// - /// - public virtual bool OnEnter (View leavingView) - { - // BUGBUG: _hasFocus should ALWAYS be false when this method is called. - if (_hasFocus) - { - Debug.WriteLine ($"BUGBUG: HasFocus should be false when OnEnter is called - Leaving: {leavingView} Entering: {this}"); - - // return true; - } - - var args = new FocusEventArgs (leavingView, this); - Enter?.Invoke (this, args); - - if (args.Handled) - { - return true; - } - - return false; - } - - /// Invoked when this view is losing focus (leaving). - /// The view that is entering focus. - /// , if the event was handled, otherwise. - /// - /// - /// Overrides must call the base class method to ensure that the event is raised. If the event - /// is handled, the method should return . - /// - /// - public virtual bool OnLeave (View enteringView) - { - // BUGBUG: _hasFocus should ALWAYS be true when this method is called. - if (!_hasFocus) - { - Debug.WriteLine ($"BUGBUG: HasFocus should be true when OnLeave is called - Leaving: {this} Entering: {enteringView}"); - - //return true; - } - - var args = new FocusEventArgs (this, enteringView); - Leave?.Invoke (this, args); - - if (args.Handled) - { - return true; - } - - return false; - } - - /// - /// Causes this view to be focused. All focusable views up the Superview hierarchy will also be focused. - /// - public void SetFocus () - { - if (!CanBeVisible (this) || !Enabled) - { - if (HasFocus) - { - // If this view is focused, make it leave focus - SetHasFocus (false, this); - } - - return; - } - - // Recursively set focus upwards in the view hierarchy - if (SuperView is { }) - { - SuperView.SetFocus (this); - } - else - { - SetFocus (this); - } - } - - /// - /// INTERNAL API that gets or sets the focus direction for this view and all subviews. - /// Setting this property will set the focus direction for all views up the SuperView hierarchy. - /// - internal NavigationDirection FocusDirection - { - get => SuperView?.FocusDirection ?? _focusDirection; - set - { - if (SuperView is { }) - { - SuperView.FocusDirection = value; - } - else - { - _focusDirection = value; - } - } - } - - /// - /// INTERNAL helper for calling or based on - /// . - /// FocusDirection is not public. This API is thus non-deterministic from a public API perspective. - /// - internal void RestoreFocus (TabBehavior? behavior) - { - if (Focused is null && _subviews?.Count > 0) - { - FocusDeepest (behavior, FocusDirection); - } - } - - /// - /// Internal API that causes to enter focus. - /// does not need to be a subview. - /// Recursively sets focus DOWN in the view hierarchy. - /// - /// - private void SetFocus (View viewToEnterFocus) - { - if (viewToEnterFocus is null) - { - return; - } - - if (!viewToEnterFocus.CanFocus || !viewToEnterFocus.Visible || !viewToEnterFocus.Enabled) - { - return; - } - - // If viewToEnterFocus is already the focused view, don't do anything - if (Focused?._hasFocus == true && Focused == viewToEnterFocus) - { - return; - } - - // If a subview has focus and viewToEnterFocus is the focused view's superview OR viewToEnterFocus is this view, - // then make viewToEnterFocus.HasFocus = true and return - if ((Focused?._hasFocus == true && Focused?.SuperView == viewToEnterFocus) || viewToEnterFocus == this) - { - if (!viewToEnterFocus._hasFocus) - { - viewToEnterFocus._hasFocus = true; - } - - return; - } - - // Make sure that viewToEnterFocus is a subview of this view - View c; - - for (c = viewToEnterFocus._superView; c != null; c = c._superView) - { - if (c == this) - { - break; - } - } - - if (c is null) - { - throw new ArgumentException (@$"The specified view {viewToEnterFocus} is not part of the hierarchy of {this}."); - } - - // If a subview has focus, make it leave focus. This will leave focus up the hierarchy. - Focused?.SetHasFocus (false, viewToEnterFocus); - - // make viewToEnterFocus Focused and enter focus - View f = Focused; - Focused = viewToEnterFocus; - Focused?.SetHasFocus (true, f, true); - Focused?.FocusDeepest (null, NavigationDirection.Forward); - - // Recursively set focus down the view hierarchy - if (SuperView is { }) - { - SuperView.SetFocus (this); - } - else - { - // If there is no SuperView, then this is a top-level view - SetFocus (this); - } - } - - /// - /// Internal API that sets . This method is called by HasFocus_set and other methods that - /// need to set or remove focus from a view. - /// - /// The new setting for . - /// The view that will be gaining or losing focus. - /// - /// to force Enter/Leave on regardless of whether it - /// already HasFocus or not. - /// - /// - /// If is and there is a focused subview ( - /// is not ), - /// this method will recursively remove focus from any focused subviews of . - /// - private void SetHasFocus (bool newHasFocus, View view, bool force = false) - { - if (HasFocus != newHasFocus || force) - { - _hasFocus = newHasFocus; - - if (newHasFocus) - { - Debug.Assert (view is null || SuperView is null || ApplicationNavigation.IsInHierarchy (SuperView, view)); - OnEnter (view); - ApplicationNavigation.Focused = this; - - //_hasFocus = true; - } - else - { - OnLeave (view); - - //_hasFocus = false; - } - - SetNeedsDisplay (); - } - - // Remove focus down the chain of subviews if focus is removed - if (!newHasFocus && Focused is { }) - { - View f = Focused; - f.OnLeave (view); - f.SetHasFocus (false, view, true); - Focused = null; - } - } - + #region Tab/Focus Handling #nullable enable diff --git a/Terminal.Gui/View/View.cs b/Terminal.Gui/View/View.cs index 60e790d5a..848f5e5bf 100644 --- a/Terminal.Gui/View/View.cs +++ b/Terminal.Gui/View/View.cs @@ -387,6 +387,11 @@ public partial class View : Responder, ISupportInitializeNotification /// Event fired when the value is being changed. public event EventHandler VisibleChanged; + /// + /// INTERNAL method for determining if all the specified view and all views up the Superview hierarchy are visible. + /// + /// The view to test. + /// if `view.Visible` is or any Superview is not visible, otherwise. private static bool CanBeVisible (View view) { if (!view.Visible) diff --git a/docfx/docs/navigation.md b/docfx/docs/navigation.md index dd73e96bb..bfb0736d3 100644 --- a/docfx/docs/navigation.md +++ b/docfx/docs/navigation.md @@ -244,3 +244,4 @@ A bunch of the above is the proposed design. Eventually `Toplevel` will be delet - The old `Toplevel` and `OverlappedTop` code. Only utilized when `IsOverlappedContainer == true` - The new code path that treats all Views the same but relies on the appropriate combination of `TabBehavior` and `ViewArrangement` settings as well as `IRunnable`. +