Skip to content

feat(v3): global (system-wide) keyboard shortcuts - #5686

Merged
leaanthony merged 2 commits into
masterfrom
worktree-global-shortcuts
Jun 28, 2026
Merged

leaanthony merged 2 commits into
masterfrom
worktree-global-shortcuts

Conversation

@taliesin-ai

@taliesin-ai taliesin-ai commented Jun 28, 2026 •

Copy link
Copy Markdown
Collaborator

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:

app.GlobalShortcut.Register("CmdOrCtrl+Shift+G", func() {
    window.Show()
    window.Focus()
})

API: Register, Unregister, UnregisterAll, IsRegistered, GetAll. It reuses the existing accelerator syntax and supports registration before app.Run (bindings are flushed at startup). Shortcuts are released automatically on shutdown.

Implementation

Clean-room, native per platform, no new third-party dependencies:

Platform Mechanism
macOS Carbon RegisterEventHotKey (no Accessibility permission needed)
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 (via the existing godbus dep)

What happens when the same shortcut is registered twice

  • Same app, twice: resolved by Wails — the second Register returns an error and preserves the original binding ("error and preserve"), uniform on all platforms.
  • Another app owns it: decided by the OS — Windows and X11 reject; macOS allows (it permits multiple owners of a hot key); Wayland's compositor (and ultimately the user) arbitrates.

Testing

  • Unit tests (register/query, duplicate rejection, invalid input, unregister, sorted GetAll, dispatch).
  • X11 integration test (driven by xdotool, self-skips when headless).
  • Runtime-verified: macOS (Carbon hot key firing, including hide/resummon round-trip), Windows (full app, interactive window station), Linux X11 (Xvfb + xdotool). The Wayland portal backend compiles on GTK3/GTK4 but is not runtime-tested (no live compositor available); documented as such.

Docs & example

  • New docs page: Features → Keyboard → Global Shortcuts (includes the same-shortcut behavior table and per-platform notes, plus a macOS note about Hide() interacting with ApplicationShouldTerminateAfterLastWindowClosed).
  • Interactive manual-test example at v3/examples/global-shortcuts/ with a live fire-log UI.
  • Changelog entry added.

Notes for reviewers

  • macOS hot keys are bound to physical key positions (ANSI/QWERTY assumed for non-QWERTY layouts).
  • On Wayland the accelerator is a preferred trigger; IsRegistered/GetAll report what was requested, not necessarily what the compositor bound.

Summary by CodeRabbit

  • New Features

    • Added system-wide global keyboard shortcuts via app.GlobalShortcut, with support across macOS, Windows, X11, and Wayland.
    • Automatically registers bindings at startup and unregisters everything on app cleanup.
    • Included a working demo showing show/hide/ping behavior plus duplicate-shortcut handling.
  • Documentation

    • Added a new global shortcuts guide covering registration, listing, removal, accelerator formats, and platform-specific notes.
  • Tests

    • Added unit tests and a Linux/X11 end-to-end test for registration, duplicate rejection, dispatch, and unregistration.

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.
@coderabbitai

coderabbitai Bot commented Jun 28, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

Caution

Review failed

The pull request is closed.

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: b9d33e21-b508-4936-9bca-efcaaa588519

📥 Commits

Reviewing files that changed from the base of the PR and between d20506a and d4b7a5c.

📒 Files selected for processing (2)
  • v3/UNRELEASED_CHANGELOG.md
  • v3/pkg/application/application.go

Walkthrough

Adds 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.

Changes

Global Shortcuts Feature

Layer / File(s) Summary
GlobalShortcutManager core and App wiring
v3/pkg/application/global_shortcut_manager.go, v3/pkg/application/global_shortcut_unsupported.go, v3/pkg/application/application.go
Defines GlobalShortcutManager with registration, query, dispatch, pending startup registration, and unsupported-platform behavior. Adds the manager to App, initializes it in App.init(), flushes pending registrations in App.Run(), and unregisters shortcuts during cleanup.
GlobalShortcutManager unit tests
v3/pkg/application/global_shortcut_test.go
Covers register/query, duplicate rejection, invalid input handling, unregister behavior, sorted listing, and asynchronous dispatch using a pre-start manager.
Windows w32 bindings
v3/pkg/w32/constants.go, v3/pkg/w32/user32.go
Adds hotkey modifier constants, RegisterHotKey/UnregisterHotKey lazy proc bindings, and exported wrapper functions.
Windows global shortcut backend and WM_HOTKEY dispatch
v3/pkg/application/global_shortcut_windows.go, v3/pkg/application/application_windows.go
Implements Windows hotkey registration and unregistration against the app window, maps accelerator keys and modifiers to Win32 values, and dispatches WM_HOTKEY messages to the manager.
macOS Carbon global shortcut backend
v3/pkg/application/global_shortcut_darwin.go
Implements macOS hotkeys with Carbon, including the event handler bridge, modifier translation, key-code mapping, registration, unregistration, and callback dispatch.
Linux session selector
v3/pkg/application/global_shortcut_linux.go
Selects the Linux backend based on Wayland or X11 session environment variables.
Linux X11 global shortcut backend
v3/pkg/application/global_shortcut_linux_x11.go
Implements X11 grabbing, event-loop dispatch, wake handling, modifier masking, and single/bulk unregistration.
Linux X11 end-to-end integration test
v3/pkg/application/global_shortcut_linux_x11_test.go
Verifies X11 registration and unregistration by synthesizing key presses with xdotool.
Linux Wayland XDG portal backend
v3/pkg/application/global_shortcut_linux_portal.go
Implements portal-based shortcut binding, session setup, request tracking, activation handling, rebind debouncing, and trigger translation.
Example app and documentation
v3/examples/global-shortcuts/..., docs/src/content/docs/features/keyboard/global-shortcuts.mdx, v3/UNRELEASED_CHANGELOG.md
Adds the demo app, frontend, README, docs page, and changelog note for global shortcuts.

