From cdcc2d3077ae0ea0e1f6871fc861cd1e64f75f12 Mon Sep 17 00:00:00 2001 From: Cody Simonds <36618932+CodySimonds65@users.noreply.github.com> Date: Tue, 6 Oct 2026 00:24:03 -0500 Subject: [PATCH] feat: let shortcuts use the middle and side mouse buttons and the scroll wheel Middle click, Mouse 4, Mouse 5, scroll up and scroll down can be recorded for any shortcut, with or without Ctrl, Alt or Shift. Windows cannot register a mouse button as a hotkey, so these are observed through raw input like plain keys: the click or scroll still reaches the game. They only act while a FourFold window is in front, and the mouse is only listened to while a mouse shortcut is bound. Left and right click stay unavailable. --- README.md | 2 + .../Input/PlainKeyShortcutMatcherTests.cs | 40 ++++ .../Models/GlobalHotkeyChordTests.cs | 45 ++++ .../Input/PlainKeyShortcutMatcher.cs | 25 +- .../Models/GlobalHotkeyChord.cs | 29 ++- .../Services/GlobalShortcutRegistryTests.cs | 4 +- .../Services/RawInputListenerTests.cs | 75 ++++++ .../MainWindow.xaml.cs | 41 ++-- .../Services/PlainKeyRoutingRegistrar.cs | 11 +- .../Services/RawInputListener.cs | 224 ++++++++++++++++++ .../Services/RawKeyboardListener.cs | 140 ----------- .../Views/SettingsDialog.xaml | 5 +- .../Views/SettingsDialog.xaml.cs | 31 ++- .../Views/ShortcutCapture.cs | 33 ++- .../Views/ShortcutText.cs | 9 + .../Views/TimerSettingsPage.xaml | 1 + .../Views/TimerSettingsPage.xaml.cs | 31 ++- 17 files changed, 553 insertions(+), 193 deletions(-) create mode 100644 src/FourFoldAccountManager.Core.Tests/Models/GlobalHotkeyChordTests.cs create mode 100644 src/FourFoldAccountManager.Desktop.Tests/Services/RawInputListenerTests.cs create mode 100644 src/FourFoldAccountManager.Desktop/Services/RawInputListener.cs delete mode 100644 src/FourFoldAccountManager.Desktop/Services/RawKeyboardListener.cs diff --git a/README.md b/README.md index ed33231..57514be 100644 --- a/README.md +++ b/README.md @@ -37,6 +37,8 @@ App shortcuts can be changed on the **Shortcuts** tab in Settings; the Timer's k | Reveal overlays tab | Ctrl+Alt+Shift+O | | Toggle divider resizing | Ctrl+Alt+Shift+L | +A shortcut can be a key, the middle or a side mouse button, or the scroll wheel, each with or without Ctrl, Alt or Shift. A mouse shortcut still reaches the game and only works while FourFold is the window in front. + **Esc** leaves full screen or theatre mode. **F5** reloads a game panel and can't be rebound. ## Install diff --git a/src/FourFoldAccountManager.Core.Tests/Input/PlainKeyShortcutMatcherTests.cs b/src/FourFoldAccountManager.Core.Tests/Input/PlainKeyShortcutMatcherTests.cs index 669998f..1ee8f10 100644 --- a/src/FourFoldAccountManager.Core.Tests/Input/PlainKeyShortcutMatcherTests.cs +++ b/src/FourFoldAccountManager.Core.Tests/Input/PlainKeyShortcutMatcherTests.cs @@ -48,4 +48,44 @@ public void HoldingAPlainKeyFiresOnceUntilItIsReleased() Assert.Equal(GlobalShortcutAction.TimerSplit, matcher.KeyDown(S)); } + + [Fact] + public void AMouseShortcutWithModifiersFiresOnlyWhenExactlyThoseModifiersAreHeld() + { + var matcher = new PlainKeyShortcutMatcher(); + matcher.SetBindings(new Dictionary + { + [GlobalShortcutAction.NextTab] = new(GlobalHotkeyChord.MiddleClick, GlobalHotkeyModifiers.Control) + }); + + // A bare middle click is the game's own; it must not switch tabs. + Assert.Null(matcher.KeyDown(GlobalHotkeyChord.MiddleClick)); + matcher.KeyUp(GlobalHotkeyChord.MiddleClick); + + Assert.Null(matcher.KeyDown(LeftControl)); + Assert.Equal(GlobalShortcutAction.NextTab, matcher.KeyDown(GlobalHotkeyChord.MiddleClick)); + matcher.KeyUp(GlobalHotkeyChord.MiddleClick); + + Assert.Null(matcher.KeyDown(LeftShift)); + Assert.Null(matcher.KeyDown(GlobalHotkeyChord.MiddleClick)); + } + + [Fact] + public void APlainMouseShortcutFiresWithModifiersHeldUnlessThatComboIsAnotherShortcut() + { + var matcher = new PlainKeyShortcutMatcher(); + matcher.SetBindings(new Dictionary + { + [GlobalShortcutAction.TimerSplit] = new(GlobalHotkeyChord.MouseButton4, GlobalHotkeyModifiers.None), + [GlobalShortcutAction.TimerReset] = new(GlobalHotkeyChord.MouseButton4, GlobalHotkeyModifiers.Shift) + }); + + Assert.Null(matcher.KeyDown(LeftShift)); + Assert.Equal(GlobalShortcutAction.TimerReset, matcher.KeyDown(GlobalHotkeyChord.MouseButton4)); + matcher.KeyUp(GlobalHotkeyChord.MouseButton4); + matcher.KeyUp(LeftShift); + + Assert.Null(matcher.KeyDown(LeftControl)); + Assert.Equal(GlobalShortcutAction.TimerSplit, matcher.KeyDown(GlobalHotkeyChord.MouseButton4)); + } } diff --git a/src/FourFoldAccountManager.Core.Tests/Models/GlobalHotkeyChordTests.cs b/src/FourFoldAccountManager.Core.Tests/Models/GlobalHotkeyChordTests.cs new file mode 100644 index 0000000..b4f65d3 --- /dev/null +++ b/src/FourFoldAccountManager.Core.Tests/Models/GlobalHotkeyChordTests.cs @@ -0,0 +1,45 @@ +using FourFoldAccountManager.Core.Models; +using Xunit; + +namespace FourFoldAccountManager.Core.Tests.Models; + +public sealed class GlobalHotkeyChordTests +{ + [Theory] + [InlineData(GlobalHotkeyChord.MiddleClick)] + [InlineData(GlobalHotkeyChord.MouseButton4)] + [InlineData(GlobalHotkeyChord.MouseButton5)] + [InlineData(GlobalHotkeyChord.ScrollUp)] + [InlineData(GlobalHotkeyChord.ScrollDown)] + public void MouseInputsAreValidAndObservedWithOrWithoutModifiers(ushort mouseInput) + { + var plain = new GlobalHotkeyChord(mouseInput, GlobalHotkeyModifiers.None); + var withModifiers = new GlobalHotkeyChord(mouseInput, GlobalHotkeyModifiers.Control | GlobalHotkeyModifiers.Shift); + + Assert.True(plain.IsValid); + Assert.True(withModifiers.IsValid); + // Windows cannot register a mouse button as a hotkey, so even Ctrl+Middle click has to be observed. + Assert.True(plain.IsObserved); + Assert.True(withModifiers.IsObserved); + } + + // Left and right click would fire on every click; F5 must stay the game panels' refresh. + [Theory] + [InlineData(0x01)] // Left click + [InlineData(0x02)] // Right click + [InlineData(0x03)] // Ctrl+Break + [InlineData(0x74)] // F5 + [InlineData(0x102)] // One past the scroll codes + public void LeftClickRightClickAndF5StayInvalid(ushort virtualKey) + { + Assert.False(new GlobalHotkeyChord(virtualKey, GlobalHotkeyModifiers.None).IsValid); + Assert.False(new GlobalHotkeyChord(virtualKey, GlobalHotkeyModifiers.Control).IsValid); + } + + [Fact] + public void AKeyWithModifiersIsStillRegisteredWithWindowsRatherThanObserved() + { + Assert.False(new GlobalHotkeyChord(0x53, GlobalHotkeyModifiers.Control).IsObserved); + Assert.True(new GlobalHotkeyChord(0x53, GlobalHotkeyModifiers.None).IsObserved); + } +} diff --git a/src/FourFoldAccountManager.Core/Input/PlainKeyShortcutMatcher.cs b/src/FourFoldAccountManager.Core/Input/PlainKeyShortcutMatcher.cs index 89ba173..a267e36 100644 --- a/src/FourFoldAccountManager.Core/Input/PlainKeyShortcutMatcher.cs +++ b/src/FourFoldAccountManager.Core/Input/PlainKeyShortcutMatcher.cs @@ -2,9 +2,10 @@ namespace FourFoldAccountManager.Core.Input; -// Decides which plain-key shortcut a key press fires. Plain keys are only observed, never blocked, so this -// tracks held keys itself: a held key fires once, and held Ctrl, Alt, or Shift never stop a plain key unless -// that exact combination is another active shortcut's modifier chord (which fires through Windows instead). +// Decides which observed shortcut a key press or mouse input fires. These are only observed, never blocked, +// so this tracks held keys itself: a held key fires once, and held Ctrl, Alt, or Shift never stop a shortcut +// bound without them unless that exact combination is another active shortcut (a key chord with a modifier +// fires through Windows instead; a mouse shortcut with modifiers fires here, on exactly those modifiers). public sealed class PlainKeyShortcutMatcher { private readonly HashSet _held = []; @@ -25,20 +26,22 @@ public void SetBindings(IReadOnlyDictionary _held.Remove(virtualKey); diff --git a/src/FourFoldAccountManager.Core/Models/GlobalHotkeyChord.cs b/src/FourFoldAccountManager.Core/Models/GlobalHotkeyChord.cs index bf33c84..d87c6b4 100644 --- a/src/FourFoldAccountManager.Core/Models/GlobalHotkeyChord.cs +++ b/src/FourFoldAccountManager.Core/Models/GlobalHotkeyChord.cs @@ -15,6 +15,14 @@ public sealed record GlobalHotkeyChord( [property: JsonRequired, JsonNumberHandling(JsonNumberHandling.Strict)] ushort VirtualKey, [property: JsonRequired] GlobalHotkeyModifiers Modifiers) { + // Mouse inputs share the key field. The buttons use their Windows virtual-key codes; the wheel has none, so + // its two directions sit just past the keyboard range, where no key can ever collide with them. + public const ushort MiddleClick = 0x04; + public const ushort MouseButton4 = 0x05; + public const ushort MouseButton5 = 0x06; + public const ushort ScrollUp = 0x100; + public const ushort ScrollDown = 0x101; + private const GlobalHotkeyModifiers SupportedModifiers = GlobalHotkeyModifiers.Control | GlobalHotkeyModifiers.Alt | GlobalHotkeyModifiers.Shift; @@ -44,17 +52,26 @@ public sealed record GlobalHotkeyChord( // Any key except the Windows keys, the modifier keys, and F5, with or without Ctrl, Alt, or Shift. F5 stays // a browser refresh for the game panels. Esc, Tab, Enter, and Backspace sit below 0x20 and stay excluded - // because they drive the Settings dialog. + // because they drive the Settings dialog. Also the middle and side mouse buttons and the wheel; left and + // right click stay excluded because they would fire on every click. [JsonIgnore] public bool IsValid => - (VirtualKey is >= 0x20 and <= 0xFE || VirtualKey == 0x13) && - VirtualKey is not (0x5B or 0x5C or 0x74 or >= 0xA0 and <= 0xA5) && + (IsMouse || + (VirtualKey is >= 0x20 and <= 0xFE || VirtualKey == 0x13) && + VirtualKey is not (0x5B or 0x5C or 0x74 or >= 0xA0 and <= 0xA5)) && (Modifiers & ~SupportedModifiers) == 0; - // A key with no Ctrl, Alt, or Shift. FourFold listens for it through raw input and never takes it from - // the game or other apps; only modifier chords are registered with Windows. [JsonIgnore] - public bool IsPlainKey => Modifiers == GlobalHotkeyModifiers.None; + public bool IsMouse => IsMouseInput(VirtualKey); + + // A key with no Ctrl, Alt, or Shift, or any mouse input. FourFold listens for these through raw input and + // never takes them from the game or other apps; only key chords with a modifier are registered with + // Windows, which cannot register a mouse button at all. + [JsonIgnore] + public bool IsObserved => IsMouse || Modifiers == GlobalHotkeyModifiers.None; + + public static bool IsMouseInput(ushort input) => + input is MiddleClick or MouseButton4 or MouseButton5 or ScrollUp or ScrollDown; public static bool TryCreate( ushort virtualKey, diff --git a/src/FourFoldAccountManager.Desktop.Tests/Services/GlobalShortcutRegistryTests.cs b/src/FourFoldAccountManager.Desktop.Tests/Services/GlobalShortcutRegistryTests.cs index 8054768..5b1e61a 100644 --- a/src/FourFoldAccountManager.Desktop.Tests/Services/GlobalShortcutRegistryTests.cs +++ b/src/FourFoldAccountManager.Desktop.Tests/Services/GlobalShortcutRegistryTests.cs @@ -74,7 +74,7 @@ public async Task FailedSaveMixingPlainKeysAndChordsKeepsEveryOldBindingAndNever Assert.True(registry.TryResolve(windows.IdOf(GlobalHotkeyChord.DefaultTimerSplit), current, out var resolved)); Assert.Equal(GlobalShortcutAction.TimerSplit, resolved); // RegisterHotKey would take a plain key from every other app, so plain keys must never reach Windows. - Assert.DoesNotContain(windows.Registered.Values, chord => chord.IsPlainKey); + Assert.DoesNotContain(windows.Registered.Values, chord => chord.IsObserved); // Retrying without the refused chord must succeed: a plain key leaked by the rollback would be refused // as a duplicate here, leaving the user unable to bind it. @@ -86,7 +86,7 @@ public async Task FailedSaveMixingPlainKeysAndChordsKeepsEveryOldBindingAndNever Assert.Equal(1, persisted); Assert.Equal(PlainF, registry.ActiveChords(retry)[GlobalShortcutAction.TimerSplit]); Assert.Equal(PlainH, registry.ActiveChords(retry)[GlobalShortcutAction.TimerFinish]); - Assert.DoesNotContain(windows.Registered.Values, chord => chord.IsPlainKey); + Assert.DoesNotContain(windows.Registered.Values, chord => chord.IsObserved); } private sealed class FakeRegistrar : IGlobalHotkeyRegistrar diff --git a/src/FourFoldAccountManager.Desktop.Tests/Services/RawInputListenerTests.cs b/src/FourFoldAccountManager.Desktop.Tests/Services/RawInputListenerTests.cs new file mode 100644 index 0000000..db5fed7 --- /dev/null +++ b/src/FourFoldAccountManager.Desktop.Tests/Services/RawInputListenerTests.cs @@ -0,0 +1,75 @@ +using FourFoldAccountManager.Core.Models; +using FourFoldAccountManager.Desktop.Services; +using Xunit; + +namespace FourFoldAccountManager.Desktop.Tests.Services; + +public sealed class RawInputListenerTests +{ + private const ushort LeftDown = 0x0001; + private const ushort RightDown = 0x0004; + private const ushort MiddleDown = 0x0010; + private const ushort MiddleUp = 0x0020; + private const ushort Button4Down = 0x0040; + private const ushort Button5Up = 0x0200; + private const ushort Wheel = 0x0400; + private const ushort HorizontalWheel = 0x0800; + + [Fact] + public void MouseButtonsDecodeToTheirShortcutCodes() + { + Assert.Equal([(GlobalHotkeyChord.MiddleClick, true)], Decode(MiddleDown)); + Assert.Equal([(GlobalHotkeyChord.MiddleClick, false)], Decode(MiddleUp)); + // One raw event can carry several button changes. + Assert.Equal( + [(GlobalHotkeyChord.MouseButton4, true), (GlobalHotkeyChord.MouseButton5, false)], + Decode(Button4Down | Button5Up)); + } + + // The wheel has no release, so each notch is a press followed at once by its release; otherwise the second + // notch would look like a held key and never fire. + [Fact] + public void EachWheelNotchDecodesToAPressAndReleaseInItsDirection() + { + Assert.Equal([(GlobalHotkeyChord.ScrollUp, true), (GlobalHotkeyChord.ScrollUp, false)], Decode(Wheel, 120)); + Assert.Equal([(GlobalHotkeyChord.ScrollDown, true), (GlobalHotkeyChord.ScrollDown, false)], Decode(Wheel, -120)); + } + + // Smooth-scrolling wheels report a notch in pieces; firing on every piece would skip several tabs at once. + [Fact] + public void ASmoothWheelFiresOncePerFullNotchAndStartsOverWhenItTurnsBack() + { + var remainder = 0; + + Assert.Empty(Decode(Wheel, 60, ref remainder)); + Assert.Equal( + [(GlobalHotkeyChord.ScrollUp, true), (GlobalHotkeyChord.ScrollUp, false)], Decode(Wheel, 60, ref remainder)); + Assert.Empty(Decode(Wheel, 90, ref remainder)); + // Turning back must not be cancelled out by the 90 still pending the other way. + Assert.Equal( + [(GlobalHotkeyChord.ScrollDown, true), (GlobalHotkeyChord.ScrollDown, false)], + Decode(Wheel, -120, ref remainder)); + } + + [Fact] + public void LeftClickRightClickSidewaysScrollAndMovementDecodeToNothing() + { + Assert.Empty(Decode(LeftDown | RightDown)); + Assert.Empty(Decode(HorizontalWheel, 120)); + Assert.Empty(Decode(0)); + } + + private static List<(ushort Input, bool IsDown)> Decode(int buttonFlags, short wheelDelta = 0) + { + var remainder = 0; + return Decode(buttonFlags, wheelDelta, ref remainder); + } + + private static List<(ushort Input, bool IsDown)> Decode(int buttonFlags, short wheelDelta, ref int remainder) + { + var inputs = new List<(ushort, bool)>(); + RawInputListener.DecodeMouse( + (ushort)buttonFlags, wheelDelta, ref remainder, (input, isDown) => inputs.Add((input, isDown))); + return inputs; + } +} diff --git a/src/FourFoldAccountManager.Desktop/MainWindow.xaml.cs b/src/FourFoldAccountManager.Desktop/MainWindow.xaml.cs index 6381687..4bb23a3 100644 --- a/src/FourFoldAccountManager.Desktop/MainWindow.xaml.cs +++ b/src/FourFoldAccountManager.Desktop/MainWindow.xaml.cs @@ -53,7 +53,7 @@ public partial class MainWindow : Window private readonly BuiltInPluginSet _plugins; private HwndSource? _windowSource; private GlobalShortcutRegistry? _shortcuts; - private RawKeyboardListener? _rawKeyboard; + private RawInputListener? _rawInput; private readonly PlainKeyShortcutMatcher _plainKeys = new(); // Recording a shortcut must not reveal overlays, toggle dividers, or change a live run. private bool _settingsDialogOpen; @@ -188,9 +188,9 @@ private void MainWindow_SourceInitialized(object? sender, EventArgs e) } _windowSource.AddHook(MainWindow_HwndSourceHook); - _rawKeyboard = RawKeyboardListener.TryRegister(windowHandle); + _rawInput = RawInputListener.TryRegister(windowHandle, HandleObservedInput); _shortcuts = new GlobalShortcutRegistry(new PlainKeyRoutingRegistrar( - new WindowsGlobalHotkeyRegistrar(windowHandle), plainKeysAvailable: _rawKeyboard is not null)); + new WindowsGlobalHotkeyRegistrar(windowHandle), plainKeysAvailable: _rawInput is not null)); } private IntPtr MainWindow_HwndSourceHook( @@ -202,12 +202,8 @@ private IntPtr MainWindow_HwndSourceHook( { if (message == WmInput) { - // Plain keys are only observed; leaving WM_INPUT unhandled lets Windows finish with it. - if (_rawKeyboard is { } rawKeyboard && rawKeyboard.TryRead(lParam, out var virtualKey, out var isKeyDown)) - { - HandlePlainKey(virtualKey, isKeyDown); - } - + // Plain keys and mouse inputs are only observed; leaving WM_INPUT unhandled lets Windows finish with it. + _rawInput?.Read(lParam); return IntPtr.Zero; } @@ -261,15 +257,18 @@ private void StepTab(int direction) } } - private void HandlePlainKey(ushort virtualKey, bool isKeyDown) + // A plain key or a mouse input, as raw input reports it whichever app is in front. + private void HandleObservedInput(ushort input, bool isDown) { - if (!isKeyDown) + if (!isDown) { - _plainKeys.KeyUp(virtualKey); + _plainKeys.KeyUp(input); return; } - if (_plainKeys.KeyDown(virtualKey) is { } action && !IsTypingInFourFold()) + // A mouse shortcut only acts while FourFold is in front: scrolling in another app must not switch tabs. + if (_plainKeys.KeyDown(input) is { } action && + (GlobalHotkeyChord.IsMouseInput(input) ? RawInputListener.IsThisAppInFront() : !IsTypingInFourFold())) { HandleGlobalShortcut(action); } @@ -281,9 +280,13 @@ private static bool IsTypingInFourFold() => System.Windows.Input.Keyboard.FocusedElement is TextBoxBase or PasswordBox && Application.Current.Windows.OfType().Any(window => window.IsActive); - private void RefreshPlainKeyBindings() => - _plainKeys.SetBindings(_shortcuts?.ActiveChords(_panelSettings) ?? - new Dictionary()); + private void RefreshPlainKeyBindings() + { + var bindings = _shortcuts?.ActiveChords(_panelSettings) ?? + new Dictionary(); + _plainKeys.SetBindings(bindings); + _rawInput?.SetMouseEnabled(bindings.Values.Any(chord => chord.IsMouse)); + } private void UpdateTimerHotkeys() { @@ -3488,11 +3491,11 @@ private void CompleteShutdown() // Native hotkey cleanup must not prevent the manager from closing. } - var rawKeyboard = _rawKeyboard; - _rawKeyboard = null; + var rawInput = _rawInput; + _rawInput = null; try { - rawKeyboard?.Dispose(); + rawInput?.Dispose(); } catch { diff --git a/src/FourFoldAccountManager.Desktop/Services/PlainKeyRoutingRegistrar.cs b/src/FourFoldAccountManager.Desktop/Services/PlainKeyRoutingRegistrar.cs index f038e6f..7f8ae57 100644 --- a/src/FourFoldAccountManager.Desktop/Services/PlainKeyRoutingRegistrar.cs +++ b/src/FourFoldAccountManager.Desktop/Services/PlainKeyRoutingRegistrar.cs @@ -2,10 +2,11 @@ namespace FourFoldAccountManager.Desktop.Services; -// RegisterHotKey takes its key from every other app, so plain keys never go there. They "register" by being -// listened for through raw input: available exactly when the raw keyboard listener is, and refused on the -// same key twice, like Windows refuses a duplicate chord. Modifier chords pass through unchanged, so the -// coordinator's atomic replace covers both kinds. +// RegisterHotKey takes its key from every other app and cannot take a mouse button at all, so plain keys and +// mouse inputs never go there. They "register" by being listened for through raw input: available exactly +// when the raw input listener is, and refused on the same input twice, like Windows refuses a duplicate +// chord. Key chords with a modifier pass through unchanged, so the coordinator's atomic replace covers both +// kinds. internal sealed class PlainKeyRoutingRegistrar(IGlobalHotkeyRegistrar chords, bool plainKeysAvailable) : IGlobalHotkeyRegistrar { @@ -14,7 +15,7 @@ internal sealed class PlainKeyRoutingRegistrar(IGlobalHotkeyRegistrar chords, bo public bool TryRegister(int id, GlobalHotkeyChord chord) { ArgumentNullException.ThrowIfNull(chord); - if (!chord.IsPlainKey) + if (!chord.IsObserved) { return chords.TryRegister(id, chord); } diff --git a/src/FourFoldAccountManager.Desktop/Services/RawInputListener.cs b/src/FourFoldAccountManager.Desktop/Services/RawInputListener.cs new file mode 100644 index 0000000..cbfde8d --- /dev/null +++ b/src/FourFoldAccountManager.Desktop/Services/RawInputListener.cs @@ -0,0 +1,224 @@ +using System.Runtime.InteropServices; +using FourFoldAccountManager.Core.Models; + +namespace FourFoldAccountManager.Desktop.Services; + +// Hears every key press, and while a mouse shortcut is bound the mouse buttons and wheel, through Windows raw +// input without taking them from the game or any other app. Observed shortcuts use this; key chords with a +// modifier still go through RegisterHotKey. WM_INPUT must be left unhandled so DefWindowProc can clean up +// after it. +internal sealed class RawInputListener : IDisposable +{ + private const ushort GenericDesktopPage = 0x01; + private const ushort MouseUsage = 0x02; + private const ushort KeyboardUsage = 0x06; + private const uint RemoveDevice = 0x00000001; + private const uint InputSink = 0x00000100; + private const uint RawInputCommand = 0x10000003; + private const uint MouseInput = 0; + private const uint KeyboardInput = 1; + private const ushort KeyBreak = 0x01; + private const ushort KeyE0 = 0x02; + private const int NumLock = 0x90; + private const ushort WheelFlag = 0x0400; + private const int WheelNotch = 120; + + // RAWMOUSE button flags: pressed, released, and the shortcut input they stand for. + private static readonly (ushort Down, ushort Up, ushort Input)[] MouseButtons = + [ + (0x0010, 0x0020, GlobalHotkeyChord.MiddleClick), + (0x0040, 0x0080, GlobalHotkeyChord.MouseButton4), + (0x0100, 0x0200, GlobalHotkeyChord.MouseButton5) + ]; + + private readonly IntPtr _windowHandle; + private readonly Action _onInput; + private bool _mouseEnabled; + private int _wheelRemainder; + + private RawInputListener(IntPtr windowHandle, Action onInput) + { + _windowHandle = windowHandle; + _onInput = onInput; + } + + // Returns null when Windows refuses the registration; observed shortcuts then show as unavailable. + // onInput receives each key or mouse input and whether it was pressed (true) or released (false). + public static RawInputListener? TryRegister(IntPtr windowHandle, Action onInput) => + Register(KeyboardUsage, InputSink, windowHandle) ? new RawInputListener(windowHandle, onInput) : null; + + // Once the mouse is registered every mouse movement arrives as a message too, so it is only switched on + // while a mouse shortcut is bound. + public void SetMouseEnabled(bool enabled) + { + if (enabled != _mouseEnabled && + Register(MouseUsage, enabled ? InputSink : RemoveDevice, enabled ? _windowHandle : IntPtr.Zero)) + { + _mouseEnabled = enabled; + _wheelRemainder = 0; + } + } + + // Raw input reaches this window whichever app is in front; mouse shortcuts only act while FourFold is. + public static bool IsThisAppInFront() => + GetWindowThreadProcessId(GetForegroundWindow(), out var processId) != 0 && processId == Environment.ProcessId; + + // Reads one WM_INPUT event and reports what it holds. Other devices and the fake keys Windows inserts + // report nothing. + public void Read(IntPtr rawInputHandle) + { + var headerSize = (uint)(8 + 2 * IntPtr.Size); + uint size = 0; + if (GetRawInputData(rawInputHandle, RawInputCommand, IntPtr.Zero, ref size, headerSize) != 0 || size == 0) + { + return; + } + + var buffer = Marshal.AllocHGlobal((int)size); + try + { + if (GetRawInputData(rawInputHandle, RawInputCommand, buffer, ref size, headerSize) != size) + { + return; + } + + var data = buffer + (int)headerSize; + switch ((uint)Marshal.ReadInt32(buffer)) + { + case KeyboardInput: + ReadKeyboard(data); + break; + case MouseInput: + // RAWMOUSE: Flags (16-bit), padding, then ButtonFlags and ButtonData (both 16-bit). + DecodeMouse( + (ushort)Marshal.ReadInt16(data, 4), Marshal.ReadInt16(data, 6), ref _wheelRemainder, _onInput); + break; + } + } + finally + { + Marshal.FreeHGlobal(buffer); + } + } + + // Turns one raw mouse event into shortcut inputs. Left click, right click, sideways scrolling and plain + // movement report nothing. The wheel has no release, so each notch is a press followed at once by its + // release; smooth-scrolling wheels send fractions of a notch, which add up in wheelRemainder first. + internal static void DecodeMouse( + ushort buttonFlags, short wheelDelta, ref int wheelRemainder, Action onInput) + { + foreach (var (down, up, input) in MouseButtons) + { + if ((buttonFlags & down) != 0) + { + onInput(input, true); + } + + if ((buttonFlags & up) != 0) + { + onInput(input, false); + } + } + + if ((buttonFlags & WheelFlag) == 0 || wheelDelta == 0) + { + return; + } + + // Turning the wheel the other way starts a fresh notch. + wheelRemainder = Math.Sign(wheelRemainder) == -Math.Sign(wheelDelta) ? wheelDelta : wheelRemainder + wheelDelta; + var scroll = wheelRemainder > 0 ? GlobalHotkeyChord.ScrollUp : GlobalHotkeyChord.ScrollDown; + for (; Math.Abs(wheelRemainder) >= WheelNotch; wheelRemainder -= Math.Sign(wheelRemainder) * WheelNotch) + { + onInput(scroll, true); + onInput(scroll, false); + } + } + + public void Dispose() + { + _ = Register(KeyboardUsage, RemoveDevice, IntPtr.Zero); + SetMouseEnabled(false); + } + + private void ReadKeyboard(IntPtr keyboard) + { + // RAWKEYBOARD: MakeCode, Flags, Reserved, VKey (all 16-bit), right after the header. + var makeCode = (ushort)Marshal.ReadInt16(keyboard, 0); + var flags = (ushort)Marshal.ReadInt16(keyboard, 2); + var reportedKey = (ushort)Marshal.ReadInt16(keyboard, 6); + var isE0 = (flags & KeyE0) != 0; + // 0xFF marks keys Windows fakes; some keyboards also wrap numpad keys in an extra Shift carrying the + // E0 flag, which a real Shift press never has. + if (reportedKey is 0 or 0xFF || (reportedKey == 0x10 && isE0)) + { + return; + } + + _onInput(Normalize(reportedKey, makeCode, isE0), (flags & KeyBreak) == 0); + } + + private static bool Register(ushort usage, uint flags, IntPtr target) + { + var device = new RawInputDevice + { + UsagePage = GenericDesktopPage, + Usage = usage, + Flags = flags, + Target = target + }; + return RegisterRawInputDevices([device], 1, (uint)Marshal.SizeOf()); + } + + // Raw input reports generic Shift, Ctrl, and Alt, and numpad keys as the navigation keys they share, so map + // them to what a key press in a window reports; recorded shortcuts use those codes. + private static ushort Normalize(ushort reportedKey, ushort makeCode, bool isE0) => reportedKey switch + { + 0x10 => makeCode == 0x36 ? (ushort)0xA1 : (ushort)0xA0, + 0x11 => isE0 ? (ushort)0xA3 : (ushort)0xA2, + 0x12 => isE0 ? (ushort)0xA5 : (ushort)0xA4, + _ when !isE0 && (GetKeyState(NumLock) & 1) != 0 && NumpadKey(reportedKey) is { } numpad => numpad, + _ => reportedKey + }; + + private static ushort? NumpadKey(ushort navigationKey) => navigationKey switch + { + 0x2D => 0x60, // Insert -> Num 0 + 0x23 => 0x61, // End -> Num 1 + 0x28 => 0x62, // Down -> Num 2 + 0x22 => 0x63, // Page Down -> Num 3 + 0x25 => 0x64, // Left -> Num 4 + 0x0C => 0x65, // Clear -> Num 5 + 0x27 => 0x66, // Right -> Num 6 + 0x24 => 0x67, // Home -> Num 7 + 0x26 => 0x68, // Up -> Num 8 + 0x21 => 0x69, // Page Up -> Num 9 + 0x2E => 0x6E, // Delete -> Num . + _ => null + }; + + [StructLayout(LayoutKind.Sequential)] + private struct RawInputDevice + { + public ushort UsagePage; + public ushort Usage; + public uint Flags; + public IntPtr Target; + } + + [DllImport("user32.dll", SetLastError = true)] + [return: MarshalAs(UnmanagedType.Bool)] + private static extern bool RegisterRawInputDevices(RawInputDevice[] devices, uint count, uint size); + + [DllImport("user32.dll", SetLastError = true)] + private static extern uint GetRawInputData(IntPtr rawInput, uint command, IntPtr data, ref uint size, uint headerSize); + + [DllImport("user32.dll")] + private static extern short GetKeyState(int virtualKey); + + [DllImport("user32.dll")] + private static extern IntPtr GetForegroundWindow(); + + [DllImport("user32.dll")] + private static extern uint GetWindowThreadProcessId(IntPtr windowHandle, out uint processId); +} diff --git a/src/FourFoldAccountManager.Desktop/Services/RawKeyboardListener.cs b/src/FourFoldAccountManager.Desktop/Services/RawKeyboardListener.cs deleted file mode 100644 index 215d0ae..0000000 --- a/src/FourFoldAccountManager.Desktop/Services/RawKeyboardListener.cs +++ /dev/null @@ -1,140 +0,0 @@ -using System.Runtime.InteropServices; - -namespace FourFoldAccountManager.Desktop.Services; - -// Hears every key press through Windows raw input without taking it from the game or any other app. Plain-key -// shortcuts use this; modifier chords still go through RegisterHotKey. WM_INPUT must be left unhandled so -// DefWindowProc can clean up after it. -internal sealed class RawKeyboardListener : IDisposable -{ - private const ushort GenericDesktopPage = 0x01; - private const ushort KeyboardUsage = 0x06; - private const uint RemoveDevice = 0x00000001; - private const uint InputSink = 0x00000100; - private const uint RawInputCommand = 0x10000003; - private const uint KeyboardInput = 1; - private const ushort KeyBreak = 0x01; - private const ushort KeyE0 = 0x02; - private const int NumLock = 0x90; - - private RawKeyboardListener() - { - } - - // Returns null when Windows refuses the registration; plain-key shortcuts then show as unavailable. - public static RawKeyboardListener? TryRegister(IntPtr windowHandle) - { - var device = new RawInputDevice - { - UsagePage = GenericDesktopPage, - Usage = KeyboardUsage, - Flags = InputSink, - Target = windowHandle - }; - return RegisterRawInputDevices([device], 1, (uint)Marshal.SizeOf()) - ? new RawKeyboardListener() - : null; - } - - // Reads one WM_INPUT event. Returns false for other devices and for the fake keys Windows inserts. - public bool TryRead(IntPtr rawInputHandle, out ushort virtualKey, out bool isKeyDown) - { - virtualKey = 0; - isKeyDown = false; - var headerSize = (uint)(8 + 2 * IntPtr.Size); - uint size = 0; - if (GetRawInputData(rawInputHandle, RawInputCommand, IntPtr.Zero, ref size, headerSize) != 0 || size == 0) - { - return false; - } - - var buffer = Marshal.AllocHGlobal((int)size); - try - { - if (GetRawInputData(rawInputHandle, RawInputCommand, buffer, ref size, headerSize) != size || - (uint)Marshal.ReadInt32(buffer) != KeyboardInput) - { - return false; - } - - // RAWKEYBOARD: MakeCode, Flags, Reserved, VKey (all 16-bit), right after the header. - var keyboard = buffer + (int)headerSize; - var makeCode = (ushort)Marshal.ReadInt16(keyboard, 0); - var flags = (ushort)Marshal.ReadInt16(keyboard, 2); - var reportedKey = (ushort)Marshal.ReadInt16(keyboard, 6); - var isE0 = (flags & KeyE0) != 0; - // 0xFF marks keys Windows fakes; some keyboards also wrap numpad keys in an extra Shift carrying the - // E0 flag, which a real Shift press never has. - if (reportedKey is 0 or 0xFF || (reportedKey == 0x10 && isE0)) - { - return false; - } - - virtualKey = Normalize(reportedKey, makeCode, isE0); - isKeyDown = (flags & KeyBreak) == 0; - return true; - } - finally - { - Marshal.FreeHGlobal(buffer); - } - } - - public void Dispose() - { - var device = new RawInputDevice - { - UsagePage = GenericDesktopPage, - Usage = KeyboardUsage, - Flags = RemoveDevice, - Target = IntPtr.Zero - }; - _ = RegisterRawInputDevices([device], 1, (uint)Marshal.SizeOf()); - } - - // Raw input reports generic Shift, Ctrl, and Alt, and numpad keys as the navigation keys they share, so map - // them to what a key press in a window reports; recorded shortcuts use those codes. - private static ushort Normalize(ushort reportedKey, ushort makeCode, bool isE0) => reportedKey switch - { - 0x10 => makeCode == 0x36 ? (ushort)0xA1 : (ushort)0xA0, - 0x11 => isE0 ? (ushort)0xA3 : (ushort)0xA2, - 0x12 => isE0 ? (ushort)0xA5 : (ushort)0xA4, - _ when !isE0 && (GetKeyState(NumLock) & 1) != 0 && NumpadKey(reportedKey) is { } numpad => numpad, - _ => reportedKey - }; - - private static ushort? NumpadKey(ushort navigationKey) => navigationKey switch - { - 0x2D => 0x60, // Insert -> Num 0 - 0x23 => 0x61, // End -> Num 1 - 0x28 => 0x62, // Down -> Num 2 - 0x22 => 0x63, // Page Down -> Num 3 - 0x25 => 0x64, // Left -> Num 4 - 0x0C => 0x65, // Clear -> Num 5 - 0x27 => 0x66, // Right -> Num 6 - 0x24 => 0x67, // Home -> Num 7 - 0x26 => 0x68, // Up -> Num 8 - 0x21 => 0x69, // Page Up -> Num 9 - 0x2E => 0x6E, // Delete -> Num . - _ => null - }; - - [StructLayout(LayoutKind.Sequential)] - private struct RawInputDevice - { - public ushort UsagePage; - public ushort Usage; - public uint Flags; - public IntPtr Target; - } - - [DllImport("user32.dll", SetLastError = true)] - [return: MarshalAs(UnmanagedType.Bool)] - private static extern bool RegisterRawInputDevices(RawInputDevice[] devices, uint count, uint size); - - [DllImport("user32.dll", SetLastError = true)] - private static extern uint GetRawInputData(IntPtr rawInput, uint command, IntPtr data, ref uint size, uint headerSize); - - [DllImport("user32.dll")] - private static extern short GetKeyState(int virtualKey); -} diff --git a/src/FourFoldAccountManager.Desktop/Views/SettingsDialog.xaml b/src/FourFoldAccountManager.Desktop/Views/SettingsDialog.xaml index 7bbe468..8eb3046 100644 --- a/src/FourFoldAccountManager.Desktop/Views/SettingsDialog.xaml +++ b/src/FourFoldAccountManager.Desktop/Views/SettingsDialog.xaml @@ -2,7 +2,8 @@ xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:views="clr-namespace:FourFoldAccountManager.Desktop.Views" - PreviewKeyDown="SettingsDialog_PreviewKeyDown" Focusable="True" + PreviewKeyDown="SettingsDialog_PreviewKeyDown" PreviewMouseDown="SettingsDialog_PreviewMouseDown" + PreviewMouseWheel="SettingsDialog_PreviewMouseWheel" Focusable="True" Title="FourFold settings" Width="500" MinWidth="500" Height="680" MinHeight="420" MaxHeight="{Binding Source={x:Static SystemParameters.WorkArea}, Path=Height}" WindowStartupLocation="CenterOwner" ResizeMode="CanResize" @@ -170,6 +171,8 @@ Title="Previous tab" Description="Show the previous tab in the Tabs layout." /> + diff --git a/src/FourFoldAccountManager.Desktop/Views/SettingsDialog.xaml.cs b/src/FourFoldAccountManager.Desktop/Views/SettingsDialog.xaml.cs index 6c3a55f..43d1b9f 100644 --- a/src/FourFoldAccountManager.Desktop/Views/SettingsDialog.xaml.cs +++ b/src/FourFoldAccountManager.Desktop/Views/SettingsDialog.xaml.cs @@ -137,14 +137,37 @@ private void SettingsDialog_PreviewKeyDown(object sender, KeyEventArgs e) _rows[action].SetStatus(ShortcutCapture.InvalidKeysMessage); break; case ShortcutKeyResult.Captured: - _shortcuts[action] = chord!; - _capturingShortcut = null; - _rows[action].SetKeysText(ShortcutText.Format(chord!)); - UpdateShortcutStatus(action); + Capture(action, chord!); break; } } + private void SettingsDialog_PreviewMouseDown(object sender, MouseButtonEventArgs e) + { + if (_capturingShortcut is { } action && ShortcutCapture.TryReadMouseButton(e, out var chord)) + { + e.Handled = true; + Capture(action, chord!); + } + } + + private void SettingsDialog_PreviewMouseWheel(object sender, MouseWheelEventArgs e) + { + if (_capturingShortcut is { } action && ShortcutCapture.TryReadWheel(e, out var chord)) + { + e.Handled = true; + Capture(action, chord!); + } + } + + private void Capture(GlobalShortcutAction action, GlobalHotkeyChord chord) + { + _shortcuts[action] = chord; + _capturingShortcut = null; + _rows[action].SetKeysText(ShortcutText.Format(chord)); + UpdateShortcutStatus(action); + } + private void CancelCapture() { if (_capturingShortcut is not { } action) diff --git a/src/FourFoldAccountManager.Desktop/Views/ShortcutCapture.cs b/src/FourFoldAccountManager.Desktop/Views/ShortcutCapture.cs index e7498f7..42fed3b 100644 --- a/src/FourFoldAccountManager.Desktop/Views/ShortcutCapture.cs +++ b/src/FourFoldAccountManager.Desktop/Views/ShortcutCapture.cs @@ -14,7 +14,8 @@ internal enum ShortcutKeyResult // Key-capture rules shared by Settings → Shortcuts and plugin settings pages. internal static class ShortcutCapture { - public const string Prompt = "Press a key, with or without Ctrl, Alt, or Shift. Esc cancels."; + public const string Prompt = + "Press a key, middle or side mouse button, or scroll the wheel, with or without Ctrl, Alt, or Shift. Esc cancels."; public const string InvalidKeysMessage = "Esc, Tab, Enter, Backspace, F5, the Windows key, and Ctrl, Alt, or Shift on their own can't be shortcuts."; @@ -56,6 +57,24 @@ public static ShortcutKeyResult Read(KeyEventArgs e, out GlobalHotkeyChord? chor return ShortcutKeyResult.Captured; } + // Left and right click are not shortcuts, so they return false and keep operating the dialog. + public static bool TryReadMouseButton(MouseButtonEventArgs e, out GlobalHotkeyChord? chord) => + TryCreateMouse( + e.ChangedButton switch + { + MouseButton.Middle => GlobalHotkeyChord.MiddleClick, + MouseButton.XButton1 => GlobalHotkeyChord.MouseButton4, + MouseButton.XButton2 => GlobalHotkeyChord.MouseButton5, + _ => 0 + }, + out chord); + + public static bool TryReadWheel(MouseWheelEventArgs e, out GlobalHotkeyChord? chord) => + TryCreateMouse( + e.Delta > 0 ? GlobalHotkeyChord.ScrollUp : e.Delta < 0 ? GlobalHotkeyChord.ScrollDown : (ushort)0, + out chord); + + public static string? DuplicateMessage(IReadOnlyDictionary chords) => GlobalShortcutActions.FindDuplicate(chords) is { } duplicate ? $"{GlobalShortcutActions.DisplayName(duplicate.First)} and " + @@ -63,6 +82,18 @@ public static ShortcutKeyResult Read(KeyEventArgs e, out GlobalHotkeyChord? chor "Choose a different shortcut for one of them." : null; + private static bool TryCreateMouse(ushort input, out GlobalHotkeyChord? chord) + { + chord = null; + if ((Keyboard.Modifiers & ModifierKeys.Windows) != 0 || + !GlobalHotkeyChord.TryCreate(input, MapSupportedModifiers(Keyboard.Modifiers), out var created)) + { + return false; + } + + chord = created; + return true; + } private static GlobalHotkeyModifiers MapSupportedModifiers(ModifierKeys modifiers) { if ((modifiers & ModifierKeys.Windows) != 0) diff --git a/src/FourFoldAccountManager.Desktop/Views/ShortcutText.cs b/src/FourFoldAccountManager.Desktop/Views/ShortcutText.cs index 9a61502..c48d48a 100644 --- a/src/FourFoldAccountManager.Desktop/Views/ShortcutText.cs +++ b/src/FourFoldAccountManager.Desktop/Views/ShortcutText.cs @@ -30,6 +30,15 @@ public static string Format(GlobalHotkeyChord chord) private static string KeyName(ushort virtualKey) { + switch (virtualKey) + { + case GlobalHotkeyChord.MiddleClick: return "Middle click"; + case GlobalHotkeyChord.MouseButton4: return "Mouse 4"; + case GlobalHotkeyChord.MouseButton5: return "Mouse 5"; + case GlobalHotkeyChord.ScrollUp: return "Scroll up"; + case GlobalHotkeyChord.ScrollDown: return "Scroll down"; + } + var key = KeyInterop.KeyFromVirtualKey(virtualKey); var name = key switch { diff --git a/src/FourFoldAccountManager.Desktop/Views/TimerSettingsPage.xaml b/src/FourFoldAccountManager.Desktop/Views/TimerSettingsPage.xaml index d9e523e..04854b1 100644 --- a/src/FourFoldAccountManager.Desktop/Views/TimerSettingsPage.xaml +++ b/src/FourFoldAccountManager.Desktop/Views/TimerSettingsPage.xaml @@ -3,6 +3,7 @@ xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:views="clr-namespace:FourFoldAccountManager.Desktop.Views" Focusable="True" PreviewKeyDown="TimerSettingsPage_PreviewKeyDown" + PreviewMouseDown="TimerSettingsPage_PreviewMouseDown" PreviewMouseWheel="TimerSettingsPage_PreviewMouseWheel" LostKeyboardFocus="TimerSettingsPage_LostKeyboardFocus">