Track fallback bridge arguments through the ownership ledger, restore mode and uplink selection after failed network applies, and reclaim per-VM locks only after holders and waiters finish. Reproduced all three review findings before changing behavior using an isolated control client, the production React component with simulated responses, and 512 synthetic VM names. Regression tests, full CI and 20 race-enabled lock runs pass. Existing virtual machines were not operated.
1203 lines
35 KiB
Go
1203 lines
35 KiB
Go
package app
|
|
|
|
import (
|
|
"context"
|
|
"errors"
|
|
"fmt"
|
|
"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/dataroot"
|
|
"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"
|
|
vmlifecycle "github.com/Nwflower/reims-go/internal/lifecycle"
|
|
"github.com/Nwflower/reims-go/internal/packetbridge"
|
|
"github.com/Nwflower/reims-go/internal/plugin"
|
|
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"
|
|
)
|
|
|
|
func (a *App) OpenWindowsSecurityExclusions() error {
|
|
a.emitLog("host", "Opening Windows Security settings...")
|
|
return host.OpenWindowsSecurityExclusions()
|
|
}
|
|
|
|
func (a *App) GetDefenderExclusionCommand() string {
|
|
a.mu.Lock()
|
|
dataRoot := a.cfg.DataRoot
|
|
a.mu.Unlock()
|
|
return host.DefenderExclusionCommand(dataRoot)
|
|
}
|
|
|
|
type PendingChange struct {
|
|
Field string `json:"field"`
|
|
From string `json:"from"`
|
|
To string `json:"to"`
|
|
}
|
|
|
|
type AppState struct {
|
|
QuitMode string `json:"quit_mode,omitempty"`
|
|
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"`
|
|
CanSuspend bool `json:"can_suspend"`
|
|
VMs []driver.VMListItem `json:"vms"`
|
|
VMListError string `json:"vm_list_error,omitempty"`
|
|
Transitions map[string]string `json:"transitions"`
|
|
PendingChanges map[string][]PendingChange `json:"pending_changes"`
|
|
ActiveGuides []string `json:"active_guides,omitempty"`
|
|
// InstallGuideEnabled reports whether the VM-window install guide service 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"`
|
|
// DataRoot says how the data folder opened; read_only means the app shows
|
|
// the read-only screen instead of the workspace (dataroot_flow.go).
|
|
DataRoot dataroot.Status `json:"data_root_status"`
|
|
DataRootMessage string `json:"data_root_message,omitempty"` // why it is read-only, localized
|
|
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
|
|
}
|
|
|
|
func vmKey(name string) string { return driver.NewVMRef("", name).Key() }
|
|
|
|
func vmKeyForDriver(driverID, name string) string { return driver.NewVMRef(driverID, name).Key() }
|
|
|
|
func vmNameFromKey(key string) string {
|
|
if ref, ok := driver.ParseVMRef(key); ok {
|
|
return ref.Name
|
|
}
|
|
return key
|
|
}
|
|
|
|
type App struct {
|
|
packetMu sync.Mutex
|
|
packetBridges map[string]*packetbridge.Bridge
|
|
packetBridgesStopped bool
|
|
vmNetworkLocks sync.Map
|
|
vmNetworkLocksMu sync.Mutex
|
|
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
|
|
guestToolsConfigLocks sync.Map
|
|
vmDeleteEpochs map[string]uint64
|
|
resolveFolderVolume func(string) (host.DirectoryVolume, error)
|
|
imeBridge *host.IMEBridge
|
|
|
|
trayMgr *tray.Manager
|
|
allowQuit bool
|
|
quitMode string
|
|
vmStarts sync.WaitGroup
|
|
lastVMs []driver.VMListItem
|
|
lastVMsAt time.Time // when pollVMs last refreshed lastVMs; zero = stale
|
|
lastVMListErr error
|
|
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
|
|
root dataroot.Status // how the current data folder opened (dataroot_flow.go)
|
|
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
|
|
lifecycleSvc *vmlifecycle.Service
|
|
runtimeKinds *rt.KindRegistry
|
|
uiHealth uiHealthState
|
|
themeMode string
|
|
vmClosePrompts sync.Map
|
|
displayHost vmDisplayHost
|
|
|
|
displayPlacements sync.Map
|
|
|
|
keymapMu sync.Mutex
|
|
keymapPIDs map[string]int
|
|
fallbackInputSvc *host.InputService
|
|
inputShuttingDown bool
|
|
}
|
|
|
|
// 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(host.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},
|
|
displayHost: vmDisplayHost{displays: host.ConnectedDisplays, move: host.MoveProcessWindowToDisplay},
|
|
}
|
|
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.mu.Lock()
|
|
needsSetup := a.needsSetup
|
|
a.mu.Unlock()
|
|
// Before first-run setup there is no chosen folder to open; CompleteSetup
|
|
// opens the one the user picks and starts plugins then.
|
|
if !needsSetup {
|
|
a.openDataRoot()
|
|
}
|
|
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()
|
|
if a.dataRootUsable() {
|
|
go a.registerExistingGuestTools(pollCtx)
|
|
go a.registerExistingPacketBridges(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
|
|
quitting := a.quitMode != ""
|
|
toTray := a.cfg.ShouldMinimizeToTray()
|
|
hasTray := a.trayMgr != nil
|
|
a.mu.Unlock()
|
|
if allow {
|
|
return false
|
|
}
|
|
if quitting {
|
|
return true
|
|
}
|
|
if toTray && hasTray {
|
|
a.setWindowHidden(true)
|
|
wailsRuntime.WindowHide(ctx)
|
|
return true
|
|
}
|
|
return false
|
|
}
|
|
|
|
func (a *App) shutdown(ctx context.Context) {
|
|
a.closePacketBridges()
|
|
if a.stopPoll != nil {
|
|
a.stopPoll()
|
|
}
|
|
tasks.cancelAll()
|
|
stopAllVMMonitors()
|
|
a.mu.Lock()
|
|
a.inputShuttingDown = true
|
|
fallback := a.fallbackInputSvc
|
|
a.mu.Unlock()
|
|
if fallback != nil {
|
|
fallback.Close()
|
|
}
|
|
a.shutdownPlugins()
|
|
a.mu.Lock()
|
|
for name, entry := range a.rebootWatchers {
|
|
entry.cancel()
|
|
delete(a.rebootWatchers, vmKey(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)
|
|
lastGuideMgr := a.getInstallGuideManager()
|
|
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)
|
|
// reims-ctl keeps its state in the data folder; leave it alone until
|
|
// setup has chosen one, and while it is open read-only.
|
|
if !a.dataRootUsable() {
|
|
continue
|
|
}
|
|
vms, err := a.listVMsInternal(ctx)
|
|
if err != nil {
|
|
a.mu.Lock()
|
|
changed := a.lastVMListErr == nil || a.lastVMListErr.Error() != err.Error()
|
|
a.lastVMListErr = err
|
|
if a.lastVMsAt.IsZero() && a.lastVMs == nil {
|
|
a.lastVMs = vms
|
|
}
|
|
a.lastVMsAt = time.Now()
|
|
a.mu.Unlock()
|
|
if changed {
|
|
a.emitLifecycleStateChanged()
|
|
}
|
|
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 {
|
|
key := vmKeyForDriver(vm.DriverID, vm.Name)
|
|
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[key]; ok {
|
|
if (tr == "starting" && vm.State == "running") ||
|
|
(tr == "stopping" && vm.State == "stopped") ||
|
|
(tr == "suspending" && (vm.State == "suspended" || vm.State == "stopped")) ||
|
|
(tr == "resuming" && vm.State == "running") {
|
|
delete(a.transitions, key)
|
|
if vm.State == "stopped" {
|
|
delete(a.pendingChanges, key)
|
|
}
|
|
}
|
|
}
|
|
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;", key, vm.State, a.transitions[key])
|
|
}
|
|
sig := b.String()
|
|
ib := a.imeBridge
|
|
liveVMs := make(map[string]struct{}, len(vms))
|
|
for _, vm := range vms {
|
|
liveVMs[vmKeyForDriver(vm.DriverID, vm.Name)] = struct{}{}
|
|
}
|
|
removedVMs := make(map[string]struct{})
|
|
for _, vm := range a.lastVMs {
|
|
key := vmKeyForDriver(vm.DriverID, vm.Name)
|
|
if _, ok := liveVMs[key]; !ok {
|
|
removedVMs[key] = 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
|
|
})
|
|
var stoppedBridges []string
|
|
for _, prev := range a.lastVMs {
|
|
if prev.State != "running" || prev.DriverID != driver.BuiltinReimsMacOSDriverID {
|
|
continue
|
|
}
|
|
key := vmKeyForDriver(prev.DriverID, prev.Name)
|
|
tr := a.transitions[key]
|
|
if tr == "starting" || tr == "resuming" {
|
|
continue
|
|
}
|
|
for _, cur := range vms {
|
|
if cur.DriverID == prev.DriverID && cur.Name == prev.Name && cur.State != "running" {
|
|
stoppedBridges = append(stoppedBridges, cur.Name)
|
|
break
|
|
}
|
|
}
|
|
}
|
|
gt := a.guestTools
|
|
a.lastVMs = append([]driver.VMListItem(nil), vms...)
|
|
a.lastVMsAt = time.Now()
|
|
listRecovered := a.lastVMListErr != nil
|
|
a.lastVMListErr = nil
|
|
a.mu.Unlock()
|
|
for _, vmName := range stoppedBridges {
|
|
a.stopPacketBridge(vmName)
|
|
if gt != nil {
|
|
gt.StopManagementNetwork(vmName)
|
|
}
|
|
}
|
|
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 key := range removedVMs {
|
|
name := vmNameFromKey(key)
|
|
if ref, ok := driver.ParseVMRef(key); ok && ref.DriverID == driver.BuiltinReimsMacOSDriverID {
|
|
a.stopPacketBridge(name)
|
|
}
|
|
a.mu.Lock()
|
|
delete(a.transitions, key)
|
|
delete(a.pendingChanges, key)
|
|
a.mu.Unlock()
|
|
stopVMMonitor(name)
|
|
a.cancelRebootWatcherKey(key)
|
|
releaseVMTyping(name)
|
|
releaseVMThumbnail(name)
|
|
if gt != nil {
|
|
gt.UnregisterVM(key)
|
|
}
|
|
}
|
|
if ib != nil {
|
|
ib.SetTargets(imeTargets)
|
|
}
|
|
a.syncKeymapRules()
|
|
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]driver.VMInfo, len(toPin))
|
|
for _, cand := range toPin {
|
|
det, err := a.resolveVMInfo(driver.BuiltinReimsMacOSDriverID, 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 := a.resolveVMInfo(vm.DriverID, 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 || listRecovered {
|
|
lastSig = sig
|
|
wailsRuntime.EventsEmit(a.ctx, "reims:state-changed", true)
|
|
}
|
|
}
|
|
}
|
|
|
|
func (a *App) listVMsInternal(ctx context.Context) ([]driver.VMListItem, error) {
|
|
a.mu.Lock()
|
|
svc := a.lifecycleSvc
|
|
a.mu.Unlock()
|
|
if svc != nil {
|
|
vms, err := svc.List(ctx)
|
|
out := make([]driver.VMListItem, 0, len(vms))
|
|
for _, vm := range vms {
|
|
out = append(out, driver.VMListItem{Name: vm.Name, DriverID: vm.DriverID, Dir: vm.Directory, PID: vm.PID, State: vm.State})
|
|
}
|
|
return out, err
|
|
}
|
|
c, err := a.client()
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
vms, err := c.List(ctx)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
for i := range vms {
|
|
vms[i].DriverID = driver.BuiltinReimsMacOSDriverID
|
|
}
|
|
enrichMacOSVMListStates(vms)
|
|
return vms, nil
|
|
}
|
|
|
|
// 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 []driver.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 []driver.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) ([]driver.VMListItem, error) {
|
|
a.mu.Lock()
|
|
if !a.lastVMsAt.IsZero() && time.Since(a.lastVMsAt) <= polledMaxAge {
|
|
vms := append([]driver.VMListItem(nil), a.lastVMs...)
|
|
err := a.lastVMListErr
|
|
a.mu.Unlock()
|
|
return vms, err
|
|
}
|
|
a.mu.Unlock()
|
|
return a.listVMsInternal(ctx)
|
|
}
|
|
|
|
// polledVM looks name up in polledVMs.
|
|
func (a *App) polledVM(name string) (driver.VMListItem, bool) {
|
|
vms, err := a.polledVMs(context.Background())
|
|
if err != nil {
|
|
return driver.VMListItem{}, false
|
|
}
|
|
for _, vm := range vms {
|
|
if vm.Name == name {
|
|
return vm, true
|
|
}
|
|
}
|
|
return driver.VMListItem{}, false
|
|
}
|
|
|
|
func (a *App) polledVMForDriver(driverID, name string) (driver.VMListItem, bool) {
|
|
vms, err := a.polledVMs(context.Background())
|
|
if err != nil {
|
|
return driver.VMListItem{}, false
|
|
}
|
|
driverID = driver.CanonicalDriverID(driverID)
|
|
if driverID == "" {
|
|
driverID = driver.BuiltinReimsMacOSDriverID
|
|
}
|
|
for _, vm := range vms {
|
|
if vm.Name == name && driver.CanonicalDriverID(vm.DriverID) == driverID {
|
|
return vm, true
|
|
}
|
|
}
|
|
return driver.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
|
|
}
|
|
|
|
func (a *App) emitVMLog(name, line string) { a.emitLog(vmKey(name), line) }
|
|
|
|
func (a *App) emitLog(source, line string) {
|
|
redacted := host.RedactLine(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
|
|
rootStatus := a.root
|
|
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.
|
|
var vms []driver.VMListItem
|
|
var listError string
|
|
if !needsSetup && !rootStatus.ReadOnly {
|
|
var err error
|
|
vms, err = a.polledVMs(context.Background())
|
|
if err != nil {
|
|
listError = host.RedactText(err.Error())
|
|
}
|
|
}
|
|
|
|
opts := a.evaluateOptimizations(rep)
|
|
|
|
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()
|
|
}
|
|
|
|
a.mu.Lock()
|
|
quitMode := a.quitMode
|
|
a.mu.Unlock()
|
|
return AppState{
|
|
QuitMode: quitMode,
|
|
Config: &cfgCopy,
|
|
Host: rep,
|
|
Optimizations: opts,
|
|
Runtimes: runtimes,
|
|
ActiveRuntime: active,
|
|
CanSuspend: active != nil && active.Manifest.HasCapability("vm-suspend"),
|
|
VMs: vms,
|
|
VMListError: listError,
|
|
Transitions: trCopy,
|
|
PendingChanges: pcCopy,
|
|
ActiveGuides: activeGuides,
|
|
InstallGuideEnabled: installGuideEnabled,
|
|
NeedsSetup: needsSetup,
|
|
DataRoot: rootStatus,
|
|
DataRootMessage: dataRootMessage(i18n.EffectiveLocale(cfgCopy.Locale), rootStatus),
|
|
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) SetLocale(raw string) error {
|
|
a.mu.Lock()
|
|
a.cfg.Locale = i18n.ParsePreference(raw)
|
|
err := a.saveConfigLocked()
|
|
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 a.saveConfigLocked()
|
|
}
|
|
|
|
func (a *App) SetMinimizeToTray(enabled bool) error {
|
|
a.mu.Lock()
|
|
v := enabled
|
|
a.cfg.MinimizeToTray = &v
|
|
err := a.saveConfigLocked()
|
|
a.mu.Unlock()
|
|
return err
|
|
}
|
|
|
|
func (a *App) SetSyncHostMemorySMBIOS(enabled bool) error {
|
|
a.mu.Lock()
|
|
defer a.mu.Unlock()
|
|
a.cfg.SyncHostMemorySMBIOS = enabled
|
|
return a.saveConfigLocked()
|
|
}
|
|
|
|
// 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 {
|
|
wailsRuntime.Quit(a.ctx) // beforeClose applies the window-close preference.
|
|
}
|
|
}
|
|
|
|
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: a.QuitApp,
|
|
GetSnapshot: func() tray.Snapshot {
|
|
a.mu.Lock()
|
|
cfgCopy := *a.cfg
|
|
loc := a.cfg.Locale
|
|
cached := append([]driver.VMListItem(nil), a.lastVMs...)
|
|
transitions := make(map[string]string, len(a.transitions))
|
|
for k, v := range a.transitions {
|
|
transitions[k] = v
|
|
}
|
|
a.mu.Unlock()
|
|
canSuspend := false
|
|
if active, err := rt.ResolveActive(&cfgCopy); err == nil && active != nil {
|
|
canSuspend = active.Manifest.HasCapability("vm-suspend")
|
|
}
|
|
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[vmKeyForDriver(vm.DriverID, 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{DriverID: vm.DriverID, Name: vm.Name, Label: label, State: state})
|
|
}
|
|
effLoc := i18n.EffectiveLocale(loc)
|
|
return tray.Snapshot{
|
|
Locale: effLoc,
|
|
LocaleZh: effLoc == i18n.ZhCN,
|
|
CanSuspend: canSuspend,
|
|
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(driverID, 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.StartVMWithDriver(driverID, name), i18n.M(loc, "tray.notify.start_fail", vars)
|
|
case tray.ActSuspend:
|
|
err, failTitle = a.SuspendVMWithDriver(driverID, name), i18n.M(loc, "tray.notify.suspend_fail", vars)
|
|
case tray.ActResume:
|
|
err, failTitle = a.ResumeVMWithDriver(driverID, name), i18n.M(loc, "tray.notify.resume_fail", vars)
|
|
case tray.ActDiscardSuspend:
|
|
a.ShowMainWindow()
|
|
if a.ctx != nil {
|
|
wailsRuntime.EventsEmit(a.ctx, "reims:tray-discard-suspend", name)
|
|
}
|
|
case tray.ActStop:
|
|
err, failTitle = a.StopVMWithDriver(driverID, name, false), i18n.M(loc, "tray.notify.stop_fail", vars)
|
|
case tray.ActForceStop:
|
|
err, failTitle = a.StopVMWithDriver(driverID, name, true), i18n.M(loc, "tray.notify.force_stop_fail", vars)
|
|
case tray.ActRestart:
|
|
err, failTitle = a.RestartVMWithDriver(driverID, 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.ActToggleFullscreen:
|
|
_, err = a.ToggleVMFullscreen(name)
|
|
failTitle = i18n.M(loc, "tray.notify.fullscreen_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.emitVMLog(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.lastVMListErr = nil
|
|
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
|
|
curSyncHostMemSMBIOS := a.cfg.SyncHostMemorySMBIOS
|
|
curHostDNS := a.hostDNSConfigLocked()
|
|
for _, v := range a.lastVMs {
|
|
if v.State == "running" || v.State == "starting" || v.State == "stopping" || v.State == "suspending" || v.State == "resuming" {
|
|
a.mu.Unlock()
|
|
return i18n.NewCodedError(loc, "E_DATAROOT_BUSY_VMS", "err.dataroot.busy_vms", nil, nil)
|
|
}
|
|
}
|
|
for _, tr := range a.transitions {
|
|
if tr != "" {
|
|
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
|
|
}
|
|
// Check (and if needed upgrade) the target before writing anything into it.
|
|
if st := dataroot.Open(dir, version.Version); st.ReadOnly {
|
|
return dataroot.Error(loc, st)
|
|
}
|
|
|
|
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
|
|
nextCfg.SyncHostMemorySMBIOS = curSyncHostMemSMBIOS
|
|
nextCfg.HostDNSMode, nextCfg.HostDNSDoHURL = curHostDNS.Mode, curHostDNS.DoHURL
|
|
}
|
|
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 folder created just now gets its version stamp here.
|
|
st := dataroot.Open(dir, version.Version)
|
|
|
|
a.mu.Lock()
|
|
wasReadOnly := a.root.ReadOnly
|
|
a.cfg = nextCfg
|
|
if a.guestTools != nil {
|
|
a.guestTools.SetHostDNSConfig(a.hostDNSConfigLocked())
|
|
}
|
|
a.root = st
|
|
a.mu.Unlock()
|
|
a.logDataRoot(st)
|
|
|
|
// Leaving a read-only folder starts the plugins and polling it held back,
|
|
// even when the user picked the same folder again after fixing it.
|
|
if filepath.Clean(prev) != filepath.Clean(dir) || wasReadOnly {
|
|
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
|
|
_ = a.saveConfigLocked()
|
|
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 a.saveConfigLocked()
|
|
}
|
|
|
|
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) deleteVMWithGuestTools(name string, deleteVM func() error, isRegistered func() (bool, error)) (removed bool, err error) {
|
|
unlock := a.lockGuestToolsVM(name)
|
|
defer unlock()
|
|
deleteErr := deleteVM()
|
|
if deleteErr != nil {
|
|
registered, err := isRegistered()
|
|
if err != nil {
|
|
return false, errors.Join(deleteErr, err)
|
|
}
|
|
if registered {
|
|
return false, deleteErr
|
|
}
|
|
}
|
|
a.mu.Lock()
|
|
if a.vmDeleteEpochs == nil {
|
|
a.vmDeleteEpochs = make(map[string]uint64)
|
|
}
|
|
a.vmDeleteEpochs[strings.ToLower(name)]++
|
|
srv := a.guestTools
|
|
a.mu.Unlock()
|
|
if srv != nil {
|
|
srv.UnregisterVM(name)
|
|
}
|
|
return true, deleteErr
|
|
}
|