Estimated code review effort

🎯 5 (Critical) | ⏱️ ~120 minutes

Suggested labels

Enhancement, Documentation, runtime, Implemented in v3, Windows, MacOS, Linux, v3-alpha, go, size:XXL

Suggested reviewers

  • leaanthony

Possibly related PRs

  • wailsapp/wails#4359: Both PRs modify v3/pkg/application/application.go to add manager wiring into the app lifecycle.

Poem

🐇 I hopped through keys from screen to screen,
With Carbon, Win32, and portals seen.
X11 hummed, the rabbit grinned,
One shortcut bound, and all began.
Tap tap — the window leaps to life,
A bunny’s boon for app and strife.

🚥 Pre-merge checks | ✅ 3 | ❌ 2

❌ Failed checks (2 warnings)

Check name Status Explanation Resolution
Description check ⚠️ Warning The description covers the feature, implementation, testing, docs, and examples, but it omits required template items like Fixes #, change type, and test checklist. Add the issue reference, select the change type, fill in the testing and checklist sections, and include wails doctor/environment details.
Docstring Coverage ⚠️ Warning Docstring coverage is 43.48% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (3 passed)
Check name Status Explanation
Title check ✅ Passed The title is concise and accurately summarizes the main change: adding global system-wide keyboard shortcuts.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch worktree-global-shortcuts

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.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@leaanthony
leaanthony enabled auto-merge (squash) June 28, 2026 13:08

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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

📥 Commits

Reviewing files that changed from the base of the PR and between 4a31edc and d20506a.

📒 Files selected for processing (18)
  • docs/src/content/docs/features/keyboard/global-shortcuts.mdx
  • v3/UNRELEASED_CHANGELOG.md
  • v3/examples/global-shortcuts/README.md
  • v3/examples/global-shortcuts/assets/index.html
  • v3/examples/global-shortcuts/main.go
  • v3/pkg/application/application.go
  • v3/pkg/application/application_windows.go
  • v3/pkg/application/global_shortcut_darwin.go
  • v3/pkg/application/global_shortcut_linux.go
  • v3/pkg/application/global_shortcut_linux_portal.go
  • v3/pkg/application/global_shortcut_linux_x11.go
  • v3/pkg/application/global_shortcut_linux_x11_test.go
  • v3/pkg/application/global_shortcut_manager.go
  • v3/pkg/application/global_shortcut_test.go
  • v3/pkg/application/global_shortcut_unsupported.go
  • v3/pkg/application/global_shortcut_windows.go
  • v3/pkg/w32/constants.go
  • v3/pkg/w32/user32.go

Comment on lines +67 to +80
```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()

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🎯 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.

Suggested change
```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.

Comment on lines +88 to +96
// 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,
})

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🎯 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.

Comment on lines +90 to +97
go func() {
time.Sleep(500 * time.Millisecond)
app.Event.Emit("shortcuts:registered", map[string]string{
"show": showShortcut,
"hide": hideShortcut,
"ping": pingShortcut,
})
}()

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🩺 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.

Comment on lines +28 to +48
// 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;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🩺 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:


🏁 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 -B3

Repository: 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.

Comment on lines +123 to +130
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))

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🩺 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:


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.

Comment on lines +195 to +203
func (g *x11GlobalShortcuts) run(fn func()) {
done := make(chan struct{})
g.opCh <- func() {
fn()
close(done)
}
g.wake()
<-done
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🩺 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.

Comment on lines +137 to +145
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)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🗄️ 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.

Suggested change
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.

Comment on lines +199 to +212
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)
})

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🗄️ 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.

Comment on lines +78 to +89
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)
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🗄️ 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.

Suggested change
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.

Comment thread v3/pkg/w32/user32.go
Comment on lines +557 to +563
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

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🎯 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:


🏁 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
done

Repository: 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/**' || true

Repository: 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 || true

Repository: 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.

@leaanthony
leaanthony merged commit ee0fdbf into master Jun 28, 2026
43 of 44 checks passed
@leaanthony
leaanthony deleted the worktree-global-shortcuts branch June 28, 2026 13:10
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants