Files
Reims-Go/internal/app/thumbnail_flow.go
T

208 lines
5.7 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"
"fmt"
"image/png"
"os"
"path/filepath"
"sync"
"time"
"github.com/Nwflower/reims-go/internal/guesttools"
"github.com/Nwflower/reims-go/internal/host"
"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 {
a.mu.Lock()
dir := a.cfg.XDGCacheDir()
a.mu.Unlock()
return filepath.Join(dir, "thumbs", name+".jpg")
}
func vmThumbLock(name string) *sync.Mutex {
thumbLocks.mu.Lock()
defer thumbLocks.mu.Unlock()
mu := thumbLocks.locks[name]
if mu == nil {
mu = &sync.Mutex{}
thumbLocks.locks[name] = 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) {
mu := vmThumbLock(name)
mu.Lock()
thumbLocks.mu.Lock()
if thumbLocks.locks[name] == mu {
delete(thumbLocks.locks, name)
}
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) {
path := a.thumbPath(name)
mu := vmThumbLock(name)
if mu.TryLock() {
defer mu.Unlock()
if t, ok := a.captureThumb(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 {
vm, ok := a.polledVM(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)
}
return 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 {
vm, ok := a.polledVM(name)
if !ok || vm.State != "running" || vm.Dir == "" {
return fmt.Errorf("VM %s is not running", name)
}
mu := vmThumbLock(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-"+name)
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.emitLog(name, "Copied VM screenshot to clipboard")
return nil
}
func (a *App) captureThumb(name, path string) (VMThumbnail, bool) {
typing.mu.Lock()
busy := typing.busy[name]
typing.mu.Unlock()
if busy {
return VMThumbnail{}, false
}
vm, ok := a.polledVM(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-"+name)
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,
}
}