package main // "Paste as keystrokes": type the host's clipboard (or a given text) into a // running VM as US-layout key presses over its QMP socket. QEMU here has no // clipboard channel to the guest (no qemu-vdagent chardev in the runtime, and // macOS has no agent for one), so typing is how text gets in with no network, // Recovery included. import ( "errors" "fmt" "sync" "github.com/Nwflower/reims-go/internal/qmp" wailsRuntime "github.com/wailsapp/wails/v2/pkg/runtime" ) // typing holds the VMs being typed into: QMP's socket serves one client, and // two jobs at once would interleave their keys. var typing = struct { mu sync.Mutex busy map[string]bool }{busy: map[string]bool{}} // ErrNotTypeable is what the UI matches to show its own message. var ErrNotTypeable = errors.New("not typeable") // TypeText types text into a running VM and returns how many keys it pressed. func (a *App) TypeText(name, text string) (int, error) { typing.mu.Lock() if typing.busy[name] { typing.mu.Unlock() return 0, fmt.Errorf("%s is already being typed into", name) } typing.busy[name] = true typing.mu.Unlock() defer func() { typing.mu.Lock() delete(typing.busy, name) typing.mu.Unlock() }() ctx := a.baseCtx() if _, running := a.currentVMPID(ctx, name); !running { return 0, fmt.Errorf("%s is not running", name) } d, err := a.GetVMDetail(name) if err != nil { return 0, err } n, err := qmp.TypeIntoVM(ctx, d.Directory, text, nil) var ue *qmp.UntypeableError if errors.As(err, &ue) { a.emitLog(name, "Paste as keystrokes refused: "+ue.Error()) return 0, fmt.Errorf("%w: %s", ErrNotTypeable, ue.Error()) } if err != nil { a.emitLog(name, fmt.Sprintf("Paste as keystrokes stopped after %d keys: %v", n, err)) return n, err } a.emitLog(name, fmt.Sprintf("Typed %d keys into %s.", n, name)) return n, nil } // TypeClipboard types the host clipboard's text into a running VM. func (a *App) TypeClipboard(name string) (int, error) { if a.ctx == nil { return 0, errors.New("no window") } text, err := wailsRuntime.ClipboardGetText(a.ctx) if err != nil { return 0, fmt.Errorf("read clipboard: %w", err) } if text == "" { return 0, errors.New("the clipboard has no text") } return a.TypeText(name, text) }