#nullable enable
using System.ComponentModel;
namespace Terminal.Gui;
///
/// Displays a command, help text, and a key binding. When the key specified by is pressed, the
/// command will be invoked. Useful for
/// displaying a command in such as a
/// menu, toolbar, or status bar.
///
///
///
/// The following user actions will invoke the , causing the
/// event to be fired:
/// - Clicking on the .
/// - Pressing the key specified by .
/// - Pressing the HotKey specified by .
///
///
/// If is , will invoke
///
/// regardless of what View has focus, enabling an application-wide keyboard shortcut.
///
///
/// By default, a Shortcut displays the command text on the left side, the help text in the middle, and the key
/// binding on the
/// right side. Set to to reverse the order.
///
///
/// The command text can be set by setting the 's Text property or by setting
/// .
///
///
/// The help text can be set by setting the property or by setting .
///
///
/// The key text is set by setting the property.
/// If the is , the text is not displayed.
///
///
public class Shortcut : View, IOrientation, IDesignable
{
///
/// Creates a new instance of .
///
public Shortcut () : this (Key.Empty, null, null, null) { }
///
/// Creates a new instance of , binding it to and
/// . The Key
/// has bound to will be used as .
///
///
///
/// This is a helper API that simplifies creation of multiple Shortcuts when adding them to -based
/// objects, like .
///
///
///
/// The View that will be invoked on when user does something that causes the Shortcut's Accept
/// event to be raised.
///
///
/// The Command to invoke on . The Key
/// has bound to will be used as
///
/// The text to display for the command.
/// The help text to display.
public Shortcut (View targetView, Command command, string commandText, string helpText)
: this (
targetView?.KeyBindings.GetKeyFromCommands (command)!,
commandText,
null,
helpText)
{
_targetView = targetView;
_command = command;
}
///
/// Creates a new instance of .
///
///
///
/// This is a helper API that mimics the V1 API for creating StatusItems.
///
///
///
/// The text to display for the command.
///
/// The help text to display.
public Shortcut (Key key, string? commandText, Action? action, string? helpText = null)
{
Id = "_shortcut";
HighlightStyle = HighlightStyle.None;
CanFocus = true;
SuperViewRendersLineCanvas = true;
Border.Settings &= ~BorderSettings.Title;
Width = GetWidthDimAuto ();
Height = Dim.Auto (DimAutoStyle.Content, 1);
_orientationHelper = new (this);
_orientationHelper.OrientationChanging += (sender, e) => OrientationChanging?.Invoke (this, e);
_orientationHelper.OrientationChanged += (sender, e) => OrientationChanged?.Invoke (this, e);
AddCommands ();
TitleChanged += Shortcut_TitleChanged; // This needs to be set before CommandView is set
CommandView = new ()
{
Id = "CommandView",
Width = Dim.Auto (),
Height = Dim.Fill()
};
Title = commandText ?? string.Empty;
HelpView.Id = "_helpView";
HelpView.CanFocus = false;
HelpView.Text = helpText ?? string.Empty;
KeyView.Id = "_keyView";
KeyView.CanFocus = false;
key ??= Key.Empty;
Key = key;
Action = action;
SubviewLayout += OnLayoutStarted;
ShowHide ();
}
// Helper to set Width consistently
internal Dim GetWidthDimAuto ()
{
return Dim.Auto (
DimAutoStyle.Content,
minimumContentDim: Dim.Func (() => _minimumNaturalWidth ?? 0),
maximumContentDim: Dim.Func (() => _minimumNaturalWidth ?? 0))!;
}
private AlignmentModes _alignmentModes = AlignmentModes.StartToEnd | AlignmentModes.IgnoreFirstOrLast;
// This is used to calculate the minimum width of the Shortcut when Width is NOT Dim.Auto
// It is calculated by setting Width to DimAuto temporarily and forcing layout.
// Once Frame.Width gets below this value, LayoutStarted makes HelpView an KeyView smaller.
private int? _minimumNaturalWidth;
///
protected override bool OnHighlight (CancelEventArgs args)
{
if (args.NewValue.HasFlag (HighlightStyle.Hover))
{
HasFocus = true;
}
return true;
}
///
/// Gets or sets the for this .
///
///
///
/// The default is . This means that the CommandView will be on the left,
/// HelpView in the middle, and KeyView on the right.
///
///
public AlignmentModes AlignmentModes
{
get => _alignmentModes;
set
{
_alignmentModes = value;
SetCommandViewDefaultLayout ();
SetHelpViewDefaultLayout ();
SetKeyViewDefaultLayout ();
}
}
// When one of the subviews is "empty" we don't want to show it. So we
// Use Add/Remove. We need to be careful to add them in the right order
// so Pos.Align works correctly.
internal void ShowHide ()
{
RemoveAll ();
if (CommandView.Visible)
{
Add (CommandView);
SetCommandViewDefaultLayout ();
}
if (HelpView.Visible && !string.IsNullOrEmpty (HelpView.Text))
{
Add (HelpView);
SetHelpViewDefaultLayout ();
}
if (KeyView.Visible && Key != Key.Empty)
{
Add (KeyView);
SetKeyViewDefaultLayout ();
}
SetColors ();
}
// Force Width to DimAuto to calculate natural width and then set it back
private void ForceCalculateNaturalWidth ()
{
// Get the natural size of each subview
CommandView.SetRelativeLayout (Application.Screen.Size);
HelpView.SetRelativeLayout (Application.Screen.Size);
KeyView.SetRelativeLayout (Application.Screen.Size);
_minimumNaturalWidth = PosAlign.CalculateMinDimension (0, Subviews, Dimension.Width);
// Reset our relative layout
SetRelativeLayout (SuperView?.GetContentSize() ?? Application.Screen.Size);
}
// TODO: Enable setting of the margin thickness
private Thickness GetMarginThickness ()
{
return new (1, 0, 1, 0);
}
// When layout starts, we need to adjust the layout of the HelpView and KeyView
private void OnLayoutStarted (object? sender, LayoutEventArgs e)
{
ShowHide ();
ForceCalculateNaturalWidth ();
if (Width is DimAuto widthAuto)
{
}
else
{
// Frame.Width is smaller than the natural width. Reduce width of HelpView.
_maxHelpWidth = int.Max (0, GetContentSize ().Width - CommandView.Frame.Width - KeyView.Frame.Width);
if (_maxHelpWidth < 3)
{
Thickness t = GetMarginThickness ();
switch (_maxHelpWidth)
{
case 0:
case 1:
// Scrunch it by removing both margins
HelpView.Margin.Thickness = new (t.Right - 1, t.Top, t.Left - 1, t.Bottom);
break;
case 2:
// Scrunch just the right margin
HelpView.Margin.Thickness = new (t.Right, t.Top, t.Left - 1, t.Bottom);
break;
}
}
else
{
// Reset to default
HelpView.Margin.Thickness = GetMarginThickness ();
}
}
}
#region Accept/Select/HotKey Command Handling
private readonly View? _targetView; // If set, _command will be invoked
private readonly Command _command; // Used when _targetView is set
private void AddCommands ()
{
// Accept (Enter key) -
AddCommand (Command.Accept, DispatchCommand);
// Hotkey -
AddCommand (Command.HotKey, DispatchCommand);
// Select (Space key or click) -
AddCommand (Command.Select, DispatchCommand);
}
private bool? DispatchCommand (CommandContext ctx)
{
if (ctx.Data != this)
{
// Invoke Select on the command view to cause it to change state if it wants to
// If this causes CommandView to raise Accept, we eat it
ctx.Data = this;
CommandView.InvokeCommand (Command.Select, ctx);
}
if (RaiseSelecting (ctx) is true)
{
return true;
}
// The default HotKey handler sets Focus
SetFocus ();
var cancel = false;
cancel = RaiseAccepting (ctx) is true;
if (cancel)
{
return true;
}
if (Action is { })
{
Action.Invoke ();
// Assume if there's a subscriber to Action, it's handled.
cancel = true;
}
if (_targetView is { })
{
_targetView.InvokeCommand (_command);
}
return cancel;
}
///
/// Gets or sets the action to be invoked when the shortcut key is pressed or the shortcut is clicked on with the
/// mouse.
///
///
/// Note, the event is fired first, and if cancelled, the event will not be invoked.
///
public Action? Action { get; set; }
#endregion Accept/Select/HotKey Command Handling
#region IOrientation members
private readonly OrientationHelper _orientationHelper;
///
/// Gets or sets the for this . The default is
/// .
///
///
///
public Orientation Orientation
{
get => _orientationHelper.Orientation;
set => _orientationHelper.Orientation = value;
}
///
public event EventHandler>? OrientationChanging;
///
public event EventHandler>? OrientationChanged;
/// Called when has changed.
///
public void OnOrientationChanged (Orientation newOrientation)
{
// TODO: Determine what, if anything, is opinionated about the orientation.
SetNeedsLayout ();
}
#endregion
#region Command
private View _commandView = new ();
///
/// Gets or sets the View that displays the command text and hotkey.
///
///
///
///
/// By default, the of the is displayed as the Shortcut's
/// command text.
///
///
/// By default, the CommandView is a with set to
/// .
///
///
/// Setting the will add it to the and remove any existing
/// .
///
///
///
///
/// This example illustrates how to add a to a that toggles the
/// property.
///
///
/// var force16ColorsShortcut = new Shortcut
/// {
/// Key = Key.F6,
/// KeyBindingScope = KeyBindingScope.HotKey,
/// CommandView = new CheckBox { Text = "Force 16 Colors" }
/// };
/// var cb = force16ColorsShortcut.CommandView as CheckBox;
/// cb.Checked = Application.Force16Colors;
///
/// cb.Toggled += (s, e) =>
/// {
/// var cb = s as CheckBox;
/// Application.Force16Colors = cb!.Checked == true;
/// Application.Refresh();
/// };
/// StatusBar.Add(force16ColorsShortcut);
///
///
public View CommandView
{
get => _commandView;
set
{
ArgumentNullException.ThrowIfNull (value);
if (value == null)
{
throw new ArgumentNullException ();
}
// Clean up old
_commandView.Selecting -= CommandViewOnSelecting;
_commandView.Accepting -= CommandViewOnAccepted;
Remove (_commandView);
_commandView?.Dispose ();
// Set new
_commandView = value;
_commandView.Id = "_commandView";
// The default behavior is for CommandView to not get focus. I
// If you want it to get focus, you need to set it.
_commandView.CanFocus = false;
_commandView.HotKeyChanged += (s, e) =>
{
if (e.NewKey != Key.Empty)
{
// Add it
AddKeyBindingsForHotKey (e.OldKey, e.NewKey);
}
};
_commandView.HotKeySpecifier = new ('_');
Title = _commandView.Text;
_commandView.Selecting += CommandViewOnSelecting;
_commandView.Accepting += CommandViewOnAccepted;
//ShowHide ();
UpdateKeyBindings (Key.Empty);
return;
void CommandViewOnAccepted (object? sender, CommandEventArgs e)
{
// Always eat CommandView.Accept
e.Cancel = true;
}
void CommandViewOnSelecting (object? sender, CommandEventArgs e)
{
if (e.Context.Data != this)
{
// Forward command to ourselves
InvokeCommand (Command.Select, new (Command.Select, null, null, this));
}
e.Cancel = true;
}
}
}
private void SetCommandViewDefaultLayout ()
{
CommandView.Margin.Thickness = GetMarginThickness ();
CommandView.X = Pos.Align (Alignment.End, AlignmentModes);
CommandView.VerticalTextAlignment = Alignment.Center;
CommandView.TextAlignment = Alignment.Start;
CommandView.TextFormatter.WordWrap = false;
CommandView.HighlightStyle = HighlightStyle.None;
}
private void Shortcut_TitleChanged (object? sender, EventArgs e)
{
// If the Title changes, update the CommandView text.
// This is a helper to make it easier to set the CommandView text.
// CommandView is public and replaceable, but this is a convenience.
_commandView.Text = Title;
}
#endregion Command
#region Help
// The maximum width of the HelpView. Calculated in OnLayoutStarted and used in HelpView.Width (Dim.Auto/Func).
private int _maxHelpWidth = 0;
///
/// The subview that displays the help text for the command. Internal for unit testing.
///
public View HelpView { get; } = new ();
private void SetHelpViewDefaultLayout ()
{
HelpView.Margin.Thickness = GetMarginThickness ();
HelpView.X = Pos.Align (Alignment.End, AlignmentModes);
_maxHelpWidth = HelpView.Text.GetColumns ();
HelpView.Width = Dim.Auto (DimAutoStyle.Text, maximumContentDim: Dim.Func ((() => _maxHelpWidth)));
HelpView.Height = Dim.Fill ();
HelpView.Visible = true;
HelpView.VerticalTextAlignment = Alignment.Center;
HelpView.TextAlignment = Alignment.Start;
HelpView.TextFormatter.WordWrap = false;
HelpView.HighlightStyle = HighlightStyle.None;
}
///
/// Gets or sets the help text displayed in the middle of the Shortcut. Identical in function to
/// .
///
public override string Text
{
get => HelpView.Text;
set
{
HelpView.Text = value;
ShowHide ();
}
}
///
/// Gets or sets the help text displayed in the middle of the Shortcut.
///
public string HelpText
{
get => HelpView.Text;
set
{
HelpView.Text = value;
ShowHide ();
}
}
#endregion Help
#region Key
private Key _key = Key.Empty;
///
/// Gets or sets the that will be bound to the command.
///
public Key Key
{
get => _key;
set
{
ArgumentNullException.ThrowIfNull (value);
Key oldKey = _key;
_key = value;
UpdateKeyBindings (oldKey);
KeyView.Text = Key == Key.Empty ? string.Empty : $"{Key}";
ShowHide ();
}
}
private KeyBindingScope _keyBindingScope = KeyBindingScope.HotKey;
///
/// Gets or sets the scope for the key binding for how is bound to .
///
public KeyBindingScope KeyBindingScope
{
get => _keyBindingScope;
set
{
if (value == _keyBindingScope)
{
return;
}
if (_keyBindingScope == KeyBindingScope.Application)
{
Application.KeyBindings.Remove (Key);
}
if (_keyBindingScope is KeyBindingScope.HotKey or KeyBindingScope.Focused)
{
KeyBindings.Remove (Key);
}
_keyBindingScope = value;
UpdateKeyBindings (Key.Empty);
}
}
///
/// Gets the subview that displays the key. Internal for unit testing.
///
public View KeyView { get; } = new ();
private int _minimumKeyTextSize;
///
/// Gets or sets the minimum size of the key text. Useful for aligning the key text with other s.
///
public int MinimumKeyTextSize
{
get => _minimumKeyTextSize;
set
{
if (value == _minimumKeyTextSize)
{
//return;
}
_minimumKeyTextSize = value;
SetKeyViewDefaultLayout ();
// TODO: Prob not needed
CommandView.SetNeedsLayout ();
HelpView.SetNeedsLayout ();
KeyView.SetNeedsLayout ();
SetSubViewNeedsDraw ();
}
}
private void SetKeyViewDefaultLayout ()
{
KeyView.Margin.Thickness = GetMarginThickness ();
KeyView.X = Pos.Align (Alignment.End, AlignmentModes);
KeyView.Width = Dim.Auto (DimAutoStyle.Text, minimumContentDim: Dim.Func (() => MinimumKeyTextSize));
KeyView.Height = Dim.Fill ();
KeyView.Visible = true;
// Right align the text in the keyview
KeyView.TextAlignment = Alignment.End;
KeyView.VerticalTextAlignment = Alignment.Center;
KeyView.KeyBindings.Clear ();
HelpView.HighlightStyle = HighlightStyle.None;
}
private void UpdateKeyBindings (Key oldKey)
{
if (Key.IsValid)
{
if (KeyBindingScope.FastHasFlags (KeyBindingScope.Application))
{
if (oldKey != Key.Empty)
{
Application.KeyBindings.Remove (oldKey);
}
Application.KeyBindings.Remove (Key);
Application.KeyBindings.Add (Key, this, Command.HotKey);
}
else
{
if (oldKey != Key.Empty)
{
KeyBindings.Remove (oldKey);
}
KeyBindings.Remove (Key);
KeyBindings.Add (Key, KeyBindingScope | KeyBindingScope.HotKey, Command.HotKey);
}
}
}
#endregion Key
#region Focus
///
public override ColorScheme? ColorScheme
{
get => base.ColorScheme;
set
{
base.ColorScheme = _nonFocusColorScheme = value;
SetColors ();
}
}
private ColorScheme? _nonFocusColorScheme;
///
///
internal void SetColors (bool highlight = false)
{
// Border should match superview.
if (Border is { })
{
// Border.ColorScheme = SuperView?.ColorScheme;
}
if (HasFocus || highlight)
{
if (_nonFocusColorScheme is null)
{
_nonFocusColorScheme = base.ColorScheme;
}
base.ColorScheme ??= new (Attribute.Default);
// When we have focus, we invert the colors
base.ColorScheme = new (base.ColorScheme)
{
Normal = base.ColorScheme.Focus,
HotNormal = base.ColorScheme.HotFocus,
HotFocus = base.ColorScheme.HotNormal,
Focus = base.ColorScheme.Normal
};
}
else
{
if (_nonFocusColorScheme is { })
{
base.ColorScheme = _nonFocusColorScheme;
//_nonFocusColorScheme = null;
}
else
{
base.ColorScheme = SuperView?.ColorScheme ?? base.ColorScheme;
}
}
// Set KeyView's colors to show "hot"
if (IsInitialized && base.ColorScheme is { })
{
var cs = new ColorScheme (base.ColorScheme)
{
Normal = base.ColorScheme.HotNormal,
HotNormal = base.ColorScheme.Normal
};
KeyView.ColorScheme = cs;
}
}
///
protected override void OnHasFocusChanged (bool newHasFocus, View? previousFocusedView, View? view) { SetColors (); }
#endregion Focus
///
public bool EnableForDesign ()
{
Title = "_Shortcut";
HelpText = "Shortcut help";
Key = Key.F1;
return true;
}
///
protected override void Dispose (bool disposing)
{
if (disposing)
{
TitleChanged -= Shortcut_TitleChanged;
if (CommandView?.IsAdded == false)
{
CommandView.Dispose ();
}
if (HelpView?.IsAdded == false)
{
HelpView.Dispose ();
}
if (KeyView?.IsAdded == false)
{
KeyView.Dispose ();
}
}
base.Dispose (disposing);
}
}