Files
magpie/internal/gui/panelkey.go
T
yetone 3bebc38393 gui: a key combination opens the quick panel from any app (ben hanks)
ben hanks on Discord asked for a global shortcut that opens the menu bar
or tray panel. Settings › General has a new row, Quick panel shortcut,
with none set by default. Clicking its field records the next combination:
a letter, a digit, Space or F1–F20 with Ctrl, Alt/Option or Cmd/Win, or an
F key on its own. Esc or a click elsewhere stops recording, and the cross
clears the shortcut. It is shown the system's way (⇧⌘K on a Mac,
Ctrl+Alt+K elsewhere).

POST /api/settings/panel-shortcut checks the combination, has the running
app bind it through Wails' GlobalShortcut (Carbon hot keys on the Mac,
RegisterHotKey on Windows, XGrabKey on X11), and saves it only once it is
bound. One the system refuses is not saved, the old one stays bound, and
the status line says why. A pressed shortcut toggles the panel as a tray
click does. The shortcut belongs to each computer (KeepOwn), the Settings
page's own save leaves it alone, and the old Mac process lets go of it as
it hands over. On Wayland no app may grab keys, so the field is turned off
and the row names the command (`magpie panel`) to bind in the desktop's
own keyboard settings.

Every string is in en, zh, zh-TW, ja and de. No size budget was raised:
app.js is 1,315,252 of its 1,315,316 after older comments were cut.

