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 ( "context" "errors" "fmt" "strings" "sync" "time" "unicode/utf8" "github.com/Nwflower/reims-go/internal/guesttools" "github.com/Nwflower/reims-go/internal/qmp" wailsRuntime "github.com/wailsapp/wails/v2/pkg/runtime" ) type remoteTextItem struct { vmDir string text string } // typing holds the VMs being typed into: QMP's socket serves one client, and // two jobs at once would interleave their keys. Remote IME phrases use a // per-VM FIFO queue so rapid continuous typing never drops characters while a // previous paste is settling. var typing = struct { mu sync.Mutex busy map[string]bool lastHintAt map[string]time.Time remoteQueues map[string]chan remoteTextItem }{ busy: map[string]bool{}, lastHintAt: map[string]time.Time{}, remoteQueues: map[string]chan remoteTextItem{}, } // ErrNotTypeable is what the UI matches to show its own message. var ErrNotTypeable = errors.New("not typeable") func isControlOnlyText(s string) bool { if s == "" { return false } for _, r := range s { if r != '\n' && r != '\t' { return false } } return true } func hasNonASCII(s string) bool { for _, r := range s { if r > 0x7E { return true } } return false } // TypeText sends text into a running VM and returns how many characters were // sent. When Guest Tools is connected, arbitrary UTF-8 (including Chinese and // emoji) is injected via the Guest Tools bridge + QMP Command+V; otherwise pure // US-ASCII falls back to direct QMP USB keyboard strokes (works in Recovery and // at the Login Window). func (a *App) TypeText(name, text string) (int, error) { return a.injectTextIntoVM(name, "", text, false) } func (a *App) injectTextIntoVM(name, knownDir, text string, fromRemoteIME bool) (int, error) { text = strings.ReplaceAll(text, "\r\n", "\n") text = strings.ReplaceAll(text, "\r", "\n") if text == "" { return 0, errors.New("nothing to type") } 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() vmDir := knownDir if vmDir == "" { 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 } vmDir = d.Directory } // Prefer Guest Tools Unicode injection for: // - any non-ASCII (Chinese, CJK punctuation, emoji), OR // - remote IME text (unless it's a bare Enter/Tab control key, which must // press the physical key so forms/terminals submit properly). wantGuestPaste := !isControlOnlyText(text) && (hasNonASCII(text) || fromRemoteIME) if !wantGuestPaste && !isControlOnlyText(text) && utf8.RuneCountInString(text) > 16 { // Long ASCII text is also much faster and immune to guest Chinese IME // interception when Guest Tools is connected. wantGuestPaste = true } if wantGuestPaste { a.mu.Lock() srv := a.guestTools a.mu.Unlock() if srv != nil { pasteCtx, cancel := context.WithTimeout(ctx, 6*time.Second) mode, err := srv.InjectText(pasteCtx, name, text, func(c context.Context) error { return qmp.SendPasteShortcut(c, vmDir) }) cancel() if err == nil { n := utf8.RuneCountInString(text) if !fromRemoteIME { a.emitLog(name, fmt.Sprintf("Injected %d character(s) into %s via Guest Tools (%s) + Cmd+V.", n, name, mode)) } return n, nil } if !errors.Is(err, guesttools.ErrGuestToolsNotConnected) { a.emitLog(name, fmt.Sprintf("Guest Tools text injection (%s) failed: %v", mode, err)) } } } // Fallback (or bare Enter/Tab / Recovery / Login screen): QMP US keystrokes. n, err := qmp.TypeIntoVM(ctx, vmDir, text, nil) var ue *qmp.UntypeableError if errors.As(err, &ue) { if fromRemoteIME { typing.mu.Lock() last := typing.lastHintAt[name] shouldLog := time.Since(last) > 15*time.Second if shouldLog { typing.lastHintAt[name] = time.Now() } typing.mu.Unlock() if shouldLog { a.emitLog(name, "Remote IME Unicode text received, but Guest Tools is not connected in macOS yet (install Guest Tools to enable Chinese/Unicode remote input).") } } else { 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 } if !fromRemoteIME { a.emitLog(name, fmt.Sprintf("Typed %d keys into %s.", n, name)) } return n, nil } // injectRemoteText queues text asynchronously from the Windows VK_PACKET hook // or the reims-vgpu-window WM_CHAR bridge (/v1/host-text) onto a per-VM FIFO // worker so rapid IME bursts are delivered strictly in order without drops. func (a *App) injectRemoteText(vmName, vmDir, text string) { if vmName == "" || text == "" { return } typing.mu.Lock() ch, ok := typing.remoteQueues[vmName] if !ok { ch = make(chan remoteTextItem, 32) typing.remoteQueues[vmName] = ch go a.runRemoteTextQueue(vmName, ch) } typing.mu.Unlock() select { case ch <- remoteTextItem{vmDir: vmDir, text: text}: default: } } func (a *App) runRemoteTextQueue(vmName string, ch <-chan remoteTextItem) { for item := range ch { dir := item.vmDir combined := item.text // Coalesce adjacent queued non-control phrases that arrived while the // previous paste was settling. if !isControlOnlyText(combined) { for draining := true; draining; { select { case next := <-ch: if isControlOnlyText(next.text) { _, _ = a.injectTextIntoVM(vmName, dir, combined, true) combined = next.text if next.vmDir != "" { dir = next.vmDir } draining = false } else { combined += next.text if dir == "" && next.vmDir != "" { dir = next.vmDir } } default: draining = false } } } _, _ = a.injectTextIntoVM(vmName, dir, combined, true) } } // TypeClipboard types or injects 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) }