Files
Reims-Go/internal/qmp/keys.go
T
Nwflower 65553e48f7 Merge remote-tracking branch 'pr-review/109' into HEAD
# Conflicts:
#	internal/app/macos_lifecycle_native.go
2026-12-04 02:53:29 -07:00

363 lines
10 KiB
Go

package qmp
import (
"context"
"errors"
"fmt"
"hash/fnv"
"math"
"os"
"path/filepath"
"runtime"
"strings"
"time"
)
// Typing text into a guest as key presses ("paste as keystrokes"). The guest
// sees a USB keyboard (`usb-kbd` in `reims-ctl command`, upstream 3731afd), so
// what each key produces depends on the guest's input source: the mapping
// below is the US / "ABC" layout macOS Recovery and a new install start with.
// Stroke is one key, pressed with or without Shift.
type Stroke struct {
Key string // QKeyCode name, as QMP's input-send-event takes it
Shift bool
}
// MaxTypedRunes caps one job: at ~30 ms a key, 4000 keys take two minutes.
const MaxTypedRunes = 4000
// UntypeableError names the first character a US keyboard can't type.
type UntypeableError struct {
Rune rune
Pos int // 1-based character position
}
func (e *UntypeableError) Error() string {
return fmt.Sprintf("character %q (U+%04X) at position %d can't be typed on a US keyboard", e.Rune, e.Rune, e.Pos)
}
var plainKeys = map[rune]string{
' ': "spc", '\n': "ret", '\t': "tab",
'-': "minus", '=': "equal", '[': "bracket_left", ']': "bracket_right",
'\\': "backslash", ';': "semicolon", '\'': "apostrophe", '`': "grave_accent",
',': "comma", '.': "dot", '/': "slash",
}
var shiftedKeys = map[rune]string{
'!': "1", '@': "2", '#': "3", '$': "4", '%': "5", '^': "6", '&': "7", '*': "8", '(': "9", ')': "0",
'_': "minus", '+': "equal", '{': "bracket_left", '}': "bracket_right", '|': "backslash",
':': "semicolon", '"': "apostrophe", '~': "grave_accent", '<': "comma", '>': "dot", '?': "slash",
}
// StrokeFor maps one character to a key on a US layout.
func StrokeFor(r rune) (Stroke, bool) {
switch {
case r >= 'a' && r <= 'z', r >= '0' && r <= '9':
return Stroke{Key: string(r)}, true
case r >= 'A' && r <= 'Z':
return Stroke{Key: string(r - 'A' + 'a'), Shift: true}, true
}
if k, ok := plainKeys[r]; ok {
return Stroke{Key: k}, true
}
if k, ok := shiftedKeys[r]; ok {
return Stroke{Key: k, Shift: true}, true
}
return Stroke{}, false
}
// Strokes turns text into key presses. It refuses the whole text if any
// character can't be typed, so a command is never typed half-way. Windows line
// ends become one Return.
func Strokes(text string) ([]Stroke, error) {
text = strings.ReplaceAll(text, "\r\n", "\n")
text = strings.ReplaceAll(text, "\r", "\n")
out := make([]Stroke, 0, len(text))
pos := 0
for _, r := range text {
pos++
if pos > MaxTypedRunes {
return nil, fmt.Errorf("text is longer than %d characters", MaxTypedRunes)
}
s, ok := StrokeFor(r)
if !ok {
return nil, &UntypeableError{Rune: r, Pos: pos}
}
out = append(out, s)
}
return out, nil
}
// Executor is the part of a QMP session typing needs.
type Executor interface {
Execute(command string, args any) error
}
func keyEvent(key string, down bool) map[string]any {
return map[string]any{
"type": "key",
"data": map[string]any{
"down": down,
"key": map[string]any{"type": "qcode", "data": key},
},
}
}
func sendKeys(q Executor, down bool, keys ...string) error {
events := make([]map[string]any, 0, len(keys))
for _, k := range keys {
events = append(events, keyEvent(k, down))
}
return q.Execute("input-send-event", map[string]any{"events": events})
}
// SendKey sends one QKeyCode transition. Callers pair a press with a release.
func SendKey(q Executor, key string, down bool) error {
if q == nil {
return errors.New("QMP session is unavailable")
}
return sendKeys(q, down, key)
}
// ReleaseInputs clears held keys and pointer buttons in one QMP input report.
func ReleaseInputs(q Executor, keys, buttons []string) error {
if q == nil {
return errors.New("QMP session is unavailable")
}
if len(keys)+len(buttons) == 0 {
return nil
}
events := make([]map[string]any, 0, len(keys)+len(buttons))
for _, key := range keys {
events = append(events, keyEvent(key, false))
}
for _, button := range buttons {
events = append(events, mouseButtonEvent(button, false))
}
return q.Execute("input-send-event", map[string]any{"events": events})
}
// TypeStrokes presses and releases each key in turn, holding it for hold and
// waiting gap before the next, so the guest's USB keyboard queue never fills.
// On any error or cancel it releases Shift so no modifier is left held down.
func TypeStrokes(ctx context.Context, q Executor, strokes []Stroke, hold, gap time.Duration, progress func(done int)) (err error) {
shiftDown := false
defer func() {
if shiftDown {
_ = sendKeys(q, false, "shift")
}
}()
for i, s := range strokes {
if err := ctx.Err(); err != nil {
return err
}
if s.Shift != shiftDown {
if err := sendKeys(q, s.Shift, "shift"); err != nil {
return err
}
shiftDown = s.Shift
}
if err := sendKeys(q, true, s.Key); err != nil {
return err
}
sleep(ctx, hold)
if err := sendKeys(q, false, s.Key); err != nil {
return err
}
sleep(ctx, gap)
if progress != nil {
progress(i + 1)
}
}
return nil
}
// SocketPath is the QMP socket reims-ctl gives every VM it starts: `-qmp
// unix:<dir>\qmp.sock,server=on,wait=off` (`reims-ctl command`, upstream
// 3731afd). It exists on every host, unlike the Win10 cold-reboot monitor.
func SocketPath(vmDir string) string {
return filepath.Join(vmDir, "qmp.sock")
}
// SocketPathForVM mirrors reims-ctl's socket placement for long VM paths.
func SocketPathForVM(vmDir, vmName, tmpDir string) string {
own := SocketPath(vmDir)
if len(own) < 100 || vmName == "" {
return own
}
if tmpDir == "" {
tmpDir = os.TempDir()
}
const maxSocketPath = 103
runtimeDir := filepath.Join(tmpDir, "reims-ctl")
if named := filepath.Join(runtimeDir, vmName+".qmp"); len(named) <= maxSocketPath {
return named
}
hash := fnv.New64a()
_, _ = hash.Write([]byte(vmName))
shortName := fmt.Sprintf("%016x.qmp", hash.Sum64())
hashed := filepath.Join(runtimeDir, shortName)
if len(hashed) > maxSocketPath && runtime.GOOS != "windows" {
return filepath.Join("/tmp/reims-ctl", shortName)
}
return hashed
}
// PressCombo holds modifiers, presses and releases key, then releases modifiers
// in reverse order. Any error or cancellation releases every key still down.
func PressCombo(ctx context.Context, q Executor, hold time.Duration, key string, modifiers ...string) error {
var downMods []string
keyDown := false
defer func() {
if keyDown {
_ = sendKeys(q, false, key)
}
for i := len(downMods) - 1; i >= 0; i-- {
_ = sendKeys(q, false, downMods[i])
}
}()
for _, m := range modifiers {
if err := ctx.Err(); err != nil {
return err
}
if err := sendKeys(q, true, m); err != nil {
return err
}
downMods = append(downMods, m)
sleep(ctx, hold)
}
if err := ctx.Err(); err != nil {
return err
}
if err := sendKeys(q, true, key); err != nil {
return err
}
keyDown = true
sleep(ctx, hold)
if err := sendKeys(q, false, key); err != nil {
return err
}
keyDown = false
sleep(ctx, hold)
for i := len(downMods) - 1; i >= 0; i-- {
m := downMods[i]
downMods = downMods[:i]
if err := sendKeys(q, false, m); err != nil {
return err
}
}
return nil
}
// DefaultPasteCombo is the paste shortcut of a macOS guest.
const DefaultPasteCombo = "meta_l+v"
// ParseKeyCombo splits a combination such as "ctrl+shift+v" into its final key
// and the modifiers held down for it, all as QKeyCode names. An empty combo or
// an empty part is an error.
func ParseKeyCombo(combo string) (key string, modifiers []string, err error) {
combo = strings.ToLower(strings.TrimSpace(combo))
if combo == "" {
return "", nil, fmt.Errorf("empty key combination")
}
parts := strings.Split(combo, "+")
for _, p := range parts {
p = strings.TrimSpace(p)
if p == "" {
return "", nil, fmt.Errorf("key combination %q has an empty key", combo)
}
for _, r := range p {
if !(r >= 'a' && r <= 'z' || r >= '0' && r <= '9' || r == '_') {
return "", nil, fmt.Errorf("key combination %q has an invalid key name %q", combo, p)
}
}
}
key = strings.TrimSpace(parts[len(parts)-1])
for _, p := range parts[:len(parts)-1] {
modifiers = append(modifiers, strings.TrimSpace(p))
}
return key, modifiers, nil
}
func absEvent(axis string, value int) map[string]any {
return map[string]any{"type": "abs", "data": map[string]any{"axis": axis, "value": value}}
}
func clampAbsCoord(norm float64) int {
switch {
case math.IsNaN(norm), math.IsInf(norm, 0), norm <= 0:
return 0
case norm >= 1:
return 32767
default:
return int(math.Round(norm * 32767))
}
}
// ClickAndPaste optionally activates the window before clicking the paste target.
func ClickAndPaste(ctx context.Context, q Executor, normX, normY float64, activateClick bool, activateGap, clickHold, focusWait, keyHold time.Duration, commandKey string) error {
if err := ctx.Err(); err != nil {
return err
}
if err := q.Execute("input-send-event", map[string]any{"events": []map[string]any{
absEvent("x", clampAbsCoord(normX)), absEvent("y", clampAbsCoord(normY)),
}}); err != nil {
return err
}
sleep(ctx, 15*time.Millisecond)
if activateClick {
if err := leftClick(ctx, q, clickHold); err != nil {
return err
}
sleep(ctx, activateGap)
}
if err := leftClick(ctx, q, clickHold); err != nil {
return err
}
sleep(ctx, focusWait)
if commandKey == "" {
commandKey = "meta_l"
}
return PressCombo(ctx, q, keyHold, "v", commandKey)
}
func leftClick(ctx context.Context, q Executor, clickHold time.Duration) error {
send := func(events ...map[string]any) error {
return q.Execute("input-send-event", map[string]any{"events": events})
}
if err := ctx.Err(); err != nil {
return err
}
if err := send(mouseButtonEvent("left", true)); err != nil {
return err
}
btnDown := true
defer func() {
if btnDown {
_ = send(mouseButtonEvent("left", false))
}
}()
sleep(ctx, clickHold)
if err := ctx.Err(); err != nil {
return err
}
if err := send(mouseButtonEvent("left", false)); err != nil {
return err
}
btnDown = false
return nil
}
func sleep(ctx context.Context, d time.Duration) {
if d <= 0 {
return
}
t := time.NewTimer(d)
defer t.Stop()
select {
case <-ctx.Done():
case <-t.C:
}
}