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

1602 lines
46 KiB
Go

package app
import (
"context"
"errors"
"fmt"
"io"
"maps"
"os"
"path/filepath"
"strings"
"sync"
"time"
"github.com/Nwflower/reims-go/internal/cli"
"github.com/Nwflower/reims-go/internal/config"
"github.com/Nwflower/reims-go/internal/driver"
"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/installguide"
"github.com/Nwflower/reims-go/internal/plugin"
"github.com/Nwflower/reims-go/internal/plugin/builtin"
"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"
"github.com/wailsapp/wails/v2/pkg/options"
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"`
ActiveGuides []string `json:"active_guides,omitempty"`
// InstallGuideEnabled is true while the builtin.install-guide plugin is active.
InstallGuideEnabled bool `json:"install_guide_enabled,omitempty"`
// NeedsSetup is true on first launch, until a data folder is chosen (setup.go).
NeedsSetup bool `json:"needs_setup"`
AppVersion string `json:"app_version"`
SafeMode bool `json:"safe_mode,omitempty"`
PluginCrashDetected bool `json:"plugin_crash_detected,omitempty"`
DetectedLocale string `json:"detected_locale,omitempty"`
EffectiveLocale string `json:"effective_locale,omitempty"`
MissingFontHint string `json:"missing_font_hint,omitempty"`
}
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
lastVMsAt time.Time // when pollVMs last refreshed lastVMs; zero = stale
pollWake chan struct{} // wakePoll: run pollVMs now instead of at its next tick
diskPaths map[string]cachedDiskPath
procSamples map[string]host.ProcessSample
recentLogs []string
needsSetup bool
launch cli.WindowArgs // flags this window was started with (window_launch.go)
trayIcon []byte // embedded PNG passed in from package main
logCaptures map[string][]*logCapture // emitLog source → captures (window_launch.go)
pluginMgr *plugin.Manager
pluginMarket *plugin.MarketClient
driverRouter *driver.Router
runtimeKinds *rt.KindRegistry
uiHealth uiHealthState
themeMode installguide.Theme
}
// Lifecycle exposes Wails lifecycle callbacks without exporting them as
// frontend-bound methods on *App.
type Lifecycle struct {
OnStartup func(context.Context)
OnBeforeClose func(context.Context) bool
OnShutdown func(context.Context)
OnSecondInstanceLaunch func(options.SecondInstanceData)
OnSuspend func()
OnResume func()
}
func New(trayIcon []byte, launch cli.WindowArgs) (*App, Lifecycle) {
i18n.SetDetailRedactor(reims.RedactText)
cfg, needsSetup, err := config.Resolve()
if err != nil {
cfg = config.Default()
}
a := &App{
cfg: cfg,
needsSetup: needsSetup,
launch: launch,
trayIcon: trayIcon,
transitions: make(map[string]string),
pendingChanges: make(map[string][]PendingChange),
rebootWatchers: make(map[string]rebootWatcherEntry),
pollWake: make(chan struct{}, 1),
diskPaths: make(map[string]cachedDiskPath),
procSamples: make(map[string]host.ProcessSample),
uiHealth: uiHealthState{windowHidden: launch.Background},
}
return a, Lifecycle{
OnStartup: a.startup,
OnBeforeClose: a.beforeClose,
OnShutdown: a.shutdown,
OnSecondInstanceLaunch: a.onSecondInstance,
OnSuspend: a.onSystemSuspend,
OnResume: a.onSystemResume,
}
}
func (a *App) startup(ctx context.Context) {
a.ctx = ctx
pollCtx, cancel := context.WithCancel(ctx)
a.stopPoll = cancel
a.bindGuideEvents(ctx)
a.startTray()
a.initPlugins()
// Without a plugin manager, run the IME bridge and Guest Tools directly.
// With one, their plugins own them, and a plugin switched off stays off.
a.mu.Lock()
pluginsUp := a.pluginMgr != nil
a.mu.Unlock()
if !pluginsUp {
a.startIMEBridge()
go a.registerExistingGuestTools(pollCtx)
}
go a.finishAppUpdate()
a.startUIHealthWatchdog(pollCtx)
go a.pollVMs(pollCtx)
a.afterStartup()
}
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 {
a.setWindowHidden(true)
wailsRuntime.WindowHide(ctx)
return true
}
return false
}
func (a *App) shutdown(ctx context.Context) {
if a.stopPoll != nil {
a.stopPoll()
}
tasks.cancelAll()
stopAllVMMonitors()
a.shutdownPlugins()
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()
}
releaseVMTyping("")
}
// pollVMs refreshes the VM list every pollBusy while a VM is starting or
// stopping and every pollSteady otherwise; each tick runs one `reims-ctl list`.
// Start, stop and delete call wakePoll so their result shows up at once.
const (
pollBusy = 2 * time.Second
// Exits are caught at once by watchExits and GUI actions call wakePoll, so
// the steady tick only has to notice VMs started or removed elsewhere (CLI).
pollSteady = 10 * time.Second
// polledMaxAge is how old lastVMs may be for polledVMs to reuse it. It sits
// above pollSteady so a poll that runs a little late still counts.
polledMaxAge = pollSteady + 3*time.Second
)
func (a *App) pollVMs(ctx context.Context) {
timer := time.NewTimer(pollBusy)
defer timer.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)
guideCheckedPIDs := make(map[int]bool)
var lastGuideMgr *installguide.Manager
exitWatched := make(map[int]bool)
for {
select {
case <-ctx.Done():
return
case <-timer.C:
case <-a.pollWake:
}
a.mu.Lock()
next := pollSteady
if len(a.transitions) > 0 {
next = pollBusy
}
a.mu.Unlock()
timer.Reset(next)
c, err := a.client()
if err != nil {
continue
}
vms, err := c.List(ctx)
if err != nil {
continue
}
watchExits(ctx, vms, exitWatched, a.wakePoll)
type pinCandidate struct {
name string
dir string
pid int
}
var toPin []pinCandidate
a.mu.Lock()
loc := a.cfg.Locale
autoPin := a.cfg.AutoPinPCores
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 vm.State == "running" && vm.PID != nil && *vm.PID > 0 && !pinnedPIDs[*vm.PID] {
pinnedPIDs[*vm.PID] = true
toPin = append(toPin, pinCandidate{name: vm.Name, dir: vm.Dir, pid: *vm.PID})
}
fmt.Fprintf(&b, "%s:%s:%s;", vm.Name, vm.State, a.transitions[vm.Name])
}
sig := b.String()
ib := a.imeBridge
liveVMs := make(map[string]struct{}, len(vms))
for _, vm := range vms {
liveVMs[vm.Name] = struct{}{}
}
removedVMs := make(map[string]struct{})
for _, vm := range a.lastVMs {
if _, ok := liveVMs[vm.Name]; !ok {
removedVMs[vm.Name] = struct{}{}
}
}
for name := range a.rebootWatchers {
if _, ok := liveVMs[name]; !ok {
removedVMs[name] = struct{}{}
}
}
for name := range a.diskPaths {
if _, ok := liveVMs[name]; !ok {
removedVMs[name] = struct{}{}
}
}
for name := range a.procSamples {
if _, ok := liveVMs[name]; !ok {
removedVMs[name] = struct{}{}
}
}
maps.DeleteFunc(a.diskPaths, func(name string, _ cachedDiskPath) bool {
_, ok := liveVMs[name]
return !ok
})
maps.DeleteFunc(a.procSamples, func(name string, _ host.ProcessSample) bool {
_, ok := liveVMs[name]
return !ok
})
gt := a.guestTools
a.lastVMs = append([]reims.VMListItem(nil), vms...)
a.lastVMsAt = time.Now()
a.mu.Unlock()
prunePinnedPIDs(pinnedPIDs, vms)
prunePinnedPIDs(guideCheckedPIDs, vms)
guideMgr := a.getInstallGuideManager()
if guideMgr != lastGuideMgr {
clear(guideCheckedPIDs)
lastGuideMgr = guideMgr
}
runningPIDs := make(map[int]bool, len(vms))
for _, vm := range vms {
if vm.State == "running" && vm.PID != nil && *vm.PID > 0 {
runningPIDs[*vm.PID] = true
}
}
guidesChanged := false
if guideMgr != nil {
guidesChanged = guideMgr.CancelStopped(runningPIDs)
}
for name := range removedVMs {
a.mu.Lock()
delete(a.transitions, name)
delete(a.pendingChanges, name)
a.mu.Unlock()
stopVMMonitor(name)
a.cancelRebootWatcher(name)
releaseVMTyping(name)
releaseVMThumbnail(name)
if gt != nil {
gt.UnregisterVM(name)
}
}
if ib != nil {
ib.SetTargets(imeTargets)
}
a.syncInputTargets(imeTargets)
if tm != nil {
effLoc := i18n.EffectiveLocale(loc)
if runningCount >= 1 {
tm.UpdateTooltip(i18n.M(effLoc, "tray.running", i18n.Vars{"count": runningCount}))
} else {
tm.UpdateTooltip("Reims-Go")
}
}
shownDetails := make(map[string]reims.VMDetail, len(toPin))
for _, cand := range toPin {
det, err := c.Show(ctx, cand.name)
if err != nil {
// Retry boot discovery if the runtime was still starting.
delete(pinnedPIDs, cand.pid)
continue
}
vmDir := cand.dir
if vmDir == "" {
vmDir = det.Directory
}
if det.Directory == "" {
det.Directory = vmDir
}
shownDetails[cand.name] = det
if line, _ := vmstart.ApplyVMAffinity(loc, cachedHost, vmDir, autoPin, cand.pid, det.CPUs, false); line != "" {
a.emitLog(cand.name, line)
}
}
if guideMgr != nil {
for _, vm := range vms {
if vm.State != "running" || vm.PID == nil || *vm.PID <= 0 {
continue
}
pid := *vm.PID
if guideCheckedPIDs[pid] {
continue
}
det, ok := shownDetails[vm.Name]
if !ok {
d, err := c.Show(ctx, vm.Name)
if err != nil {
continue
}
if d.Directory == "" {
d.Directory = vm.Dir
}
det = d
}
guideCheckedPIDs[pid] = true
if a.maybeStartInstallGuide(ctx, guideMgr, vm.Name, pid, det, loc) {
guidesChanged = true
}
}
}
if sig != lastSig || guidesChanged {
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)
}
// qemuImage is the executable reims-ctl reports as a running VM's PID.
const qemuImage = "qemu-system-x86_64.exe"
// watchExits waits on every running VM's QEMU process not yet watched and
// calls onExit the moment one exits, so a VM that stops by itself (macOS shut
// down, QEMU quit or crashed) shows as stopped at once instead of at the next
// steady poll. watched holds the PIDs being waited on; PIDs no longer running
// are dropped so a reused PID is watched again.
func watchExits(ctx context.Context, vms []reims.VMListItem, watched map[int]bool, onExit func()) {
running := make(map[int]bool, len(vms))
for _, vm := range vms {
if vm.State != "running" || vm.PID == nil || *vm.PID <= 0 {
continue
}
pid := *vm.PID
running[pid] = true
if watched[pid] {
continue
}
watched[pid] = true
go func() {
if err := host.WaitProcessExit(ctx, uint32(pid), qemuImage); err == nil {
onExit()
}
}()
}
for pid := range watched {
if !running[pid] {
delete(watched, pid)
}
}
}
func prunePinnedPIDs(pinned map[int]bool, vms []reims.VMListItem) {
running := make(map[int]struct{}, len(vms))
for _, vm := range vms {
if vm.State == "running" && vm.PID != nil && *vm.PID > 0 {
running[*vm.PID] = struct{}{}
}
}
for pid := range pinned {
if _, ok := running[pid]; !ok {
delete(pinned, pid)
}
}
}
// polledVMs returns the list pollVMs saw last if it is at most polledMaxAge
// old, so per-VM samplers (stats, thumbnails, heartbeats) don't each spawn
// their own `reims-ctl list`. A stale or missing poll falls back to one.
func (a *App) polledVMs(ctx context.Context) ([]reims.VMListItem, error) {
a.mu.Lock()
if !a.lastVMsAt.IsZero() && time.Since(a.lastVMsAt) <= polledMaxAge {
vms := append([]reims.VMListItem(nil), a.lastVMs...)
a.mu.Unlock()
return vms, nil
}
a.mu.Unlock()
return a.listVMsInternal(ctx)
}
// polledVM looks name up in polledVMs.
func (a *App) polledVM(name string) (reims.VMListItem, bool) {
vms, err := a.polledVMs(context.Background())
if err != nil {
return reims.VMListItem{}, false
}
for _, vm := range vms {
if vm.Name == name {
return vm, true
}
}
return reims.VMListItem{}, false
}
// wakePoll marks the polled list stale and runs pollVMs now. Call it after
// anything that changes which VMs exist or run.
func (a *App) wakePoll() {
a.mu.Lock()
a.lastVMsAt = time.Time{}
a.mu.Unlock()
select {
case a.pollWake <- struct{}{}:
default:
}
}
// cachedDiskPath is one VM's disk path from `reims-ctl show`, kept for
// diskPathTTL so GetVMStats doesn't run `show` every few seconds.
type cachedDiskPath struct {
path string
at time.Time
}
const diskPathTTL = time.Minute
// vmDiskPath resolves name's disk image path, reusing a recent answer. The
// path only changes through `reims-ctl set`, so at worst the disk-usage
// figure follows such a change a minute late.
func (a *App) vmDiskPath(ctx context.Context, c *reims.Client, name string) string {
a.mu.Lock()
cur, ok := a.diskPaths[name]
a.mu.Unlock()
if ok && time.Since(cur.at) < diskPathTTL {
return cur.path
}
d, err := c.Show(ctx, name)
if err != nil {
return ""
}
path := resolveVMDiskPath(d)
a.mu.Lock()
a.diskPaths[name] = cachedDiskPath{path: path, at: time.Now()}
a.mu.Unlock()
return path
}
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:]
}
for _, c := range a.logCaptures[source] {
c.add(redacted)
}
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.noteUIAlive()
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)
// The poller's list (≤ polledMaxAge old, and invalidated by wakePoll after
// start/stop/delete) instead of another `reims-ctl list` per refresh.
vms, _ := a.polledVMs(context.Background())
var activePatches []string
if active != nil {
for _, p := range active.Manifest.Patches {
activePatches = append(activePatches, p.Name)
}
}
opts := host.EvaluateOptimizations(rep, activePatches)
a.mu.Lock()
mgr := a.pluginMgr
a.mu.Unlock()
safeMode := a.launch.SafeMode
crashDetected := false
if mgr != nil {
safeMode = mgr.SafeMode()
crashDetected = mgr.CrashDetected()
}
guideMgr := a.getInstallGuideManager()
installGuideEnabled := guideMgr != nil
var activeGuides []string
if guideMgr != nil {
activeGuides = guideMgr.ActiveNames()
}
return AppState{
Config: &cfgCopy,
Host: rep,
Optimizations: opts,
Runtimes: runtimes,
ActiveRuntime: active,
VMs: vms,
Transitions: trCopy,
PendingChanges: pcCopy,
ActiveGuides: activeGuides,
InstallGuideEnabled: installGuideEnabled,
NeedsSetup: needsSetup,
AppVersion: version.Version,
SafeMode: safeMode,
PluginCrashDetected: crashDetected,
DetectedLocale: string(i18n.DetectOSLocaleTag()),
EffectiveLocale: string(i18n.EffectiveLocale(cfgCopy.Locale)),
MissingFontHint: host.CheckMissingLocaleFontsForUI(string(i18n.EffectiveLocale(cfgCopy.Locale)), i18n.EffectiveLocale(cfgCopy.Locale)),
}
}
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()
a.cfg.Locale = i18n.ParsePreference(raw)
err := config.Save("", a.cfg)
eff := i18n.EffectiveLocale(a.cfg.Locale)
mgr := a.pluginMgr
a.mu.Unlock()
if mgr != nil {
mgr.NotifyLocaleChanged(eff)
}
if a.ctx != nil {
wailsRuntime.EventsEmit(a.ctx, "reims:state-changed", true)
}
return err
}
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
}
a.setWindowHidden(false)
wailsRuntime.WindowUnminimise(a.ctx)
wailsRuntime.WindowShow(a.ctx)
a.scheduleUIHealthProbe("window restore", 1500*time.Millisecond)
}
// 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 {
a.setWindowHidden(true)
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(a.trayIcon, "Reims-Go", tray.Callbacks{
OnShow: func() {
a.ShowMainWindow()
},
OnNewVM: func() {
a.ShowMainWindow()
if a.ctx != nil {
wailsRuntime.EventsEmit(a.ctx, "reims:tray-new-vm")
}
},
OnVMAction: a.trayVMAction,
OnQuit: func() {
a.QuitApp()
},
GetSnapshot: func() tray.Snapshot {
a.mu.Lock()
loc := a.cfg.Locale
cached := append([]reims.VMListItem(nil), a.lastVMs...)
transitions := make(map[string]string, len(a.transitions))
for k, v := range a.transitions {
transitions[k] = v
}
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 {
state := vm.State
if t := transitions[vm.Name]; t != "" {
state = t
}
// The display name is the VM's note, read straight from its
// folder (no reims-ctl call while the menu is opening).
label := ""
if vm.Dir != "" {
if b, err := os.ReadFile(filepath.Join(vm.Dir, vmNoteFileName)); err == nil {
label = sanitizeVMNote(string(b))
}
}
items = append(items, tray.VMItem{Name: vm.Name, Label: label, State: state})
}
effLoc := i18n.EffectiveLocale(loc)
return tray.Snapshot{
Locale: effLoc,
LocaleZh: effLoc == 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()
}
// trayVMAction runs a command picked from the tray menu. The main window may
// be hidden, so failures (and a copied screenshot, which has no other visible
// result) are reported as a Windows notification from the tray icon.
func (a *App) trayVMAction(name string, act tray.Action) {
a.mu.Lock()
rawLoc := a.cfg.Locale
tm := a.trayMgr
a.mu.Unlock()
loc := i18n.EffectiveLocale(rawLoc)
vars := i18n.Vars{"name": name}
var err error
var failTitle string
switch act {
case tray.ActStart:
err, failTitle = a.StartVM(name), i18n.M(loc, "tray.notify.start_fail", vars)
case tray.ActStop:
err, failTitle = a.StopVM(name, false), i18n.M(loc, "tray.notify.stop_fail", vars)
case tray.ActForceStop:
err, failTitle = a.StopVM(name, true), i18n.M(loc, "tray.notify.force_stop_fail", vars)
case tray.ActRestart:
err, failTitle = a.RestartVM(name), i18n.M(loc, "tray.notify.restart_fail", vars)
case tray.ActShowWindow:
err, failTitle = a.FocusVMWindow(name), i18n.M(loc, "tray.notify.focus_fail", vars)
case tray.ActScreenshot:
if err = a.CopyVMScreenshot(name); err == nil && tm != nil {
tm.Notify(i18n.T(loc, "tray.notify.screenshot_ok"), name, false)
}
failTitle = i18n.M(loc, "tray.notify.screenshot_fail", vars)
case tray.ActSharedFolder:
err, failTitle = a.OpenSharedFolder(name), i18n.T(loc, "tray.notify.shared_fail")
case tray.ActOpenInApp:
a.ShowMainWindow()
if a.ctx != nil {
wailsRuntime.EventsEmit(a.ctx, "reims:tray-select-vm", name)
}
}
if err != nil {
a.emitLog(name, failTitle+": "+err.Error())
if tm != nil {
tm.Notify(failTitle, err.Error(), true)
}
}
}
func (a *App) resetDataRootCaches() {
a.mu.Lock()
a.lastVMs = nil
a.lastVMsAt = time.Time{}
a.diskPaths = make(map[string]cachedDiskPath)
a.procSamples = make(map[string]host.ProcessSample)
a.mu.Unlock()
}
func (a *App) SetDataRoot(dir string) error {
a.mu.Lock()
loc := i18n.EffectiveLocale(a.cfg.Locale)
prev := a.cfg.DataRoot
curLocalePref := a.cfg.Locale
curAutoPin := a.cfg.AutoPinPCores
curRuntimeChannel := a.cfg.RuntimeChannel
curAppUpdateChannel := a.cfg.AppUpdateChannel
curMinToTray := a.cfg.MinimizeToTray
for _, v := range a.lastVMs {
if v.State == "running" || v.State == "starting" || v.State == "stopping" {
a.mu.Unlock()
return i18n.NewCodedError(loc, "E_DATAROOT_BUSY_VMS", "err.dataroot.busy_vms", nil, nil)
}
}
a.mu.Unlock()
for _, t := range tasks.list() {
if t.Status == TaskRunning {
return i18n.NewCodedError(loc, "E_DATAROOT_BUSY_TASKS", "err.dataroot.busy_tasks", nil, nil)
}
}
dir = strings.TrimSpace(dir)
if dir != "" {
dir = filepath.Clean(dir)
}
if err := validateDataRoot(dir, loc); err != nil {
return err
}
cfgPath := filepath.Join(dir, "reims-go.json")
nextCfg, err := config.Load(cfgPath)
if err != nil {
return fmt.Errorf("read %s: %w", cfgPath, err)
}
nextCfg.DataRoot = dir
if _, statErr := os.Stat(cfgPath); statErr != nil {
nextCfg.Locale = curLocalePref
nextCfg.AutoPinPCores = curAutoPin
nextCfg.RuntimeChannel = curRuntimeChannel
nextCfg.AppUpdateChannel = curAppUpdateChannel
nextCfg.MinimizeToTray = curMinToTray
}
if err := nextCfg.EnsureDirs(); err != nil {
return err
}
if err := writable(dir); err != nil {
return err
}
if err := config.Save(cfgPath, nextCfg); err != nil {
return err
}
if err := config.SaveLocation(dir); err != nil {
return err
}
a.mu.Lock()
a.cfg = nextCfg
a.mu.Unlock()
if filepath.Clean(prev) != filepath.Clean(dir) {
a.resetDataRootCaches()
a.reloadPlugins()
a.wakePoll()
if a.ctx != nil {
wailsRuntime.EventsEmit(a.ctx, "reims:state-changed", true)
}
}
return nil
}
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()
}
// OpenProcessorScheduling opens Windows' Performance Options as administrator
// (one UAC prompt) for the processor scheduling choice. Declining the prompt
// is not an error.
func (a *App) OpenProcessorScheduling() error {
a.emitLog("host", "Requesting Windows UAC to open Performance Options (processor scheduling)...")
err := host.OpenPerformanceOptionsElevated()
if errors.Is(err, host.ErrElevationDeclined) {
a.emitLog("host", "UAC prompt declined; Performance Options not opened")
return nil
}
return err
}
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) RemoveRuntime(commit string) error {
a.mu.Lock()
cfg := a.cfg
loc := i18n.EffectiveLocale(a.cfg.Locale)
ctx := a.ctx
a.mu.Unlock()
inst, err := rt.Remove(cfg, commit)
if err != nil {
switch {
case errors.Is(err, rt.ErrNotFound):
return errors.New(i18n.T(loc, "runtime.not_found", commit))
case errors.Is(err, rt.ErrRemoveActive):
return errors.New(i18n.T(loc, "runtime.remove_active", commit))
case errors.Is(err, rt.ErrRuntimeInUse):
return errors.New(i18n.T(loc, "runtime.remove_in_use", commit))
default:
return err
}
}
a.emitLog("runtime", fmt.Sprintf("Removed runtime %s (%s)", inst.Commit, inst.Dir))
if ctx != nil {
wailsRuntime.EventsEmit(ctx, "reims:state-changed", true)
}
return nil
}
func (a *App) ValidateCreate(opts reims.CreateOpts) []reims.ValidationIssue {
a.mu.Lock()
root := a.cfg.DataRoot
loc := i18n.EffectiveLocale(a.cfg.Locale)
a.mu.Unlock()
issues := reims.ValidateCreateLocalized(opts, host.Inspect(root), loc)
// 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: i18n.T(loc, "validate.name_taken", vm.Name)})
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
loc := a.cfg.Locale
a.mu.Unlock()
return reims.ValidateSetLocalized(opts, cur, host.Inspect(root), loc), 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
loc := a.cfg.Locale
a.mu.Unlock()
if issues := reims.ValidateSetLocalized(opts, cur, host.Inspect(root), loc); 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
}
const (
vmExitWaitTimeout = 12 * time.Second
vmMemoryReclaimWaitTimeout = 15 * time.Second
)
func (a *App) cachedVMPID(name string) int {
a.mu.Lock()
defer a.mu.Unlock()
for _, vm := range a.lastVMs {
if vm.Name == name && vm.State == "running" && vm.PID != nil && *vm.PID > 0 {
return *vm.PID
}
}
return 0
}
func (a *App) waitForVMProcessExit(ctx context.Context, pid int, timeout time.Duration) {
if pid <= 0 || timeout <= 0 {
return
}
waitCtx, cancel := context.WithTimeout(ctx, timeout)
defer cancel()
_ = host.WaitProcessExit(waitCtx, uint32(pid), qemuImage)
}
func (a *App) waitForCommitMemoryReclaim(ctx context.Context, c *reims.Client, name, logPrefix string) {
if ctx.Err() != nil || c == nil {
return
}
detail, err := c.Show(ctx, name)
if err != nil || detail.Memory == "" {
return
}
vmstart.WaitForCommitMemory(ctx, detail.Memory, vmMemoryReclaimWaitTimeout, func(availGB, neededGB float64) {
a.emitLog(name, fmt.Sprintf("%s: waiting for Windows to release VM memory (available %.1f GB, need %.1f GB)...", logPrefix, availGB, neededGB))
})
}
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...")
oldPID := a.cachedVMPID(name)
c, err := a.client()
if err != nil {
a.emitLog(name, "Win10 WHPX cold-reboot aborted: "+err.Error())
return
}
// Wait for QEMU to finish exiting cleanly under -no-reboot. Wait on the
// OS process handle when known so we don't race against QEMU teardown
// even if `reims-ctl list` reports stopped early.
deadline := time.Now().Add(vmExitWaitTimeout)
waitedPID := 0
if oldPID > 0 {
a.waitForVMProcessExit(watchCtx, oldPID, time.Until(deadline))
waitedPID = oldPID
}
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 {
continue
}
if vm.PID != nil && *vm.PID > 0 && oldPID == 0 {
oldPID = *vm.PID
}
if vm.State == "stopped" {
stopped = true
}
break
}
if stopped {
break
}
if oldPID > 0 && oldPID != waitedPID {
a.waitForVMProcessExit(watchCtx, oldPID, time.Until(deadline))
waitedPID = oldPID
continue
}
}
select {
case <-watchCtx.Done():
return
case <-time.After(300 * time.Millisecond):
}
}
if oldPID > 0 && oldPID != waitedPID {
a.waitForVMProcessExit(watchCtx, oldPID, time.Until(deadline))
}
if watchCtx.Err() != nil {
return
}
a.waitForCommitMemoryReclaim(watchCtx, c, name, "Win10 WHPX cold-reboot")
if watchCtx.Err() != nil {
return
}
if err := a.StartVM(name); err != nil {
a.emitLog(name, "Win10 WHPX cold-reboot start failed: "+err.Error())
}
}()
}
// stripLegacyManagedExtraArgs removes reims-go internally managed QEMU arg
// fragments (reimstools, reimshelp, and legacy managed Win10 QMP targets)
// before ledger reconciliation so pre-plugin VMs and out-of-band helpers never
// produce duplicate QEMU device IDs on upgrade.
func stripLegacyManagedExtraArgs(extraArgs string) string {
s := reims.StripGuestToolsArgs(extraArgs)
s = reims.StripOfflineHelperArgs(s)
s = qmp.StripLegacyWin10RebootArgs(s)
return strings.TrimSpace(s)
}
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)
if err := prep.CheckWHPX(rep); err != nil {
a.emitLog(name, "Start refused: "+err.Error())
return err
}
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.mu.Lock()
mgr := a.pluginMgr
a.mu.Unlock()
var qmpAddr string
if mgr != nil {
// Unified plugin-kernel start pipeline (§4.4): collect all vm.beforeStart
// intents (builtin + L1 rule hooks + L3 code hooks) and write merged
// extra-args via AT MOST ONE `reims-ctl set --extra-args` call.
rtCaps := prep.Runtime.Manifest.EffectiveCapabilities()
intents, blockErr := mgr.Registry().Hooks().DispatchBeforeStart(context.Background(), plugin.BeforeStartPayload{
VMName: name,
VMDir: curDetail.Directory,
DriverID: builtin.IDDriverReimsMacOS,
ExtraArgs: curDetail.ExtraArgs,
HasInstaller: curDetail.HasInstaller,
InstallerPath: curDetail.InstallerPath,
RuntimeKind: prep.Runtime.Manifest.EffectiveKind(),
RuntimeCaps: rtCaps,
HostFacts: buildHostFacts(rep, rtCaps),
VMCaps: driver.ReimsMacOSCapabilities,
State: curDetail.State,
})
if blockErr != nil {
a.emitLog(name, "Start blocked: "+blockErr.Error())
return blockErr
}
ledger, ledgerErr := plugin.LoadArgLedger(curDetail.Directory)
if ledgerErr != nil {
a.emitLog(name, "Warning: could not read arg ledger: "+ledgerErr.Error())
ledger = &plugin.ArgLedger{Version: 1, Owners: map[string][]plugin.ArgFragment{}}
}
// Fragments written before the builtins were merged into the core
// belong to the core now; carry them instead of re-adding them.
builtin.MigrateLedger(ledger)
// Adopt/strip pre-ledger or out-of-band managed fragments before reconciling
// so upgrading existing VMs never duplicates QEMU device IDs (B1).
// BeforeStartPayload above already saw the original curDetail.ExtraArgs.
baseExtraArgs := stripLegacyManagedExtraArgs(curDetail.ExtraArgs)
reconciled := plugin.ReconcileStartIntents(baseExtraArgs, ledger, mgr.Registry().ActivePluginIDs(), intents)
reconciled.Changed = strings.TrimSpace(curDetail.ExtraArgs) != reconciled.ExtraArgs
for _, warn := range reconciled.Warnings {
a.emitLog(name, "[plugin] "+warn)
}
if len(reconciled.Env) > 0 {
c.Env = append(c.Env, reconciled.Env...)
}
if reconciled.Changed {
if err := c.Set(context.Background(), reims.SetOpts{Name: name, ExtraArgs: &reconciled.ExtraArgs}, io.Discard, io.Discard); err != nil {
a.emitLog(name, "Warning: could not apply reconciled start extra-args: "+err.Error())
} else {
curDetail.ExtraArgs = reconciled.ExtraArgs
_ = plugin.SaveArgLedger(curDetail.Directory, ledger)
}
} else {
_ = plugin.SaveArgLedger(curDetail.Directory, ledger)
}
for _, act := range reconciled.PostStart {
if act.Kind == "qmp.watch_cold_reboot" {
if addr, ok := act.Params["qmp_addr"].(string); ok && addr != "" {
qmpAddr = addr
}
}
}
} else {
a.syncGuestTools(c, name, &curDetail)
if prep.Runtime.Manifest.HasCapability("win32-unicode-input") {
if env := a.inputBridgeEnv(name, curDetail.Directory); len(env) > 0 {
c.Env = append(c.Env, env...)
}
}
prep.Prepare(context.Background(), name, rep, &curDetail)
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 != "" && mgr == nil {
a.watchWin10ColdReboot(name, qmpAddr)
}
if mgr != nil {
mgr.Registry().Hooks().DispatchObserve(plugin.EventVMAfterStart, plugin.VMEventPayload{
VMName: name,
VMDir: curDetail.Directory,
DriverID: builtin.IDDriverReimsMacOS,
QMPAddr: qmpAddr,
})
}
a.startVMMonitor(name, curDetail, startAt)
a.wakePoll()
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()
mgr := a.pluginMgr
a.transitions[name] = "stopping"
a.mu.Unlock()
if mgr != nil {
mgr.Registry().Hooks().DispatchObserve(plugin.EventVMBeforeStop, plugin.VMEventPayload{
VMName: name,
DriverID: builtin.IDDriverReimsMacOS,
})
}
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()
if mgr != nil {
mgr.Registry().Hooks().DispatchObserve(plugin.EventVMAfterStop, plugin.VMEventPayload{
VMName: name,
DriverID: builtin.IDDriverReimsMacOS,
})
}
a.wakePoll()
wailsRuntime.EventsEmit(a.ctx, "reims:state-changed", true)
return nil
}
func (a *App) RestartVM(name string) error {
_, err := a.restartVM(name)
return err
}
func (a *App) restartVM(name string) (stopped bool, err error) {
oldPID := a.cachedVMPID(name)
if err := a.StopVM(name, false); err != nil {
return false, err
}
ctx := a.baseCtx()
a.waitForVMProcessExit(ctx, oldPID, vmExitWaitTimeout)
if c, err := a.client(); err == nil {
a.waitForCommitMemoryReclaim(ctx, c, name, "Restart")
}
if err := ctx.Err(); err != nil {
return true, err
}
return true, 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)
delete(a.diskPaths, name)
delete(a.procSamples, name)
gt := a.guestTools
a.mu.Unlock()
releaseVMTyping(name)
releaseVMThumbnail(name)
if gt != nil {
gt.UnregisterVM(name)
}
a.mu.Lock()
delMgr := a.pluginMgr
a.mu.Unlock()
if delMgr != nil {
delMgr.Registry().Hooks().DispatchObserve(plugin.EventVMDeleted, plugin.VMEventPayload{
VMName: name,
DriverID: builtin.IDDriverReimsMacOS,
})
}
a.wakePoll()
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)
}