Route generic App and CLI code through lifecycle and driver models. Move native macOS detail, create, settings and legacy flows into explicit files, share progress and redaction through host, and enforce the boundary with a file-scoped architecture ratchet.
282 lines
9.0 KiB
Go
282 lines
9.0 KiB
Go
package app
|
|
|
|
// VM screen thumbnails for the VM page: while a VM runs,
|
|
// grab one frame over its QMP socket (`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/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/qmp"
|
|
"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(name string) string { return a.thumbPathForDriver("", name) }
|
|
func (a *App) thumbPathForDriver(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(name string) *sync.Mutex { return vmThumbLockForDriver("", name) }
|
|
func vmThumbLockForDriver(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) {
|
|
key := vmKey(name)
|
|
mu := vmThumbLock(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(name string) (VMThumbnail, error) {
|
|
return a.GetVMThumbnailWithDriver("", name)
|
|
}
|
|
func (a *App) GetVMThumbnailWithDriver(driverID, name string) (VMThumbnail, error) {
|
|
path := a.thumbPathForDriver(driverID, name)
|
|
mu := vmThumbLockForDriver(driverID, name)
|
|
if mu.TryLock() {
|
|
defer mu.Unlock()
|
|
if t, ok := a.captureThumbWithDriver(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(name string) error { return a.FocusVMWindowWithDriver("", name) }
|
|
func (a *App) FocusVMWindowWithDriver(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" || vm.PID == nil || *vm.PID <= 0 {
|
|
return fmt.Errorf("VM %s is not running", name)
|
|
}
|
|
if !host.FocusProcessWindow(uint32(*vm.PID)) {
|
|
return fmt.Errorf("could not locate display window for %s", name)
|
|
}
|
|
a.unfoldInstallGuide(name, *vm.PID)
|
|
return nil
|
|
}
|
|
|
|
// ToggleVMFullscreen switches the running VM's display through its owning driver.
|
|
func (a *App) ToggleVMFullscreen(name string) (bool, error) {
|
|
return a.ToggleVMFullscreenWithDriver("", name)
|
|
}
|
|
func (a *App) ToggleVMFullscreenWithDriver(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 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 || listed.PID == nil || *listed.PID <= 0 {
|
|
return false, i18n.NewCodedError(loc, "E_VM_NOT_RUNNING", "err.vm_not_running", vars, nil)
|
|
}
|
|
fullscreen, err := host.ToggleProcessWindowFullscreen(uint32(*listed.PID))
|
|
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.emitLifecycleStateChanged()
|
|
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(name string) error { return a.CopyVMScreenshotWithDriver("", name) }
|
|
func (a *App) CopyVMScreenshotWithDriver(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" || vm.Dir == "" {
|
|
return fmt.Errorf("VM %s is not running", name)
|
|
}
|
|
mu := vmThumbLockForDriver(driverID, name)
|
|
mu.Lock()
|
|
defer mu.Unlock()
|
|
|
|
a.mu.Lock()
|
|
tmp := a.cfg.TempDir()
|
|
a.mu.Unlock()
|
|
if err := os.MkdirAll(tmp, 0o755); err != nil {
|
|
return err
|
|
}
|
|
raw := filepath.Join(tmp, "screenshot-"+strings.TrimSuffix(filepath.Base(a.thumbPathForDriver(driverID, name)), ".jpg"))
|
|
defer os.Remove(raw)
|
|
|
|
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
|
|
defer cancel()
|
|
format, err := qmp.ScreendumpVM(ctx, vm.Dir, raw)
|
|
if err != nil {
|
|
return fmt.Errorf("capture screen: %w", err)
|
|
}
|
|
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(name, path string) (VMThumbnail, bool) {
|
|
return a.captureThumbWithDriver("", name, path)
|
|
}
|
|
func (a *App) captureThumbWithDriver(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" || vm.Dir == "" {
|
|
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.
|
|
if vm.PID != nil && *vm.PID > 0 && host.ForegroundPID() == uint32(*vm.PID) {
|
|
return VMThumbnail{}, false
|
|
}
|
|
a.mu.Lock()
|
|
tmp := a.cfg.TempDir()
|
|
a.mu.Unlock()
|
|
if err := os.MkdirAll(tmp, 0o755); err != nil {
|
|
return VMThumbnail{}, false
|
|
}
|
|
raw := filepath.Join(tmp, "screendump-"+strings.TrimSuffix(filepath.Base(path), ".jpg"))
|
|
defer os.Remove(raw)
|
|
|
|
ctx, cancel := context.WithTimeout(context.Background(), 4*time.Second)
|
|
defer cancel()
|
|
format, err := qmp.ScreendumpVM(ctx, vm.Dir, raw)
|
|
if err != nil {
|
|
return VMThumbnail{}, false
|
|
}
|
|
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 {
|
|
part := path + ".part"
|
|
if os.WriteFile(part, jpg, 0o644) == nil {
|
|
_ = os.Rename(part, path)
|
|
}
|
|
}
|
|
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,
|
|
}
|
|
}
|