Every VM action had two bindings: one by name and one by driver and name. The window used only the second, so the first is gone and the WithDriver suffix with it. Unused bindings and frontend exports are removed too. Tests now reject bindings the window never calls, stale generated bindings and unused frontend exports. TypeScript rejects unused locals. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
309 lines
9.4 KiB
Go
309 lines
9.4 KiB
Go
package app
|
|
|
|
// VM screen thumbnails for the VM page: while a VM runs,
|
|
// grab one frame through the built-in computer-use console (`screendump`), shrink it to a small
|
|
// JPEG and keep it under <data root>\cache\thumbs, so a stopped VM can still
|
|
// show its last screen. Nothing here touches vm.toml or the guest.
|
|
|
|
import (
|
|
"bytes"
|
|
"context"
|
|
"encoding/base64"
|
|
"errors"
|
|
"fmt"
|
|
"image/png"
|
|
"os"
|
|
"path/filepath"
|
|
"strings"
|
|
"sync"
|
|
"time"
|
|
|
|
"github.com/Nwflower/reims-go/internal/atomicfile"
|
|
"github.com/Nwflower/reims-go/internal/driver"
|
|
"github.com/Nwflower/reims-go/internal/guesttools"
|
|
"github.com/Nwflower/reims-go/internal/host"
|
|
"github.com/Nwflower/reims-go/internal/i18n"
|
|
"github.com/Nwflower/reims-go/internal/thumb"
|
|
)
|
|
|
|
// VMThumbnail is one frame of a VM's screen as a data URL.
|
|
type VMThumbnail struct {
|
|
DataURL string `json:"data_url"`
|
|
CapturedAt int64 `json:"captured_at"` // Unix milliseconds
|
|
Live bool `json:"live"` // captured just now from the running VM
|
|
}
|
|
|
|
const thumbWidth = 640
|
|
|
|
// thumbLocks keeps one capture per VM in flight: QMP serves a single client
|
|
// and the page polls on a timer.
|
|
var thumbLocks = struct {
|
|
mu sync.Mutex
|
|
locks map[string]*sync.Mutex
|
|
}{locks: make(map[string]*sync.Mutex)}
|
|
|
|
func (a *App) thumbPath(driverID, name string) string {
|
|
a.mu.Lock()
|
|
dir := a.cfg.XDGCacheDir()
|
|
a.mu.Unlock()
|
|
prefix := ""
|
|
if id := driver.CanonicalDriverID(driverID); id != "" && id != driver.BuiltinReimsMacOSDriverID {
|
|
prefix = strings.Map(func(r rune) rune {
|
|
if (r >= 'a' && r <= 'z') || (r >= 'A' && r <= 'Z') || (r >= '0' && r <= '9') || r == '-' || r == '_' {
|
|
return r
|
|
}
|
|
return '_'
|
|
}, id) + "__"
|
|
}
|
|
return filepath.Join(dir, "thumbs", prefix+name+".jpg")
|
|
}
|
|
|
|
func vmThumbLock(driverID, name string) *sync.Mutex {
|
|
key := vmKeyForDriver(driverID, name)
|
|
thumbLocks.mu.Lock()
|
|
defer thumbLocks.mu.Unlock()
|
|
mu := thumbLocks.locks[key]
|
|
if mu == nil {
|
|
mu = &sync.Mutex{}
|
|
thumbLocks.locks[key] = mu
|
|
}
|
|
return mu
|
|
}
|
|
|
|
// releaseVMThumbnail waits for an in-flight capture before releasing its lock,
|
|
// so an old request cannot install a new lock after the VM has been deleted.
|
|
func releaseVMThumbnail(name string) { releaseVMThumbnailForDriver("", name) }
|
|
|
|
func releaseVMThumbnailForDriver(driverID, name string) {
|
|
key := vmKeyForDriver(driverID, name)
|
|
mu := vmThumbLock(driverID, name)
|
|
mu.Lock()
|
|
thumbLocks.mu.Lock()
|
|
if thumbLocks.locks[key] == mu {
|
|
delete(thumbLocks.locks, key)
|
|
}
|
|
thumbLocks.mu.Unlock()
|
|
mu.Unlock()
|
|
}
|
|
|
|
// GetVMThumbnail returns the VM's screen: a fresh frame while it runs, else
|
|
// the last one saved. An empty DataURL means there is no frame to show.
|
|
func (a *App) GetVMThumbnail(driverID, name string) (VMThumbnail, error) {
|
|
path := a.thumbPath(driverID, name)
|
|
mu := vmThumbLock(driverID, name)
|
|
if mu.TryLock() {
|
|
defer mu.Unlock()
|
|
if t, ok := a.captureThumb(driverID, name, path); ok {
|
|
return t, nil
|
|
}
|
|
}
|
|
return readThumb(path, false), nil
|
|
}
|
|
|
|
// FocusVMWindow brings a running VM's QEMU display window to the foreground,
|
|
// restoring it first if minimized.
|
|
func (a *App) FocusVMWindow(driverID, name string) error {
|
|
info, err := a.resolveVMInfo(driverID, name)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
if driver.IsHosted(info.Capabilities) {
|
|
// A hosted VM has no window of its own: bring up its best endpoint.
|
|
ep, ok := driver.PrimaryHostedEndpoint(info.Endpoints)
|
|
if !ok {
|
|
return fmt.Errorf("%s has no ready endpoint to open", name)
|
|
}
|
|
return a.OpenVMEndpoint(info.DriverID, info.Name, ep.Kind, "")
|
|
}
|
|
vm, ok := a.polledVMForDriver(info.DriverID, name)
|
|
if !ok || vm.State != "running" {
|
|
return fmt.Errorf("VM %s is not running", name)
|
|
}
|
|
rootPID := 0
|
|
if vm.PID != nil {
|
|
rootPID = *vm.PID
|
|
}
|
|
pids := a.vmProcessPIDs(info.Ref(), rootPID)
|
|
if len(pids) == 0 {
|
|
return fmt.Errorf("VM %s is not running", name)
|
|
}
|
|
if !host.FocusProcessTreeWindow(pids) {
|
|
return fmt.Errorf("could not locate display window for %s", name)
|
|
}
|
|
if rootPID > 0 && driver.CanonicalDriverID(info.DriverID) == driver.BuiltinReimsMacOSDriverID {
|
|
a.unfoldInstallGuide(name, rootPID)
|
|
}
|
|
return nil
|
|
}
|
|
|
|
// ToggleVMFullscreen switches the running VM's display through its owning driver.
|
|
func (a *App) ToggleVMFullscreen(driverID, name string) (bool, error) {
|
|
a.mu.Lock()
|
|
preference := a.cfg.Locale
|
|
a.mu.Unlock()
|
|
loc := i18n.EffectiveLocale(preference)
|
|
vars := i18n.Vars{"name": name}
|
|
vm, err := a.resolveVMInfo(driverID, name)
|
|
if err != nil {
|
|
return false, i18n.NewCodedError(loc, "E_FULLSCREEN_FAILED", "err.fullscreen_failed", vars, err)
|
|
}
|
|
if vm.State != "running" {
|
|
return false, i18n.NewCodedError(loc, "E_VM_NOT_RUNNING", "err.vm_not_running", vars, nil)
|
|
}
|
|
if driver.IsHosted(vm.Capabilities) {
|
|
// The driver owns a hosted VM's display; the host has no window to resize.
|
|
return false, i18n.NewCodedError(loc, "E_VM_WINDOW_NOT_FOUND", "err.vm_window_not_found", vars, nil)
|
|
}
|
|
if graphics, _ := vm.DriverData["graphics"].(string); graphics == "vmware-svga" {
|
|
return false, i18n.NewCodedError(loc, "E_FULLSCREEN_VMWARE_SVGA", "err.fullscreen_vmware_svga", vars, nil)
|
|
}
|
|
listed, ok := a.polledVMForDriver(vm.DriverID, name)
|
|
if !ok {
|
|
return false, i18n.NewCodedError(loc, "E_VM_NOT_RUNNING", "err.vm_not_running", vars, nil)
|
|
}
|
|
rootPID := 0
|
|
if listed.PID != nil {
|
|
rootPID = *listed.PID
|
|
}
|
|
pids := a.vmProcessPIDs(vm.Ref(), rootPID)
|
|
if len(pids) == 0 {
|
|
return false, i18n.NewCodedError(loc, "E_VM_NOT_RUNNING", "err.vm_not_running", vars, nil)
|
|
}
|
|
fullscreen, err := host.ToggleProcessTreeWindowFullscreen(pids)
|
|
if errors.Is(err, host.ErrDisplayWindowNotFound) {
|
|
return false, i18n.NewCodedError(loc, "E_VM_WINDOW_NOT_FOUND", "err.vm_window_not_found", vars, err)
|
|
}
|
|
if err != nil {
|
|
return false, i18n.NewCodedError(loc, "E_FULLSCREEN_FAILED", "err.fullscreen_failed", vars, err)
|
|
}
|
|
a.emitVMLogForDriver(vm.DriverID, name, fmt.Sprintf("VM window full screen: %t", fullscreen))
|
|
a.emitStateChanged()
|
|
return fullscreen, nil
|
|
}
|
|
|
|
// CopyVMScreenshot captures a full-resolution frame from a running VM over QMP
|
|
// and writes it as a PNG/DIB image to the Windows clipboard.
|
|
func (a *App) CopyVMScreenshot(driverID, name string) error {
|
|
info, err := a.resolveVMInfo(driverID, name)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
vm, ok := a.polledVMForDriver(info.DriverID, name)
|
|
if !ok || vm.State != "running" {
|
|
return fmt.Errorf("VM %s is not running", name)
|
|
}
|
|
route, err := a.resolveConsoleRoute(info)
|
|
if err != nil {
|
|
return fmt.Errorf("screenshots are not available for %s", name)
|
|
}
|
|
if route.vm.Directory == "" {
|
|
route.vm.Directory = vm.Dir
|
|
}
|
|
if route.kind == consoleRouteQMP && route.vm.Directory == "" {
|
|
return fmt.Errorf("VM %s is not running", name)
|
|
}
|
|
mu := vmThumbLock(driverID, name)
|
|
mu.Lock()
|
|
defer mu.Unlock()
|
|
|
|
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
|
|
defer cancel()
|
|
raw, format, cleanup, err := a.consoleCaptureInternal(ctx, route, 0)
|
|
if err != nil {
|
|
return fmt.Errorf("capture screen: %w", err)
|
|
}
|
|
defer cleanup()
|
|
img, err := thumb.Load(raw, format)
|
|
if err != nil {
|
|
return fmt.Errorf("decode screen: %w", err)
|
|
}
|
|
var buf bytes.Buffer
|
|
if err := png.Encode(&buf, img); err != nil {
|
|
return fmt.Errorf("encode PNG: %w", err)
|
|
}
|
|
if err := (&guesttools.OSClipboard{}).WritePNG(buf.Bytes()); err != nil {
|
|
return fmt.Errorf("copy image to clipboard: %w", err)
|
|
}
|
|
a.emitVMLogForDriver(driverID, name, "Copied VM screenshot to clipboard")
|
|
return nil
|
|
}
|
|
|
|
func (a *App) captureThumb(driverID, name, path string) (VMThumbnail, bool) {
|
|
typing.mu.Lock()
|
|
busy := typing.busy[vmKeyForDriver(driverID, name)]
|
|
typing.mu.Unlock()
|
|
if busy {
|
|
return VMThumbnail{}, false
|
|
}
|
|
info, err := a.resolveVMInfo(driverID, name)
|
|
if err != nil {
|
|
return VMThumbnail{}, false
|
|
}
|
|
vm, ok := a.polledVMForDriver(info.DriverID, name)
|
|
if !ok || vm.State != "running" {
|
|
return VMThumbnail{}, false
|
|
}
|
|
route, err := a.resolveConsoleRoute(info)
|
|
if err != nil {
|
|
return VMThumbnail{}, false
|
|
}
|
|
if route.vm.Directory == "" {
|
|
route.vm.Directory = vm.Dir
|
|
}
|
|
if route.kind == consoleRouteQMP {
|
|
if route.vm.Directory == "" {
|
|
return VMThumbnail{}, false
|
|
}
|
|
// The user is looking at the VM window itself, not this page: skip the
|
|
// screendump, which runs on QEMU's main loop and writes a full-size frame
|
|
// (about 25 MB at 4K) to disk.
|
|
rootPID := 0
|
|
if vm.PID != nil {
|
|
rootPID = *vm.PID
|
|
}
|
|
if host.ForegroundInPIDs(a.vmProcessPIDs(info.Ref(), rootPID)) {
|
|
return VMThumbnail{}, false
|
|
}
|
|
}
|
|
|
|
ctx, cancel := context.WithTimeout(context.Background(), 4*time.Second)
|
|
defer cancel()
|
|
raw, format, cleanup, err := a.consoleCaptureInternal(ctx, route, thumbWidth)
|
|
if err != nil {
|
|
return VMThumbnail{}, false
|
|
}
|
|
defer cleanup()
|
|
img, err := thumb.LoadPreview(raw, format, thumbWidth)
|
|
if err != nil || img == nil {
|
|
return VMThumbnail{}, false
|
|
}
|
|
jpg, err := thumb.JPEG(img, 80)
|
|
if err != nil {
|
|
return VMThumbnail{}, false
|
|
}
|
|
if err := os.MkdirAll(filepath.Dir(path), 0o755); err == nil {
|
|
_ = atomicfile.Write(path, jpg, 0o644)
|
|
}
|
|
return VMThumbnail{
|
|
DataURL: "data:image/jpeg;base64," + base64.StdEncoding.EncodeToString(jpg),
|
|
CapturedAt: time.Now().UnixMilli(),
|
|
Live: true,
|
|
}, true
|
|
}
|
|
|
|
func readThumb(path string, live bool) VMThumbnail {
|
|
b, err := os.ReadFile(path)
|
|
if err != nil || len(b) == 0 {
|
|
return VMThumbnail{}
|
|
}
|
|
var at int64
|
|
if st, err := os.Stat(path); err == nil {
|
|
at = st.ModTime().UnixMilli()
|
|
}
|
|
return VMThumbnail{
|
|
DataURL: "data:image/jpeg;base64," + base64.StdEncoding.EncodeToString(b),
|
|
CapturedAt: at,
|
|
Live: live,
|
|
}
|
|
}
|