From 1ba2d7618473bb76c2ff552689f0a25b9fc442f8 Mon Sep 17 00:00:00 2001 From: Devan <68340659+DevanMetz@users.noreply.github.com> Date: Tue, 27 Oct 2026 16:13:50 -0500 Subject: [PATCH 1/3] Parse shortcuts in the same text form Windows stores. A settings file can move between the two apps, and the grab plan refuses a bare typing key. --- linux/HotkeyChord.cs | 309 ++++++++++++++++++ linux/OpenSnip.Linux.csproj | 1 + tests/OpenSnip.Hotkeys.Tests/HotkeyTests.cs | 112 +++++++ .../OpenSnip.Hotkeys.Tests.csproj | 25 ++ 4 files changed, 447 insertions(+) create mode 100644 linux/HotkeyChord.cs create mode 100644 tests/OpenSnip.Hotkeys.Tests/HotkeyTests.cs create mode 100644 tests/OpenSnip.Hotkeys.Tests/OpenSnip.Hotkeys.Tests.csproj diff --git a/linux/HotkeyChord.cs b/linux/HotkeyChord.cs new file mode 100644 index 0000000..64a8ea5 --- /dev/null +++ b/linux/HotkeyChord.cs @@ -0,0 +1,309 @@ +namespace OpenSnip; + +/// What a global shortcut does. Names and priority match the Windows hook. +enum HotkeyCommand +{ + Snip, + SnipDelay, + Repeat, +} + +/// +/// One shortcut in the same text form Windows stores, for example "Win+Shift+S". +/// Key names follow System.Windows.Forms.Keys so a settings file means the same thing on both. +/// +readonly record struct HotkeyChord(string Key, bool Win, bool Ctrl, bool Alt, bool Shift) +{ + public bool IsEmpty => string.IsNullOrEmpty(Key); + public bool HasModifier => Win || Ctrl || Alt || Shift; + + public static HotkeyChord Parse(string text) + { + if (string.IsNullOrWhiteSpace(text)) return default; + bool win = false, ctrl = false, alt = false, shift = false; + string key = null; + foreach (var part in text.Split('+', StringSplitOptions.TrimEntries | StringSplitOptions.RemoveEmptyEntries)) + { + switch (part.ToLowerInvariant()) + { + case "win": win = true; break; + case "ctrl": + case "control": ctrl = true; break; + case "alt": alt = true; break; + case "shift": shift = true; break; + default: + key = CanonicalKey(part); + if (key == null) return default; + break; + } + } + return key == null ? default : new HotkeyChord(key, win, ctrl, alt, shift); + } + + public string Serialize() => IsEmpty ? "" : string.Join("+", Parts(Key)); + + public string Display => IsEmpty ? "None" : string.Join(" + ", Parts(DisplayOf(Key))); + + IEnumerable Parts(string key) + { + if (Win) yield return "Win"; + if (Ctrl) yield return "Ctrl"; + if (Alt) yield return "Alt"; + if (Shift) yield return "Shift"; + yield return key; + } + + /// Keys that are safe as a global shortcut on their own, without breaking normal typing. + public static bool OkWithoutModifier(string key) + { + if (string.IsNullOrEmpty(key)) return false; + if (key.Length is >= 2 and <= 3 && key[0] == 'F' && + int.TryParse(key.AsSpan(1), out int n) && n is >= 1 and <= 24) + return true; + return key is "PrintScreen" or "Pause" or "Scroll" or "Insert"; + } + + public static string CanonicalKey(string name) + { + if (string.IsNullOrWhiteSpace(name)) return null; + EnsureTable(); + return Names.TryGetValue(name, out var canonical) ? canonical : null; + } + + public static string DisplayOf(string key) + { + EnsureTable(); + return key != null && Displays.TryGetValue(key, out var display) ? display : key ?? ""; + } + + /// X keysyms for a canonical key, most likely first. Empty when the key has no X equivalent. + public static ulong[] Keysyms(string key) + { + EnsureTable(); + return key != null && Syms.TryGetValue(key, out var syms) ? syms : Array.Empty(); + } + + /// Canonical key for an X keysym, or null for modifiers and unknown keys. + public static string FromKeysym(ulong keysym) + { + EnsureTable(); + return BySym.TryGetValue(keysym, out var key) ? key : null; + } + + static Dictionary Names; + static Dictionary Displays; + static Dictionary Syms; + static Dictionary BySym; + + static void EnsureTable() + { + if (Names != null) return; + var names = new Dictionary(StringComparer.OrdinalIgnoreCase); + var displays = new Dictionary(StringComparer.Ordinal); + var syms = new Dictionary(StringComparer.Ordinal); + var bySym = new Dictionary(); + + void Add(string name, string display, params ulong[] keysyms) + { + names[name] = name; + displays[name] = display; + syms[name] = keysyms; + foreach (var sym in keysyms) + bySym.TryAdd(sym, name); + } + + void Alias(string alias, string name) => names[alias] = name; + + for (int i = 0; i < 26; i++) + { + char upper = (char)('A' + i); + char lower = (char)('a' + i); + Add(upper.ToString(), upper.ToString(), (ulong)lower, (ulong)upper); + } + for (int i = 0; i < 10; i++) + { + Add("D" + i, i.ToString(), (ulong)('0' + i)); + Add("NumPad" + i, "Num " + i, 0xffb0UL + (ulong)i); + } + for (int i = 1; i <= 24; i++) + Add("F" + i, "F" + i, 0xffbeUL + (ulong)(i - 1)); + + Add("PrintScreen", "PrtSc", 0xff61); + Add("Return", "Enter", 0xff0d, 0xff8d); + Add("Prior", "PgUp", 0xff55); + Add("Next", "PgDn", 0xff56); + Add("Back", "Backspace", 0xff08); + Add("Scroll", "ScrLk", 0xff14); + Add("Capital", "CapsLock", 0xffe5); + Add("Space", "Space", 0x20); + Add("Tab", "Tab", 0xff09); + Add("Escape", "Escape", 0xff1b); + Add("Insert", "Insert", 0xff63); + Add("Delete", "Delete", 0xffff); + Add("Home", "Home", 0xff50); + Add("End", "End", 0xff57); + Add("Left", "Left", 0xff51); + Add("Up", "Up", 0xff52); + Add("Right", "Right", 0xff53); + Add("Down", "Down", 0xff54); + Add("Pause", "Pause", 0xff13); + Add("Add", "Add", 0xffab); + Add("Subtract", "Subtract", 0xffad); + Add("Multiply", "Multiply", 0xffaa); + Add("Divide", "Divide", 0xffaf); + Add("Decimal", "Decimal", 0xffae); + Add("Apps", "Apps", 0xff67); + + // Same value, different enum name. Keep the name Windows writes. + Alias("Snapshot", "PrintScreen"); + Alias("Enter", "Return"); + Alias("PageUp", "Prior"); + Alias("PageDown", "Next"); + Alias("CapsLock", "Capital"); + + Names = names; + Displays = displays; + Syms = syms; + BySym = bySym; + } +} + +/// The shortcuts this process should honor. +sealed class HotkeyBindings +{ + public HotkeyChord Snip { get; init; } + public HotkeyChord Delay { get; init; } + public HotkeyChord Repeat { get; init; } + public bool UsePrintScreen { get; init; } + + public static HotkeyBindings From(Settings settings) => new() + { + Snip = HotkeyChord.Parse(settings.SnipHotkey), + Delay = HotkeyChord.Parse(settings.DelayHotkey), + Repeat = HotkeyChord.Parse(settings.RepeatHotkey), + UsePrintScreen = settings.UsePrintScreen, + }; + + /// + /// Custom shortcuts win over the Print Screen family. Ctrl+PrtSc repeats, Shift+PrtSc delays, + /// and Ctrl+Shift+PrtSc repeats, matching the Windows hook. Alt and Win leave Print Screen alone. + /// + public static HotkeyCommand? Match(HotkeyChord chord, HotkeyBindings bindings) + { + if (chord.IsEmpty || bindings == null) return null; + if (!bindings.Snip.IsEmpty && chord == bindings.Snip) return HotkeyCommand.Snip; + if (!bindings.Delay.IsEmpty && chord == bindings.Delay) return HotkeyCommand.SnipDelay; + if (!bindings.Repeat.IsEmpty && chord == bindings.Repeat) return HotkeyCommand.Repeat; + if (bindings.UsePrintScreen && chord.Key == "PrintScreen" && !chord.Alt && !chord.Win) + { + if (chord.Ctrl) return HotkeyCommand.Repeat; + if (chord.Shift) return HotkeyCommand.SnipDelay; + return HotkeyCommand.Snip; + } + return null; + } + + public string Summary + { + get + { + var items = new List(); + void Add(HotkeyChord chord) + { + if (Match(chord, this) == null) return; + string text = chord.Display; + if (!items.Contains(text)) items.Add(text); + } + Add(Snip); + Add(Delay); + Add(Repeat); + if (UsePrintScreen) + { + Add(new HotkeyChord("PrintScreen", false, false, false, false)); + Add(new HotkeyChord("PrintScreen", false, false, false, true)); + Add(new HotkeyChord("PrintScreen", false, true, false, false)); + } + return items.Count == 0 ? "off" : string.Join(", ", items); + } + } +} + +/// Passive grabs for a binding set, including the lock combinations X11 otherwise ignores. +static class HotkeyGrabs +{ + public const uint ShiftMask = 1; + public const uint LockMask = 2; + public const uint ControlMask = 4; + public const uint Mod2Mask = 16; + public const uint Mod5Mask = 128; + public const uint AnyModifier = 32768; + + public static readonly uint[] LockExtras = + { + 0, + LockMask, + Mod2Mask, + LockMask | Mod2Mask, + Mod5Mask, + LockMask | Mod5Mask, + Mod2Mask | Mod5Mask, + LockMask | Mod2Mask | Mod5Mask, + }; + + public readonly record struct Grab(int Keycode, uint Modifiers, HotkeyCommand Command); + + public static bool IsSafe(HotkeyChord chord) => + !chord.IsEmpty && (chord.HasModifier || HotkeyChord.OkWithoutModifier(chord.Key)); + + public static uint ModifierMask(HotkeyChord chord, uint altMask, uint superMask) + { + uint mask = 0; + if (chord.Shift) mask |= ShiftMask; + if (chord.Ctrl) mask |= ControlMask; + if (chord.Alt) mask |= altMask; + if (chord.Win) mask |= superMask; + return mask; + } + + public static List Plan(HotkeyBindings bindings, Func keycode, uint altMask, uint superMask) + { + var planned = new List(); + if (bindings == null || keycode == null) return planned; + + var chords = new List(); + void Consider(HotkeyChord chord) + { + // A bare letter in the settings file must not swallow typing. + if (!IsSafe(chord) || HotkeyBindings.Match(chord, bindings) == null) return; + if (chords.Contains(chord)) return; + chords.Add(chord); + } + + Consider(bindings.Snip); + Consider(bindings.Delay); + Consider(bindings.Repeat); + if (bindings.UsePrintScreen) + { + Consider(new HotkeyChord("PrintScreen", false, false, false, false)); + Consider(new HotkeyChord("PrintScreen", false, false, false, true)); + Consider(new HotkeyChord("PrintScreen", false, true, false, false)); + Consider(new HotkeyChord("PrintScreen", false, true, false, true)); + } + + var seen = new HashSet<(int Keycode, uint Modifiers)>(); + foreach (var chord in chords) + { + int code = keycode(chord.Key); + if (code == 0) continue; + var command = HotkeyBindings.Match(chord, bindings).Value; + uint mask = ModifierMask(chord, altMask, superMask); + foreach (var extra in LockExtras) + { + uint full = mask | extra; + if (!seen.Add((code, full))) continue; + planned.Add(new Grab(code, full, command)); + } + } + return planned; + } +} diff --git a/linux/OpenSnip.Linux.csproj b/linux/OpenSnip.Linux.csproj index f1519e3..d785a18 100644 --- a/linux/OpenSnip.Linux.csproj +++ b/linux/OpenSnip.Linux.csproj @@ -18,6 +18,7 @@ + diff --git a/tests/OpenSnip.Hotkeys.Tests/HotkeyTests.cs b/tests/OpenSnip.Hotkeys.Tests/HotkeyTests.cs new file mode 100644 index 0000000..1cd2b34 --- /dev/null +++ b/tests/OpenSnip.Hotkeys.Tests/HotkeyTests.cs @@ -0,0 +1,112 @@ +namespace OpenSnip.Hotkeys.Tests; + +public class HotkeyTests +{ + [Fact] + public void ParseUsesTheWindowsTextForm() + { + var chord = HotkeyChord.Parse("win+shift+s"); + Assert.Equal("Win+Shift+S", chord.Serialize()); + Assert.Equal("Win + Shift + S", chord.Display); + Assert.Equal(chord, HotkeyChord.Parse("Shift+Win+S")); + Assert.Equal("Ctrl+S", HotkeyChord.Parse("control+s").Serialize()); + } + + [Fact] + public void ParseRejectsUnknownAndModifierOnlyChords() + { + Assert.True(HotkeyChord.Parse(null).IsEmpty); + Assert.True(HotkeyChord.Parse("").IsEmpty); + Assert.True(HotkeyChord.Parse("Shift").IsEmpty); + Assert.True(HotkeyChord.Parse("Ctrl+Nope").IsEmpty); + Assert.True(HotkeyChord.Parse("PrtSc").IsEmpty); + } + + [Fact] + public void AliasesCanonicalizeToTheNameWindowsWrites() + { + Assert.Equal("PrintScreen", HotkeyChord.Parse("Snapshot").Key); + Assert.Equal("PrtSc", HotkeyChord.Parse("PrintScreen").Display); + Assert.Equal("Return", HotkeyChord.Parse("Enter").Key); + Assert.Equal("Enter", HotkeyChord.Parse("Return").Display); + Assert.Equal("Prior", HotkeyChord.Parse("PageUp").Key); + Assert.Equal("PgUp", HotkeyChord.Parse("Prior").Display); + Assert.Equal("D1", HotkeyChord.Parse("d1").Key); + Assert.Equal("1", HotkeyChord.Parse("D1").Display); + Assert.Equal("Num 2", HotkeyChord.Parse("NumPad2").Display); + Assert.Equal("Backspace", HotkeyChord.Parse("Back").Display); + } + + [Fact] + public void BareTypingKeysAreNotSafeShortcuts() + { + Assert.True(HotkeyChord.OkWithoutModifier("F5")); + Assert.True(HotkeyChord.OkWithoutModifier("F24")); + Assert.True(HotkeyChord.OkWithoutModifier("PrintScreen")); + Assert.True(HotkeyChord.OkWithoutModifier("Pause")); + Assert.False(HotkeyChord.OkWithoutModifier("F25")); + Assert.False(HotkeyChord.OkWithoutModifier("A")); + Assert.False(HotkeyGrabs.IsSafe(HotkeyChord.Parse("A"))); + Assert.True(HotkeyGrabs.IsSafe(HotkeyChord.Parse("Ctrl+A"))); + Assert.True(HotkeyGrabs.IsSafe(HotkeyChord.Parse("PrintScreen"))); + } + + [Fact] + public void CustomChordsBeatThePrintScreenFamily() + { + var bindings = new HotkeyBindings + { + Snip = HotkeyChord.Parse("Ctrl+PrintScreen"), + Delay = HotkeyChord.Parse("Ctrl+Shift+D"), + Repeat = HotkeyChord.Parse("Ctrl+Shift+R"), + UsePrintScreen = true, + }; + + Assert.Equal(HotkeyCommand.Snip, HotkeyBindings.Match(HotkeyChord.Parse("Ctrl+PrintScreen"), bindings)); + Assert.Equal(HotkeyCommand.SnipDelay, HotkeyBindings.Match(HotkeyChord.Parse("Shift+PrintScreen"), bindings)); + Assert.Equal(HotkeyCommand.Repeat, HotkeyBindings.Match(HotkeyChord.Parse("Ctrl+Shift+PrintScreen"), bindings)); + Assert.Equal(HotkeyCommand.Snip, HotkeyBindings.Match(HotkeyChord.Parse("PrintScreen"), bindings)); + Assert.Null(HotkeyBindings.Match(HotkeyChord.Parse("Alt+PrintScreen"), bindings)); + Assert.Null(HotkeyBindings.Match(HotkeyChord.Parse("Win+PrintScreen"), bindings)); + Assert.Equal(HotkeyCommand.SnipDelay, HotkeyBindings.Match(HotkeyChord.Parse("Ctrl+Shift+D"), bindings)); + } + + [Fact] + public void DefaultSummaryMatchesTheWindowsDefaults() + { + Assert.Equal( + "Win + Shift + S, PrtSc, Shift + PrtSc, Ctrl + PrtSc", + HotkeyBindings.From(new Settings()).Summary); + Assert.Equal("off", new HotkeyBindings().Summary); + } + + [Fact] + public void PlanGrabsLockVariantsAndSkipsUnsafeOrUnknownKeys() + { + var bindings = new HotkeyBindings + { + Snip = HotkeyChord.Parse("Win+Shift+S"), + Delay = HotkeyChord.Parse("A"), + UsePrintScreen = true, + }; + var grabs = HotkeyGrabs.Plan(bindings, key => key switch + { + "S" => 39, + "PrintScreen" => 107, + _ => 0, + }, altMask: 8, superMask: 64); + + Assert.Equal(40, grabs.Count); + Assert.Contains(grabs, g => g.Keycode == 39 && g.Modifiers == (64 | HotkeyGrabs.ShiftMask) && g.Command == HotkeyCommand.Snip); + Assert.Contains(grabs, g => g.Keycode == 39 && g.Modifiers == (64 | HotkeyGrabs.ShiftMask | HotkeyGrabs.Mod2Mask)); + Assert.Contains(grabs, g => g.Keycode == 107 && g.Modifiers == HotkeyGrabs.ControlMask && g.Command == HotkeyCommand.Repeat); + Assert.Contains(grabs, g => g.Keycode == 107 + && g.Modifiers == (HotkeyGrabs.ControlMask | HotkeyGrabs.ShiftMask) + && g.Command == HotkeyCommand.Repeat); + Assert.DoesNotContain(grabs, g => g.Keycode == 0); + + Assert.Empty(HotkeyGrabs.Plan( + new HotkeyBindings { Snip = HotkeyChord.Parse("Win+Shift+S"), UsePrintScreen = false }, + _ => 0, 8, 64)); + } +} diff --git a/tests/OpenSnip.Hotkeys.Tests/OpenSnip.Hotkeys.Tests.csproj b/tests/OpenSnip.Hotkeys.Tests/OpenSnip.Hotkeys.Tests.csproj new file mode 100644 index 0000000..dece916 --- /dev/null +++ b/tests/OpenSnip.Hotkeys.Tests/OpenSnip.Hotkeys.Tests.csproj @@ -0,0 +1,25 @@ + + + + net9.0 + enable + disable + false + OpenSnip.Hotkeys.Tests + + + + + + + + + + + + + + + + + From 222940f40c760aeb27d6a5afdfed5da0cb919089 Mon Sep 17 00:00:00 2001 From: Devan <68340659+DevanMetz@users.noreply.github.com> Date: Tue, 27 Oct 2026 16:13:54 -0500 Subject: [PATCH 2/3] Grab global shortcuts on a private X11 connection. The hotkey thread does not share Avalonia's Display. A chord the desktop already owns is skipped, and changing a shortcut grabs the keyboard only until the next chord. --- linux/Program.cs | 1 + linux/X11Hotkeys.cs | 679 ++++++++++++++++++ .../OpenSnip.Hotkeys.Tests/X11HotkeyTests.cs | 100 +++ 3 files changed, 780 insertions(+) create mode 100644 linux/X11Hotkeys.cs create mode 100644 tests/OpenSnip.Hotkeys.Tests/X11HotkeyTests.cs diff --git a/linux/Program.cs b/linux/Program.cs index d220a3c..d8930e7 100644 --- a/linux/Program.cs +++ b/linux/Program.cs @@ -8,6 +8,7 @@ static class Program public static int Main(string[] args) { ConfigPaths.EnsureConfigHome(); + X11Native.InitThreads(); AppDomain.CurrentDomain.UnhandledException += (_, e) => Log.Error(e.ExceptionObject as Exception ?? new Exception("Unhandled exception")); diff --git a/linux/X11Hotkeys.cs b/linux/X11Hotkeys.cs new file mode 100644 index 0000000..114a79c --- /dev/null +++ b/linux/X11Hotkeys.cs @@ -0,0 +1,679 @@ +using System.Runtime.InteropServices; + +namespace OpenSnip; + +/// +/// Loads libX11 by its soname. The runtime package ships libX11.so.6; libX11.so +/// exists only in the development package. +/// +static class X11Native +{ + public static bool Available { get; private set; } + + public static XOpenDisplayFn XOpenDisplay; + public static XCloseDisplayFn XCloseDisplay; + public static XDefaultRootWindowFn XDefaultRootWindow; + public static XGrabKeyFn XGrabKey; + public static XUngrabKeyFn XUngrabKey; + public static XGrabKeyboardFn XGrabKeyboard; + public static XUngrabKeyboardFn XUngrabKeyboard; + public static XPendingFn XPending; + public static XNextEventFn XNextEvent; + public static XFlushFn XFlush; + public static XSyncFn XSync; + public static XConnectionNumberFn XConnectionNumber; + public static XKeysymToKeycodeFn XKeysymToKeycode; + public static XkbKeycodeToKeysymFn XkbKeycodeToKeysym; + public static XGetModifierMappingFn XGetModifierMapping; + public static XFreeModifiermapFn XFreeModifiermap; + public static XSetErrorHandlerFn XSetErrorHandler; + public static XkbSetDetectableAutoRepeatFn XkbSetDetectableAutoRepeat; + static XInitThreadsFn _initThreads; + + static X11Native() + { + try { Load(); } + catch { Available = false; } + } + + /// Must run before Avalonia touches Xlib, so a second thread can use its own Display. + public static void InitThreads() + { + try { _initThreads?.Invoke(); } + catch { } + } + + static void Load() + { + IntPtr lib = IntPtr.Zero; + foreach (var name in new[] { "libX11.so.6", "libX11.so", "libX11" }) + { + if (NativeLibrary.TryLoad(name, out lib)) break; + } + if (lib == IntPtr.Zero) return; + + XOpenDisplay = Req(lib, "XOpenDisplay"); + XCloseDisplay = Req(lib, "XCloseDisplay"); + XDefaultRootWindow = Req(lib, "XDefaultRootWindow"); + XGrabKey = Req(lib, "XGrabKey"); + XUngrabKey = Req(lib, "XUngrabKey"); + XGrabKeyboard = Req(lib, "XGrabKeyboard"); + XUngrabKeyboard = Req(lib, "XUngrabKeyboard"); + XPending = Req(lib, "XPending"); + XNextEvent = Req(lib, "XNextEvent"); + XFlush = Req(lib, "XFlush"); + XSync = Req(lib, "XSync"); + XConnectionNumber = Req(lib, "XConnectionNumber"); + XKeysymToKeycode = Req(lib, "XKeysymToKeycode"); + XkbKeycodeToKeysym = Req(lib, "XkbKeycodeToKeysym"); + XGetModifierMapping = Req(lib, "XGetModifierMapping"); + XFreeModifiermap = Req(lib, "XFreeModifiermap"); + XSetErrorHandler = Req(lib, "XSetErrorHandler"); + try { XkbSetDetectableAutoRepeat = Opt(lib, "XkbSetDetectableAutoRepeat"); } + catch { XkbSetDetectableAutoRepeat = null; } + try { _initThreads = Opt(lib, "XInitThreads"); } + catch { _initThreads = null; } + Available = true; + } + + static T Req(IntPtr lib, string name) where T : Delegate => + Marshal.GetDelegateForFunctionPointer(NativeLibrary.GetExport(lib, name)); + + static T Opt(IntPtr lib, string name) where T : Delegate => Req(lib, name); + + public delegate IntPtr XOpenDisplayFn(string name); + public delegate int XCloseDisplayFn(IntPtr display); + public delegate ulong XDefaultRootWindowFn(IntPtr display); + public delegate int XGrabKeyFn(IntPtr display, int keycode, uint modifiers, ulong grabWindow, int ownerEvents, int pointerMode, int keyboardMode); + public delegate int XUngrabKeyFn(IntPtr display, int keycode, uint modifiers, ulong grabWindow); + public delegate int XGrabKeyboardFn(IntPtr display, ulong grabWindow, int ownerEvents, int pointerMode, int keyboardMode, ulong time); + public delegate int XUngrabKeyboardFn(IntPtr display, ulong time); + public delegate int XPendingFn(IntPtr display); + public delegate int XNextEventFn(IntPtr display, IntPtr eventReturn); + public delegate int XFlushFn(IntPtr display); + public delegate int XSyncFn(IntPtr display, int discard); + public delegate int XConnectionNumberFn(IntPtr display); + public delegate int XKeysymToKeycodeFn(IntPtr display, ulong keysym); + public delegate ulong XkbKeycodeToKeysymFn(IntPtr display, int keycode, int group, int level); + public delegate IntPtr XGetModifierMappingFn(IntPtr display); + public delegate int XFreeModifiermapFn(IntPtr map); + public delegate IntPtr XSetErrorHandlerFn(IntPtr handler); + public delegate int XkbSetDetectableAutoRepeatFn(IntPtr display, int detectable, IntPtr supported); + delegate int XInitThreadsFn(); +} + +/// +/// Global shortcuts on X11. Wayland compositors do not deliver these events. +/// The connection is private to one thread; Avalonia keeps its own. +/// +sealed class X11HotkeyService : IDisposable +{ + const int KeyPress = 2; + const int KeyRelease = 3; + const int GrabModeAsync = 1; + const int EventBytes = 192; + const int PollIn = 1; + const int ONonBlock = 0x800; + const int OCloExec = 0x80000; + + static X11HotkeyService _active; + static XErrorFn _errorHandler; + static IntPtr _previousHandler; + + readonly Action _onCommand; + readonly object _gate = new(); + readonly Queue _commands = new(); + readonly HashSet _down = new(); + + Thread _thread; + IntPtr _display; + IntPtr _probeDisplay; + IntPtr _event; + int _wakeRead = -1; + int _wakeWrite = -1; + int _errorCount; + int _disposed; + uint _altMask = 8; + uint _superMask = 64; + ulong _root; + volatile bool _running; + bool _keyboardGrabbed; + bool _listening; + DateTime _listenDeadline; + HotkeyBindings _bindings; + Action _listenCallback; + + X11HotkeyService(HotkeyBindings bindings, Action onCommand) + { + _bindings = bindings ?? new HotkeyBindings(); + _onCommand = onCommand ?? (_ => { }); + } + + public static bool IsSupported + { + get + { + if (PlatformInfo.IsWayland || !PlatformInfo.HasDisplay || !X11Native.Available) return false; + // A stale DISPLAY still looks present. Open and close before reporting success. + // Callers use this before the shortcut thread exists, on their own thread. + X11Native.InitThreads(); + var display = X11Native.XOpenDisplay(null); + if (display == IntPtr.Zero) return false; + X11Native.XCloseDisplay(display); + return true; + } + } + + public static X11HotkeyService TryStart(HotkeyBindings bindings, Action onCommand) + { + if (!IsSupported) return null; + var service = new X11HotkeyService(bindings, onCommand); + if (service.Start()) return service; + service.Dispose(); + return null; + } + + public void Update(HotkeyBindings bindings) + { + var next = bindings ?? new HotkeyBindings(); + Post(() => + { + _bindings = next; + ApplyBindings(); + }); + } + + /// Takes the keyboard until , Escape is handled by the caller, or the timeout. + public bool BeginListen(Action onChord) + { + if (Volatile.Read(ref _disposed) != 0) return false; + var done = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + Post(() => + { + try + { + ReleaseKeyboard(); + _listenCallback = onChord; + _listening = true; + _down.Clear(); + _listenDeadline = DateTime.UtcNow.AddSeconds(20); + int result = X11Native.XGrabKeyboard(_display, _root, 0, GrabModeAsync, GrabModeAsync, 0); + X11Native.XFlush(_display); + _keyboardGrabbed = result == 0; + if (!_keyboardGrabbed) + { + _listening = false; + _listenCallback = null; + } + done.TrySetResult(_keyboardGrabbed); + } + catch (Exception ex) + { + Log.Error(ex); + _listening = false; + _listenCallback = null; + done.TrySetResult(false); + } + }); + return done.Task.Wait(TimeSpan.FromSeconds(2)) && done.Task.Result; + } + + public void EndListen() => Post(() => CancelListen(invoke: false)); + + public void Dispose() + { + if (Interlocked.Exchange(ref _disposed, 1) != 0) return; + _running = false; + Wake(); + if (_thread != null && Thread.CurrentThread != _thread) + _thread.Join(1000); + } + + internal int KeycodeFor(string key) + { + int code = 0; + var done = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + Post(() => done.TrySetResult(LookupKeycode(key))); + if (done.Task.Wait(TimeSpan.FromSeconds(2))) code = done.Task.Result; + return code; + } + + internal uint MaskFor(HotkeyChord chord) => HotkeyGrabs.ModifierMask(chord, _altMask, _superMask); + + internal bool ForeignGrabSucceeds(int keycode, uint modifiers) + { + var done = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + Post(() => done.TrySetResult(ProbeGrab(keycode, modifiers))); + return done.Task.Wait(TimeSpan.FromSeconds(2)) && done.Task.Result; + } + + /// True when this process can grab the combination. Call only while no service is running. + internal static bool ProbeGrabSucceeds(int keycode, uint modifiers) + { + if (!X11Native.Available || _active != null) return false; + var display = X11Native.XOpenDisplay(null); + if (display == IntPtr.Zero) return false; + try + { + _probeErrors = 0; + _probeDisplayStatic = display; + InstallHandler(); + int before = _probeErrors; + var root = X11Native.XDefaultRootWindow(display); + X11Native.XGrabKey(display, keycode, modifiers, root, 0, GrabModeAsync, GrabModeAsync); + X11Native.XSync(display, 0); + bool ok = _probeErrors == before; + if (ok) + { + X11Native.XUngrabKey(display, keycode, modifiers, root); + X11Native.XFlush(display); + } + return ok; + } + finally + { + X11Native.XCloseDisplay(display); + _probeDisplayStatic = IntPtr.Zero; + if (_active == null) RestoreHandler(); + } + } + + static int _probeErrors; + static IntPtr _probeDisplayStatic; + + bool Start() + { + var ready = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + _running = true; + _thread = new Thread(() => Loop(ready)) { IsBackground = true, Name = "OpenSnip shortcuts" }; + _thread.Start(); + if (!ready.Task.Wait(TimeSpan.FromSeconds(2))) return false; + return ready.Task.Result; + } + + void Loop(TaskCompletionSource ready) + { + try + { + if (!OpenDisplay()) + { + ready.TrySetResult(false); + return; + } + ApplyBindings(); + ready.TrySetResult(true); + while (_running) + { + while (_running && X11Native.XPending(_display) > 0) + DispatchEvent(); + if (!_running) break; + Poll(); + DrainWake(); + DrainCommands(); + if (_listening && DateTime.UtcNow >= _listenDeadline) + CancelListen(invoke: true); + } + } + catch (Exception ex) + { + Log.Error(ex); + ready.TrySetResult(false); + } + finally + { + CloseDisplay(); + } + } + + bool OpenDisplay() + { + _display = X11Native.XOpenDisplay(null); + if (_display == IntPtr.Zero) return false; + _event = Marshal.AllocHGlobal(EventBytes); + _root = X11Native.XDefaultRootWindow(_display); + // Claim the slot first so CloseDisplay restores Avalonia's handler if setup throws. + _active = this; + InstallHandler(); + OpenWakePipe(); + try { X11Native.XkbSetDetectableAutoRepeat?.Invoke(_display, 1, IntPtr.Zero); } + catch { } + ReadModifierMasks(); + return true; + } + + void CloseDisplay() + { + try + { + if (_display != IntPtr.Zero) + { + ReleaseKeyboard(); + X11Native.XUngrabKey(_display, 0, HotkeyGrabs.AnyModifier, _root); + X11Native.XFlush(_display); + X11Native.XCloseDisplay(_display); + } + } + catch { } + _display = IntPtr.Zero; + if (_event != IntPtr.Zero) + { + Marshal.FreeHGlobal(_event); + _event = IntPtr.Zero; + } + CloseWakePipe(); + if (ReferenceEquals(_active, this)) + { + _active = null; + RestoreHandler(); + } + } + + void ApplyBindings() + { + if (_display == IntPtr.Zero) return; + // A release can be lost across an ungrab. Forget held keys so the next press still fires. + _down.Clear(); + X11Native.XUngrabKey(_display, 0, HotkeyGrabs.AnyModifier, _root); + X11Native.XSync(_display, 0); + var grabs = HotkeyGrabs.Plan(_bindings, LookupKeycode, _altMask, _superMask); + foreach (var grab in grabs) + { + int before = _errorCount; + X11Native.XGrabKey(_display, grab.Keycode, grab.Modifiers, _root, 0, GrabModeAsync, GrabModeAsync); + X11Native.XSync(_display, 0); + if (_errorCount != before) + { + // Another client already owns this combination. The others still work. + } + } + } + + int LookupKeycode(string key) + { + if (_display == IntPtr.Zero || string.IsNullOrEmpty(key)) return 0; + foreach (var sym in HotkeyChord.Keysyms(key)) + { + int code = X11Native.XKeysymToKeycode(_display, sym); + if (code != 0) return code; + } + return 0; + } + + void ReadModifierMasks() + { + var map = X11Native.XGetModifierMapping(_display); + if (map == IntPtr.Zero) return; + try + { + int max = Marshal.ReadInt32(map); + var keys = Marshal.ReadIntPtr(map, IntPtr.Size); + if (max <= 0 || keys == IntPtr.Zero) return; + uint alt = 0, super = 0; + for (int mod = 0; mod < 8; mod++) + { + for (int i = 0; i < max; i++) + { + int code = Marshal.ReadByte(keys, mod * max + i); + if (code == 0) continue; + ulong sym = X11Native.XkbKeycodeToKeysym(_display, code, 0, 0); + if (sym is 0xffe9 or 0xffea or 0xffe7 or 0xffe8) alt |= 1u << mod; + if (sym is 0xffeb or 0xffec) super |= 1u << mod; + } + } + if (alt != 0) _altMask = alt; + if (super != 0) _superMask = super; + } + finally + { + X11Native.XFreeModifiermap(map); + } + } + + void DispatchEvent() + { + X11Native.XNextEvent(_display, _event); + int type = Marshal.ReadInt32(_event); + if (type != KeyPress && type != KeyRelease) return; + int keycode = Marshal.ReadInt32(_event, 84); + uint state = (uint)Marshal.ReadInt32(_event, 80); + if (keycode == 0) return; + + if (type == KeyRelease) + { + _down.Remove(keycode); + return; + } + if (!_down.Add(keycode)) return; + + var chord = ChordFrom(state, keycode); + if (chord == null) return; + if (_listening) + { + DeliverListen(chord.Value); + return; + } + + var command = HotkeyBindings.Match(chord.Value, _bindings); + if (command == null) return; + try { _onCommand(command.Value); } + catch (Exception ex) { Log.Error(ex); } + } + + void DeliverListen(HotkeyChord chord) + { + // Stay grabbed so a rejected key (a bare letter) can be followed by another try. + // The caller ends the grab on accept, cancel, or close. + var callback = _listenCallback; + if (callback == null) return; + try { callback(chord); } + catch (Exception ex) { Log.Error(ex); } + } + + HotkeyChord? ChordFrom(uint state, int keycode) + { + string key = KeyFromCode(keycode, 0) ?? KeyFromCode(keycode, 1); + if (key == null) return null; + return new HotkeyChord( + key, + (_superMask != 0) && (state & _superMask) != 0, + (state & HotkeyGrabs.ControlMask) != 0, + (_altMask != 0) && (state & _altMask) != 0, + (state & HotkeyGrabs.ShiftMask) != 0); + } + + string KeyFromCode(int keycode, int level) + { + ulong sym = X11Native.XkbKeycodeToKeysym(_display, keycode, 0, level); + return HotkeyChord.FromKeysym(sym); + } + + void CancelListen(bool invoke) + { + bool was = _listening || _keyboardGrabbed; + _listening = false; + ReleaseKeyboard(); + var callback = _listenCallback; + _listenCallback = null; + if (!invoke || !was || callback == null) return; + try { callback(null); } + catch (Exception ex) { Log.Error(ex); } + } + + void ReleaseKeyboard() + { + if (!_keyboardGrabbed || _display == IntPtr.Zero) return; + _keyboardGrabbed = false; + _down.Clear(); + try + { + X11Native.XUngrabKeyboard(_display, 0); + X11Native.XFlush(_display); + } + catch { } + } + + bool ProbeGrab(int keycode, uint modifiers) + { + var other = X11Native.XOpenDisplay(null); + if (other == IntPtr.Zero) return false; + try + { + _probeDisplay = other; + int before = _errorCount; + var root = X11Native.XDefaultRootWindow(other); + X11Native.XGrabKey(other, keycode, modifiers, root, 0, GrabModeAsync, GrabModeAsync); + X11Native.XSync(other, 0); + bool ok = _errorCount == before; + if (ok) + { + X11Native.XUngrabKey(other, keycode, modifiers, root); + X11Native.XFlush(other); + } + return ok; + } + finally + { + _probeDisplay = IntPtr.Zero; + X11Native.XCloseDisplay(other); + } + } + + void Post(Action command) + { + if (Volatile.Read(ref _disposed) != 0) return; + lock (_gate) _commands.Enqueue(command); + Wake(); + } + + void DrainCommands() + { + while (true) + { + Action command; + lock (_gate) + { + if (_commands.Count == 0) return; + command = _commands.Dequeue(); + } + try { command(); } + catch (Exception ex) { Log.Error(ex); } + } + } + + void Poll() + { + int timeout = _wakeRead >= 0 ? -1 : 50; + if (_listening) + { + int remaining = (int)Math.Max(1, (_listenDeadline - DateTime.UtcNow).TotalMilliseconds); + timeout = timeout < 0 ? remaining : Math.Min(timeout, remaining); + } + + var fds = new PollFd[2]; + fds[0].fd = X11Native.XConnectionNumber(_display); + fds[0].events = PollIn; + uint count = 1; + if (_wakeRead >= 0) + { + fds[1].fd = _wakeRead; + fds[1].events = PollIn; + count = 2; + } + int rc = poll(fds, count, timeout); + if (rc < 0 && Marshal.GetLastPInvokeError() != 4) Thread.Sleep(5); // EINTR retries via the outer loop + } + + void OpenWakePipe() + { + var fds = new int[2]; + if (pipe2(fds, ONonBlock | OCloExec) != 0) return; + _wakeRead = fds[0]; + _wakeWrite = fds[1]; + } + + void CloseWakePipe() + { + if (_wakeRead >= 0) close(_wakeRead); + if (_wakeWrite >= 0) close(_wakeWrite); + _wakeRead = -1; + _wakeWrite = -1; + } + + void Wake() + { + if (_wakeWrite < 0) return; + var one = new byte[] { 1 }; + write(_wakeWrite, one, 1); + } + + void DrainWake() + { + if (_wakeRead < 0) return; + var buf = new byte[32]; + while (read(_wakeRead, buf, (nuint)buf.Length) > 0) { } + } + + static void InstallHandler() + { + if (_errorHandler != null) return; + _errorHandler = OnError; + // Keep the previous handler as a raw pointer. Avalonia's handler is a + // different delegate type, and wrapping that pointer throws. + _previousHandler = X11Native.XSetErrorHandler(Marshal.GetFunctionPointerForDelegate(_errorHandler)); + } + + static void RestoreHandler() + { + if (_errorHandler == null) return; + X11Native.XSetErrorHandler(_previousHandler); + _errorHandler = null; + _previousHandler = IntPtr.Zero; + } + + static unsafe int OnError(IntPtr display, IntPtr error) + { + var active = _active; + if (active != null && (display == active._display || display == active._probeDisplay)) + { + Interlocked.Increment(ref active._errorCount); + return 0; + } + if (display != IntPtr.Zero && display == _probeDisplayStatic) + { + Interlocked.Increment(ref _probeErrors); + return 0; + } + if (_previousHandler != IntPtr.Zero) + { + var previous = (delegate* unmanaged[Cdecl])_previousHandler; + return previous(display, error); + } + return 0; + } + + [UnmanagedFunctionPointer(CallingConvention.Cdecl)] + delegate int XErrorFn(IntPtr display, IntPtr error); + + [StructLayout(LayoutKind.Sequential)] + struct PollFd + { + public int fd; + public short events; + public short revents; + } + + [DllImport("libc", SetLastError = true)] + static extern int poll(PollFd[] fds, uint nfds, int timeout); + + [DllImport("libc", SetLastError = true)] + static extern int pipe2(int[] pipefd, int flags); + + [DllImport("libc", SetLastError = true)] + static extern int close(int fd); + + [DllImport("libc", SetLastError = true)] + static extern long read(int fd, byte[] buffer, nuint count); + + [DllImport("libc", SetLastError = true)] + static extern long write(int fd, byte[] buffer, nuint count); +} diff --git a/tests/OpenSnip.Hotkeys.Tests/X11HotkeyTests.cs b/tests/OpenSnip.Hotkeys.Tests/X11HotkeyTests.cs new file mode 100644 index 0000000..8bcad97 --- /dev/null +++ b/tests/OpenSnip.Hotkeys.Tests/X11HotkeyTests.cs @@ -0,0 +1,100 @@ +using System.Diagnostics; + +namespace OpenSnip.Hotkeys.Tests; + +public class X11HotkeyTests +{ + [Fact] + public async Task GrabbedChordFiresAndPlainKeysStayFree() + { + if (!X11HotkeyService.IsSupported || !File.Exists("/usr/bin/xdotool")) return; + + var bindings = new HotkeyBindings + { + Snip = HotkeyChord.Parse("Ctrl+Alt+Shift+Z"), + UsePrintScreen = false, + }; + int hits = 0; + var listen = new List(); + var listenDone = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + using var service = X11HotkeyService.TryStart(bindings, _ => Interlocked.Increment(ref hits)); + Assert.NotNull(service); + + int codeZ = service.KeycodeFor("Z"); + int codeA = service.KeycodeFor("A"); + uint mask = service.MaskFor(bindings.Snip); + Assert.NotEqual(0, codeZ); + Assert.False(service.ForeignGrabSucceeds(codeZ, mask), $"keycode {codeZ} mask {mask} was not held"); + Assert.False(service.ForeignGrabSucceeds(codeZ, mask | HotkeyGrabs.LockMask)); + Assert.True(service.ForeignGrabSucceeds(codeA, 0)); + + Press("ctrl+alt+shift+z"); + Wait(() => Volatile.Read(ref hits) >= 1); + Assert.Equal(1, Volatile.Read(ref hits)); + + Press("z"); + Thread.Sleep(250); + Assert.Equal(1, Volatile.Read(ref hits)); + + Press("ctrl+alt+shift+z"); + Wait(() => Volatile.Read(ref hits) >= 2); + Assert.Equal(2, Volatile.Read(ref hits)); + + Assert.True(service.BeginListen(chord => + { + if (chord == null) return; + lock (listen) listen.Add(chord.Value); + if (chord.Value.HasModifier) listenDone.TrySetResult(chord.Value); + })); + Press("a"); + Wait(() => { lock (listen) return listen.Count >= 1; }); + Press("ctrl+shift+b"); + var completed = await Task.WhenAny(listenDone.Task, Task.Delay(TimeSpan.FromSeconds(2))); + Assert.Same(listenDone.Task, completed); + service.EndListen(); + lock (listen) + { + Assert.Contains(listen, chord => chord == HotkeyChord.Parse("A")); + Assert.Contains(listen, chord => chord == HotkeyChord.Parse("Ctrl+Shift+B")); + } + + // The keys from capture must not stay "down" after the grab ends, or the new shortcut never fires. + service.Update(new HotkeyBindings + { + Snip = HotkeyChord.Parse("Ctrl+Shift+B"), + UsePrintScreen = false, + }); + Thread.Sleep(200); + Press("ctrl+shift+b"); + Wait(() => Volatile.Read(ref hits) >= 3); + Assert.Equal(3, Volatile.Read(ref hits)); + Press("ctrl+alt+shift+z"); + Thread.Sleep(250); + Assert.Equal(3, Volatile.Read(ref hits)); + + service.Dispose(); + Assert.True(X11HotkeyService.ProbeGrabSucceeds(codeZ, mask)); + } + + static void Press(string combo) + { + var start = new ProcessStartInfo("/usr/bin/xdotool") { UseShellExecute = false }; + start.ArgumentList.Add("key"); + start.ArgumentList.Add(combo); + using var process = Process.Start(start); + Assert.NotNull(process); + Assert.True(process.WaitForExit(3000)); + Assert.Equal(0, process.ExitCode); + } + + static void Wait(Func ready) + { + var deadline = DateTime.UtcNow.AddSeconds(2); + while (DateTime.UtcNow < deadline) + { + if (ready()) return; + Thread.Sleep(20); + } + Assert.Fail("Timed out waiting for the shortcut."); + } +} From dad66ae3ba697d15212a2d1ff48f7b0324d47e70 Mon Sep 17 00:00:00 2001 From: Devan <68340659+DevanMetz@users.noreply.github.com> Date: Tue, 27 Oct 2026 16:13:58 -0500 Subject: [PATCH 3/3] Use the X11 shortcuts in the Linux app and settings. On X11 the Shortcuts page edits the chords. Wayland keeps the command list, and the tray names the snip shortcut. --- .github/workflows/build.yml | 3 + README.md | 10 ++- linux/App.cs | 40 +++++++++ linux/Diagnostics.cs | 4 + linux/SettingsWindow.cs | 172 ++++++++++++++++++++++++++++++++++-- 5 files changed, 221 insertions(+), 8 deletions(-) diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index 07db7a9..b2764d4 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -47,6 +47,9 @@ jobs: with: dotnet-version: 9.0.x + - name: Test + run: dotnet test tests/OpenSnip.Hotkeys.Tests/OpenSnip.Hotkeys.Tests.csproj -c Release --nologo + - name: Publish run: dotnet publish linux/OpenSnip.Linux.csproj -c Release -r linux-x64 --self-contained true -p:PublishSingleFile=true -p:IncludeNativeLibrariesForSelfExtract=true -p:EnableCompressionInSingleFile=true -p:DebugType=none -o dist/linux diff --git a/README.md b/README.md index 987b573..71abbb6 100644 --- a/README.md +++ b/README.md @@ -115,9 +115,9 @@ Run `OpenSnip.exe --diagnostics` to write a report (displays, audio devices, and ## Linux -The Linux app is a separate native Avalonia build. It covers the screenshot side of OpenSnip; recording, the annotation editor, pins and built-in global shortcuts remain Windows-only. +The Linux app is a separate native Avalonia build. It covers the screenshot side of OpenSnip; recording, the annotation editor and pins remain Windows-only. -**What works:** X11 capture through libX11, with `maim`, ImageMagick `import` and `scrot` as fallbacks; Wayland capture through the `xdg-desktop-portal` Screenshot API, with `grim`, `gnome-screenshot` and `spectacle` as fallbacks; region, monitor and all-monitor selection with a magnifier; clipboard as PNG; auto-save as PNG or JPG; preview; tray icon; and settings. +**What works:** X11 capture through libX11, with `maim`, ImageMagick `import` and `scrot` as fallbacks; Wayland capture through the `xdg-desktop-portal` Screenshot API, with `grim`, `gnome-screenshot` and `spectacle` as fallbacks; region, monitor and all-monitor selection with a magnifier; clipboard as PNG; auto-save as PNG or JPG; preview; tray icon; global shortcuts on X11; and settings. **Install:** download `OpenSnip-linux-x64.tar.gz` from [Releases](https://github.com/DevanMetz/OpenSnip/releases), then: @@ -133,7 +133,9 @@ The installer copies the binary to `~/.local/bin/opensnip`, so make sure `~/.loc ### Shortcuts -There are no built-in global shortcuts on Linux; bind your own in GNOME Settings → Keyboard → Custom Shortcuts, or KDE System Settings → Shortcuts. Use `opensnip --snip` for a normal snip, `opensnip --snip-delay` for a delayed one, `opensnip --repeat` to re-capture the last region, and `opensnip --settings` to open settings. +On X11, OpenSnip uses the same shortcuts as Windows. The defaults are `Win` + `Shift` + `S`, `PrtSc`, `Shift` + `PrtSc`, and `Ctrl` + `PrtSc`. Change them in **Settings → Shortcuts**. `Alt` + `PrtSc` and `Win` + `PrtSc` stay with the desktop, as does any chord the desktop already owns. + +On Wayland, bind `opensnip --snip`, `opensnip --snip-delay`, or `opensnip --repeat` in the desktop's shortcut settings. `opensnip --settings` opens settings. ### Selecting a region @@ -209,6 +211,8 @@ Issues and pull requests are welcome. The code is plain WinForms + GDI+; recordi | `linux/Capture.cs` / `linux/DBus.cs` | X11, Wayland portal and external capture backends | | `linux/OverlayWindow.cs` | Linux selection overlay and magnifier | | `linux/SettingsWindow.cs` | Linux Settings window | +| `linux/HotkeyChord.cs` | Shortcut parsing, matching, and grab planning | +| `linux/X11Hotkeys.cs` | X11 global shortcuts | ## License diff --git a/linux/App.cs b/linux/App.cs index 5df37c6..f167099 100644 --- a/linux/App.cs +++ b/linux/App.cs @@ -17,6 +17,7 @@ sealed class App : Application NativeMenuItem _delayItem; SettingsWindow _settingsWindow; ThumbnailWindow _thumbnail; + X11HotkeyService _hotkeys; PixelRect? _lastRegion; bool _trayAvailable; bool _busy; @@ -61,6 +62,9 @@ async Task StartAsync() async Task StartAsyncCore() { + try { _hotkeys = X11HotkeyService.TryStart(HotkeyBindings.From(Settings), OnHotkey); } + catch (Exception ex) { Log.Error(ex); } + try { _trayAvailable = await DBus.TrayHostAvailableAsync(); } catch (Exception ex) { Log.Error(ex); _trayAvailable = false; } @@ -119,6 +123,7 @@ void CreateTray() }; _tray.Clicked += (_, _) => StartSnip(); TrayIcon.SetIcons(this, new TrayIcons { _tray }); + UpdateTrayText(); } static NativeMenuItem Item(string header, Action action) @@ -142,6 +147,39 @@ void HandleAction(LaunchAction action) public void SettingsChanged() { if (_delayItem != null) _delayItem.Header = $"Snip after delay ({Settings.DelaySeconds}s)"; + _hotkeys?.Update(HotkeyBindings.From(Settings)); + UpdateTrayText(); + } + + public bool HasGlobalHotkeys => _hotkeys != null; + + public bool BeginShortcutCapture(Action onChord) => + _hotkeys != null && _hotkeys.BeginListen(onChord); + + public void EndShortcutCapture() => _hotkeys?.EndListen(); + + void OnHotkey(HotkeyCommand command) + { + Dispatcher.UIThread.Post(() => + { + if (_busy) return; + switch (command) + { + case HotkeyCommand.Snip: StartSnip(); break; + case HotkeyCommand.SnipDelay: StartSnip(Settings.DelaySeconds); break; + case HotkeyCommand.Repeat: RepeatLast(); break; + } + }); + } + + void UpdateTrayText() + { + if (_tray == null) return; + var bindings = HotkeyBindings.From(Settings); + string keys = !bindings.Snip.IsEmpty ? bindings.Snip.Display + : bindings.UsePrintScreen ? "PrtSc" : null; + string text = keys != null ? $"OpenSnip — {keys} to snip" : "OpenSnip"; + _tray.ToolTipText = text.Length <= 63 ? text : text[..62] + "…"; } public void SettingsWindowClosed(SettingsWindow window) @@ -328,6 +366,8 @@ async Task ShowErrorAsync(string message) public void ExitApp() { + try { _hotkeys?.Dispose(); } catch { } + _hotkeys = null; try { _tray?.Dispose(); } catch { } _tray = null; SingleInstance.Stop(); diff --git a/linux/Diagnostics.cs b/linux/Diagnostics.cs index b5de7f4..98094bd 100644 --- a/linux/Diagnostics.cs +++ b/linux/Diagnostics.cs @@ -28,6 +28,10 @@ public static async Task RunAsync(string file) bool tray = await DBus.TrayHostAvailableAsync(); report.AppendLine("xdg-desktop-portal: " + (portal ? "available" : "unavailable")); report.AppendLine("Tray host: " + (tray ? "available" : "unavailable")); + var settings = Settings.Load(); + SettingsDefaults.ApplyLinux(settings); + string shortcuts = X11HotkeyService.IsSupported ? HotkeyBindings.From(settings).Summary : "off"; + report.AppendLine("Global shortcuts: " + shortcuts); report.AppendLine("Settings: " + ConfigPaths.Dir); string text = report.ToString(); diff --git a/linux/SettingsWindow.cs b/linux/SettingsWindow.cs index 2a2d202..b398554 100644 --- a/linux/SettingsWindow.cs +++ b/linux/SettingsWindow.cs @@ -31,6 +31,11 @@ sealed class SettingsWindow : Window ComboBox _format; CheckBox _monthly; CheckBox _startOnLogin; + CheckBox _printScreen; + TextBlock _shortcutStatus; + readonly List _shortcuts = new(); + ShortcutRow _listeningRow; + int _listenGeneration; public SettingsWindow(App app, string startPage = "Capture") { @@ -96,7 +101,11 @@ public SettingsWindow(App app, string startPage = "Capture") e.Handled = true; } }; - Closed += (_, _) => app.SettingsWindowClosed(this); + Closed += (_, _) => + { + StopShortcutCapture(); + app.SettingsWindowClosed(this); + }; } void AddPage(string name, Control page) @@ -147,6 +156,7 @@ void AddPage(string name, Control page) public void ShowPage(string name) { + StopShortcutCapture(); if (!_pages.TryGetValue(name, out var page)) name = "Capture"; if (!_pages.TryGetValue(name, out page)) return; _currentPage = name; @@ -262,10 +272,34 @@ Control BuildSaving() Control BuildShortcuts() { var panel = Page("Shortcuts"); - panel.Children.Add(Heading("Commands")); - panel.Children.Add(CommandRow("Snip", PlatformInfo.Command("--snip"))); - panel.Children.Add(CommandRow("Delayed snip", PlatformInfo.Command("--snip-delay"))); - panel.Children.Add(CommandRow("Repeat last region", PlatformInfo.Command("--repeat"))); + if (_app.HasGlobalHotkeys) + { + ShortcutRowFor(panel, "Snip", () => _s.SnipHotkey, v => _s.SnipHotkey = v); + ShortcutRowFor(panel, "Snip after delay", () => _s.DelayHotkey, v => _s.DelayHotkey = v); + ShortcutRowFor(panel, "Repeat last region", () => _s.RepeatHotkey, v => _s.RepeatHotkey = v); + _printScreen = Check("Also use the Print Screen key", _s.UsePrintScreen, v => _s.UsePrintScreen = v); + panel.Children.Add(_printScreen); + _shortcutStatus = new TextBlock + { + Foreground = new SolidColorBrush(Color.Parse("#FFAA5A")), + FontSize = 12.5, + TextWrapping = TextWrapping.Wrap, + IsVisible = false, + }; + panel.Children.Add(_shortcutStatus); + _refresh.Add(() => + { + foreach (var row in _shortcuts) ShowShortcut(row); + if (_printScreen != null) _printScreen.IsChecked = _s.UsePrintScreen; + }); + } + else + { + panel.Children.Add(Heading("Commands")); + panel.Children.Add(CommandRow("Snip", PlatformInfo.Command("--snip"))); + panel.Children.Add(CommandRow("Delayed snip", PlatformInfo.Command("--snip-delay"))); + panel.Children.Add(CommandRow("Repeat last region", PlatformInfo.Command("--repeat"))); + } return panel; } @@ -344,6 +378,7 @@ Control CommandRow(string label, string command) void ResetToDefaults() { + StopShortcutCapture(); _s.CopyToClipboard = true; _s.AutoSave = true; _s.SaveFolder = SettingsDefaults.DefaultSaveFolder; @@ -353,6 +388,10 @@ void ResetToDefaults() _s.PreviewSeconds = 6; _s.ShowMagnifier = true; _s.DelaySeconds = 3; + _s.SnipHotkey = "Win+Shift+S"; + _s.DelayHotkey = ""; + _s.RepeatHotkey = ""; + _s.UsePrintScreen = true; Save(); foreach (var refresh in _refresh) refresh(); } @@ -465,6 +504,129 @@ static StackPanel Page(string title) Margin = new Thickness(0, 13, 0, 1), }; + void ShortcutRowFor(StackPanel panel, string label, Func get, Action set) + { + var row = new ShortcutRow { Get = get, Set = set }; + row.Value = new TextBlock + { + FontWeight = FontWeight.SemiBold, + HorizontalAlignment = HorizontalAlignment.Center, + VerticalAlignment = VerticalAlignment.Center, + }; + var box = new Border + { + Background = AppTheme.Panel, + BorderBrush = AppTheme.Border, + BorderThickness = new Thickness(1), + CornerRadius = new CornerRadius(6), + MinWidth = 180, + MinHeight = 32, + Padding = new Thickness(10, 4), + Child = row.Value, + }; + row.Change = new Button { Content = "Change…", MinWidth = 88 }; + var clear = new Button { Content = "Clear", MinWidth = 72 }; + row.Change.Click += (_, _) => + { + if (_listeningRow == row) StopShortcutCapture(); + else StartShortcutCapture(row); + }; + clear.Click += (_, _) => + { + StopShortcutCapture(); + row.Set(""); + ShowShortcut(row); + Save(); + }; + var controls = new Grid + { + ColumnDefinitions = new ColumnDefinitions("*,Auto,Auto"), + ColumnSpacing = 8, + }; + controls.Children.Add(box); + Grid.SetColumn(box, 0); + controls.Children.Add(row.Change); + Grid.SetColumn(row.Change, 1); + controls.Children.Add(clear); + Grid.SetColumn(clear, 2); + panel.Children.Add(Row(label, controls)); + _shortcuts.Add(row); + ShowShortcut(row); + } + + void ShowShortcut(ShortcutRow row) + { + var chord = HotkeyChord.Parse(row.Get()); + bool listening = _listeningRow == row; + row.Value.Text = listening ? "Press keys…" : chord.Display; + row.Value.Foreground = listening ? AppTheme.Accent : chord.IsEmpty ? AppTheme.Muted : AppTheme.Text; + row.Change.Content = listening ? "Cancel" : "Change…"; + } + + void StartShortcutCapture(ShortcutRow row) + { + StopShortcutCapture(); + int generation = ++_listenGeneration; + if (!_app.BeginShortcutCapture(chord => + Dispatcher.UIThread.Post(() => OnShortcutCaptured(row, generation, chord)))) + { + _ = MessageDialog.AlertAsync(this, "Couldn't listen for a shortcut."); + return; + } + _listeningRow = row; + if (_shortcutStatus != null) _shortcutStatus.IsVisible = false; + ShowShortcut(row); + } + + void OnShortcutCaptured(ShortcutRow row, int generation, HotkeyChord? chord) + { + if (generation != _listenGeneration) return; + if (chord == null || (chord.Value.Key == "Escape" && !chord.Value.HasModifier)) + { + StopShortcutCapture(); + return; + } + if (!HotkeyGrabs.IsSafe(chord.Value)) + { + if (_shortcutStatus != null) + { + _shortcutStatus.Text = $"{chord.Value.Display} needs Ctrl, Alt, Shift, or Win."; + _shortcutStatus.IsVisible = true; + } + return; + } + foreach (var other in _shortcuts) + { + if (ReferenceEquals(other, row)) continue; + if (HotkeyChord.Parse(other.Get()) == chord.Value) + { + other.Set(""); + ShowShortcut(other); + } + } + row.Set(chord.Value.Serialize()); + StopShortcutCapture(); + Save(); + } + + void StopShortcutCapture() + { + _listenGeneration++; + var row = _listeningRow; + _listeningRow = null; + _app.EndShortcutCapture(); + if (row != null) ShowShortcut(row); + if (_shortcutStatus != null) _shortcutStatus.IsVisible = false; + } + + sealed class ShortcutRow + { + public Func Get; + public Action Set; + public TextBlock Value; + public Button Change; + } + static Grid Row(string label, Control control) { var grid = new Grid