Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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, GlobalHotkeyChord>
{
[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, GlobalHotkeyChord>
{
[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));
}
}
Original file line number Diff line number Diff line change
@@ -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);
}
}
25 changes: 14 additions & 11 deletions src/FourFoldAccountManager.Core/Input/PlainKeyShortcutMatcher.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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<ushort> _held = [];
Expand All @@ -25,20 +26,22 @@ public void SetBindings(IReadOnlyDictionary<GlobalShortcutAction, GlobalHotkeyCh
}

var pressed = new GlobalHotkeyChord(virtualKey, HeldModifiers());
if (!pressed.IsPlainKey && _bindings.ContainsValue(pressed))
{
return null;
}

GlobalShortcutAction? unmodified = null;
foreach (var (action, chord) in _bindings)
{
if (chord.IsPlainKey && chord.VirtualKey == virtualKey)
if (chord == pressed)
{
// A key chord with a modifier fires through Windows, so it is not fired again here.
return chord.IsObserved ? action : null;
}

if (chord.VirtualKey == virtualKey && chord.Modifiers == GlobalHotkeyModifiers.None)
{
return action;
unmodified = action;
}
}

return null;
return unmodified;
}

public void KeyUp(ushort virtualKey) => _held.Remove(virtualKey);
Expand Down
29 changes: 23 additions & 6 deletions src/FourFoldAccountManager.Core/Models/GlobalHotkeyChord.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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;

Expand Down Expand Up @@ -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,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand All @@ -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
Expand Down
Original file line number Diff line number Diff line change
@@ -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;
}
}
41 changes: 22 additions & 19 deletions src/FourFoldAccountManager.Desktop/MainWindow.xaml.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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(
Expand All @@ -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;
}

Expand Down Expand Up @@ -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);
}
Expand All @@ -281,9 +280,13 @@ private static bool IsTypingInFourFold() =>
System.Windows.Input.Keyboard.FocusedElement is TextBoxBase or PasswordBox &&
Application.Current.Windows.OfType<Window>().Any(window => window.IsActive);

private void RefreshPlainKeyBindings() =>
_plainKeys.SetBindings(_shortcuts?.ActiveChords(_panelSettings) ??
new Dictionary<GlobalShortcutAction, GlobalHotkeyChord>());
private void RefreshPlainKeyBindings()
{
var bindings = _shortcuts?.ActiveChords(_panelSettings) ??
new Dictionary<GlobalShortcutAction, GlobalHotkeyChord>();
_plainKeys.SetBindings(bindings);
_rawInput?.SetMouseEnabled(bindings.Values.Any(chord => chord.IsMouse));
}

private void UpdateTimerHotkeys()
{
Expand Down Expand Up @@ -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
{
Expand Down
Loading
Loading