Run at this head (rebased on origin/main 1534474c8):
- mote (macOS 27): gofmt; go vet for darwin, GOOS=linux -tags nogui and
  GOOS=windows on internal/gui and internal/settings; go build ./...:
  ok. go test: settings ok; gui ok except TestMainWindowCorners/
  macOS_26_SDK, red on macOS 27 already (#3949).
- Windows (xiaomi-gpu, win-run): go test internal/gui internal/settings.
  settings ok; gui has 5 reds, the same 5 on origin/main d19afb4c9
  (TestGatewayHeldByAContainer #2107/#3649; TestLodyImportHandoff,
  TestImportStatusUnreadableIsUnknown, TestAionUiImportRow and
  TestUpdateThatWontStart #4115).
- Linux (WSL magpie-desktop, wsl-run -tags nogui): internal/gui (the
  Wayland branch included) and internal/settings: ok.
- GUI: panel-shortcut.test.cjs (new) in Chromium and WebKit, in all 5
  languages, faking both a Mac and Windows: ok. Whole suite (make test-ui)
  on mote: unfinished at the push. Three other sessions' suites were on
  the same box (load 130 to 250), and after 1605 tests it was still in
  the "c" files. Its reds so far are agent-panel-name-width and
  connect-snippet-shell and context-map (each on #4304), and allow-ips
  zh, which is red alone on origin/main too (#4357).

Broken by hand, each red:
- leaving the shortcut out of the general Settings save:
  TestPanelShortcutSetting "the Settings page's save changed the
  shortcut";
- dropping KeepOwn's line: "a synced setup took this computer's shortcut";
- dropping the recorder's stopImmediatePropagation: panel-shortcut.test.cjs
  "a key typing needs was sent, or a window key ran".
TestSettingsSaveKeepsWhatItDoesNotSend now sets the new field.

Real build on mote: a dev build in a sandbox HOME bound a saved
Ctrl+Option+Shift+Cmd+F18 as it started, and a POST of F16 saved it and
bound it.

Not tried:
- a real key press on any system: mote gives ssh no Accessibility access
  to post events, and Windows' ssh session has no desktop;
- the Windows and X11 refusal of a combination another app holds (only
  the fake). On the Mac, Carbon takes a combination a second app
  registered too, so both apps get it and magpie can't say so. This was
  checked on mote with a helper holding F17;
- Wails' GlobalShortcuts portal on Wayland, which isn't used;
- a Linux GUI-tag build (WSL has no gtk4/webkitgtk-6.0).
2026-10-30 12:06:33 +08:00

147 lines
4.8 KiB
Go
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
package gui
import (
"errors"
"os"
"runtime"
"slices"
"strings"
"sync/atomic"
)
// The quick panel's global shortcut (Settings › General): a key
// combination the user records, which opens the tray's panel from any app
// (ben hanks on Discord). There is none by default, so nothing magpie
// takes clashes with another app's until the user picks it.
// onPanelShortcut binds the shortcut s ("" for none) in the running app in
// place of the one before, and says why it couldn't; the app sets it
// (app.go). Off the app (magpie web, tests) it is nil and the choice is
// only saved.
var onPanelShortcut func(s string) error
// panelKeyTaken is the shortcut the app couldn't bind as it started,
// another app holding it; "" once one is bound or none is set.
var panelKeyTaken atomic.Value // string
// errPanelKeyTaken is what the page is told when the system refuses the
// combination, as Windows and X11 do for one another app holds (the Mac's
// Carbon hot keys take it twice, so there it isn't said).
var errPanelKeyTaken = errors.New("Another app already uses this shortcut")
// panelKeysJSON is what Settings' row needs beside the saved shortcut.
type panelKeysJSON struct {
// Can is whether this system lets magpie take a global shortcut at all
Can bool `json:"can"`
// Command opens the panel from a shortcut the desktop binds itself,
// where magpie can't (Wayland)
Command string `json:"command,omitempty"`
// Taken is the saved shortcut the system refused as magpie started
Taken string `json:"taken,omitempty"`
}
func panelKeysState() panelKeysJSON {
st := panelKeysJSON{Can: !waylandSession(runtime.GOOS, os.Getenv)}
if !st.Can {
exe, err := os.Executable()
if err != nil || exe == "" {
exe = "magpie"
}
st.Command = shellWord(exe) + " panel"
}
st.Taken, _ = panelKeyTaken.Load().(string)
return st
}
// waylandSession says the desktop is a Wayland session, where no app may
// grab a key for itself: only the desktop's own settings (or its
// GlobalShortcuts portal, which leaves the keys to the compositor and on
// Hyprland binds none until the user writes one) can. It reads the session
// as Wails does in choosing its backend.
func waylandSession(goos string, getenv func(string) string) bool {
if goos != "linux" {
return false
}
switch strings.ToLower(getenv("XDG_SESSION_TYPE")) {
case "wayland":
return true
case "x11":
return false
}
return getenv("WAYLAND_DISPLAY") != ""
}
// shellWord quotes a path with a space or a quote for a POSIX shell.
func shellWord(s string) string {
if !strings.ContainsAny(s, " '\"\\$`!&;()|<>*?[]#~") {
return s
}
return "'" + strings.ReplaceAll(s, "'", `'\''`) + "'"
}
// panelShortcut checks a shortcut the page recorded and writes it as
// Wails' accelerator, its modifiers in the Mac's order (Ctrl, Option,
// Shift, Cmd) and the key last: "Ctrl+Option+K", "Cmd+Shift+Space". The
// Command key is "Cmd" on the Mac and the Windows or Super key "Super" off
// it, as Wails reads them (its "Cmd" off the Mac is Ctrl). A key is a
// letter, a digit, Space or F1–F20, the keys every system's hot key table
// has; one with no modifier but Shift is refused, since it would take a
// key from typing everywhere, but an F key may stand alone. "" is none.
func panelShortcut(s, goos string) (string, error) {
s = strings.TrimSpace(s)
if s == "" {
return "", nil
}
var ctrl, alt, shift, meta bool
parts := strings.Split(s, "+")
key := strings.ToLower(strings.TrimSpace(parts[len(parts)-1]))
for _, part := range parts[:len(parts)-1] {
switch strings.ToLower(strings.TrimSpace(part)) {
case "ctrl", "control":
ctrl = true
case "alt", "option":
alt = true
case "shift":
shift = true
case "cmd", "command", "super", "win", "meta":
meta = true
default:
return "", errNotShortcut
}
}
fkey := len(key) >= 2 && key[0] == 'f' && slices.Contains(fKeys, key[1:])
switch {
case len(key) == 1 && (key[0] >= 'a' && key[0] <= 'z' || key[0] >= '0' && key[0] <= '9'):
key = strings.ToUpper(key)
case key == "space":
key = "Space"
case fkey:
key = strings.ToUpper(key)
default:
return "", errNotShortcut
}
if !ctrl && !alt && !meta && !fkey {
return "", errNotShortcut
}
var out []string
if ctrl {
out = append(out, "Ctrl")
}
if alt {
out = append(out, map[bool]string{true: "Option", false: "Alt"}[goos == "darwin"])
}
if shift {
out = append(out, "Shift")
}
if meta {
out = append(out, map[bool]string{true: "Cmd", false: "Super"}[goos == "darwin"])
}
return strings.Join(append(out, key), "+"), nil
}
// errNotShortcut is what the page is told of a combination it shouldn't
// have sent: the page checks each press itself first.
var errNotShortcut = errors.New("Not a shortcut magpie can use")
var fKeys = []string{"1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15", "16", "17", "18", "19", "20"}