| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381 |
- namespace Terminal.Gui.App;
- /// <summary>
- /// INTERNAL: Implements <see cref="IKeyboard"/> to manage keyboard input and key bindings at the Application level.
- /// <para>
- /// This implementation decouples keyboard handling state from the static <see cref="App"/> class,
- /// enabling parallelizable unit tests and better testability.
- /// </para>
- /// <para>
- /// See <see cref="IKeyboard"/> for usage details.
- /// </para>
- /// </summary>
- internal class KeyboardImpl : IKeyboard
- {
- private Key _quitKey = Key.Esc; // Resources/config.json overrides
- private Key _arrangeKey = Key.F5.WithCtrl; // Resources/config.json overrides
- private Key _nextTabGroupKey = Key.F6; // Resources/config.json overrides
- private Key _nextTabKey = Key.Tab; // Resources/config.json overrides
- private Key _prevTabGroupKey = Key.F6.WithShift; // Resources/config.json overrides
- private Key _prevTabKey = Key.Tab.WithShift; // Resources/config.json overrides
- /// <summary>
- /// Commands for Application.
- /// </summary>
- private readonly Dictionary<Command, View.CommandImplementation> _commandImplementations = new ();
- /// <inheritdoc/>
- public IApplication? App { get; set; }
- /// <inheritdoc/>
- public KeyBindings KeyBindings { get; internal set; } = new (null);
- /// <inheritdoc/>
- public Key QuitKey
- {
- get => _quitKey;
- set
- {
- KeyBindings.Replace (_quitKey, value);
- _quitKey = value;
- }
- }
- /// <inheritdoc/>
- public Key ArrangeKey
- {
- get => _arrangeKey;
- set
- {
- KeyBindings.Replace (_arrangeKey, value);
- _arrangeKey = value;
- }
- }
- /// <inheritdoc/>
- public Key NextTabGroupKey
- {
- get => _nextTabGroupKey;
- set
- {
- KeyBindings.Replace (_nextTabGroupKey, value);
- _nextTabGroupKey = value;
- }
- }
- /// <inheritdoc/>
- public Key NextTabKey
- {
- get => _nextTabKey;
- set
- {
- KeyBindings.Replace (_nextTabKey, value);
- _nextTabKey = value;
- }
- }
- /// <inheritdoc/>
- public Key PrevTabGroupKey
- {
- get => _prevTabGroupKey;
- set
- {
- KeyBindings.Replace (_prevTabGroupKey, value);
- _prevTabGroupKey = value;
- }
- }
- /// <inheritdoc/>
- public Key PrevTabKey
- {
- get => _prevTabKey;
- set
- {
- KeyBindings.Replace (_prevTabKey, value);
- _prevTabKey = value;
- }
- }
- /// <inheritdoc/>
- public event EventHandler<Key>? KeyDown;
- /// <inheritdoc/>
- public event EventHandler<Key>? KeyUp;
- /// <summary>
- /// Initializes keyboard bindings.
- /// </summary>
- public KeyboardImpl ()
- {
- AddKeyBindings ();
- }
- /// <inheritdoc/>
- public bool RaiseKeyDownEvent (Key key)
- {
- //ebug.Assert (App.Application.MainThreadId == Thread.CurrentThread.ManagedThreadId);
- //Logging.Debug ($"{key}");
- // TODO: Add a way to ignore certain keys, esp for debugging.
- //#if DEBUG
- // if (key == Key.Empty.WithAlt || key == Key.Empty.WithCtrl)
- // {
- // Logging.Debug ($"Ignoring {key}");
- // return false;
- // }
- //#endif
- // TODO: This should match standard event patterns
- KeyDown?.Invoke (null, key);
- if (key.Handled)
- {
- return true;
- }
- if (App?.Popover?.DispatchKeyDown (key) is true)
- {
- return true;
- }
- if (App?.Current is null)
- {
- if (App?.SessionStack is { })
- {
- foreach (Toplevel topLevel in App.SessionStack.ToList ())
- {
- if (topLevel.NewKeyDownEvent (key))
- {
- return true;
- }
- if (topLevel.Modal)
- {
- break;
- }
- }
- }
- }
- else
- {
- if (App.Current.NewKeyDownEvent (key))
- {
- return true;
- }
- }
- bool? commandHandled = InvokeCommandsBoundToKey (key);
- if(commandHandled is true)
- {
- return true;
- }
- return false;
- }
- /// <inheritdoc/>
- public bool RaiseKeyUpEvent (Key key)
- {
- if (App?.Initialized != true)
- {
- return true;
- }
- KeyUp?.Invoke (null, key);
- if (key.Handled)
- {
- return true;
- }
- // TODO: Add Popover support
- if (App?.SessionStack is { })
- {
- foreach (Toplevel topLevel in App.SessionStack.ToList ())
- {
- if (topLevel.NewKeyUpEvent (key))
- {
- return true;
- }
- if (topLevel.Modal)
- {
- break;
- }
- }
- }
- return false;
- }
- /// <inheritdoc/>
- public bool? InvokeCommandsBoundToKey (Key key)
- {
- bool? handled = null;
- // Invoke any Application-scoped KeyBindings.
- // The first view that handles the key will stop the loop.
- // foreach (KeyValuePair<Key, KeyBinding> binding in KeyBindings.GetBindings (key))
- if (KeyBindings.TryGet (key, out KeyBinding binding))
- {
- if (binding.Target is { })
- {
- if (!binding.Target.Enabled)
- {
- return null;
- }
- handled = binding.Target?.InvokeCommands (binding.Commands, binding);
- }
- else
- {
- bool? toReturn = null;
- foreach (Command command in binding.Commands)
- {
- toReturn = InvokeCommand (command, key, binding);
- }
- handled = toReturn ?? true;
- }
- }
- return handled;
- }
- /// <inheritdoc/>
- public bool? InvokeCommand (Command command, Key key, KeyBinding binding)
- {
- if (!_commandImplementations.ContainsKey (command))
- {
- throw new NotSupportedException (
- @$"A KeyBinding was set up for the command {command} ({key}) but that command is not supported by Application."
- );
- }
- if (_commandImplementations.TryGetValue (command, out View.CommandImplementation? implementation))
- {
- CommandContext<KeyBinding> context = new (command, null, binding); // Create the context here
- return implementation (context);
- }
- return null;
- }
- /// <summary>
- /// <para>
- /// Sets the function that will be invoked for a <see cref="Command"/>.
- /// </para>
- /// <para>
- /// If AddCommand has already been called for <paramref name="command"/> <paramref name="f"/> will
- /// replace the old one.
- /// </para>
- /// </summary>
- /// <remarks>
- /// <para>
- /// This version of AddCommand is for commands that do not require a <see cref="ICommandContext"/>.
- /// </para>
- /// </remarks>
- /// <param name="command">The command.</param>
- /// <param name="f">The function.</param>
- private void AddCommand (Command command, Func<bool?> f) { _commandImplementations [command] = ctx => f (); }
- internal void AddKeyBindings ()
- {
- _commandImplementations.Clear ();
- // Things Application knows how to do
- AddCommand (
- Command.Quit,
- () =>
- {
- App?.RequestStop ();
- return true;
- }
- );
- AddCommand (
- Command.Suspend,
- () =>
- {
- App?.Driver?.Suspend ();
- return true;
- }
- );
- AddCommand (
- Command.NextTabStop,
- () => App?.Navigation?.AdvanceFocus (NavigationDirection.Forward, TabBehavior.TabStop));
- AddCommand (
- Command.PreviousTabStop,
- () => App?.Navigation?.AdvanceFocus (NavigationDirection.Backward, TabBehavior.TabStop));
- AddCommand (
- Command.NextTabGroup,
- () => App?.Navigation?.AdvanceFocus (NavigationDirection.Forward, TabBehavior.TabGroup));
- AddCommand (
- Command.PreviousTabGroup,
- () => App?.Navigation?.AdvanceFocus (NavigationDirection.Backward, TabBehavior.TabGroup));
- AddCommand (
- Command.Refresh,
- () =>
- {
- App?.LayoutAndDraw (true);
- return true;
- }
- );
- AddCommand (
- Command.Arrange,
- () =>
- {
- View? viewToArrange = App?.Navigation?.GetFocused ();
- // Go up the superview hierarchy and find the first that is not ViewArrangement.Fixed
- while (viewToArrange is { SuperView: { }, Arrangement: ViewArrangement.Fixed })
- {
- viewToArrange = viewToArrange.SuperView;
- }
- if (viewToArrange is { })
- {
- return viewToArrange.Border?.EnterArrangeMode (ViewArrangement.Fixed);
- }
- return false;
- });
- //SetKeysToHardCodedDefaults ();
- // Need to clear after setting the above to ensure actually clear
- // because set_QuitKey etc.. may call Add
- KeyBindings.Clear ();
- KeyBindings.Add (QuitKey, Command.Quit);
- KeyBindings.Add (NextTabKey, Command.NextTabStop);
- KeyBindings.Add (PrevTabKey, Command.PreviousTabStop);
- KeyBindings.Add (NextTabGroupKey, Command.NextTabGroup);
- KeyBindings.Add (PrevTabGroupKey, Command.PreviousTabGroup);
- KeyBindings.Add (ArrangeKey, Command.Arrange);
- KeyBindings.Add (Key.CursorRight, Command.NextTabStop);
- KeyBindings.Add (Key.CursorDown, Command.NextTabStop);
- KeyBindings.Add (Key.CursorLeft, Command.PreviousTabStop);
- KeyBindings.Add (Key.CursorUp, Command.PreviousTabStop);
- // TODO: Refresh Key should be configurable
- KeyBindings.Add (Key.F5, Command.Refresh);
- // TODO: Suspend Key should be configurable
- if (Environment.OSVersion.Platform == PlatformID.Unix)
- {
- KeyBindings.Add (Key.Z.WithCtrl, Command.Suspend);
- }
- }
- }
|