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

934 lines
29 KiB
Go

package app
import (
"context"
"errors"
"fmt"
"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/control"
"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/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"`
CurrentAgentVersion int `json:"current_agent_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"`
RuntimeCaptureSupported bool `json:"runtime_capture_supported"`
}
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
configMu sync.Mutex // serializes config writes and data root changes
selectionMu sync.Mutex // keeps a GUI selection in its data root across UAC
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
appWindowGate sync.Mutex
vmDeleteEpochs map[string]uint64
resolveFolderVolume func(string) (host.DirectoryVolume, error)
imeBridge *host.IMEBridge
trayMgr *tray.Manager
allowQuit bool
launchPrevDataRoot string
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
pluginFiles map[string]pluginFileGrant
pluginMarket *plugin.MarketClient
controlServer *control.Server
driverRouter *driver.Router
vmStateTable *driver.StateTable
lifecycleSvc *vmlifecycle.Service
runtimeKinds *rt.KindRegistry
uiHealth uiHealthState
themeMode string
vmClosePrompts sync.Map
displayHost vmDisplayHost
displayPlacements sync.Map
inputShuttingDown bool
// computerUseOwnedVMs caches ownership markers for MCP-created temporary VMs.
computerUseOwnedVMs map[string]map[string]bool
computerUseCloneMu sync.Mutex
// computerUseHeld records the keys and pointer buttons each plugin left
// held in a guest, so the host can release them when the plugin goes away.
computerUseHeld map[string]map[string]*heldInputs
computerUseHeldMu sync.Mutex
fullscreenHotkey host.FullscreenHotkeyService
fullscreenSyncMu sync.Mutex
fullscreenTargets fullscreenHotkeyTargetCache
// Plugin elevation requests (elevate_flow.go).
elevatePromptMu sync.Mutex
elevateMu sync.Mutex
elevatePending map[string]chan bool
elevateSeq uint64
elevateEmit func(ElevationPrompt)
elevateDismiss func(string)
elevateRunner elevationRunner
}
// 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()
launchPrevDataRoot := ""
if launch.DataRoot != "" {
cfg, err = config.Load(filepath.Join(launch.DataRoot, "reims-go.json"))
if err != nil {
cfg = config.Default()
} else if cfg.DataRoot != "" && !sameDataFolder(cfg.DataRoot, launch.DataRoot) {
launchPrevDataRoot = cfg.DataRoot
}
cfg.DataRoot = launch.DataRoot
needsSetup = false
} else if err != nil {
cfg = config.Default()
}
a := &App{
cfg: cfg,
needsSetup: needsSetup,
launch: launch,
launchPrevDataRoot: launchPrevDataRoot,
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),
pluginFiles: make(map[string]pluginFileGrant),
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()
a.syncFullscreenHotkeyTargets()
// 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
}
if tasks.hasRunningDownload() {
// Closing now would abort a download: ask first. The window's
// confirmation calls QuitApp, which lets the next close through.
a.emit("reims:confirm-close-downloads", true)
return true
}
return false
}
func (a *App) shutdown(ctx context.Context) {
a.closePacketBridges()
if a.stopPoll != nil {
a.stopPoll()
}
tasks.cancelAll()
a.cancelPendingElevations()
stopAllVMMonitors()
a.stopPluginControlServer()
a.mu.Lock()
a.inputShuttingDown = true
a.mu.Unlock()
a.fullscreenHotkey.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("")
}
// 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
}
a.emit("reims:log", map[string]string{
"ts": ts,
"source": source,
"line": redacted,
})
}
func (a *App) GetState() AppState {
a.noteUIAlive()
cfgCopy := a.runtimeConfig()
a.mu.Lock()
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)
if needsSetup || rootStatus.ReadOnly {
rep.PendingHypervisorBoot = host.ReadPendingHypervisorBoot("", rep.WHPX)
}
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,
CurrentAgentVersion: guesttools.CurrentAgentVersion,
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)),
RuntimeCaptureSupported: !needsSetup && !rootStatus.ReadOnly && active != nil && runtimeAllowsCapture(*active),
}
}
func (a *App) SetLocale(raw string) error {
if err := a.setPreference(func(cfg *config.Config) { cfg.Locale = i18n.ParsePreference(raw) }); err != nil {
return err
}
a.mu.Lock()
eff := i18n.EffectiveLocale(a.cfg.Locale)
mgr := a.pluginMgr
a.mu.Unlock()
if mgr != nil {
mgr.NotifyLocaleChanged(eff)
}
a.emitStateChanged()
return nil
}
func (a *App) SetAutoPinPCores(enabled bool) error {
return a.setPreference(func(cfg *config.Config) { cfg.AutoPinPCores = enabled })
}
func (a *App) SetMinimizeToTray(enabled bool) error {
return a.setPreference(func(cfg *config.Config) { cfg.MinimizeToTray = &enabled })
}
// 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()
a.emit("reims:tray-new-vm")
},
OnVMAction: a.trayVMAction,
OnQuit: a.QuitApp,
GetSnapshot: func() tray.Snapshot {
cfgCopy := a.runtimeConfig()
a.mu.Lock()
loc := cfgCopy.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.StartVM(driverID, name), i18n.M(loc, "tray.notify.start_fail", vars)
case tray.ActSuspend:
err, failTitle = a.SuspendVM(driverID, name), i18n.M(loc, "tray.notify.suspend_fail", vars)
case tray.ActResume:
err, failTitle = a.ResumeVM(driverID, name), i18n.M(loc, "tray.notify.resume_fail", vars)
case tray.ActDiscardSuspend:
a.showMainWindow()
a.emit("reims:tray-discard-suspend", name)
case tray.ActStop:
err, failTitle = a.StopVM(driverID, name, false), i18n.M(loc, "tray.notify.stop_fail", vars)
case tray.ActForceStop:
err, failTitle = a.StopVM(driverID, name, true), i18n.M(loc, "tray.notify.force_stop_fail", vars)
case tray.ActRestart:
err, failTitle = a.RestartVM(driverID, name), i18n.M(loc, "tray.notify.restart_fail", vars)
case tray.ActShowWindow:
err, failTitle = a.FocusVMWindow(driverID, name), i18n.M(loc, "tray.notify.focus_fail", vars)
case tray.ActToggleFullscreen:
_, err = a.ToggleVMFullscreen(driverID, name)
failTitle = i18n.M(loc, "tray.notify.fullscreen_fail", vars)
case tray.ActScreenshot:
if err = a.CopyVMScreenshot(driverID, 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()
a.emit("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.pluginFiles = make(map[string]pluginFileGrant)
a.mu.Unlock()
cancelPluginTasks("")
}
func (a *App) SetDataRoot(dir string) error {
return a.setDataRoot(dir, host.SyncQEMUASLR)
}
func (a *App) checkDataRootSwitch(loc i18n.Locale) error {
a.mu.Lock()
defer a.mu.Unlock()
for _, v := range a.lastVMs {
if v.State == "running" || v.State == "starting" || v.State == "stopping" || v.State == "suspending" || v.State == "resuming" {
return i18n.NewCodedError(loc, "E_DATAROOT_BUSY_VMS", "err.dataroot.busy_vms", nil, nil)
}
}
for _, tr := range a.transitions {
if tr != "" {
return i18n.NewCodedError(loc, "E_DATAROOT_BUSY_VMS", "err.dataroot.busy_vms", nil, nil)
}
}
// Plugin tasks do not block the switch; resetDataRootCaches cancels them.
if hostTaskRunning() {
return i18n.NewCodedError(loc, "E_DATAROOT_BUSY_TASKS", "err.dataroot.busy_tasks", nil, nil)
}
return nil
}
func (a *App) setDataRoot(dir string, syncPolicy func(context.Context, string, string) error) (err error) {
a.selectionMu.Lock()
defer a.selectionMu.Unlock()
a.mu.Lock()
prev := *a.cfg
wasReadOnly, setup := a.root.ReadOnly, a.needsSetup
a.mu.Unlock()
loc := i18n.EffectiveLocale(prev.Locale)
if err := a.checkDataRootSwitch(loc); err != nil {
return err
}
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)
}
target := config.Config{DataRoot: dir}
if err := target.EnsureDirs(); err != nil {
return err
}
if err := writable(dir); err != nil {
return err
}
st := dataroot.Open(dir, version.Version)
if st.ReadOnly {
return dataroot.Error(loc, st)
}
ctx := a.baseCtx()
changed := !sameDataFolder(prev.DataRoot, dir)
source := ""
if changed && !setup && !wasReadOnly {
if _, err := os.Stat(prev.DataRoot); err == nil {
source = prev.RuntimesDir()
} else if !errors.Is(err, os.ErrNotExist) {
return err
}
}
release, err := lockDataRootSelections(ctx, source, target.RuntimesDir())
if err != nil {
return err
}
defer release()
if changed && !setup && !wasReadOnly {
if err := rt.RefreshSelection(&prev); err != nil {
// A damaged source config must still allow switching to a healthy folder.
a.emitLog("runtime", "Read previous runtime selection: "+err.Error())
}
}
cfgPath := filepath.Join(dir, "reims-go.json")
nextCfg, err := config.LoadExisting(cfgPath)
fresh := errors.Is(err, os.ErrNotExist)
recordedOldRoot := ""
if fresh {
nextCfg = config.Default()
nextCfg.Locale = prev.Locale
nextCfg.QEMUASLR = prev.QEMUASLR
} else if err != nil {
return fmt.Errorf("read %s: %w", cfgPath, err)
} else {
recordedOldRoot = nextCfg.DataRoot
}
if recordedOldRoot == "" || sameDataFolder(recordedOldRoot, dir) {
recordedOldRoot = prev.DataRoot
}
nextCfg.DataRoot = dir
if changed && !setup {
restore, policyErr := a.moveDataRootASLR(ctx, &prev, nextCfg, fresh, syncPolicy)
if policyErr != nil {
return policyErr
}
defer func() {
if err != nil {
err = errors.Join(err, restore())
}
}()
}
a.configMu.Lock()
defer a.configMu.Unlock()
if err := a.checkDataRootSwitch(loc); err != nil {
return err
}
if fresh {
// Keep preference edits made while Windows was asking for consent.
a.mu.Lock()
cur := *a.cfg
a.mu.Unlock()
nextCfg.Locale = cur.Locale
nextCfg.AutoPinPCores = cur.AutoPinPCores
nextCfg.RuntimeChannel = cur.RuntimeChannel
nextCfg.AppUpdateChannel = cur.AppUpdateChannel
nextCfg.MinimizeToTray = cur.MinimizeToTray
nextCfg.EnableHypervisorSwitch = cur.EnableHypervisorSwitch
nextCfg.HostDNSMode, nextCfg.HostDNSDoHURL = cur.HostDNSMode, cur.HostDNSDoHURL
nextCfg.FullscreenHotkeyEnabled = cur.FullscreenHotkeyEnabled
nextCfg.FullscreenHotkey = cur.FullscreenHotkey
} else {
// Preserve independent preference saves in the destination during UAC.
nextCfg, err = config.LoadExisting(cfgPath)
if err != nil {
return err
}
nextCfg.DataRoot = dir
}
if err := rt.SavePreferences(nextCfg); err != nil {
return err
}
if err := config.SaveLocation(dir); err != nil {
return err
}
a.mu.Lock()
a.cfg = nextCfg
if a.guestTools != nil {
a.guestTools.SetHostDNSConfig(a.hostDNSConfigLocked())
}
a.root = st
a.syncClipboardStagingLocked()
a.mu.Unlock()
a.logDataRoot(st)
if st.Writable() {
a.relocateRegisteredVMs(dir, recordedOldRoot)
}
// 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.
rootChanged := changed || wasReadOnly
if rootChanged {
a.resetDataRootCaches()
}
a.syncFullscreenHotkeyTargets()
if rootChanged {
a.reloadPlugins()
a.wakePoll()
a.emitStateChanged()
}
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)
}
// 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
loc := i18n.EffectiveLocale(cfg.Locale)
a.mu.Unlock()
if err := a.requireWritableDataRoot(); err != nil {
return nil, err
}
a.emitLog("runtime", "Installing portable runtime: "+archivePath)
inst, err := rt.InstallFromArchive(&cfg, archivePath)
if err != nil {
a.emitLog("runtime", "Install failed: "+err.Error())
if errors.Is(err, rt.ErrRuntimeInUse) {
return nil, i18n.NewCodedError(loc, "E_RUNTIME_IN_USE", "runtime.install_in_use", nil, err)
}
return nil, err
}
if err := a.activateInstalledRuntime(&cfg, inst.Commit); err != nil {
inst.Active = false
a.emitLog("runtime", err.Error())
return inst, err
}
a.emitLog("runtime", fmt.Sprintf("Runtime %s installed & activated -> %s", inst.Commit, inst.Dir))
return inst, nil
}
func (a *App) UseRuntime(commit string) error {
return a.activateRuntime("", commit)
}
func (a *App) activateInstalledRuntime(cfg *config.Config, commit string) error {
if err := a.activateRuntime(cfg.DataRoot, commit); err != nil {
return i18n.NewCodedError(i18n.EffectiveLocale(cfg.Locale), "E_RUNTIME_ACTIVATION",
"runtime.installed_not_activated", i18n.Vars{"commit": commit}, err)
}
return nil
}
func (a *App) activateRuntime(dataRoot, commit string) error {
return a.updateSelection(func(cfg *config.Config) error {
if dataRoot != "" && cfg.DataRoot != dataRoot {
return errors.New("data folder changed during runtime install")
}
return rt.Activate(a.baseCtx(), cfg, commit, a.warnRuntime)
})
}
func (a *App) warnRuntime(warning error) {
message := warning.Error()
a.emitLog("runtime", message)
a.emit("reims:runtime-warning", message)
}
func (a *App) SetQEMUASLR(enabled bool) error {
return a.updateSelection(func(cfg *config.Config) error {
return rt.SetQEMUASLR(a.baseCtx(), cfg, enabled)
})
}
func (a *App) RemoveRuntime(commit string) error {
a.mu.Lock()
if err := a.requireWritableDataRootLocked(); err != nil {
a.mu.Unlock()
return err
}
cfg := *a.cfg
loc := i18n.EffectiveLocale(cfg.Locale)
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))
a.emitStateChanged()
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
}