Combined KeyBinding classes

This commit is contained in:
Tig
2024-12-07 23:42:38 -08:00
parent 0b72db2785
commit 0f137579c8
11 changed files with 79 additions and 327 deletions

View File

@@ -45,7 +45,7 @@ public static partial class Application // Keyboard handling
// Invoke any Application-scoped KeyBindings.
// The first view that handles the key will stop the loop.
foreach (KeyValuePair<Key, ApplicationKeyBinding> binding in KeyBindings.GetBindings (key))
foreach (KeyValuePair<Key, KeyBinding> binding in KeyBindings.GetBindings (key))
{
if (binding.Value.Target is { })
{
@@ -63,7 +63,7 @@ public static partial class Application // Keyboard handling
}
else
{
if (!KeyBindings.TryGet (key, out ApplicationKeyBinding appBinding))
if (!KeyBindings.TryGet (key, out KeyBinding appBinding))
{
continue;
}
@@ -81,7 +81,7 @@ public static partial class Application // Keyboard handling
return false;
static bool? InvokeCommand (Command command, Key key, ApplicationKeyBinding appBinding)
static bool? InvokeCommand (Command command, Key key, KeyBinding appBinding)
{
if (!_commandImplementations!.ContainsKey (command))
{
@@ -92,7 +92,7 @@ public static partial class Application // Keyboard handling
if (_commandImplementations.TryGetValue (command, out View.CommandImplementation? implementation))
{
CommandContext<ApplicationKeyBinding> context = new (command, appBinding); // Create the context here
CommandContext<KeyBinding> context = new (command, appBinding); // Create the context here
return implementation (context);
}
@@ -159,7 +159,7 @@ public static partial class Application // Keyboard handling
static Application () { AddKeyBindings (); }
/// <summary>Gets the Application-scoped key bindings.</summary>
public static ApplicationKeyBindings KeyBindings { get; internal set; } = new ();
public static KeyBindings KeyBindings { get; internal set; } = new (null);
internal static void AddKeyBindings ()
{

View File

@@ -184,7 +184,7 @@ public static partial class Application // Mouse handling
}
// Create a view-relative mouse event to send to the view that is under the mouse.
MouseEventArgs? viewMouseEvent;
MouseEventArgs viewMouseEvent;
if (deepestViewUnderMouse is Adornment adornment)
{

View File

@@ -509,7 +509,7 @@ internal class WindowsDriver : ConsoleDriver
case WindowsConsole.EventType.Mouse:
MouseEventArgs me = ToDriverMouse (inputEvent.MouseEvent);
if (me is null || me.Flags == MouseFlags.None)
if (/*me is null ||*/ me.Flags == MouseFlags.None)
{
break;
}

View File

@@ -1,41 +0,0 @@
#nullable enable
// These classes use a key binding system based on the design implemented in Scintilla.Net which is an
// MIT licensed open source project https://github.com/jacobslusser/ScintillaNET/blob/master/src/ScintillaNET/Command.cs
namespace Terminal.Gui;
/// <summary>
/// Provides a collection of <see cref="Command"/> objects that are scoped to the <see cref="Application"/>.
/// </summary>
/// <seealso cref="Command"/>
public record struct ApplicationKeyBinding
{
/// <summary>Initializes a new instance.</summary>
/// <param name="commands">The commands this key binding will invoke.</param>
public ApplicationKeyBinding (Command [] commands)
{
Commands = commands;
}
/// <summary>Initializes a new instance.</summary>
/// <param name="commands">The commands this key binding will invoke.</param>
/// <param name="target">The view the Application-scoped key binding is bound to. If <see langword="null"/> the commands will be invoked on
/// the <see cref="Application"/>.</param>
public ApplicationKeyBinding (Command [] commands, View? target)
{
Commands = commands;
Target = target;
}
/// <summary>The commands this binding will invoke.</summary>
public Command [] Commands { get; set; }
/// <summary>
/// The Key that is bound to the <see cref="Commands"/>.
/// </summary>
public Key? Key { get; set; }
/// <summary>The view the Application-scoped key binding is bound to.</summary>
public View? Target { get; set; }
}

View File

@@ -1,252 +0,0 @@
#nullable enable
namespace Terminal.Gui;
/// <summary>
/// Provides a collection of <see cref="ApplicationKeyBinding"/> objects bound to a <see cref="Key"/>.
/// </summary>
/// <remarks>
/// This is used for <see cref="Application.KeyBindings"/>.
/// </remarks>
/// <seealso cref="Application.KeyBindings"/>
/// <seealso cref="Command"/>
public class ApplicationKeyBindings
{
/// <summary>
/// Initializes a new instance. This constructor is used when the <see cref="ApplicationKeyBindings"/> are not bound to a
/// <see cref="View"/>. This is used for <see cref="Application.KeyBindings"/>.
/// </summary>
public ApplicationKeyBindings () { }
/// <summary>Adds a <see cref="ApplicationKeyBinding"/> to the collection.</summary>
/// <param name="key"></param>
/// <param name="binding"></param>
public void Add (Key key, ApplicationKeyBinding binding)
{
if (TryGet (key, out ApplicationKeyBinding _))
{
throw new InvalidOperationException (@$"A key binding for {key} exists ({binding}).");
}
// IMPORTANT: Add a COPY of the key. This is needed because ConfigurationManager.Apply uses DeepMemberWiseCopy
// IMPORTANT: update the memory referenced by the key, and Dictionary uses caching for performance, and thus
// IMPORTANT: Apply will update the Dictionary with the new key, but the old key will still be in the dictionary.
// IMPORTANT: See the ConfigurationManager.Illustrate_DeepMemberWiseCopy_Breaks_Dictionary test for details.
Bindings.Add (new (key), binding);
}
/// <summary>
/// <para>
/// Adds a new key combination that will trigger the commands in <paramref name="commands"/> on the View
/// specified by <paramref name="boundView"/>.
/// </para>
/// <para>
/// If the key is already bound to a different array of <see cref="Command"/>s it will be rebound
/// <paramref name="commands"/>.
/// </para>
/// </summary>
/// <remarks>
/// </remarks>
/// <param name="key">The key to check.</param>
/// <param name="boundView">The View the commands will be invoked on. If <see langword="null"/>, the key will be bound to <see cref="Application"/>.</param>
/// <param name="commands">
/// The command to invoked on the <see paramref="boundView"/> when <paramref name="key"/> is pressed. When
/// multiple commands are provided,they will be applied in sequence. The bound <paramref name="key"/> strike will be
/// consumed if any took effect.
/// </param>
public void Add (Key key, View? boundView, params Command [] commands)
{
ApplicationKeyBinding binding = new (commands, boundView);
Add (key, binding);
}
/// <summary>
/// <para>
/// Adds a new key combination that will trigger the commands in <paramref name="commands"/> on <see cref="Application"/>.
/// </para>
/// <para>
/// If the key is already bound to a different array of <see cref="Command"/>s it will be rebound
/// <paramref name="commands"/>.
/// </para>
/// </summary>
/// <remarks>
/// </remarks>
/// <param name="key">The key to check.</param>
/// <param name="commands">
/// The commands to invoke on <see cref="Application"/> when <paramref name="key"/> is pressed. When
/// multiple commands are provided,they will be applied in sequence. The bound <paramref name="key"/> strike will be
/// consumed if any took effect.
/// </param>
public void Add (Key key, params Command [] commands)
{
ApplicationKeyBinding binding = new (commands, null);
Add (key, binding);
}
private Dictionary<Key, ApplicationKeyBinding> Bindings { get; } = new (new KeyEqualityComparer ());
/// <summary>
/// Gets the keys that are bound.
/// </summary>
/// <returns></returns>
public IEnumerable<Key> GetBoundKeys ()
{
return Bindings.Keys;
}
/// <summary>
/// Gets the bindings bound to <paramref name="key"/>.
/// </summary>
/// <param name="key"></param>
/// <returns></returns>
public IEnumerable<KeyValuePair<Key, ApplicationKeyBinding>> GetBindings (Key key)
{
return Bindings.Where (b => b.Key == key.KeyCode);
}
/// <summary>Removes all <see cref="ApplicationKeyBinding"/> objects from the collection.</summary>
public void Clear () { Bindings.Clear (); }
/// <summary>
/// Removes all key bindings that trigger the given command set. Views can have multiple different keys bound to
/// the same command sets and this method will clear all of them.
/// </summary>
/// <param name="command"></param>
public void Clear (params Command [] command)
{
KeyValuePair<Key, ApplicationKeyBinding> [] kvps = Bindings
.Where (kvp => kvp.Value.Commands.SequenceEqual (command))
.ToArray ();
foreach (KeyValuePair<Key, ApplicationKeyBinding> kvp in kvps)
{
Remove (kvp.Key);
}
}
/// <summary>Gets the <see cref="ApplicationKeyBinding"/> for the specified <see cref="Key"/>.</summary>
/// <param name="key"></param>
/// <returns></returns>
public ApplicationKeyBinding Get (Key key)
{
if (TryGet (key, out ApplicationKeyBinding binding))
{
return binding;
}
throw new InvalidOperationException ($"Key {key} is not bound.");
}
/// <summary>Gets the array of <see cref="Command"/>s bound to <paramref name="key"/> if it exists.</summary>
/// <param name="key">The key to check.</param>
/// <returns>
/// The array of <see cref="Command"/>s if <paramref name="key"/> is bound. An empty <see cref="Command"/> array
/// if not.
/// </returns>
public Command [] GetCommands (Key key)
{
if (TryGet (key, out ApplicationKeyBinding bindings))
{
return bindings.Commands;
}
return [];
}
/// <summary>Gets the first Key bound to the set of commands specified by <paramref name="commands"/>.</summary>
/// <param name="commands">The set of commands to search.</param>
/// <returns>The first <see cref="Key"/> bound to the set of commands specified by <paramref name="commands"/>. <see langword="null"/> if the set of caommands was not found.</returns>
public Key? GetKeyFromCommands (params Command [] commands)
{
return Bindings.FirstOrDefault (a => a.Value.Commands.SequenceEqual (commands)).Key;
}
/// <summary>Gets Keys bound to the set of commands specified by <paramref name="commands"/>.</summary>
/// <param name="commands">The set of commands to search.</param>
/// <returns>The <see cref="Key"/>s bound to the set of commands specified by <paramref name="commands"/>. An empty list if the set of caommands was not found.</returns>
public IEnumerable<Key> GetKeysFromCommands (params Command [] commands)
{
return Bindings.Where (a => a.Value.Commands.SequenceEqual (commands)).Select (a => a.Key);
}
/// <summary>Removes a <see cref="ApplicationKeyBinding"/> from the collection.</summary>
/// <param name="key"></param>
public void Remove (Key key)
{
if (!TryGet (key, out ApplicationKeyBinding _))
{
return;
}
Bindings.Remove (key);
}
/// <summary>Replaces the commands already bound to a key.</summary>
/// <remarks>
/// <para>
/// If the key is not already bound, it will be added.
/// </para>
/// </remarks>
/// <param name="key">The key bound to the command to be replaced.</param>
/// <param name="newCommands">The set of commands to replace the old ones with.</param>
public void ReplaceCommands (Key key, params Command [] newCommands)
{
if (TryGet (key, out ApplicationKeyBinding binding))
{
Remove (key);
Add (key, binding.Target, newCommands);
return;
}
throw new InvalidOperationException ($"Key {key} is not bound.");
}
/// <summary>Replaces a key combination bound to a set of <see cref="Command"/>s.</summary>
/// <remarks>If <paramref name="oldKey"/> is not bound, this method has the same effect as <see cref="Add(Terminal.Gui.Key,Terminal.Gui.ApplicationKeyBinding)"/>.</remarks>
/// <param name="oldKey">The key to be replaced.</param>
/// <param name="newKey">The new key to be used. If <see cref="Key.Empty"/> this method has the same effect as <see cref="Remove"/>.</param>
public void ReplaceKey (Key oldKey, Key newKey)
{
if (!newKey.IsValid)
{
throw new InvalidOperationException ($"Key {newKey} is is not valid.");
}
if (newKey == Key.Empty)
{
Remove (oldKey);
return;
}
if (TryGet (oldKey, out ApplicationKeyBinding binding))
{
Remove (oldKey);
Add (newKey, binding);
}
else
{
Add (newKey, binding);
}
}
/// <summary>Gets the commands bound with the specified Key.</summary>
/// <remarks></remarks>
/// <param name="key">The key to check.</param>
/// <param name="binding">
/// When this method returns, contains the commands bound with the specified Key, if the Key is
/// found; otherwise, null. This parameter is passed uninitialized.
/// </param>
/// <returns><see langword="true"/> if the Key is bound; otherwise <see langword="false"/>.</returns>
public bool TryGet (Key key, out ApplicationKeyBinding binding)
{
binding = new ([], null);
if (key.IsValid)
{
return Bindings.TryGetValue (key, out binding);
}
return false;
}
}

View File

@@ -24,12 +24,12 @@ public record struct KeyBinding
/// <summary>Initializes a new instance.</summary>
/// <param name="commands">The commands this key binding will invoke.</param>
/// <param name="boundView">The view the key binding is bound to.</param>
/// <param name="target">The view the key binding is bound to.</param>
/// <param name="data">Arbitrary data that can be associated with this key binding.</param>
public KeyBinding (Command [] commands, View? boundView, object? data = null)
public KeyBinding (Command [] commands, View? target, object? data = null)
{
Commands = commands;
BoundView = boundView;
Target = target;
Data = data;
}
@@ -42,7 +42,7 @@ public record struct KeyBinding
public Key? Key { get; set; }
/// <summary>The view the key binding is bound to.</summary>
public View? BoundView { get; set; }
public View? Target { get; set; }
/// <summary>
/// Arbitrary context that can be associated with this key binding.

View File

@@ -9,8 +9,8 @@ namespace Terminal.Gui;
/// <seealso cref="Command"/>
public class KeyBindings
{
/// <summary>Initializes a new instance bound to <paramref name="boundView"/>.</summary>
public KeyBindings (View? boundView) { BoundView = boundView; }
/// <summary>Initializes a new instance bound to <paramref name="target"/>.</summary>
public KeyBindings (View? target) { Target = target; }
/// <summary>Adds a <see cref="KeyBinding"/> to the collection.</summary>
/// <param name="key"></param>
@@ -24,7 +24,7 @@ public class KeyBindings
throw new ArgumentException (nameof (key));
}
if (binding.Commands.Length == 0)
if (binding.Commands is { Length: 0 })
{
throw new ArgumentException (nameof (binding));
}
@@ -36,9 +36,9 @@ public class KeyBindings
//Bindings [key] = binding;
}
if (BoundView is { })
if (Target is { })
{
binding.BoundView = BoundView;
binding.Target = Target;
}
// IMPORTANT: Add a COPY of the key. This is needed because ConfigurationManager.Apply uses DeepMemberWiseCopy
@@ -76,11 +76,47 @@ public class KeyBindings
Add (key, new KeyBinding (commands));
}
/// <summary>
/// <para>
/// Adds a new key combination that will trigger the commands in <paramref name="commands"/> on the View
/// specified by <paramref name="target"/>.
/// </para>
/// <para>
/// If the key is already bound to a different array of <see cref="Command"/>s it will be rebound
/// <paramref name="commands"/>.
/// </para>
/// </summary>
/// <remarks>
/// </remarks>
/// <param name="key">The key to check.</param>
/// <param name="target">The View the commands will be invoked on. If <see langword="null"/>, the key will be bound to <see cref="Application"/>.</param>
/// <param name="commands">
/// The command to invoked on the <see paramref="target"/> when <paramref name="key"/> is pressed. When
/// multiple commands are provided,they will be applied in sequence. The bound <paramref name="key"/> strike will be
/// consumed if any took effect.
/// </param>
public void Add (Key key, View? target, params Command [] commands)
{
KeyBinding binding = new (commands, target);
Add (key, binding);
}
// TODO: Add a dictionary comparer that ignores Scope
// TODO: This should not be public!
/// <summary>The collection of <see cref="KeyBinding"/> objects.</summary>
public Dictionary<Key, KeyBinding> Bindings { get; } = new (new KeyEqualityComparer ());
/// <summary>
/// Gets the bindings bound to <paramref name="key"/>.
/// </summary>
/// <param name="key"></param>
/// <returns></returns>
public IEnumerable<KeyValuePair<Key, KeyBinding>> GetBindings (Key key)
{
return Bindings.Where (b => b.Key == key.KeyCode);
}
/// <summary>
/// Gets the keys that are bound.
/// </summary>
@@ -93,7 +129,7 @@ public class KeyBindings
/// <remarks>
/// If <see langword="null"/> the KeyBindings object is being used for Application.KeyBindings.
/// </remarks>
public View? BoundView { get; init; }
public View? Target { get; init; }
/// <summary>Removes all <see cref="KeyBinding"/> objects from the collection.</summary>
public void Clear () { Bindings.Clear (); }
@@ -202,19 +238,27 @@ public class KeyBindings
/// <param name="newKey">The new key to be used. If <see cref="Key.Empty"/> no action will be taken.</param>
public void ReplaceKey (Key oldKey, Key newKey)
{
if (!TryGet (oldKey, out KeyBinding _))
{
throw new InvalidOperationException ($"Key {oldKey} is not bound.");
}
if (!newKey.IsValid)
{
throw new InvalidOperationException ($"Key {newKey} is is not valid.");
}
KeyBinding value = Bindings [oldKey];
Remove (oldKey);
Add (newKey, value);
if (newKey == Key.Empty)
{
Remove (oldKey);
return;
}
if (TryGet (oldKey, out KeyBinding binding))
{
Remove (oldKey);
Add (newKey, binding);
}
else
{
Add (newKey, binding);
}
}
/// <summary>Gets the commands bound with the specified Key.</summary>

View File

@@ -370,7 +370,7 @@ public static class MessageBox
{
Clicked = (int)button.Data!;
}
else if (keyCommandContext.Binding.BoundView is Button btn)
else if (keyCommandContext.Binding.Target is Button btn)
{
Clicked = (int)btn.Data!;
}

View File

@@ -69,7 +69,7 @@ public class RadioGroup : View, IDesignable, IOrientation
if (HasFocus)
{
if (keyCommandContext is { Binding : { } } && (keyCommandContext.Binding.BoundView != this || HotKey == keyCommandContext.Binding.Key?.NoAlt.NoCtrl.NoShift))
if (keyCommandContext is { Binding : { } } && (keyCommandContext.Binding.Target != this || HotKey == keyCommandContext.Binding.Key?.NoAlt.NoCtrl.NoShift))
{
// It's this.HotKey OR Another View (Label?) forwarded the hotkey command to us - Act just like `Space` (Select)
return InvokeCommand (Command.Select);
@@ -248,7 +248,7 @@ public class RadioGroup : View, IDesignable, IOrientation
if (c > -1)
{
// Just like the user pressing the items' hotkey
e.Handled = InvokeCommand<KeyBinding> (Command.HotKey, new KeyBinding ([Command.HotKey], boundView: this, data: c)) == true;
e.Handled = InvokeCommand<KeyBinding> (Command.HotKey, new KeyBinding ([Command.HotKey], target: this, data: c)) == true;
}
}

View File

@@ -140,12 +140,12 @@ public class KeyboardTests
Application.KeyBindings.Add (Key.A, Command.Accept);
Application.KeyBindings.Add (Key.B, Command.Accept);
Assert.True (Application.KeyBindings.TryGet (Key.A, out ApplicationKeyBinding binding));
Assert.True (Application.KeyBindings.TryGet (Key.A, out KeyBinding binding));
Assert.Null (binding.Target);
Assert.True (Application.KeyBindings.TryGet (Key.B, out binding));
Assert.Null (binding.Target);
}
[Fact]
[AutoInitShutdown]
public void KeyBindings_Remove_Removes ()

View File

@@ -58,7 +58,7 @@ public class KeyBindingsTests ()
public void Add_With_Throws_If_Exists ()
{
var keyBindings = new KeyBindings (new View ());
keyBindings.Add (Key.A, Command.HotKey);
keyBindings.Add (Key.A, Command.HotKey);
Assert.Throws<InvalidOperationException> (() => keyBindings.Add (Key.A, Command.Accept));
Command [] resultCommands = keyBindings.GetCommands (Key.A);
@@ -105,7 +105,7 @@ public class KeyBindingsTests ()
var keyBindings = new KeyBindings (new ());
Assert.Empty (keyBindings.Bindings);
Assert.Null (keyBindings.GetKeyFromCommands (Command.Accept));
Assert.NotNull (keyBindings.BoundView);
Assert.NotNull (keyBindings.Target);
}
[Fact]
@@ -243,10 +243,11 @@ public class KeyBindingsTests ()
}
[Fact]
public void ReplaceKey_Throws_If_DoesNotContain_Old ()
public void ReplaceKey_Adds_If_DoesNotContain_Old ()
{
var keyBindings = new KeyBindings (new ());
Assert.Throws<InvalidOperationException> (() => keyBindings.ReplaceKey (Key.A, Key.B));
keyBindings.ReplaceKey (Key.A, Key.B);
Assert.NotEmpty (keyBindings.GetBindings (Key.B));
}
[Fact]