#nullable enable
namespace Terminal.Gui;
public partial class View // Keyboard APIs
{
///
/// Helper to configure all things keyboard related for a View. Called from the View constructor.
///
private void SetupKeyboard ()
{
KeyBindings = new (this);
KeyBindings.Add (Key.Space, Command.Select);
KeyBindings.Add (Key.Enter, Command.Accept);
HotKeyBindings = new (this);
// Note, setting HotKey will bind HotKey to Command.HotKey
HotKeySpecifier = (Rune)'_';
TitleTextFormatter.HotKeyChanged += TitleTextFormatter_HotKeyChanged;
}
///
/// Helper to dispose all things keyboard related for a View. Called from the View Dispose method.
///
private void DisposeKeyboard () { TitleTextFormatter.HotKeyChanged -= TitleTextFormatter_HotKeyChanged; }
#region HotKey Support
/// Raised when the is changed.
public event EventHandler? HotKeyChanged;
private Key _hotKey = new ();
private void TitleTextFormatter_HotKeyChanged (object? sender, KeyChangedEventArgs e) { HotKeyChanged?.Invoke (this, e); }
///
/// Gets or sets the hot key defined for this view. Pressing the hot key on the keyboard while this view has focus will
/// invoke . By default, the HotKey is set to the first character of
/// that is prefixed with .
///
/// A HotKey is a keypress that causes a visible UI item to perform an action. For example, in a Dialog,
/// with a Button with the text of "_Text" Alt+T will cause the button to gain focus and to raise its
/// event.
/// Or, in a
/// with "_File _Edit", Alt+F will select (show) the "_File" menu. If the "_File" menu
/// has a
/// sub-menu of "_New" Alt+N or N will ONLY select the "_New" sub-menu if the "_File" menu is already
/// opened.
///
///
/// View subclasses can use to
/// define the
/// behavior of the hot key.
///
///
///
/// See for an overview of Terminal.Gui keyboard APIs.
///
/// This is a helper API for configuring a key binding for the hot key. By default, this property is set whenever
/// changes.
///
///
/// By default, when the Hot Key is set, key bindings are added for both the base key (e.g.
/// ) and the Alt-shifted key (e.g. .
/// ). This behavior can be overriden by overriding
/// .
///
///
/// By default, when the HotKey is set to through key bindings will
/// be added for both the un-shifted and shifted versions. This means if the HotKey is , key
/// bindings for Key.A and Key.A.WithShift will be added. This behavior can be overriden by
/// overriding .
///
/// If the hot key is changed, the event is fired.
/// Set to to disable the hot key.
///
public Key HotKey
{
get => _hotKey;
set
{
if (value is null)
{
throw new ArgumentException (
@"HotKey must not be null. Use Key.Empty to clear the HotKey.",
nameof (value)
);
}
if (AddKeyBindingsForHotKey (_hotKey, value))
{
// This will cause TextFormatter_HotKeyChanged to be called, firing HotKeyChanged
// BUGBUG: _hotkey should be set BEFORE setting TextFormatter.HotKey
_hotKey = value;
TitleTextFormatter.HotKey = value;
}
}
}
///
/// Adds key bindings for the specified HotKey. Useful for views that contain multiple items that each have their
/// own HotKey such as .
///
///
///
/// By default, key bindings are added for both the base key (e.g. ) and the Alt-shifted key
/// (e.g. Key.D3.WithAlt) This behavior can be overriden by overriding
/// .
///
///
/// By default, when is through key bindings
/// will be added for both the un-shifted and shifted versions. This means if the HotKey is ,
/// key bindings for Key.A and Key.A.WithShift will be added. This behavior can be overriden by
/// overriding .
///
///
/// The HotKey is replacing. Key bindings for this key will be removed.
/// The new HotKey. If bindings will be removed.
/// Arbitrary context that can be associated with this key binding.
/// if the HotKey bindings were added.
///
public virtual bool AddKeyBindingsForHotKey (Key prevHotKey, Key hotKey, object? context = null)
{
if (_hotKey == hotKey)
{
return false;
}
Key newKey = hotKey;
Key baseKey = newKey.NoAlt.NoShift.NoCtrl;
if (newKey != Key.Empty && (baseKey == Key.Space || Rune.IsControl (baseKey.AsRune)))
{
throw new ArgumentException (@$"HotKey must be a printable (and non-space) key ({hotKey}).");
}
if (newKey != baseKey)
{
if (newKey.IsCtrl)
{
throw new ArgumentException (@$"HotKey does not support CtrlMask ({hotKey}).");
}
// Strip off the shift mask if it's A...Z
if (baseKey.IsKeyCodeAtoZ)
{
newKey = newKey.NoShift;
}
// Strip off the Alt mask
newKey = newKey.NoAlt;
}
// Remove base version
if (HotKeyBindings.TryGet (prevHotKey, out _))
{
HotKeyBindings.Remove (prevHotKey);
}
// Remove the Alt version
if (HotKeyBindings.TryGet (prevHotKey.WithAlt, out _))
{
HotKeyBindings.Remove (prevHotKey.WithAlt);
}
if (_hotKey.IsKeyCodeAtoZ)
{
// Remove the shift version
if (HotKeyBindings.TryGet (prevHotKey.WithShift, out _))
{
HotKeyBindings.Remove (prevHotKey.WithShift);
}
// Remove alt | shift version
if (HotKeyBindings.TryGet (prevHotKey.WithShift.WithAlt, out _))
{
HotKeyBindings.Remove (prevHotKey.WithShift.WithAlt);
}
}
// Add the new
if (newKey != Key.Empty)
{
KeyBinding keyBinding = new ()
{
Commands = [Command.HotKey],
Key = newKey,
Data = context
};
// Add the base and Alt key
HotKeyBindings.Remove (newKey);
HotKeyBindings.Add (newKey, keyBinding);
HotKeyBindings.Remove (newKey.WithAlt);
HotKeyBindings.Add (newKey.WithAlt, keyBinding);
// If the Key is A..Z, add ShiftMask and AltMask | ShiftMask
if (newKey.IsKeyCodeAtoZ)
{
HotKeyBindings.Remove (newKey.WithShift);
HotKeyBindings.Add (newKey.WithShift, keyBinding);
HotKeyBindings.Remove (newKey.WithShift.WithAlt);
HotKeyBindings.Add (newKey.WithShift.WithAlt, keyBinding);
}
}
return true;
}
///
/// Gets or sets the specifier character for the hot key (e.g. '_'). Set to '\xffff' to disable automatic hot key
/// setting support for this View instance. The default is '\xffff'.
///
public virtual Rune HotKeySpecifier
{
get => TitleTextFormatter.HotKeySpecifier;
set
{
TitleTextFormatter.HotKeySpecifier = TextFormatter.HotKeySpecifier = value;
SetHotKeyFromTitle ();
}
}
private void SetHotKeyFromTitle ()
{
if (HotKeySpecifier == new Rune ('\xFFFF'))
{
return; // throw new InvalidOperationException ("Can't set HotKey unless a TextFormatter has been created");
}
if (TextFormatter.FindHotKey (_title, HotKeySpecifier, out _, out Key hk))
{
if (_hotKey != hk)
{
HotKey = hk;
}
}
else
{
HotKey = Key.Empty;
}
}
#endregion HotKey Support
#region Low-level Key handling
#region Key Down Event
///
/// If the view is enabled, raises the related key down events on the view, and returns if the
/// event was
/// handled.
///
///
///
/// If the view has a sub view that is focused, will be called on the focused view
/// first.
///
///
/// If a more focused subview does not handle the key press, this method raises /
/// to allow the
/// view to pre-process the key press. If / is not handled any commands
/// bound to the key will be invoked.
/// Then, only if no key bindings are
/// handled, / will be raised allowing the view to
/// process the key press.
///
///
/// Calling this method for a key bound to the view via an Application-scoped keybinding will have no effect.
/// Instead,
/// use .
///
/// See for an overview of Terminal.Gui keyboard APIs.
///
///
/// if the event was handled.
public bool NewKeyDownEvent (Key key)
{
if (!Enabled)
{
return false;
}
// If there's a Focused subview, give it a chance (this recurses down the hierarchy)
if (Focused?.NewKeyDownEvent (key) == true)
{
return true;
}
// Before (fire the cancellable event)
if (RaiseKeyDown (key) || key.Handled)
{
return true;
}
// During (this is what can be cancelled)
// TODO: NewKeyDownEvent returns bool. It should be bool? so state of InvokeCommands can be reflected up stack
if (InvokeCommands (key) is true || key.Handled)
{
return true;
}
bool? handled = false;
if (InvokeCommandsBoundToHotKey (key, ref handled))
{
return true;
}
// After
if (RaiseKeyDownNotHandled (key) || key.Handled)
{
return true;
}
return key.Handled;
bool RaiseKeyDown (Key k)
{
// Before (fire the cancellable event)
if (OnKeyDown (k) || k.Handled)
{
return true;
}
// fire event
KeyDown?.Invoke (this, k);
return k.Handled;
}
bool RaiseKeyDownNotHandled (Key k)
{
if (OnKeyDownNotHandled (k) || k.Handled)
{
return true;
}
KeyDownNotHandled?.Invoke (this, k);
return false;
}
}
///
/// Called when the user presses a key, allowing subscribers to pre-process the key down event. Called
/// before key bindings are invoked and is raised. Set
///
/// to true to
/// stop the key from being processed further.
///
/// The key that produced the event.
///
/// if the key down event was not handled. if the event was handled
/// and processing should stop.
///
///
/// Fires the event.
///
protected virtual bool OnKeyDown (Key key) { return false; }
///
/// Raised when the user presses a key, allowing subscribers to pre-process the key down event. Called
/// before key bindings are invoked and is raised. Set
///
/// to true to
/// stop the key from being processed further.
///
///
///
/// Not all terminals support key distinct up notifications, Applications should avoid depending on distinct
/// KeyUp events.
///
/// See for an overview of Terminal.Gui keyboard APIs.
///
public event EventHandler? KeyDown;
///
/// Called when the user has pressed key it wasn't handled by and was not bound to a key binding.
///
///
///
/// Not all terminals support distinct key up notifications; applications should avoid depending on distinct
/// KeyUp events.
///
///
/// Contains the details about the key that produced the event.
///
/// if the key press was not handled. if the keypress was handled
/// and no other view should see it.
///
protected virtual bool OnKeyDownNotHandled (Key key) { return key.Handled; }
///
/// Raised when the user has pressed key it wasn't handled by and was not bound to a key binding.
///
///
///
/// SubViews can use the of their super view override the default behavior of when
/// key bindings are invoked.
///
/// See for an overview of Terminal.Gui keyboard APIs.
///
public event EventHandler? KeyDownNotHandled;
#endregion KeyDown Event
#region KeyUp Event
///
/// If the view is enabled, raises the related key up events on the view, and returns if the
/// event was
/// handled.
///
///
///
/// Not all terminals support key distinct down/up notifications, Applications should avoid depending on distinct
/// KeyUp events.
///
///
/// If the view has a sub view that is focused, will be called on the focused view
/// first.
///
///
/// If the focused sub view does not handle the key press, this method raises /
/// to allow the
/// view to pre-process the key press.
///
/// See for an overview of Terminal.Gui keyboard APIs.
///
///
/// if the event was handled.
public bool NewKeyUpEvent (Key key)
{
if (!Enabled)
{
return false;
}
// Before
if (RaiseKeyUp (key) || key.Handled)
{
return true;
}
// During
// After
return false;
bool RaiseKeyUp (Key k)
{
// Before (fire the cancellable event)
if (OnKeyUp (k) || k.Handled)
{
return true;
}
// fire event
KeyUp?.Invoke (this, k);
return k.Handled;
}
}
/// Called when a key is released. This method is called from .
/// Contains the details about the key that produced the event.
///
/// if the keys up event was not handled. if no other view should see
/// it.
///
///
/// Not all terminals support key distinct down/up notifications, Applications should avoid depending on distinct KeyUp
/// events.
///
/// Overrides must call into the base and return if the base returns
/// .
///
/// See for an overview of Terminal.Gui keyboard APIs.
///
public virtual bool OnKeyUp (Key key) { return false; }
///
/// Raised when a key is released. Set to true to stop the key up event from being processed
/// by other views.
///
/// Not all terminals support key distinct down/up notifications, Applications should avoid depending on
/// distinct KeyDown and KeyUp events and instead should use .
/// See for an overview of Terminal.Gui keyboard APIs.
///
///
public event EventHandler? KeyUp;
#endregion KeyUp Event
#endregion Low-level Key handling
#region Key Bindings
/// Gets the bindings for this view that will be invoked only if this view has focus.
public KeyBindings KeyBindings { get; internal set; } = null!;
/// Gets the bindings for this view that will be invoked regardless of whether this view has focus or not.
public KeyBindings HotKeyBindings { get; internal set; } = null!;
///
/// INTERNAL API: Invokes any commands bound to on this view, adornments, and subviews.
///
///
///
/// if no command was invoked or there was no matching key binding; input processing should
/// continue.
/// if a command was invoked and was not handled (or cancelled); input processing should
/// continue.
/// if at least one command was invoked and handled (or
/// cancelled); input processing should stop.
///
internal bool? InvokeCommands (Key key)
{
// * If no key binding was found, `InvokeKeyBindings` returns `null`.
// Continue passing the event (return `false` from `OnInvokeKeyBindings`).
// * If key bindings were found, but none handled the key (all `Command`s returned `false`),
// `InvokeKeyBindings` returns `false`. Continue passing the event (return `false` from `OnInvokeKeyBindings`)..
// * If key bindings were found, and any handled the key (at least one `Command` returned `true`),
// `InvokeKeyBindings` returns `true`. Continue passing the event (return `false` from `OnInvokeKeyBindings`).
bool? handled = DoInvokeCommands (key);
if (handled is true)
{
// Stop processing if any key binding handled the key.
// DO NOT stop processing if there are no matching key bindings or none of the key bindings handled the key
return handled;
}
if (Margin is { } && InvokeCommandsBoundToKeyOnAdornment (Margin, key, ref handled))
{
return true;
}
if (Padding is { } && InvokeCommandsBoundToKeyOnAdornment (Padding, key, ref handled))
{
return true;
}
if (Border is { } && InvokeCommandsBoundToKeyOnAdornment (Border, key, ref handled))
{
return true;
}
return handled;
}
private static bool InvokeCommandsBoundToKeyOnAdornment (Adornment adornment, Key key, ref bool? handled)
{
bool? adornmentHandled = adornment.InvokeCommands (key);
if (adornmentHandled is true)
{
return true;
}
if (adornment?.InternalSubViews is null)
{
return false;
}
foreach (View subview in adornment.InternalSubViews)
{
bool? subViewHandled = subview.InvokeCommands (key);
if (subViewHandled is { })
{
handled = subViewHandled;
if ((bool)subViewHandled)
{
return true;
}
}
}
return false;
}
// BUGBUG: This will miss any hotkeys in subviews of Adornments.
///
/// Invokes any commands bound to on this view and subviews.
///
///
///
///
internal bool InvokeCommandsBoundToHotKey (Key hotKey, ref bool? handled)
{
// Process this View
if (HotKeyBindings.TryGet (hotKey, out KeyBinding binding))
{
if (InvokeCommands (binding.Commands, binding) is true)
{
return true;
}
}
// Now, process any HotKey bindings in the subviews
foreach (View subview in InternalSubViews)
{
if (subview == Focused)
{
continue;
}
bool recurse = subview.InvokeCommandsBoundToHotKey (hotKey, ref handled);
if (recurse || (handled is { } && (bool)handled))
{
return true;
}
}
return false;
}
///
/// Invokes the Commands bound to .
/// See for an overview of Terminal.Gui keyboard APIs.
///
/// The key event passed.
///
/// if no command was invoked; input processing should continue.
/// if at least one command was invoked and was not handled (or cancelled); input processing
/// should continue.
/// if at least one command was invoked and handled (or cancelled); input processing should
/// stop.
///
protected bool? DoInvokeCommands (Key key)
{
if (!KeyBindings.TryGet (key, out KeyBinding binding))
{
return null;
}
return InvokeCommands (binding.Commands, binding);
}
///
/// Invokes the Commands bound to .
/// See for an overview of Terminal.Gui keyboard APIs.
///
/// The hot key event passed.
///
/// if no command was invoked; input processing should continue.
/// if at least one command was invoked and was not handled (or cancelled); input processing
/// should continue.
/// if at least one command was invoked and handled (or cancelled); input processing should
/// stop.
///
protected bool? InvokeCommandsBoundToHotKey (Key hotKey)
{
if (!HotKeyBindings.TryGet (hotKey, out KeyBinding binding))
{
return null;
}
return InvokeCommands (binding.Commands, binding);
}
#endregion Key Bindings
}