Repository navigation
feat(v3): global (system-wide) keyboard shortcuts - #5686
Conversation
Add app.GlobalShortcut for registering system-wide hotkeys that fire even when the application is not focused. The manager exposes Register, Unregister, UnregisterAll, IsRegistered and GetAll, reuses the existing accelerator syntax, and supports registration before app.Run (bindings are flushed at startup). Implemented natively per platform with no third party dependencies: - macOS: Carbon RegisterEventHotKey (no Accessibility permission required) - Windows: Win32 RegisterHotKey + WM_HOTKEY - Linux X11: XGrabKey (single-threaded Xlib loop with self-pipe wakeup) - Linux Wayland: XDG Desktop Portal org.freedesktop.portal.GlobalShortcuts Same-shortcut behavior: an intra-app duplicate returns an error and preserves the original binding on every platform; an inter-app conflict is resolved by the OS (Windows/X11 reject, macOS allows, Wayland compositor arbitrates). Includes unit tests, an X11 integration test, an interactive manual-test example, and documentation.
|
Caution Review failedThe pull request is closed. ℹ️ Recent review info⚙️ Run configurationConfiguration used: Path: .coderabbit.yaml Review profile: CHILL Plan: Pro Run ID: 📒 Files selected for processing (2)
WalkthroughAdds system-wide global shortcut support to Wails v3 through a new manager wired into app startup and cleanup. Platform backends are added for macOS, Windows, Linux X11, and Linux Wayland, along with an example app, docs, and changelog entry. ChangesGlobal Shortcuts Feature
Estimated code review effort🎯 5 (Critical) | ⏱️ ~120 minutes Suggested labels
Suggested reviewers
Possibly related PRs
Poem
🚥 Pre-merge checks | ✅ 3 | ❌ 2❌ Failed checks (2 warnings)
✅ Passed checks (3 passed)
✨ Finishing Touches📝 Generate docstrings
🧪 Generate unit tests (beta)
Warning There were issues while running some tools. Please review the errors and either fix the tool's configuration or disable the tool if it's a critical failure. 🔧 golangci-lint (2.12.2)level=error msg="[linters_context] typechecking error: pattern ./...: directory prefix . does not contain modules listed in go.work or their selected dependencies" Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
There was a problem hiding this comment.
Actionable comments posted: 13
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Inline comments:
In `@docs/src/content/docs/features/keyboard/global-shortcuts.mdx`:
- Around line 67-80: Update the global-shortcuts docs example so it uses the
exact same accelerator token for registration, IsRegistered, and Unregister
instead of hardcoding Ctrl+Shift+G in later calls. The sample should either
reuse the same variable or consistently use the same accelerator string in
app.GlobalShortcut.IsRegistered, app.GlobalShortcut.Unregister, and the
registration example so readers see the correct cross-platform usage.
In `@v3/examples/global-shortcuts/main.go`:
- Around line 90-97: The startup delay in the global shortcuts example is
nondeterministic because the `time.Sleep(500 * time.Millisecond)` can fire
before the frontend is listening, causing `shortcuts:registered` to be missed.
Replace the sleep-based emit in `main.go` with an explicit readiness handshake:
have the frontend signal when its listeners are registered and then request or
receive the shortcut data, or trigger the emit from a real ready event in the
app flow. Use the existing `app.Event.Emit("shortcuts:registered", ...)` flow
and the shortcut values (`showShortcut`, `hideShortcut`, `pingShortcut`) as the
data source.
- Around line 88-96: The shortcuts:registered payload in main.go is still
emitting the raw CmdOrCtrl-based constants instead of the platform-specific
display shortcuts. Update the shortcut registration flow around the goroutine
that emits shortcuts:registered so it resolves the actual keys for the current
platform before sending showShortcut, hideShortcut, and pingShortcut, or adjust
the frontend copy if you intend to keep the cross-platform accelerator syntax.
In `@v3/pkg/application/global_shortcut_darwin.go`:
- Around line 28-48: The shortcut setup in installHotKeyHandler currently
ignores the InstallApplicationEventHandler result, so registerHotKey can proceed
even when no kEventHotKeyPressed handler was installed. Update
installHotKeyHandler to return the OSStatus from InstallApplicationEventHandler
and have registerHotKey check that status before calling RegisterEventHotKey,
propagating any failure back to the caller; use the existing
installHotKeyHandler and registerHotKey symbols to keep the fix localized.
- Around line 123-130: The unregister path in macosGlobalShortcuts.unregister
removes the hotkey reference before C.unregisterHotKey succeeds, which can lose
the only handle needed for retrying cleanup. Update unregister so g.refs[id] is
only deleted after C.unregisterHotKey(ref) returns success, and keep the
existing ref available if the Carbon call fails.
In `@v3/pkg/application/global_shortcut_linux_portal.go`:
- Around line 146-147: The portal signal setup in global shortcut handling is
ignoring registration failures and not scoping activations to the current
session. Update the `AddMatchSignal` calls in `global_shortcut_linux_portal.go`
to handle and surface any errors so `Response` and `Activated` listeners are
actually registered, and in the `Activated` handling path ensure the signal’s
first argument matches `w.sessionPath` before dispatching, not just the
`shortcut_id`. Use the existing `portalRequestIf`, `portalShortcutIf`, and
session state in `w` to keep the fix localized.
In `@v3/pkg/application/global_shortcut_linux_x11_test.go`:
- Around line 68-74: The post-unregister assertion in the global shortcut X11
test is currently not validating that xdotool actually synthesized the key
event. In the test around the fired channel check, capture the result of the
exec.Command(xdotool, "key", "--clearmodifiers", "ctrl+shift+a").Run() call and
fail the test if it returns an error, so the timeout only proves unregister
behavior and not a missing key injection. Use the existing fired channel and
unregister flow in global_shortcut_linux_x11_test to keep the intent unchanged.
In `@v3/pkg/application/global_shortcut_linux_x11.go`:
- Around line 195-203: The x11GlobalShortcuts flow can deadlock after the X
event loop exits because run still enqueues work on opCh and waits on done even
when the connection is already lost. Add a closed/error state to
x11GlobalShortcuts that is set when eventLoop returns, then update run to fail
fast instead of blocking, and make register and unregister return that stored
error immediately when the loop is no longer active.
- Around line 24-28: The X error handler is being installed in gsOpenDisplay too
broadly, which can leave partial shortcut grabs behind when gsGrabKey fails
partway through. Move the handler setup into the grab flow around gsGrabKey, and
if any variant grab succeeds before an error, explicitly ungrab those
already-grabbed lock-mask variants before returning failure so no shortcut
remains active unless registration fully succeeds.
In `@v3/pkg/application/global_shortcut_manager.go`:
- Around line 199-212: The unregister flow in GlobalShortcutManager is removing
entries from byName and byID before the native release succeeds, so if
impl.unregister or impl.unregisterAll fails the manager state becomes
inconsistent. Update Unregister and UnregisterAll to either defer deleting the
shortcut from the manager maps until the native call completes successfully, or
capture the removed entries and restore them on error. Keep the logic centered
around the Unregister, UnregisterAll, and getImpl paths so IsRegistered remains
accurate and failed cleanup can be retried.
- Around line 137-145: The rollback in global shortcut registration is deleting
byName[name] unconditionally, which can remove a newer binding if the shortcut
was unregistered and re-registered while impl.register was still in flight.
Update the failure path in global_shortcut_manager.go to mirror the identity
check used in flushPending, so the rollback only deletes the reservation when
the current entry still matches the same shortcut id/registration attempt. Keep
the existing byID cleanup consistent with that guard and leave newer
registrations intact.
In `@v3/pkg/application/global_shortcut_windows.go`:
- Around line 78-89: The unregister path in windowsGlobalShortcuts.unregister
removes the shortcut from g.ids before the Windows unregister call, which can
desync local state if hwnd() or w32.UnregisterHotKey fails. Move the
delete(g.ids, id) so it only happens after UnregisterHotKey succeeds, while
keeping the existing early returns for missing ids and hwnd() errors. This keeps
the shortcut tracked locally until the system hotkey is actually released and
preserves retry/cleanup behavior in UnregisterAll.
In `@v3/pkg/w32/user32.go`:
- Around line 557-563: `RegisterHotKey` and `UnregisterHotKey` are swallowing
the Win32 failure detail by returning only a bool, which prevents callers like
`global_shortcut_windows.go` from distinguishing
`ERROR_HOTKEY_ALREADY_REGISTERED` from other errors. Update the hotkey wrapper
functions in `user32.go` to return the syscall error/errno alongside success,
using the existing `procRegisterHotKey` and `procUnregisterHotKey` calls, and
then adjust the caller to branch on the specific error instead of treating every
failure as already-registered.
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: Path: .coderabbit.yaml
Review profile: CHILL
Plan: Pro
Run ID: 7715aabd-472d-4ddf-9446-f85b62e7e09f
📒 Files selected for processing (18)
docs/src/content/docs/features/keyboard/global-shortcuts.mdxv3/UNRELEASED_CHANGELOG.mdv3/examples/global-shortcuts/README.mdv3/examples/global-shortcuts/assets/index.htmlv3/examples/global-shortcuts/main.gov3/pkg/application/application.gov3/pkg/application/application_windows.gov3/pkg/application/global_shortcut_darwin.gov3/pkg/application/global_shortcut_linux.gov3/pkg/application/global_shortcut_linux_portal.gov3/pkg/application/global_shortcut_linux_x11.gov3/pkg/application/global_shortcut_linux_x11_test.gov3/pkg/application/global_shortcut_manager.gov3/pkg/application/global_shortcut_test.gov3/pkg/application/global_shortcut_unsupported.gov3/pkg/application/global_shortcut_windows.gov3/pkg/w32/constants.gov3/pkg/w32/user32.go
| ```go | ||
| // Check whether a shortcut is registered (modifier order does not matter). | ||
| registered := app.GlobalShortcut.IsRegistered("Ctrl+Shift+G") | ||
|
|
||
| // List every shortcut this application has registered. | ||
| for _, accelerator := range app.GlobalShortcut.GetAll() { | ||
| app.Logger.Info("global shortcut", "accelerator", accelerator) | ||
| } | ||
|
|
||
| // Release a single shortcut. | ||
| app.GlobalShortcut.Unregister("Ctrl+Shift+G") | ||
|
|
||
| // Release everything (also done automatically on shutdown). | ||
| app.GlobalShortcut.UnregisterAll() |
There was a problem hiding this comment.
🎯 Functional Correctness | 🟠 Major | ⚡ Quick win
Use the same accelerator token you registered.
IsRegistered and Unregister re-parse the string, so Ctrl+Shift+G is not equivalent to CmdOrCtrl+Shift+G on macOS. This sample will mislead readers into thinking the API is broken there; it should use the same accelerator string (or the same variable) throughout.
Suggested doc fix
-registered := app.GlobalShortcut.IsRegistered("Ctrl+Shift+G")
+registered := app.GlobalShortcut.IsRegistered("CmdOrCtrl+Shift+G")
@@
-app.GlobalShortcut.Unregister("Ctrl+Shift+G")
+app.GlobalShortcut.Unregister("CmdOrCtrl+Shift+G")📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| ```go | |
| // Check whether a shortcut is registered (modifier order does not matter). | |
| registered := app.GlobalShortcut.IsRegistered("Ctrl+Shift+G") | |
| // List every shortcut this application has registered. | |
| for _, accelerator := range app.GlobalShortcut.GetAll() { | |
| app.Logger.Info("global shortcut", "accelerator", accelerator) | |
| } | |
| // Release a single shortcut. | |
| app.GlobalShortcut.Unregister("Ctrl+Shift+G") | |
| // Release everything (also done automatically on shutdown). | |
| app.GlobalShortcut.UnregisterAll() |
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@docs/src/content/docs/features/keyboard/global-shortcuts.mdx` around lines 67
- 80, Update the global-shortcuts docs example so it uses the exact same
accelerator token for registration, IsRegistered, and Unregister instead of
hardcoding Ctrl+Shift+G in later calls. The sample should either reuse the same
variable or consistently use the same accelerator string in
app.GlobalShortcut.IsRegistered, app.GlobalShortcut.Unregister, and the
registration example so readers see the correct cross-platform usage.
| // Tell the frontend which accelerators were registered (they differ per | ||
| // platform because of CmdOrCtrl). Wait for the window to be ready first. | ||
| go func() { | ||
| time.Sleep(500 * time.Millisecond) | ||
| app.Event.Emit("shortcuts:registered", map[string]string{ | ||
| "show": showShortcut, | ||
| "hide": hideShortcut, | ||
| "ping": pingShortcut, | ||
| }) |
There was a problem hiding this comment.
🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win
Emit actual display shortcuts here.
This payload still sends the raw CmdOrCtrl+... constants, so the demo does not show “the right keys for this platform” as the comment says. On macOS especially, the UI will render a shortcut the user cannot press verbatim. Either resolve the display string before emitting it, or change the UI copy to say it shows the cross-platform accelerator syntax.
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@v3/examples/global-shortcuts/main.go` around lines 88 - 96, The
shortcuts:registered payload in main.go is still emitting the raw
CmdOrCtrl-based constants instead of the platform-specific display shortcuts.
Update the shortcut registration flow around the goroutine that emits
shortcuts:registered so it resolves the actual keys for the current platform
before sending showShortcut, hideShortcut, and pingShortcut, or adjust the
frontend copy if you intend to keep the cross-platform accelerator syntax.
| go func() { | ||
| time.Sleep(500 * time.Millisecond) | ||
| app.Event.Emit("shortcuts:registered", map[string]string{ | ||
| "show": showShortcut, | ||
| "hide": hideShortcut, | ||
| "ping": pingShortcut, | ||
| }) | ||
| }() |
There was a problem hiding this comment.
🩺 Stability & Availability | 🟡 Minor | ⚡ Quick win
Replace the fixed startup sleep with an explicit ready handshake.
The time.Sleep(500 * time.Millisecond) makes this example nondeterministic: if the frontend subscribes after the timer fires, shortcuts:registered is dropped and the shortcut table stays blank. Have the frontend request the data after registering its listeners, or emit it from a real ready signal instead of sleeping.
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@v3/examples/global-shortcuts/main.go` around lines 90 - 97, The startup delay
in the global shortcuts example is nondeterministic because the `time.Sleep(500
* time.Millisecond)` can fire before the frontend is listening, causing
`shortcuts:registered` to be missed. Replace the sleep-based emit in `main.go`
with an explicit readiness handshake: have the frontend signal when its
listeners are registered and then request or receive the shortcut data, or
trigger the emit from a real ready event in the app flow. Use the existing
`app.Event.Emit("shortcuts:registered", ...)` flow and the shortcut values
(`showShortcut`, `hideShortcut`, `pingShortcut`) as the data source.
| // installHotKeyHandler installs the shared handler exactly once. | ||
| static void installHotKeyHandler(void) { | ||
| if (gHotKeyHandler != NULL) { | ||
| return; | ||
| } | ||
| EventTypeSpec evt; | ||
| evt.eventClass = kEventClassKeyboard; | ||
| evt.eventKind = kEventHotKeyPressed; | ||
| InstallApplicationEventHandler(&hotKeyHandlerProc, 1, &evt, NULL, &gHotKeyHandler); | ||
| } | ||
|
|
||
| // registerHotKey binds (keyCode, modifiers) to id and returns the OSStatus. | ||
| // On success *outRef receives the hot key reference used to unregister later. | ||
| static int registerHotKey(unsigned int keyCode, unsigned int modifiers, int id, EventHotKeyRef *outRef) { | ||
| installHotKeyHandler(); | ||
| EventHotKeyID hkID; | ||
| hkID.signature = 'WLgs'; // "Wails global shortcut" | ||
| hkID.id = (unsigned int)id; | ||
| OSStatus status = RegisterEventHotKey(keyCode, modifiers, hkID, | ||
| GetApplicationEventTarget(), 0, outRef); | ||
| return (int)status; |
There was a problem hiding this comment.
🩺 Stability & Availability | 🟠 Major | ⚡ Quick win
🧩 Analysis chain
🌐 Web query:
Apple Carbon InstallApplicationEventHandler RegisterEventHotKey OSStatus documentation
💡 Result:
The functions InstallApplicationEventHandler and RegisterEventHotKey are part of the Carbon Event Manager framework, which is a legacy API set for macOS [1][2][3]. While still available in modern macOS for historical compatibility, they are largely superseded by more modern Cocoa APIs (such as NSEvent global monitors) [4]. 1. InstallApplicationEventHandler This is a convenience macro that installs an event handler specifically for the application's event target [5][6][3]. Signature: OSStatus InstallApplicationEventHandler( EventHandlerUPP inHandler, UInt32 inNumTypes, const EventTypeSpec *inList, void *inUserData, EventHandlerRef *outRef); It internally calls InstallEventHandler using GetApplicationEventTarget() as the target [5][3]. It returns noErr (0) on success or a non-zero OSStatus error code upon failure [5][7]. 2. RegisterEventHotKey This function registers a system-wide global hot key [7]. When the specified key combination is pressed, a kEventHotKeyPressed event is dispatched to the target specified in the function call [7]. Signature: OSStatus RegisterEventHotKey( UInt32 inHotKeyCode, UInt32 inHotKeyModifiers, EventHotKeyID inHotKeyID, EventTargetRef inTarget, OptionBits inOptions, EventHotKeyRef *outRef); Commonly, developers pass GetApplicationEventTarget() as the target to receive these hot key events [8][9][10]. The inOptions parameter is currently unused and must be set to 0 [7]. Notes for Implementation: - Event Handling: You must provide an EventHandlerUPP (Universal Procedure Pointer) to handle the incoming kEventHotKeyPressed event [9][4]. - Main Thread: Carbon event handlers typically require the main thread's event loop to be running (e.g., via RunApplicationEventLoop or by servicing the NSApplication event loop) to receive and process events correctly [8][10][2]. - Error Codes: Always check the OSStatus returned by these functions [10][11]. A value of 0 indicates noErr [5][7]. Non-zero values indicate errors (e.g., -50 for paramErr) [10][7].
Citations:
- 1: https://web.archive.org/web/20140806115511/developer.apple.com/legacy/library/documentation/Carbon/Reference/Carbon_Event_Manager_Ref/Reference/reference.html
- 2: https://developer.apple.com/library/archive/documentation/Carbon/Conceptual/Carbon_Event_Manager/Concept/CarbonEventsConcept.html
- 3: https://leopard-adc.pepas.com/documentation/Carbon/Conceptual/Carbon_Event_Manager/CarbonEvents.pdf
- 4: https://stackoverflow.com/questions/4807319/register-hotkey
- 5: https://developer.apple.com/library/archive/documentation/Carbon/Conceptual/Carbon_Event_Manager/Tasks/CarbonEventsTasks.html
- 6: https://leopard-adc.pepas.com/documentation/Carbon/Conceptual/appservices/appservices.pdf
- 7: https://leopard-adc.pepas.com/documentation/Carbon/Reference/Carbon_Event_Manager_Ref/Reference/reference.html
- 8: https://stackoverflow.com/questions/39704702/creating-a-main-event-loop-for-hotkeys-etc
- 9: https://bdunagan.com/2010/10/14/cocoa-tip-global-hot-keys/
- 10: https://stackoverflow.com/questions/35879162/registereventhotkey-from-thread
- 11: https://github.com/soffes/HotKey/blob/master/Sources/HotKey/HotKeysController.swift
🏁 Script executed:
#!/bin/bash
set -euo pipefail
# Locate the file and inspect the relevant region plus nearby helpers/callers.
git ls-files 'v3/pkg/application/global_shortcut_darwin.go'
echo '---'
sed -n '1,220p' v3/pkg/application/global_shortcut_darwin.go
echo '--- CALLERS ---'
rg -n "installHotKeyHandler|registerHotKey|RegisterEventHotKey|InstallApplicationEventHandler|gHotKeyHandler" v3/pkg/application -A3 -B3Repository: wailsapp/wails
Length of output: 12792
Propagate handler-install failures before calling RegisterEventHotKey.
installHotKeyHandler() drops the InstallApplicationEventHandler status, so a shortcut can register successfully even when no kEventHotKeyPressed handler is installed to dispatch it.
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@v3/pkg/application/global_shortcut_darwin.go` around lines 28 - 48, The
shortcut setup in installHotKeyHandler currently ignores the
InstallApplicationEventHandler result, so registerHotKey can proceed even when
no kEventHotKeyPressed handler was installed. Update installHotKeyHandler to
return the OSStatus from InstallApplicationEventHandler and have registerHotKey
check that status before calling RegisterEventHotKey, propagating any failure
back to the caller; use the existing installHotKeyHandler and registerHotKey
symbols to keep the fix localized.
| func (g *macosGlobalShortcuts) unregister(id int) error { | ||
| ref, ok := g.refs[id] | ||
| if !ok { | ||
| return nil | ||
| } | ||
| delete(g.refs, id) | ||
| if status := C.unregisterHotKey(ref); status != 0 { | ||
| return fmt.Errorf("UnregisterEventHotKey failed (OSStatus %d)", int(status)) |
There was a problem hiding this comment.
🩺 Stability & Availability | 🟠 Major | ⚡ Quick win
🧩 Analysis chain
🌐 Web query:
Apple Carbon UnregisterEventHotKey OSStatus documentation
💡 Result:
UnregisterEventHotKey is a legacy Carbon function used to unregister a previously registered global hot key in macOS applications [1][2]. It returns an OSStatus value, which is a signed 32-bit integer used to report success or errors [2][3]. Function Signature: OSStatus UnregisterEventHotKey(EventHotKeyRef inHotKey); Parameters: inHotKey: An EventHotKeyRef (an opaque pointer) representing the hot key reference that was returned by a successful call to RegisterEventHotKey [2][3]. Return Value: The function returns an OSStatus [2][3]. A return value of noErr (which is defined as 0) indicates that the hot key was successfully unregistered [4]. If the function fails, it returns a non-zero error code indicating the specific issue [4]. Context: This function is part of the Carbon Event Manager [1]. As Carbon is a legacy framework, it is generally recommended to use modern alternatives available in the Cocoa framework (such as NSEvent local/global monitors) for new macOS development [1][5]. The Carbon Event Manager documentation is archived and reflects APIs that have been available since early versions of Mac OS X [1][2].
Citations:
- 1: https://web.archive.org/web/20140806115511/developer.apple.com/legacy/library/documentation/Carbon/Reference/Carbon_Event_Manager_Ref/Reference/reference.html
- 2: https://leopard-adc.pepas.com/documentation/Carbon/Reference/Carbon_Event_Manager_Ref/Reference/reference.html
- 3: https://java-native-access.github.io/jna/5.18.1/javadoc/com/sun/jna/platform/mac/Carbon.html
- 4: https://github.com/soffes/HotKey/blob/main/Sources/HotKey/HotKeysController.swift
- 5: https://developer.apple.com/library/archive/documentation/Carbon/Conceptual/Carbon_Event_Manager/Tasks/CarbonEventsTasks.html
Keep the hotkey ref until unregister succeeds.
Deleting g.refs[id] before C.unregisterHotKey(ref) returns nil drops the only handle needed to retry cleanup if Carbon returns an error, while the hotkey may still remain registered.
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@v3/pkg/application/global_shortcut_darwin.go` around lines 123 - 130, The
unregister path in macosGlobalShortcuts.unregister removes the hotkey reference
before C.unregisterHotKey succeeds, which can lose the only handle needed for
retrying cleanup. Update unregister so g.refs[id] is only deleted after
C.unregisterHotKey(ref) returns success, and keep the existing ref available if
the Carbon call fails.
| func (g *x11GlobalShortcuts) run(fn func()) { | ||
| done := make(chan struct{}) | ||
| g.opCh <- func() { | ||
| fn() | ||
| close(done) | ||
| } | ||
| g.wake() | ||
| <-done | ||
| } |
There was a problem hiding this comment.
🩺 Stability & Availability | 🟠 Major | 🏗️ Heavy lift
Avoid deadlocking callers after the X event loop exits.
If the X connection is lost, eventLoop returns, but later run calls can still enqueue work and wait forever on done. Track a closed/error state and have register/unregister return that error instead of blocking.
Also applies to: 222-223
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@v3/pkg/application/global_shortcut_linux_x11.go` around lines 195 - 203, The
x11GlobalShortcuts flow can deadlock after the X event loop exits because run
still enqueues work on opCh and waits on done even when the connection is
already lost. Add a closed/error state to x11GlobalShortcuts that is set when
eventLoop returns, then update run to fail fast instead of blocking, and make
register and unregister return that stored error immediately when the loop is no
longer active.
| if regErr := InvokeSyncWithError(func() error { | ||
| return impl.register(shortcut.id, parsed) | ||
| }); regErr != nil { | ||
| // Roll back the reservation so the accelerator can be retried later. | ||
| m.mu.Lock() | ||
| delete(m.byName, name) | ||
| delete(m.byID, shortcut.id) | ||
| m.mu.Unlock() | ||
| return fmt.Errorf("failed to register global shortcut %q: %w", name, regErr) |
There was a problem hiding this comment.
🗄️ Data Integrity & Integration | 🟠 Major | ⚡ Quick win
Protect rollback from deleting a newer registration.
The failure path deletes byName[name] unconditionally. If the shortcut is unregistered/re-registered while the native registration is in flight, this can remove the newer binding from byName. Mirror the identity guard used in flushPending.
Proposed fix
m.mu.Lock()
- delete(m.byName, name)
- delete(m.byID, shortcut.id)
+ if current, ok := m.byName[name]; ok && current == shortcut {
+ delete(m.byName, name)
+ }
+ if current, ok := m.byID[shortcut.id]; ok && current == shortcut {
+ delete(m.byID, shortcut.id)
+ }
m.mu.Unlock()📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| if regErr := InvokeSyncWithError(func() error { | |
| return impl.register(shortcut.id, parsed) | |
| }); regErr != nil { | |
| // Roll back the reservation so the accelerator can be retried later. | |
| m.mu.Lock() | |
| delete(m.byName, name) | |
| delete(m.byID, shortcut.id) | |
| m.mu.Unlock() | |
| return fmt.Errorf("failed to register global shortcut %q: %w", name, regErr) | |
| if regErr := InvokeSyncWithError(func() error { | |
| return impl.register(shortcut.id, parsed) | |
| }); regErr != nil { | |
| // Roll back the reservation so the accelerator can be retried later. | |
| m.mu.Lock() | |
| if current, ok := m.byName[name]; ok && current == shortcut { | |
| delete(m.byName, name) | |
| } | |
| if current, ok := m.byID[shortcut.id]; ok && current == shortcut { | |
| delete(m.byID, shortcut.id) | |
| } | |
| m.mu.Unlock() | |
| return fmt.Errorf("failed to register global shortcut %q: %w", name, regErr) |
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@v3/pkg/application/global_shortcut_manager.go` around lines 137 - 145, The
rollback in global shortcut registration is deleting byName[name]
unconditionally, which can remove a newer binding if the shortcut was
unregistered and re-registered while impl.register was still in flight. Update
the failure path in global_shortcut_manager.go to mirror the identity check used
in flushPending, so the rollback only deletes the reservation when the current
entry still matches the same shortcut id/registration attempt. Keep the existing
byID cleanup consistent with that guard and leave newer registrations intact.
| delete(m.byName, name) | ||
| delete(m.byID, shortcut.id) | ||
| started := m.started | ||
| impl := m.getImpl() | ||
| m.mu.Unlock() | ||
|
|
||
| if !started { | ||
| // Never bound with the OS yet; just drop it from the pending list. | ||
| m.removePending(shortcut) | ||
| return nil | ||
| } | ||
| return InvokeSyncWithError(func() error { | ||
| return impl.unregister(shortcut.id) | ||
| }) |
There was a problem hiding this comment.
🗄️ Data Integrity & Integration | 🟠 Major | ⚡ Quick win
Preserve manager state when native unregister fails.
Unregister and UnregisterAll clear byName/byID before the OS release succeeds. If impl.unregister or impl.unregisterAll returns an error, the manager forgets a binding that may still be active, so IsRegistered lies and later cleanup cannot retry. Delay removal until success, or snapshot and restore on error.
Also applies to: 230-245
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@v3/pkg/application/global_shortcut_manager.go` around lines 199 - 212, The
unregister flow in GlobalShortcutManager is removing entries from byName and
byID before the native release succeeds, so if impl.unregister or
impl.unregisterAll fails the manager state becomes inconsistent. Update
Unregister and UnregisterAll to either defer deleting the shortcut from the
manager maps until the native call completes successfully, or capture the
removed entries and restore them on error. Keep the logic centered around the
Unregister, UnregisterAll, and getImpl paths so IsRegistered remains accurate
and failed cleanup can be retried.
| func (g *windowsGlobalShortcuts) unregister(id int) error { | ||
| if _, ok := g.ids[id]; !ok { | ||
| return nil | ||
| } | ||
| delete(g.ids, id) | ||
| hwnd, err := g.hwnd() | ||
| if err != nil { | ||
| return err | ||
| } | ||
| if !w32.UnregisterHotKey(hwnd, id) { | ||
| return fmt.Errorf("UnregisterHotKey failed for shortcut id %d", id) | ||
| } |
There was a problem hiding this comment.
🗄️ Data Integrity & Integration | 🟠 Major | ⚡ Quick win
Only drop g.ids[id] after UnregisterHotKey succeeds.
If hwnd() or UnregisterHotKey fails here, the hotkey can stay registered in Windows while the manager forgets it locally. That breaks retries and can leave UnregisterAll() unable to clean it up later.
Suggested fix
func (g *windowsGlobalShortcuts) unregister(id int) error {
if _, ok := g.ids[id]; !ok {
return nil
}
- delete(g.ids, id)
hwnd, err := g.hwnd()
if err != nil {
return err
}
if !w32.UnregisterHotKey(hwnd, id) {
return fmt.Errorf("UnregisterHotKey failed for shortcut id %d", id)
}
+ delete(g.ids, id)
return nil
}📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| func (g *windowsGlobalShortcuts) unregister(id int) error { | |
| if _, ok := g.ids[id]; !ok { | |
| return nil | |
| } | |
| delete(g.ids, id) | |
| hwnd, err := g.hwnd() | |
| if err != nil { | |
| return err | |
| } | |
| if !w32.UnregisterHotKey(hwnd, id) { | |
| return fmt.Errorf("UnregisterHotKey failed for shortcut id %d", id) | |
| } | |
| func (g *windowsGlobalShortcuts) unregister(id int) error { | |
| if _, ok := g.ids[id]; !ok { | |
| return nil | |
| } | |
| hwnd, err := g.hwnd() | |
| if err != nil { | |
| return err | |
| } | |
| if !w32.UnregisterHotKey(hwnd, id) { | |
| return fmt.Errorf("UnregisterHotKey failed for shortcut id %d", id) | |
| } | |
| delete(g.ids, id) | |
| return nil | |
| } |
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@v3/pkg/application/global_shortcut_windows.go` around lines 78 - 89, The
unregister path in windowsGlobalShortcuts.unregister removes the shortcut from
g.ids before the Windows unregister call, which can desync local state if hwnd()
or w32.UnregisterHotKey fails. Move the delete(g.ids, id) so it only happens
after UnregisterHotKey succeeds, while keeping the existing early returns for
missing ids and hwnd() errors. This keeps the shortcut tracked locally until the
system hotkey is actually released and preserves retry/cleanup behavior in
UnregisterAll.
| func RegisterHotKey(hwnd HWND, id int, fsModifiers uint, vk uint) bool { | ||
| ret, _, _ := procRegisterHotKey.Call( | ||
| uintptr(hwnd), | ||
| uintptr(id), | ||
| uintptr(fsModifiers), | ||
| uintptr(vk)) | ||
| return ret != 0 |
There was a problem hiding this comment.
🎯 Functional Correctness | 🟠 Major | ⚡ Quick win
🧩 Analysis chain
🌐 Web query:
For the Win32 RegisterHotKey and UnregisterHotKey APIs, what errors can GetLastError report on failure, and is ERROR_HOTKEY_ALREADY_REGISTERED only one of several possible RegisterHotKey failure reasons?
💡 Result:
For the Win32 RegisterHotKey and UnregisterHotKey APIs, GetLastError provides extended error information when the functions return zero (indicating failure) [1][2]. Yes, ERROR_HOTKEY_ALREADY_REGISTERED is only one of several possible failure reasons for RegisterHotKey [3]. While a common cause for failure is that the specified hotkey combination is already in use by another application or the system [1][3], RegisterHotKey can fail for other reasons as well [4]. For example, providing invalid parameters can result in errors such as ERROR_INVALID_FLAGS (0x3EC) [4]. Additionally, the documentation explicitly notes that the function fails if you attempt to associate a hotkey with a window created by a different thread [1][5]. Because RegisterHotKey and UnregisterHotKey interact with system-wide resources and thread-specific window handles, they can encounter a variety of standard Windows system error codes depending on the nature of the invalid input or state conflict [1][6][2]. Developers should always check GetLastError immediately after a function returns FALSE to identify the specific cause of the failure [3][7].
Citations:
- 1: https://learn.microsoft.com/en-us/windows/win32/api/winuser/nf-winuser-registerhotkey
- 2: https://learn.microsoft.com/en-us/windows/win32/api/winuser/nf-winuser-unregisterhotkey
- 3: https://stackoverflow.com/questions/77223888/error-in-powershell-script-intercepting-keyboard-shortcut
- 4: https://stackoverflow.com/questions/75983759/registerhotkey-fails-and-getlastwin32error-returns-error-invalid-flags
- 5: https://github.com/MicrosoftDocs/sdk-api/blob/docs/sdk-api-src/content/winuser/nf-winuser-registerhotkey.md
- 6: https://learn.microsoft.com/en-us/windows/win32/debug/system-error-codes--0-499-
- 7: https://stackoverflow.com/questions/34054785/is-there-a-way-to-register-hotkey-on-windows-without-conflict
🏁 Script executed:
#!/bin/bash
set -euo pipefail
git ls-files 'v3/pkg/w32/user32.go' 'global_shortcut_windows.go' | sed 's#^`#FILE` #'
echo
for f in v3/pkg/w32/user32.go global_shortcut_windows.go; do
if [ -f "$f" ]; then
echo "===== $f ====="
wc -l "$f"
echo "--- outline ---"
ast-grep outline "$f" --view expanded || true
echo "--- relevant lines ---"
rg -n -A6 -B6 'RegisterHotKey|UnregisterHotKey|duplicate|hotkey|shortcut' "$f" || true
echo
fi
doneRepository: wailsapp/wails
Length of output: 25609
🏁 Script executed:
#!/bin/bash
set -euo pipefail
fd -a 'global_shortcut_windows.go|shortcut' . || true
echo
rg -n -A8 -B8 'RegisterHotKey|UnregisterHotKey|duplicate|already registered|hotkey' . -g '!**/vendor/**' -g '!**/node_modules/**' || trueRepository: wailsapp/wails
Length of output: 50373
🏁 Script executed:
#!/bin/bash
set -euo pipefail
echo "===== v3/pkg/w32/user32.go (lines 552-574) ====="
sed -n '552,574p' v3/pkg/w32/user32.go
echo
echo "===== v3/pkg/application/global_shortcut_windows.go ====="
wc -l v3/pkg/application/global_shortcut_windows.go
echo "--- outline ---"
ast-grep outline v3/pkg/application/global_shortcut_windows.go --view expanded || true
echo "--- relevant lines ---"
rg -n -A12 -B12 'RegisterHotKey|UnregisterHotKey|hotkey|duplicate|already registered|shortcut' v3/pkg/application/global_shortcut_windows.go || trueRepository: wailsapp/wails
Length of output: 4901
Surface the Win32 error from hotkey wrappers
RegisterHotKey and UnregisterHotKey currently drop GetLastError and return only bool, so the caller can’t tell ERROR_HOTKEY_ALREADY_REGISTERED apart from other failures. global_shortcut_windows.go then reports every RegisterHotKey failure as “already registered,” which mislabels invalid-input and other runtime errors. Return the syscall error/errno here so the caller can handle duplicate vs. real failure paths separately.
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@v3/pkg/w32/user32.go` around lines 557 - 563, `RegisterHotKey` and
`UnregisterHotKey` are swallowing the Win32 failure detail by returning only a
bool, which prevents callers like `global_shortcut_windows.go` from
distinguishing `ERROR_HOTKEY_ALREADY_REGISTERED` from other errors. Update the
hotkey wrapper functions in `user32.go` to return the syscall error/errno
alongside success, using the existing `procRegisterHotKey` and
`procUnregisterHotKey` calls, and then adjust the caller to branch on the
specific error instead of treating every failure as already-registered.
Description
Adds global shortcuts to Wails v3: system-wide keyboard hotkeys that fire even when the application is not focused. Ideal for show/hide hotkeys, quick-capture tools, and media controls.
A new manager is exposed as
app.GlobalShortcut:API:
Register,Unregister,UnregisterAll,IsRegistered,GetAll. It reuses the existing accelerator syntax and supports registration beforeapp.Run(bindings are flushed at startup). Shortcuts are released automatically on shutdown.Implementation
Clean-room, native per platform, no new third-party dependencies:
RegisterEventHotKey(no Accessibility permission needed)RegisterHotKey+WM_HOTKEYXGrabKey(single-threaded Xlib loop with self-pipe wakeup)org.freedesktop.portal.GlobalShortcuts(via the existing godbus dep)What happens when the same shortcut is registered twice
Registerreturns an error and preserves the original binding ("error and preserve"), uniform on all platforms.Testing
GetAll, dispatch).xdotool, self-skips when headless).Docs & example
Hide()interacting withApplicationShouldTerminateAfterLastWindowClosed).v3/examples/global-shortcuts/with a live fire-log UI.Notes for reviewers
IsRegistered/GetAllreport what was requested, not necessarily what the compositor bound.Summary by CodeRabbit
New Features
app.GlobalShortcut, with support across macOS, Windows, X11, and Wayland.Documentation
Tests