* fix(installer): use 8 KiB HFS+ catalog B-tree nodes for REIMSTOOLS image * feat(guesttools): support Windows-to-macOS window drag-and-drop (Agent v13) --------- Co-authored-by: Shroap <184123002+YinLiaoCo@users.noreply.github.com>
337 lines
9.4 KiB
Go
337 lines
9.4 KiB
Go
package qmp
|
|
|
|
import (
|
|
"context"
|
|
"fmt"
|
|
"math"
|
|
"path/filepath"
|
|
"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})
|
|
}
|
|
|
|
// 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")
|
|
}
|
|
|
|
// 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
|
|
}
|
|
|
|
// SendPasteShortcut presses Command+V (meta_l + v) in a running macOS VM over
|
|
// its QMP socket. Works in every macOS app without Accessibility permissions.
|
|
func SendPasteShortcut(ctx context.Context, vmDir string) error {
|
|
q, err := Dial(ctx, "unix", SocketPath(vmDir))
|
|
if err != nil {
|
|
return err
|
|
}
|
|
defer q.Close()
|
|
return PressCombo(ctx, q, 25*time.Millisecond, "v", "meta_l")
|
|
}
|
|
|
|
func absEvent(axis string, value int) map[string]any {
|
|
return map[string]any{"type": "abs", "data": map[string]any{"axis": axis, "value": value}}
|
|
}
|
|
|
|
func btnEvent(button string, down bool) map[string]any {
|
|
return map[string]any{"type": "btn", "data": map[string]any{"down": down, "button": button}}
|
|
}
|
|
|
|
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 clicks at normalized absolute coordinates and presses Command+V.
|
|
func ClickAndPaste(ctx context.Context, q Executor, normX, normY float64, clickHold, focusWait, keyHold time.Duration) error {
|
|
return ClickAndPasteWithActivate(ctx, q, normX, normY, false, 0, clickHold, focusWait, keyHold, "")
|
|
}
|
|
|
|
// ClickAndPasteWithActivate optionally activates the window before clicking the paste target.
|
|
func ClickAndPasteWithActivate(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(btnEvent("left", true)); err != nil {
|
|
return err
|
|
}
|
|
btnDown := true
|
|
defer func() {
|
|
if btnDown {
|
|
_ = send(btnEvent("left", false))
|
|
}
|
|
}()
|
|
sleep(ctx, clickHold)
|
|
if err := ctx.Err(); err != nil {
|
|
return err
|
|
}
|
|
if err := send(btnEvent("left", false)); err != nil {
|
|
return err
|
|
}
|
|
btnDown = false
|
|
return nil
|
|
}
|
|
|
|
// SendAbsoluteClickAndPaste clicks and pastes through the VM's QMP socket.
|
|
func SendAbsoluteClickAndPaste(ctx context.Context, vmDir string, normX, normY float64, activateClick bool, commandKey string, focusWait time.Duration) error {
|
|
q, err := Dial(ctx, "unix", SocketPath(vmDir))
|
|
if err != nil {
|
|
return err
|
|
}
|
|
defer q.Close()
|
|
if focusWait <= 0 {
|
|
focusWait = 120 * time.Millisecond
|
|
}
|
|
return ClickAndPasteWithActivate(ctx, q, normX, normY, activateClick, 550*time.Millisecond, 25*time.Millisecond, focusWait, 25*time.Millisecond, commandKey)
|
|
}
|
|
|
|
// TypeIntoVM types text into a running VM through its QMP socket and returns
|
|
// how many keys it pressed.
|
|
func TypeIntoVM(ctx context.Context, vmDir, text string, progress func(done, total int)) (int, error) {
|
|
strokes, err := Strokes(text)
|
|
if err != nil {
|
|
return 0, err
|
|
}
|
|
if len(strokes) == 0 {
|
|
return 0, fmt.Errorf("nothing to type")
|
|
}
|
|
q, err := Dial(ctx, "unix", SocketPath(vmDir))
|
|
if err != nil {
|
|
return 0, err
|
|
}
|
|
defer q.Close()
|
|
done := 0
|
|
err = TypeStrokes(ctx, q, strokes, 20*time.Millisecond, 15*time.Millisecond, func(n int) {
|
|
done = n
|
|
if progress != nil {
|
|
progress(n, len(strokes))
|
|
}
|
|
})
|
|
return done, err
|
|
}
|
|
|
|
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:
|
|
}
|
|
}
|