using System.Diagnostics;
namespace Terminal.Gui;
public partial class View // Focus and cross-view navigation management (TabStop, TabIndex, etc...)
{
/// Returns a value indicating if this View is currently on Top (Active)
public bool IsCurrentTop => Application.Current == this;
// BUGBUG: This API is poorly defined and implemented. It deeply intertwines the view hierarchy with the tab order.
/// Exposed as `internal` for unit tests. Indicates focus navigation direction.
internal enum NavigationDirection
{
/// Navigate forward.
Forward,
/// Navigate backwards.
Backward
}
/// 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)
{
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)
{
var args = new FocusEventArgs (this, enteringView);
Leave?.Invoke (this, args);
if (args.Handled)
{
return true;
}
return false;
}
/// Raised when the view is gaining (entering) focus. Can be cancelled.
///
/// Raised by the virtual method.
///
public event EventHandler Enter;
/// Raised when the view is losing (leaving) focus. Can be cancelled.
///
/// Raised by the virtual method.
///
public event EventHandler Leave;
private NavigationDirection _focusDirection;
///
/// 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;
}
}
}
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;
}
///
/// 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)
{
OnEnter (view);
}
else
{
OnLeave (view);
}
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);
Focused = null;
}
}
// 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.
// Makes it so CanFocus will update the SuperView's CanFocus property.
internal bool _addingViewSoCanFocusAlsoUpdatesSuperView;
// 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
private bool _oldCanFocus;
private bool _canFocus;
/// Gets or sets a value indicating whether this can be focused.
///
///
/// must also have set to .
///
///
/// When set to , if this view is focused, the focus will be set to the next focusable view.
///
///
/// When set to , the will be set to -1.
///
///
/// When set to , the values of and for all
/// subviews will be cached so that when is set back to , the subviews
/// will be restored to their previous values.
///
///
public bool CanFocus
{
get => _canFocus;
set
{
if (!_addingViewSoCanFocusAlsoUpdatesSuperView && IsInitialized && SuperView?.CanFocus == false && value)
{
throw new InvalidOperationException ("Cannot set CanFocus to true if the SuperView CanFocus is false!");
}
if (_canFocus == value)
{
return;
}
_canFocus = value;
switch (_canFocus)
{
case false when _tabIndex > -1:
TabIndex = -1;
break;
case true when SuperView?.CanFocus == false && _addingViewSoCanFocusAlsoUpdatesSuperView:
SuperView.CanFocus = true;
break;
}
if (_canFocus && _tabIndex == -1)
{
TabIndex = SuperView is { } ? SuperView._tabIndexes.IndexOf (this) : -1;
}
TabStop = _canFocus;
if (!_canFocus && SuperView?.Focused == this)
{
SuperView.Focused = null;
}
if (!_canFocus && HasFocus)
{
SetHasFocus (false, this);
SuperView?.FocusFirstOrLast ();
// If EnsureFocus () didn't set focus to a view, focus the next focusable view in the application
if (SuperView is { Focused: null })
{
SuperView.FocusNext ();
if (SuperView.Focused is null && Application.Current is { })
{
Application.Current.FocusNext ();
}
ApplicationOverlapped.BringOverlappedTopToFront ();
}
}
if (_subviews is { } && IsInitialized)
{
foreach (View view in _subviews)
{
if (view.CanFocus != value)
{
if (!value)
{
// Cache the old CanFocus and TabIndex so that they can be restored when CanFocus is changed back to true
view._oldCanFocus = view.CanFocus;
view._oldTabIndex = view._tabIndex;
view.CanFocus = false;
view._tabIndex = -1;
}
else
{
if (_addingViewSoCanFocusAlsoUpdatesSuperView)
{
view._addingViewSoCanFocusAlsoUpdatesSuperView = true;
}
// Restore the old CanFocus and TabIndex to the values they held before CanFocus was set to false
view.CanFocus = view._oldCanFocus;
view._tabIndex = view._oldTabIndex;
view._addingViewSoCanFocusAlsoUpdatesSuperView = false;
}
}
}
if (this is Toplevel && Application.Current!.Focused != this)
{
ApplicationOverlapped.BringOverlappedTopToFront ();
}
}
OnCanFocusChanged ();
SetNeedsDisplay ();
}
}
/// Raised when has been changed.
///
/// Raised by the virtual method.
///
public event EventHandler CanFocusChanged;
/// Invoked when the property from a view is changed.
///
/// Raises the event.
///
public virtual void OnCanFocusChanged () { CanFocusChanged?.Invoke (this, EventArgs.Empty); }
/// Returns the currently focused Subview inside this view, or if nothing is focused.
/// The currently focused Subview.
public View Focused { get; private set; }
///
/// Returns the most focused Subview in the chain of subviews (the leaf view that has the focus), or
/// if nothing is focused.
///
/// The most focused Subview.
public View MostFocused
{
get
{
if (Focused is null)
{
return null;
}
View most = Focused.MostFocused;
if (most is { })
{
return most;
}
return Focused;
}
}
/// Causes subview specified by to enter focus.
/// View.
private void SetFocus (View view)
{
if (view is null)
{
return;
}
//Console.WriteLine ($"Request to focus {view}");
if (!view.CanFocus || !view.Visible || !view.Enabled)
{
return;
}
if (Focused?._hasFocus == true && Focused == view)
{
return;
}
if ((Focused?._hasFocus == true && Focused?.SuperView == view) || view == this)
{
if (!view._hasFocus)
{
view._hasFocus = true;
}
return;
}
// Make sure that this view is a subview
View c;
for (c = view._superView; c != null; c = c._superView)
{
if (c == this)
{
break;
}
}
if (c is null)
{
throw new ArgumentException ("the specified view is not part of the hierarchy of this view");
}
if (Focused is { })
{
Focused.SetHasFocus (false, view);
}
View f = Focused;
Focused = view;
Focused.SetHasFocus (true, f);
Focused.FocusFirstOrLast ();
// Send focus upwards
if (SuperView is { })
{
SuperView.SetFocus (this);
}
else
{
SetFocus (this);
}
}
/// Causes this view to be focused and entire Superview hierarchy to have the focused order updated.
public void SetFocus ()
{
if (!CanBeVisible (this) || !Enabled)
{
if (HasFocus)
{
SetHasFocus (false, this);
}
return;
}
if (SuperView is { })
{
SuperView.SetFocus (this);
}
else
{
SetFocus (this);
}
}
///
/// INTERNAL helper for calling or based on
/// .
/// FocusDirection is not public. This API is thus non-deterministic from a public API perspective.
///
internal void FocusFirstOrLast ()
{
if (Focused is null && _subviews?.Count > 0)
{
if (FocusDirection == NavigationDirection.Forward)
{
FocusFirst ();
}
else
{
FocusLast ();
}
}
}
///
/// Focuses the first focusable view in if one exists. If there are no views in
/// then the focus is set to the view itself.
///
///
/// If , only subviews where has set
/// will be considered.
///
public void FocusFirst (bool overlappedOnly = false)
{
if (!CanBeVisible (this))
{
return;
}
if (_tabIndexes is null)
{
SuperView?.SetFocus (this);
return;
}
foreach (View view in _tabIndexes.Where (v => !overlappedOnly || v.Arrangement.HasFlag (ViewArrangement.Overlapped)))
{
if (view.CanFocus && view._tabStop && view.Visible && view.Enabled)
{
SetFocus (view);
return;
}
}
}
///
/// Focuses the last focusable view in if one exists. If there are no views in
/// then the focus is set to the view itself.
///
///
/// If , only subviews where has set
/// will be considered.
///
public void FocusLast (bool overlappedOnly = false)
{
if (!CanBeVisible (this))
{
return;
}
if (_tabIndexes is null)
{
SuperView?.SetFocus (this);
return;
}
foreach (View view in _tabIndexes.Where (v => !overlappedOnly || v.Arrangement.HasFlag (ViewArrangement.Overlapped)).Reverse ())
{
if (view.CanFocus && view._tabStop && view.Visible && view.Enabled)
{
SetFocus (view);
return;
}
}
}
///
/// Focuses the previous view in . If there is no previous view, the focus is set to the
/// view itself.
///
/// if previous was focused, otherwise.
public bool FocusPrev ()
{
if (!CanBeVisible (this))
{
return false;
}
FocusDirection = NavigationDirection.Backward;
if (TabIndexes is null || TabIndexes.Count == 0)
{
return false;
}
if (Focused is null)
{
FocusLast ();
return Focused != null;
}
int focusedIdx = -1;
for (int i = TabIndexes.Count; i > 0;)
{
i--;
View w = TabIndexes [i];
if (w.HasFocus)
{
if (w.FocusPrev ())
{
return true;
}
focusedIdx = i;
continue;
}
if (w.CanFocus && focusedIdx != -1 && w._tabStop && w.Visible && w.Enabled)
{
Focused.SetHasFocus (false, w);
// If the focused view is overlapped don't focus on the next if it's not overlapped.
if (Focused.Arrangement.HasFlag (ViewArrangement.Overlapped) && !w.Arrangement.HasFlag (ViewArrangement.Overlapped))
{
FocusLast (true);
return true;
}
// If the focused view is not overlapped and the next is, skip it
if (!Focused.Arrangement.HasFlag (ViewArrangement.Overlapped) && w.Arrangement.HasFlag (ViewArrangement.Overlapped))
{
continue;
}
if (w.CanFocus && w._tabStop && w.Visible && w.Enabled)
{
w.FocusLast ();
}
SetFocus (w);
return true;
}
}
// There's no prev view in tab indexes.
if (Focused is { })
{
// Leave Focused
Focused.SetHasFocus (false, this);
if (Focused.Arrangement.HasFlag (ViewArrangement.Overlapped))
{
FocusLast (true);
return true;
}
// Signal to caller no next view was found
Focused = null;
}
return false;
}
///
/// Focuses the next view in . If there is no next view, the focus is set to the view
/// itself.
///
/// if focus was changed to another subview (or stayed on this one), otherwise.
public bool FocusNext ()
{
if (!CanBeVisible (this))
{
return false;
}
FocusDirection = NavigationDirection.Forward;
if (TabIndexes is null || TabIndexes.Count == 0)
{
return false;
}
if (Focused is null)
{
FocusFirst ();
return Focused is { };
}
int focusedIdx = -1;
for (var i = 0; i < TabIndexes.Count; i++)
{
View w = TabIndexes [i];
if (w.HasFocus)
{
// A subview has focus, tell *it* to FocusNext
if (w.FocusNext ())
{
// The subview changed which of it's subviews had focus
return true;
}
Debug.Assert (w.HasFocus);
// The subview has no subviews that can be next. Cache that we found a focused subview.
focusedIdx = i;
continue;
}
// The subview does not have focus, but at least one other that can. Can this one be focused?
if (focusedIdx != -1 && w.CanFocus && w._tabStop && w.Visible && w.Enabled)
{
// Make Focused Leave
Focused.SetHasFocus (false, w);
//// If the focused view is overlapped don't focus on the next if it's not overlapped.
//if (Focused.Arrangement.HasFlag (ViewArrangement.Overlapped)/* && !w.Arrangement.HasFlag (ViewArrangement.Overlapped)*/)
//{
// return false;
//}
//// If the focused view is not overlapped and the next is, skip it
//if (!Focused.Arrangement.HasFlag (ViewArrangement.Overlapped) && w.Arrangement.HasFlag (ViewArrangement.Overlapped))
//{
// continue;
//}
// QUESTION: Why do we check these again here?
if (w.CanFocus && w._tabStop && w.Visible && w.Enabled)
{
w.FocusFirst ();
}
SetFocus (w);
return true;
}
}
// There's no next view in tab indexes.
if (Focused is { })
{
// Leave
Focused.SetHasFocus (false, this);
//if (Focused.Arrangement.HasFlag (ViewArrangement.Overlapped))
//{
// FocusFirst (true);
// return true;
//}
// Signal to caller no next view was found; this will enable it to make a peer
// or view up the superview hierarchy have focus.
Focused = null;
}
return false;
}
private View GetMostFocused (View view)
{
if (view is null)
{
return null;
}
return view.Focused is { } ? GetMostFocused (view.Focused) : view;
}
#region Tab/Focus Handling
private List _tabIndexes;
// TODO: This should be a get-only property?
// BUGBUG: This returns an AsReadOnly list, but isn't declared as such.
/// Gets a list of the subviews that are a .
/// The tabIndexes.
public IList TabIndexes => _tabIndexes?.AsReadOnly () ?? _empty;
// TODO: Change this to int? and use null to indicate the view is not in the tab order.
private int _tabIndex = -1;
private int _oldTabIndex;
///
/// Indicates the index of the current from the list. See also:
/// .
///
///
///
/// If the value is -1, the view is not part of the tab order.
///
///
/// On set, if is , will be set to -1.
///
///
/// On set, if is or has not TabStops, will
/// be set to 0.
///
///
/// On set, if has only one TabStop, will be set to 0.
///
///
public int TabIndex
{
get => _tabIndex;
set
{
if (!CanFocus)
{
// BUGBUG: Property setters should set the property to the value passed in and not have side effects.
_tabIndex = -1;
return;
}
if (SuperView?._tabIndexes is null || SuperView?._tabIndexes.Count == 1)
{
// BUGBUG: Property setters should set the property to the value passed in and not have side effects.
_tabIndex = 0;
return;
}
if (_tabIndex == value && TabIndexes.IndexOf (this) == value)
{
return;
}
_tabIndex = value > SuperView!.TabIndexes.Count - 1 ? SuperView._tabIndexes.Count - 1 :
value < 0 ? 0 : value;
_tabIndex = GetGreatestTabIndexInSuperView (_tabIndex);
if (SuperView._tabIndexes.IndexOf (this) != _tabIndex)
{
// BUGBUG: we have to use _tabIndexes and not TabIndexes because TabIndexes returns is a read-only version of _tabIndexes
SuperView._tabIndexes.Remove (this);
SuperView._tabIndexes.Insert (_tabIndex, this);
ReorderSuperViewTabIndexes ();
}
}
}
///
/// Gets the greatest of the 's that is less
/// than or equal to .
///
///
/// The minimum of and the 's .
private int GetGreatestTabIndexInSuperView (int idx)
{
var i = 0;
foreach (View superViewTabStop in SuperView._tabIndexes)
{
if (superViewTabStop._tabIndex == -1 || superViewTabStop == this)
{
continue;
}
i++;
}
return Math.Min (i, idx);
}
///
/// Re-orders the s of the views in the 's .
///
private void ReorderSuperViewTabIndexes ()
{
var i = 0;
foreach (View superViewTabStop in SuperView._tabIndexes)
{
if (superViewTabStop._tabIndex == -1)
{
continue;
}
superViewTabStop._tabIndex = i;
i++;
}
}
private bool _tabStop = true;
///
/// Gets or sets whether the view is a stop-point for keyboard navigation of focus. Will be
/// only if is . Set to to prevent the
/// view from being a stop-point for keyboard navigation.
///
///
/// The default keyboard navigation keys are Key.Tab and Key>Tab.WithShift. These can be changed by
/// modifying the key bindings (see ) of the SuperView.
///
public bool TabStop
{
get => _tabStop;
set
{
if (_tabStop == value)
{
return;
}
_tabStop = CanFocus && value;
}
}
#endregion Tab/Focus Handling
}