- "Send text to VM..." dialog: arbitrary Unicode goes through Guest Tools (clipboard paste in the guest, agent v3 /v1/text-input long poll); without Guest Tools only US-keyboard ASCII is typed via QMP. - Host IME / dictation: a low-level keyboard hook (internal/host/ime_*) catches VK_PACKET input aimed at a running VM window, coalesces bursts and forwards them in order through a per-VM queue (type_flow.go). - reims-vgpu-window bridge: new runtime patch reims-vgpu-win32-unicode-input enables SDL text input and posts committed text to /v1/host-text; StartVM passes REIMS_GO_INPUT_URL/TOKEN to the window process. This also adds the patch file that patches/series.txt already listed. - Guest Tools auth returns a field snapshot instead of copying the VM entry (it now holds a mutex and text queues). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
880 lines
23 KiB
Go
880 lines
23 KiB
Go
package main
|
|
|
|
import (
|
|
"context"
|
|
"fmt"
|
|
"io"
|
|
"os"
|
|
"path/filepath"
|
|
"strings"
|
|
"sync"
|
|
"time"
|
|
|
|
"github.com/Nwflower/reims-go/internal/config"
|
|
"github.com/Nwflower/reims-go/internal/driver/reims"
|
|
"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"
|
|
rt "github.com/Nwflower/reims-go/internal/runtime"
|
|
"github.com/Nwflower/reims-go/internal/tray"
|
|
"github.com/Nwflower/reims-go/internal/version"
|
|
"github.com/Nwflower/reims-go/internal/vmstart"
|
|
wailsRuntime "github.com/wailsapp/wails/v2/pkg/runtime"
|
|
)
|
|
|
|
type PendingChange struct {
|
|
Field string `json:"field"`
|
|
From string `json:"from"`
|
|
To string `json:"to"`
|
|
}
|
|
|
|
type AppState struct {
|
|
Config *config.Config `json:"config"`
|
|
Host host.Report `json:"host"`
|
|
Optimizations []host.Optimization `json:"optimizations"`
|
|
Runtimes []rt.Installed `json:"runtimes"`
|
|
ActiveRuntime *rt.Installed `json:"active_runtime,omitempty"`
|
|
VMs []reims.VMListItem `json:"vms"`
|
|
Transitions map[string]string `json:"transitions"`
|
|
PendingChanges map[string][]PendingChange `json:"pending_changes"`
|
|
// NeedsSetup is true on first launch, until a data folder is chosen (setup.go).
|
|
NeedsSetup bool `json:"needs_setup"`
|
|
AppVersion string `json:"app_version"`
|
|
}
|
|
|
|
type rebootWatcherEntry struct {
|
|
id uint64
|
|
cancel context.CancelFunc
|
|
}
|
|
|
|
type App struct {
|
|
ctx context.Context
|
|
mu sync.Mutex
|
|
cfg *config.Config
|
|
transitions map[string]string
|
|
pendingChanges map[string][]PendingChange
|
|
rebootWatchers map[string]rebootWatcherEntry
|
|
nextWatcherID uint64
|
|
stopPoll context.CancelFunc
|
|
guestTools *guesttools.Server
|
|
imeBridge *host.IMEBridge
|
|
trayMgr *tray.Manager
|
|
allowQuit bool
|
|
lastVMs []reims.VMListItem
|
|
procSamples map[string]host.ProcessSample
|
|
recentLogs []string
|
|
needsSetup bool
|
|
}
|
|
|
|
func NewApp() *App {
|
|
cfg, needsSetup, err := config.Resolve()
|
|
if err != nil {
|
|
cfg = config.Default()
|
|
}
|
|
return &App{
|
|
cfg: cfg,
|
|
needsSetup: needsSetup,
|
|
transitions: make(map[string]string),
|
|
pendingChanges: make(map[string][]PendingChange),
|
|
rebootWatchers: make(map[string]rebootWatcherEntry),
|
|
procSamples: make(map[string]host.ProcessSample),
|
|
}
|
|
}
|
|
|
|
func (a *App) startup(ctx context.Context) {
|
|
a.ctx = ctx
|
|
pollCtx, cancel := context.WithCancel(ctx)
|
|
a.stopPoll = cancel
|
|
a.startTray()
|
|
a.startIMEBridge()
|
|
go a.registerExistingGuestTools(pollCtx)
|
|
go a.pollVMs(pollCtx)
|
|
}
|
|
|
|
func (a *App) startIMEBridge() {
|
|
bridge, err := host.StartIMEBridge(func(target host.IMETarget, text string) {
|
|
go a.injectRemoteText(target.VMName, target.VMDir, text)
|
|
})
|
|
if err != nil {
|
|
a.emitLog("app", "Remote IME hook unavailable: "+err.Error())
|
|
return
|
|
}
|
|
a.mu.Lock()
|
|
a.imeBridge = bridge
|
|
a.mu.Unlock()
|
|
}
|
|
|
|
func (a *App) beforeClose(ctx context.Context) bool {
|
|
a.mu.Lock()
|
|
allow := a.allowQuit
|
|
toTray := a.cfg.ShouldMinimizeToTray()
|
|
hasTray := a.trayMgr != nil
|
|
a.mu.Unlock()
|
|
if !allow && toTray && hasTray {
|
|
wailsRuntime.WindowHide(ctx)
|
|
return true
|
|
}
|
|
return false
|
|
}
|
|
|
|
func (a *App) shutdown(ctx context.Context) {
|
|
if a.stopPoll != nil {
|
|
a.stopPoll()
|
|
}
|
|
tasks.cancelAll()
|
|
stopAllVMMonitors()
|
|
a.mu.Lock()
|
|
for name, entry := range a.rebootWatchers {
|
|
entry.cancel()
|
|
delete(a.rebootWatchers, name)
|
|
}
|
|
gt := a.guestTools
|
|
ib := a.imeBridge
|
|
tm := a.trayMgr
|
|
a.imeBridge = nil
|
|
a.trayMgr = nil
|
|
a.mu.Unlock()
|
|
if ib != nil {
|
|
ib.Close()
|
|
}
|
|
if tm != nil {
|
|
tm.Close()
|
|
}
|
|
if gt != nil {
|
|
shutCtx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
|
|
_ = gt.Close(shutCtx)
|
|
cancel()
|
|
}
|
|
}
|
|
|
|
func (a *App) pollVMs(ctx context.Context) {
|
|
ticker := time.NewTicker(2 * time.Second)
|
|
defer ticker.Stop()
|
|
// Cache static hybrid P-core mask once instead of querying host every tick.
|
|
a.mu.Lock()
|
|
initRoot := a.cfg.DataRoot
|
|
a.mu.Unlock()
|
|
cachedHost := host.Inspect(initRoot)
|
|
var lastSig string
|
|
pinnedPIDs := make(map[int]bool)
|
|
|
|
for {
|
|
select {
|
|
case <-ctx.Done():
|
|
return
|
|
case <-ticker.C:
|
|
vms, err := a.listVMsInternal(ctx)
|
|
if err != nil {
|
|
continue
|
|
}
|
|
type pinCandidate struct {
|
|
name string
|
|
pid int
|
|
}
|
|
var toPin []pinCandidate
|
|
a.mu.Lock()
|
|
loc := a.cfg.Locale
|
|
autoPin := a.cfg.AutoPinPCores
|
|
a.lastVMs = append([]reims.VMListItem(nil), vms...)
|
|
tm := a.trayMgr
|
|
runningCount := 0
|
|
var b strings.Builder
|
|
var imeTargets []host.IMETarget
|
|
for _, vm := range vms {
|
|
if vm.State == "running" {
|
|
runningCount++
|
|
if vm.PID != nil && *vm.PID > 0 {
|
|
imeTargets = append(imeTargets, host.IMETarget{
|
|
VMName: vm.Name,
|
|
VMDir: vm.Dir,
|
|
PID: uint32(*vm.PID),
|
|
})
|
|
}
|
|
}
|
|
if tr, ok := a.transitions[vm.Name]; ok {
|
|
if (tr == "starting" && vm.State == "running") || (tr == "stopping" && vm.State == "stopped") {
|
|
delete(a.transitions, vm.Name)
|
|
if vm.State == "stopped" {
|
|
delete(a.pendingChanges, vm.Name)
|
|
}
|
|
}
|
|
}
|
|
if autoPin && vm.State == "running" && vm.PID != nil && *vm.PID > 0 && !pinnedPIDs[*vm.PID] {
|
|
if cachedHost.HasHybridCores && cachedHost.PCoreMask > 0 {
|
|
pinnedPIDs[*vm.PID] = true
|
|
toPin = append(toPin, pinCandidate{name: vm.Name, pid: *vm.PID})
|
|
}
|
|
}
|
|
fmt.Fprintf(&b, "%s:%s:%s;", vm.Name, vm.State, a.transitions[vm.Name])
|
|
}
|
|
sig := b.String()
|
|
ib := a.imeBridge
|
|
a.mu.Unlock()
|
|
if ib != nil {
|
|
ib.SetTargets(imeTargets)
|
|
}
|
|
if tm != nil {
|
|
if runningCount > 0 {
|
|
if loc == i18n.ZhCN {
|
|
tm.UpdateTooltip(fmt.Sprintf("Reims-Go — %d 台虚拟机运行中", runningCount))
|
|
} else {
|
|
tm.UpdateTooltip(fmt.Sprintf("Reims-Go — %d VM(s) running", runningCount))
|
|
}
|
|
} else {
|
|
tm.UpdateTooltip("Reims-Go")
|
|
}
|
|
}
|
|
for _, cand := range toPin {
|
|
vmCPUs := 0
|
|
if c, cerr := a.client(); cerr == nil {
|
|
if det, derr := c.Show(ctx, cand.name); derr == nil {
|
|
vmCPUs = det.CPUs
|
|
}
|
|
}
|
|
a.emitLog(cand.name, vmstart.PinQEMU(loc, cachedHost, cand.pid, vmCPUs))
|
|
}
|
|
if sig != lastSig {
|
|
lastSig = sig
|
|
wailsRuntime.EventsEmit(a.ctx, "reims:state-changed", true)
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
func (a *App) client() (*reims.Client, error) {
|
|
a.mu.Lock()
|
|
cfg := a.cfg
|
|
a.mu.Unlock()
|
|
active, err := rt.ResolveActive(cfg)
|
|
if err != nil {
|
|
return nil, fmt.Errorf("%s", i18n.T(cfg.Locale, "err.runtime_not_installed"))
|
|
}
|
|
return reims.NewClient(cfg, *active), nil
|
|
}
|
|
|
|
func (a *App) listVMsInternal(ctx context.Context) ([]reims.VMListItem, error) {
|
|
c, err := a.client()
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
return c.List(ctx)
|
|
}
|
|
|
|
func (a *App) emitLog(source, line string) {
|
|
redacted := reims.RedactLogLine(line)
|
|
ts := time.Now().Format("15:04:05")
|
|
a.mu.Lock()
|
|
a.recentLogs = append(a.recentLogs, fmt.Sprintf("%s [%s] %s", ts, source, redacted))
|
|
if len(a.recentLogs) > 1000 {
|
|
a.recentLogs = a.recentLogs[len(a.recentLogs)-1000:]
|
|
}
|
|
a.mu.Unlock()
|
|
if a.ctx == nil {
|
|
return
|
|
}
|
|
wailsRuntime.EventsEmit(a.ctx, "reims:log", map[string]string{
|
|
"ts": ts,
|
|
"source": source,
|
|
"line": redacted,
|
|
})
|
|
}
|
|
|
|
func (a *App) GetState() AppState {
|
|
a.mu.Lock()
|
|
cfgCopy := *a.cfg
|
|
trCopy := make(map[string]string, len(a.transitions))
|
|
for k, v := range a.transitions {
|
|
trCopy[k] = v
|
|
}
|
|
pcCopy := make(map[string][]PendingChange, len(a.pendingChanges))
|
|
for k, v := range a.pendingChanges {
|
|
pcCopy[k] = append([]PendingChange(nil), v...)
|
|
}
|
|
needsSetup := a.needsSetup
|
|
a.mu.Unlock()
|
|
|
|
rep := host.Inspect(cfgCopy.DataRoot)
|
|
runtimes, _ := rt.List(&cfgCopy)
|
|
active, _ := rt.ResolveActive(&cfgCopy)
|
|
vms, _ := a.listVMsInternal(context.Background())
|
|
|
|
var activePatches []string
|
|
if active != nil {
|
|
for _, p := range active.Manifest.Patches {
|
|
activePatches = append(activePatches, p.Name)
|
|
}
|
|
}
|
|
opts := host.EvaluateOptimizations(rep, activePatches)
|
|
|
|
return AppState{
|
|
Config: &cfgCopy,
|
|
Host: rep,
|
|
Optimizations: opts,
|
|
Runtimes: runtimes,
|
|
ActiveRuntime: active,
|
|
VMs: vms,
|
|
Transitions: trCopy,
|
|
PendingChanges: pcCopy,
|
|
NeedsSetup: needsSetup,
|
|
AppVersion: version.Version,
|
|
}
|
|
}
|
|
|
|
func (a *App) GetVMDetail(name string) (reims.VMDetail, error) {
|
|
c, err := a.client()
|
|
if err != nil {
|
|
return reims.VMDetail{}, err
|
|
}
|
|
d, err := c.Show(context.Background(), name)
|
|
if err != nil {
|
|
return d, err
|
|
}
|
|
d.RecoveryMode = isRecoveryModeActive(d)
|
|
a.populateGuestToolsDetail(&d)
|
|
a.populateGuestLangDetail(&d)
|
|
return d, nil
|
|
}
|
|
|
|
func (a *App) SetLocale(raw string) error {
|
|
a.mu.Lock()
|
|
defer a.mu.Unlock()
|
|
a.cfg.Locale = i18n.Normalize(raw)
|
|
return config.Save("", a.cfg)
|
|
}
|
|
|
|
func (a *App) SetAutoPinPCores(enabled bool) error {
|
|
a.mu.Lock()
|
|
defer a.mu.Unlock()
|
|
a.cfg.AutoPinPCores = enabled
|
|
return config.Save("", a.cfg)
|
|
}
|
|
|
|
func (a *App) SetMinimizeToTray(enabled bool) error {
|
|
a.mu.Lock()
|
|
v := enabled
|
|
a.cfg.MinimizeToTray = &v
|
|
err := config.Save("", a.cfg)
|
|
a.mu.Unlock()
|
|
return err
|
|
}
|
|
|
|
// ShowMainWindow restores and focuses the Wails window from the system tray.
|
|
func (a *App) ShowMainWindow() {
|
|
if a.ctx == nil {
|
|
return
|
|
}
|
|
wailsRuntime.WindowUnminimise(a.ctx)
|
|
wailsRuntime.WindowShow(a.ctx)
|
|
}
|
|
|
|
// RequestClose handles the custom titlebar close button: hides to system tray
|
|
// when MinimizeToTray is enabled, or quits the application otherwise.
|
|
func (a *App) RequestClose() {
|
|
if a.ctx == nil {
|
|
return
|
|
}
|
|
a.mu.Lock()
|
|
toTray := a.cfg.ShouldMinimizeToTray()
|
|
hasTray := a.trayMgr != nil
|
|
a.mu.Unlock()
|
|
if toTray && hasTray {
|
|
wailsRuntime.WindowHide(a.ctx)
|
|
return
|
|
}
|
|
a.QuitApp()
|
|
}
|
|
|
|
// QuitApp exits Reims-Go completely (bypassing minimize-to-tray).
|
|
func (a *App) QuitApp() {
|
|
a.mu.Lock()
|
|
a.allowQuit = true
|
|
a.mu.Unlock()
|
|
if a.ctx != nil {
|
|
wailsRuntime.Quit(a.ctx)
|
|
}
|
|
}
|
|
|
|
func (a *App) startTray() {
|
|
mgr, err := tray.Start(trayIconPNG, "Reims-Go", tray.Callbacks{
|
|
OnShow: func() {
|
|
a.ShowMainWindow()
|
|
},
|
|
OnStartVM: func(name string) {
|
|
_ = a.StartVM(name)
|
|
},
|
|
OnStopVM: func(name string) {
|
|
_ = a.StopVM(name, false)
|
|
},
|
|
OnOpenSharedDir: func(name string) {
|
|
_ = a.OpenSharedFolder(name)
|
|
},
|
|
OnQuit: func() {
|
|
a.QuitApp()
|
|
},
|
|
GetSnapshot: func() tray.Snapshot {
|
|
a.mu.Lock()
|
|
loc := a.cfg.Locale
|
|
cached := append([]reims.VMListItem(nil), a.lastVMs...)
|
|
a.mu.Unlock()
|
|
if len(cached) == 0 {
|
|
if vms, err := a.listVMsInternal(context.Background()); err == nil {
|
|
cached = vms
|
|
}
|
|
}
|
|
items := make([]tray.VMItem, 0, len(cached))
|
|
for _, vm := range cached {
|
|
items = append(items, tray.VMItem{
|
|
Name: vm.Name,
|
|
Running: vm.State == "running",
|
|
})
|
|
}
|
|
return tray.Snapshot{
|
|
LocaleZh: loc == i18n.ZhCN,
|
|
VMs: items,
|
|
}
|
|
},
|
|
})
|
|
if err != nil {
|
|
a.emitLog("app", "Warning: system tray unavailable: "+err.Error())
|
|
return
|
|
}
|
|
a.mu.Lock()
|
|
a.trayMgr = mgr
|
|
a.mu.Unlock()
|
|
}
|
|
|
|
func (a *App) SetDataRoot(dir string) error {
|
|
dir = strings.TrimSpace(dir)
|
|
if dir == "" {
|
|
return fmt.Errorf("data root cannot be empty")
|
|
}
|
|
a.mu.Lock()
|
|
a.cfg.DataRoot = dir
|
|
err := a.cfg.EnsureDirs()
|
|
if err == nil {
|
|
err = config.Save("", a.cfg)
|
|
}
|
|
if err == nil {
|
|
err = config.SaveLocation(dir)
|
|
}
|
|
a.mu.Unlock()
|
|
return err
|
|
}
|
|
|
|
func (a *App) PickDirectory(title string) (string, error) {
|
|
return wailsRuntime.OpenDirectoryDialog(a.ctx, wailsRuntime.OpenDialogOptions{
|
|
Title: title,
|
|
})
|
|
}
|
|
|
|
func (a *App) PickFile(title, pattern string) (string, error) {
|
|
opts := wailsRuntime.OpenDialogOptions{Title: title}
|
|
if pattern != "" {
|
|
opts.Filters = []wailsRuntime.FileFilter{{DisplayName: pattern, Pattern: pattern}}
|
|
}
|
|
return wailsRuntime.OpenFileDialog(a.ctx, opts)
|
|
}
|
|
|
|
func (a *App) EnableWHPX() error {
|
|
a.emitLog("host", "Requesting Windows UAC to enable HypervisorPlatform...")
|
|
return host.EnableWHPXElevated()
|
|
}
|
|
|
|
func (a *App) InstallRuntimeArchive(archivePath string) (*rt.Installed, error) {
|
|
a.mu.Lock()
|
|
cfg := a.cfg
|
|
a.mu.Unlock()
|
|
a.emitLog("runtime", "Installing portable runtime: "+archivePath)
|
|
inst, err := rt.InstallFromArchive(cfg, archivePath)
|
|
if err != nil {
|
|
a.emitLog("runtime", "Install failed: "+err.Error())
|
|
return nil, err
|
|
}
|
|
a.mu.Lock()
|
|
a.cfg.ActiveRuntime = inst.Commit
|
|
_ = config.Save("", a.cfg)
|
|
a.mu.Unlock()
|
|
a.emitLog("runtime", fmt.Sprintf("Runtime %s installed & activated -> %s", inst.Commit, inst.Dir))
|
|
return inst, nil
|
|
}
|
|
|
|
func (a *App) UseRuntime(commit string) error {
|
|
a.mu.Lock()
|
|
defer a.mu.Unlock()
|
|
a.cfg.ActiveRuntime = commit
|
|
return config.Save("", a.cfg)
|
|
}
|
|
|
|
func (a *App) ValidateCreate(opts reims.CreateOpts) []reims.ValidationIssue {
|
|
a.mu.Lock()
|
|
root := a.cfg.DataRoot
|
|
a.mu.Unlock()
|
|
issues := reims.ValidateCreate(opts, host.Inspect(root))
|
|
// reims-ctl refuses a name already registered; say so before the create runs.
|
|
if vms, err := a.listVMsInternal(context.Background()); err == nil {
|
|
for _, vm := range vms {
|
|
if strings.EqualFold(vm.Name, strings.TrimSpace(opts.Name)) {
|
|
issues = append(issues, reims.ValidationIssue{Field: "name", Code: "name_taken", Message: "A VM named " + vm.Name + " already exists"})
|
|
break
|
|
}
|
|
}
|
|
}
|
|
return issues
|
|
}
|
|
|
|
func (a *App) PreviewCreate(opts reims.CreateOpts) (string, error) {
|
|
return reims.PreviewCreateCommand(opts)
|
|
}
|
|
|
|
func (a *App) CreateVM(opts reims.CreateOpts) error {
|
|
return a.createVMFlow(opts)
|
|
}
|
|
|
|
func (a *App) ValidateSet(opts reims.SetOpts) ([]reims.ValidationIssue, error) {
|
|
cur, err := a.GetVMDetail(opts.Name)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
a.mu.Lock()
|
|
root := a.cfg.DataRoot
|
|
a.mu.Unlock()
|
|
return reims.ValidateSet(opts, cur, host.Inspect(root)), nil
|
|
}
|
|
|
|
func (a *App) ApplyVMSettings(opts reims.SetOpts) error {
|
|
cur, err := a.GetVMDetail(opts.Name)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
a.mu.Lock()
|
|
root := a.cfg.DataRoot
|
|
a.mu.Unlock()
|
|
if issues := reims.ValidateSet(opts, cur, host.Inspect(root)); len(issues) > 0 {
|
|
return fmt.Errorf("%s", issues[0].Message)
|
|
}
|
|
c, err := a.client()
|
|
if err != nil {
|
|
return err
|
|
}
|
|
w := vmstart.LineWriter(func(line string) { a.emitLog(opts.Name, line) })
|
|
if reims.HasCtlSetChanges(opts) {
|
|
if err := c.Set(context.Background(), opts, w, w); err != nil {
|
|
a.emitLog(opts.Name, "Set error: "+err.Error())
|
|
return err
|
|
}
|
|
}
|
|
guestLangChanged := strings.TrimSpace(opts.GuestLang) != "" && strings.TrimSpace(opts.GuestLang) != cur.GuestLang
|
|
if guestLangChanged {
|
|
prep, err := a.prep(opts.Name)
|
|
if err == nil {
|
|
err = prep.ApplyGuestLang(context.Background(), cur.Directory, opts.GuestLang, cur.State == "running")
|
|
}
|
|
if err != nil {
|
|
a.emitLog(opts.Name, "Guest language error: "+err.Error())
|
|
return err
|
|
}
|
|
} else if cur.State != "running" && opts.Graphics != "" && opts.Graphics != cur.Graphics {
|
|
// Switching graphics rebuilds opencore.qcow2; replay any saved prev-lang:kbd.
|
|
if prep, err := a.prep(opts.Name); err == nil {
|
|
prep.ReplayGuestLang(context.Background(), cur.Directory)
|
|
}
|
|
}
|
|
if cur.State == "running" {
|
|
var diffs []PendingChange
|
|
if opts.CPUs > 0 && opts.CPUs != cur.CPUs {
|
|
diffs = append(diffs, PendingChange{Field: "cpus", From: fmt.Sprintf("%d", cur.CPUs), To: fmt.Sprintf("%d", opts.CPUs)})
|
|
}
|
|
if opts.Memory != "" && !strings.EqualFold(opts.Memory, cur.Memory) {
|
|
diffs = append(diffs, PendingChange{Field: "memory", From: cur.Memory, To: opts.Memory})
|
|
}
|
|
if opts.Resolution != "" && opts.Resolution != cur.Resolution {
|
|
diffs = append(diffs, PendingChange{Field: "resolution", From: cur.Resolution, To: opts.Resolution})
|
|
}
|
|
if opts.GPU != "" && opts.GPU != cur.GPU {
|
|
diffs = append(diffs, PendingChange{Field: "gpu", From: cur.GPU, To: opts.GPU})
|
|
}
|
|
if opts.Displays > 0 && opts.Displays != cur.Displays {
|
|
diffs = append(diffs, PendingChange{Field: "displays", From: fmt.Sprintf("%d", cur.Displays), To: fmt.Sprintf("%d", opts.Displays)})
|
|
}
|
|
if opts.Borderless != nil && *opts.Borderless != cur.Borderless {
|
|
diffs = append(diffs, PendingChange{Field: "borderless", From: fmt.Sprintf("%v", cur.Borderless), To: fmt.Sprintf("%v", *opts.Borderless)})
|
|
}
|
|
if opts.Audio != nil && *opts.Audio != cur.Audio {
|
|
diffs = append(diffs, PendingChange{Field: "audio", From: fmt.Sprintf("%v", cur.Audio), To: fmt.Sprintf("%v", *opts.Audio)})
|
|
}
|
|
if opts.AudioBackend != "" && opts.AudioBackend != cur.AudioBackend {
|
|
from := cur.AudioBackend
|
|
if from == "" {
|
|
from = "auto"
|
|
}
|
|
diffs = append(diffs, PendingChange{Field: "audio_backend", From: from, To: opts.AudioBackend})
|
|
}
|
|
if guestLangChanged {
|
|
from := cur.GuestLang
|
|
if from == "" {
|
|
from = "en-US:0"
|
|
}
|
|
diffs = append(diffs, PendingChange{Field: "guest_lang", From: from, To: strings.TrimSpace(opts.GuestLang)})
|
|
}
|
|
if len(diffs) > 0 {
|
|
a.mu.Lock()
|
|
a.pendingChanges[opts.Name] = append(a.pendingChanges[opts.Name], diffs...)
|
|
a.mu.Unlock()
|
|
}
|
|
}
|
|
a.emitLog(opts.Name, "Updated VM settings for "+opts.Name)
|
|
wailsRuntime.EventsEmit(a.ctx, "reims:state-changed", true)
|
|
return nil
|
|
}
|
|
|
|
func (a *App) cancelRebootWatcher(name string) {
|
|
a.mu.Lock()
|
|
if entry, ok := a.rebootWatchers[name]; ok {
|
|
entry.cancel()
|
|
delete(a.rebootWatchers, name)
|
|
}
|
|
a.mu.Unlock()
|
|
}
|
|
|
|
func (a *App) watchWin10ColdReboot(name, qmpAddr string) {
|
|
a.cancelRebootWatcher(name)
|
|
baseCtx := a.ctx
|
|
if baseCtx == nil {
|
|
baseCtx = context.Background()
|
|
}
|
|
watchCtx, cancel := context.WithCancel(baseCtx)
|
|
a.mu.Lock()
|
|
a.nextWatcherID++
|
|
myID := a.nextWatcherID
|
|
a.rebootWatchers[name] = rebootWatcherEntry{id: myID, cancel: cancel}
|
|
a.mu.Unlock()
|
|
|
|
go func() {
|
|
defer func() {
|
|
cancel()
|
|
a.mu.Lock()
|
|
if cur, ok := a.rebootWatchers[name]; ok && cur.id == myID {
|
|
delete(a.rebootWatchers, name)
|
|
}
|
|
a.mu.Unlock()
|
|
}()
|
|
|
|
reason, err := qmp.WatchShutdownReason(watchCtx, qmpAddr)
|
|
if err != nil {
|
|
if watchCtx.Err() == nil {
|
|
a.emitLog(name, "Win10 WHPX cold-reboot monitor disconnected: "+err.Error())
|
|
}
|
|
return
|
|
}
|
|
if reason != "guest-reset" {
|
|
if reason != "" {
|
|
a.emitLog(name, "Win10 WHPX cold-reboot: VM exited ("+reason+"), not restarting")
|
|
}
|
|
return
|
|
}
|
|
a.mu.Lock()
|
|
tr := a.transitions[name]
|
|
a.mu.Unlock()
|
|
if tr == "stopping" {
|
|
return
|
|
}
|
|
|
|
a.emitLog(name, "Win10 WHPX cold-reboot: guest requested reboot (guest-reset), restarting in a fresh Hyper-V partition...")
|
|
c, err := a.client()
|
|
if err != nil {
|
|
a.emitLog(name, "Win10 WHPX cold-reboot aborted: "+err.Error())
|
|
return
|
|
}
|
|
// Wait briefly for QEMU to finish exiting cleanly under -no-reboot.
|
|
deadline := time.Now().Add(12 * time.Second)
|
|
for time.Now().Before(deadline) {
|
|
if watchCtx.Err() != nil {
|
|
return
|
|
}
|
|
vms, err := c.List(watchCtx)
|
|
if err == nil {
|
|
stopped := false
|
|
for _, vm := range vms {
|
|
if vm.Name == name && vm.State == "stopped" {
|
|
stopped = true
|
|
break
|
|
}
|
|
}
|
|
if stopped {
|
|
break
|
|
}
|
|
}
|
|
time.Sleep(300 * time.Millisecond)
|
|
}
|
|
if watchCtx.Err() != nil {
|
|
return
|
|
}
|
|
if err := a.StartVM(name); err != nil {
|
|
a.emitLog(name, "Win10 WHPX cold-reboot start failed: "+err.Error())
|
|
}
|
|
}()
|
|
}
|
|
|
|
func (a *App) StartVM(name string) error {
|
|
prep, err := a.prep(name)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
c := prep.Client
|
|
a.mu.Lock()
|
|
root := a.cfg.DataRoot
|
|
tmpDir := a.cfg.TempDir()
|
|
a.mu.Unlock()
|
|
rep := host.Inspect(root)
|
|
curDetail, _ := c.Show(context.Background(), name)
|
|
if err := prep.CheckMemory(curDetail.Memory, rep); err != nil {
|
|
a.emitLog(name, "Start refused: "+err.Error())
|
|
return err
|
|
}
|
|
a.cancelRebootWatcher(name)
|
|
|
|
a.syncGuestTools(c, name, &curDetail)
|
|
if env := a.inputBridgeEnv(name, curDetail.Directory); len(env) > 0 {
|
|
c.Env = append(c.Env, env...)
|
|
}
|
|
prep.Prepare(context.Background(), name, rep, &curDetail)
|
|
var qmpAddr string
|
|
if rep.NeedsColdRebootWorkaround {
|
|
sockPath := qmp.RebootSocketPath(curDetail.Directory, tmpDir, name)
|
|
_ = os.MkdirAll(filepath.Dir(sockPath), 0o755)
|
|
_ = os.Remove(sockPath)
|
|
merged := qmp.MergeWin10RebootUnixArgs(curDetail.ExtraArgs, sockPath)
|
|
if err := c.Set(context.Background(), reims.SetOpts{Name: name, ExtraArgs: &merged}, io.Discard, io.Discard); err != nil {
|
|
a.emitLog(name, "Win10 cold-reboot extra-args setup skipped: "+err.Error())
|
|
} else {
|
|
qmpAddr = "unix:" + sockPath
|
|
curDetail.ExtraArgs = merged
|
|
}
|
|
}
|
|
|
|
a.mu.Lock()
|
|
a.transitions[name] = "starting"
|
|
delete(a.pendingChanges, name)
|
|
a.mu.Unlock()
|
|
wailsRuntime.EventsEmit(a.ctx, "reims:state-changed", true)
|
|
|
|
startAt := time.Now()
|
|
a.emitStartSummary(name, curDetail, rep, qmpAddr)
|
|
w := vmstart.LineWriter(func(line string) { a.emitLog(name, line) })
|
|
a.emitLog(name, "Starting "+name+"...")
|
|
if err := c.StartWithCompat(context.Background(), name, w, w, func(msg string) {
|
|
a.emitLog(name, msg)
|
|
}); err != nil {
|
|
a.mu.Lock()
|
|
delete(a.transitions, name)
|
|
a.mu.Unlock()
|
|
a.emitLog(name, "Start error: "+err.Error())
|
|
wailsRuntime.EventsEmit(a.ctx, "reims:state-changed", true)
|
|
return err
|
|
}
|
|
if qmpAddr != "" {
|
|
a.watchWin10ColdReboot(name, qmpAddr)
|
|
}
|
|
a.startVMMonitor(name, curDetail, startAt)
|
|
wailsRuntime.EventsEmit(a.ctx, "reims:state-changed", true)
|
|
return nil
|
|
}
|
|
|
|
func (a *App) StopVM(name string, force bool) error {
|
|
c, err := a.client()
|
|
if err != nil {
|
|
return err
|
|
}
|
|
a.cancelRebootWatcher(name)
|
|
stopVMMonitor(name)
|
|
a.mu.Lock()
|
|
a.transitions[name] = "stopping"
|
|
a.mu.Unlock()
|
|
wailsRuntime.EventsEmit(a.ctx, "reims:state-changed", true)
|
|
|
|
w := vmstart.LineWriter(func(line string) { a.emitLog(name, line) })
|
|
a.emitLog(name, fmt.Sprintf("Stopping %s (force=%v)...", name, force))
|
|
if force {
|
|
err = c.StopForce(context.Background(), name, w, w)
|
|
} else {
|
|
err = c.Stop(context.Background(), name, w, w)
|
|
}
|
|
if err != nil {
|
|
a.mu.Lock()
|
|
delete(a.transitions, name)
|
|
a.mu.Unlock()
|
|
a.emitLog(name, "Stop error: "+err.Error())
|
|
return err
|
|
}
|
|
a.mu.Lock()
|
|
delete(a.pendingChanges, name)
|
|
a.mu.Unlock()
|
|
wailsRuntime.EventsEmit(a.ctx, "reims:state-changed", true)
|
|
return nil
|
|
}
|
|
|
|
func (a *App) RestartVM(name string) error {
|
|
if err := a.StopVM(name, false); err != nil {
|
|
return err
|
|
}
|
|
return a.StartVM(name)
|
|
}
|
|
|
|
func (a *App) EjectInstaller(name string) error {
|
|
c, err := a.client()
|
|
if err != nil {
|
|
return err
|
|
}
|
|
w := vmstart.LineWriter(func(line string) { a.emitLog(name, line) })
|
|
a.emitLog(name, "Ejecting installer from "+name+"...")
|
|
if err := c.Eject(context.Background(), name, w, w); err != nil {
|
|
a.emitLog(name, "Eject error: "+err.Error())
|
|
return err
|
|
}
|
|
a.emitLog(name, "Installer ejected.")
|
|
wailsRuntime.EventsEmit(a.ctx, "reims:state-changed", true)
|
|
return nil
|
|
}
|
|
|
|
func (a *App) DeleteVM(name string, keepFiles bool) error {
|
|
c, err := a.client()
|
|
if err != nil {
|
|
return err
|
|
}
|
|
a.cancelRebootWatcher(name)
|
|
stopVMMonitor(name)
|
|
w := vmstart.LineWriter(func(line string) { a.emitLog(name, line) })
|
|
a.emitLog(name, fmt.Sprintf("Deleting VM %s (keepFiles=%v)...", name, keepFiles))
|
|
if err := c.Delete(context.Background(), name, keepFiles, w, w); err != nil {
|
|
a.emitLog(name, "Delete error: "+err.Error())
|
|
return err
|
|
}
|
|
a.mu.Lock()
|
|
delete(a.pendingChanges, name)
|
|
delete(a.transitions, name)
|
|
a.mu.Unlock()
|
|
wailsRuntime.EventsEmit(a.ctx, "reims:state-changed", true)
|
|
return nil
|
|
}
|
|
|
|
// OpenVMFolder shows the VM's directory in File Explorer.
|
|
func (a *App) OpenVMFolder(name string) error {
|
|
d, err := a.GetVMDetail(name)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
if d.Directory == "" {
|
|
return fmt.Errorf("VM %s has no directory", name)
|
|
}
|
|
return host.OpenFolder(d.Directory)
|
|
}
|
|
|
|
func (a *App) ReadVMLogs(name string, serial bool) (string, error) {
|
|
c, err := a.client()
|
|
if err != nil {
|
|
return "", err
|
|
}
|
|
return c.ReadLogs(context.Background(), name, serial)
|
|
}
|