refactor: merge duplicated helpers and the window event contract

Events to the frontend go through App.emit, and a test keeps their names
in step with wails.ts. QEMU argument splitting, hidden console processes,
the macOS release record, the running check and a few smaller helpers
now exist once.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
千川白浪andClaude Opus 5.5 committed 2026-12-03 21:09:19 -07:00
1 parent 90fbce8b47
commit b203bde650
70 files changed
+396 -571

No files matched your search

+1 -4
View File
@@ -7,7 +7,6 @@ import (
"github.com/Nwflower/reims-go/internal/driver"
"github.com/Nwflower/reims-go/internal/host"
"github.com/Nwflower/reims-go/internal/vmstart"
wailsRuntime "github.com/wailsapp/wails/v2/pkg/runtime"
)
// VMAffinityUpdate is the payload passed from the UI to save and live-apply a
@@ -180,8 +179,6 @@ func (a *App) SetVMAffinityWithDriver(driverID, name string, req VMAffinityUpdat
return buildVMAffinityStatus(detail, rep, globalAutoPin, pid), applyErr
}
}
if a.ctx != nil {
wailsRuntime.EventsEmit(a.ctx, "reims:state-changed", true)
}
a.emitStateChanged()
return buildVMAffinityStatus(detail, rep, globalAutoPin, pid), nil
}
+10 -23
View File
@@ -284,7 +284,7 @@ func (a *App) beforeClose(ctx context.Context) bool {
if tasks.hasRunningDownload() {
// Closing now would abort a download: ask first. The window's
// confirmation calls QuitApp, which lets the next close through.
wailsRuntime.EventsEmit(ctx, "reims:confirm-close-downloads", true)
a.emit("reims:confirm-close-downloads", true)
return true
}
return false
@@ -390,7 +390,7 @@ func (a *App) pollVMs(ctx context.Context) {
a.lastVMsAt = time.Now()
a.mu.Unlock()
if changed {
a.emitLifecycleStateChanged()
a.emitStateChanged()
}
continue
}
@@ -633,7 +633,7 @@ func (a *App) pollVMs(ctx context.Context) {
}
if sig != lastSig || guidesChanged || listRecovered {
lastSig = sig
wailsRuntime.EventsEmit(a.ctx, "reims:state-changed", true)
a.emitStateChanged()
}
}
}
@@ -797,7 +797,7 @@ func (a *App) emitLog(source, line string) {
if a.ctx == nil {
return
}
wailsRuntime.EventsEmit(a.ctx, "reims:log", map[string]string{
a.emit("reims:log", map[string]string{
"ts": ts,
"source": source,
"line": redacted,
@@ -897,9 +897,7 @@ func (a *App) SetLocale(raw string) error {
if mgr != nil {
mgr.NotifyLocaleChanged(eff)
}
if a.ctx != nil {
wailsRuntime.EventsEmit(a.ctx, "reims:state-changed", true)
}
a.emitStateChanged()
return err
}
@@ -952,9 +950,7 @@ func (a *App) startTray() {
},
OnNewVM: func() {
a.ShowMainWindow()
if a.ctx != nil {
wailsRuntime.EventsEmit(a.ctx, "reims:tray-new-vm")
}
a.emit("reims:tray-new-vm")
},
OnVMAction: a.trayVMAction,
OnQuit: a.QuitApp,
@@ -1032,9 +1028,7 @@ func (a *App) trayVMAction(driverID, name string, act tray.Action) {
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)
}
a.emit("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:
@@ -1055,9 +1049,7 @@ func (a *App) trayVMAction(driverID, name string, act tray.Action) {
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)
}
a.emit("reims:tray-select-vm", name)
}
if err != nil {
a.emitVMLog(name, failTitle+": "+err.Error())
@@ -1178,9 +1170,7 @@ func (a *App) SetDataRoot(dir string) error {
if rootChanged {
a.reloadPlugins()
a.wakePoll()
if a.ctx != nil {
wailsRuntime.EventsEmit(a.ctx, "reims:state-changed", true)
}
a.emitStateChanged()
}
return nil
}
@@ -1245,7 +1235,6 @@ 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)
@@ -1262,9 +1251,7 @@ func (a *App) RemoveRuntime(commit string) error {
}
}
a.emitLog("runtime", fmt.Sprintf("Removed runtime %s (%s)", inst.Commit, inst.Dir))
if ctx != nil {
wailsRuntime.EventsEmit(ctx, "reims:state-changed", true)
}
a.emitStateChanged()
return nil
}
+1 -1
View File
@@ -31,6 +31,6 @@ func (a *App) cloneVMCoWWithDriverInfo(driverID, sourceName, cloneName string) (
return driver.VMInfo{}, err
}
a.wakePoll()
a.emitLifecycleStateChanged()
a.emitStateChanged()
return cloned, nil
}
+3 -8
View File
@@ -17,7 +17,6 @@ import (
"github.com/Nwflower/reims-go/internal/networkmsg"
"github.com/Nwflower/reims-go/internal/packetbridge"
rt "github.com/Nwflower/reims-go/internal/runtime"
wailsRuntime "github.com/wailsapp/wails/v2/pkg/runtime"
)
func (a *App) createVMFlow(opts reims.CreateOpts) (err error) {
@@ -203,7 +202,7 @@ func (a *App) createVMFlow(opts reims.CreateOpts) (err error) {
vmDir = filepath.Join(cfgCopy.XDGDataDir(), "reims-ctl", "vms", opts.Name)
}
}
if werr := writeVMMacOS(vmDir, release); werr != nil {
if werr := reims.WriteReleaseRecord(vmDir, release); werr != nil {
a.emitVMLog(opts.Name, fmt.Sprintf("Warning: could not record macOS release (%s): %v", release, werr))
}
if guestLang != "" {
@@ -220,17 +219,13 @@ func (a *App) createVMFlow(opts reims.CreateOpts) (err error) {
err = networkmsg.Error("create_bridge_pending", networkErr, "name", opts.Name)
finishTask(err)
a.emitLog(opts.Name, networkmsg.Text(a.locale(), "log.create_bridge_failed")+" "+networkmsg.Localize(networkErr, a.locale()).Error())
if a.ctx != nil {
wailsRuntime.EventsEmit(a.ctx, "reims:state-changed", true)
}
a.emitStateChanged()
return err
}
}
finishTask(nil)
a.emitVMLog(opts.Name, "VM "+opts.Name+" ready.")
if a.ctx != nil {
wailsRuntime.EventsEmit(a.ctx, "reims:state-changed", true)
}
a.emitStateChanged()
if startAfterCreate && ctx.Err() == nil {
return a.StartVMWithDriver(driver.BuiltinReimsMacOSDriverID, opts.Name)
}
+1 -4
View File
@@ -9,7 +9,6 @@ import (
"github.com/Nwflower/reims-go/internal/dataroot"
"github.com/Nwflower/reims-go/internal/i18n"
"github.com/Nwflower/reims-go/internal/version"
wailsRuntime "github.com/wailsapp/wails/v2/pkg/runtime"
)
// openDataRoot opens the current data folder (dataroot.Open: version check,
@@ -107,9 +106,7 @@ func (a *App) ReopenDataRoot(repair bool) (dataroot.Status, error) {
a.reloadPlugins()
a.wakePoll()
}
if a.ctx != nil {
wailsRuntime.EventsEmit(a.ctx, "reims:state-changed", true)
}
a.emitStateChanged()
return st, nil
}
+2 -2
View File
@@ -34,7 +34,7 @@ func (a *App) ResizeVMDiskWithDriver(driverID, name, newSize string) (driver.Dis
finishTask(nil)
a.emitVMLogForDriver(driverID, name, fmt.Sprintf("Expanded disk for %s: %.0f GB -> %.0f GB", name, float64(res.OldVirtualBytes)/float64(1<<30), float64(res.NewVirtualBytes)/float64(1<<30)))
a.wakePoll()
a.emitLifecycleStateChanged()
a.emitStateChanged()
return res, nil
}
@@ -89,6 +89,6 @@ func (a *App) runCompactVMDisk(driverID, name string, optimize bool) (driver.Dis
finishTask(nil)
a.emitVMLogForDriver(driverID, name, fmt.Sprintf("Rewrote disk for %s: %.2f GB -> %.2f GB (reclaimed %.2f GB, extended L2: %t)", name, float64(res.BeforeBytes)/float64(1<<30), float64(res.AfterBytes)/float64(1<<30), float64(res.ReclaimedBytes)/float64(1<<30), res.ExtendedL2Enabled))
a.wakePoll()
a.emitLifecycleStateChanged()
a.emitStateChanged()
return res, nil
}
+1 -1
View File
@@ -103,7 +103,7 @@ func (a *App) SetVMDisplayWithDriver(driverID, name, targetDisplay string) (VMDi
if _, err := vmstart.SaveVMDisplay(vm.Directory, cfg); err != nil {
return VMDisplayStatus{}, err
}
defer a.emitLifecycleStateChanged()
defer a.emitStateChanged()
if !status.Running || len(displays) == 0 {
return status, nil
}
+1 -4
View File
@@ -7,7 +7,6 @@ import (
"github.com/Nwflower/reims-go/internal/guesttools"
"github.com/Nwflower/reims-go/internal/host"
wailsRuntime "github.com/wailsapp/wails/v2/pkg/runtime"
)
// DriveShareInfo describes one currently available internal fixed drive.
@@ -208,8 +207,6 @@ func (a *App) SetVMDriveShareSettings(name string, enabled bool, drives []string
return DriveShareSettings{}, err
}
a.emitVMLog(name, fmt.Sprintf("Read-only Windows drive sharing enabled=%v drives=%v", enabled, normalized))
if a.ctx != nil {
wailsRuntime.EventsEmit(a.ctx, "reims:state-changed", true)
}
a.emitStateChanged()
return makeDriveShareSettings(cfg, available), nil
}
+3 -4
View File
@@ -12,7 +12,6 @@ import (
"github.com/Nwflower/reims-go/internal/host"
"github.com/Nwflower/reims-go/internal/i18n"
"github.com/Nwflower/reims-go/internal/plugin"
wailsRuntime "github.com/wailsapp/wails/v2/pkg/runtime"
)
// elevatePromptTimeout is how long a confirmation waits for the person.
@@ -122,8 +121,8 @@ func (a *App) requestElevation(ctx context.Context, broker *plugin.Broker, reg *
dismissed = true
if dismiss != nil {
dismiss(prompt.ID)
} else if emit == nil && winCtx != nil {
wailsRuntime.EventsEmit(winCtx, "reims:elevate-resolved", prompt.ID)
} else if emit == nil {
a.emit("reims:elevate-resolved", prompt.ID)
}
}
defer clearPrompt()
@@ -132,7 +131,7 @@ func (a *App) requestElevation(ctx context.Context, broker *plugin.Broker, reg *
emit(prompt)
} else {
a.ShowMainWindow()
wailsRuntime.EventsEmit(winCtx, "reims:elevate-request", prompt)
a.emit("reims:elevate-request", prompt)
}
timer := time.NewTimer(elevatePromptTimeout)
+14
View File
@@ -0,0 +1,14 @@
package app
import wailsRuntime "github.com/wailsapp/wails/v2/pkg/runtime"
// emit sends an event to the frontend, which subscribes in frontend/src/wails.ts.
// Without a window it does nothing.
func (a *App) emit(name string, data ...any) {
if a.ctx != nil {
wailsRuntime.EventsEmit(a.ctx, name, data...)
}
}
// emitStateChanged asks the frontend to read the application state again.
func (a *App) emitStateChanged() { a.emit("reims:state-changed", true) }
-12
View File
@@ -25,18 +25,6 @@ func TestParseDiskSnapshotsJSON(t *testing.T) {
}
}
func TestValidateSnapshotName(t *testing.T) {
if got, err := reims.ValidateSnapshotName(" before-ota-26.2 "); err != nil || got != "before-ota-26.2" {
t.Fatalf("valid name failed: %q %v", got, err)
}
if _, err := reims.ValidateSnapshotName(" "); err == nil {
t.Fatal("expected error for empty snapshot name")
}
if _, err := reims.ValidateSnapshotName(`bad"quote`); err == nil {
t.Fatal("expected error for quote in snapshot name")
}
}
func TestSanitizeVMNoteAndStorageBreakdown(t *testing.T) {
if got := sanitizeVMNote(" Xcode 26\nBuilder "); got != "Xcode 26 Builder" {
t.Fatalf("sanitizeVMNote = %q", got)
+1 -4
View File
@@ -13,7 +13,6 @@ import (
"github.com/Nwflower/reims-go/internal/guesttools"
"github.com/Nwflower/reims-go/internal/host"
wailsRuntime "github.com/wailsapp/wails/v2/pkg/runtime"
)
type SharedFolderInfo struct {
@@ -382,8 +381,6 @@ func (a *App) changeVMSharedFolder(vmName, vmDir, folderID, action, hostPath str
}
srv.RegisterVM(validated)
a.emitVMLog(vmName, fmt.Sprintf("Shared folder id=%s mode=%s count=%d", id, logMode, len(cfg.SharedFolders)))
if a.ctx != nil {
wailsRuntime.EventsEmit(a.ctx, "reims:state-changed", true)
}
a.emitStateChanged()
return settings, nil
}
+1 -1
View File
@@ -65,7 +65,7 @@ func (a *App) SetFullscreenHotkey(req FullscreenHotkeyConfig) (FullscreenHotkeyS
a.mu.Unlock()
a.syncFullscreenHotkeyTargets()
a.emitLifecycleStateChanged()
a.emitStateChanged()
return a.GetFullscreenHotkey(), nil
}
+5 -11
View File
@@ -478,7 +478,7 @@ func (a *App) AttachGuestTools(name string) error {
return err
}
}
if a.isVMRunning(ctx, c, name, d) {
if c.IsRunning(ctx, d) {
a.mu.Lock()
a.pendingChanges[vmKey(name)] = append(a.pendingChanges[vmKey(name)], PendingChange{
Field: "guest_tools",
@@ -488,9 +488,7 @@ func (a *App) AttachGuestTools(name string) error {
a.mu.Unlock()
}
a.emitVMLog(name, fmt.Sprintf("Guest Tools disk (REIMSTOOLS) attached on 127.0.0.1:%d; shared folder: %s", port, sharedDir))
if a.ctx != nil {
wailsRuntime.EventsEmit(a.ctx, "reims:state-changed", true)
}
a.emitStateChanged()
return nil
}
@@ -513,7 +511,7 @@ func (a *App) DetachGuestTools(name string) error {
if err := c.Set(ctx, reims.SetOpts{Name: name, ExtraArgs: &stripped}, w, w); err != nil {
return err
}
if a.isVMRunning(ctx, c, name, d) {
if c.IsRunning(ctx, d) {
a.mu.Lock()
a.pendingChanges[vmKey(name)] = append(a.pendingChanges[vmKey(name)], PendingChange{
Field: "guest_tools",
@@ -524,9 +522,7 @@ func (a *App) DetachGuestTools(name string) error {
}
}
a.emitVMLog(name, "Guest Tools disk (REIMSTOOLS) ejected; clipboard & shared folder bridge remains active")
if a.ctx != nil {
wailsRuntime.EventsEmit(a.ctx, "reims:state-changed", true)
}
a.emitStateChanged()
return nil
}
@@ -575,9 +571,7 @@ func (a *App) SetGuestPreventSleep(name string, enabled bool) error {
return err
}
a.emitVMLog(name, fmt.Sprintf("Guest Tools prevent-sleep guard set to %v", enabled))
if a.ctx != nil {
wailsRuntime.EventsEmit(a.ctx, "reims:state-changed", true)
}
a.emitStateChanged()
return nil
}
+1 -4
View File
@@ -6,7 +6,6 @@ import (
"time"
"github.com/Nwflower/reims-go/internal/guesttools"
wailsRuntime "github.com/wailsapp/wails/v2/pkg/runtime"
)
func (a *App) hostDNSConfigLocked() guesttools.HostDNSConfig {
@@ -119,8 +118,6 @@ func (a *App) SetGuestToolsHostDNS(name string, enabled bool) error {
if err := a.registerGuestToolsConfig(srv, d.Directory, cfg); err != nil {
return err
}
if a.ctx != nil {
wailsRuntime.EventsEmit(a.ctx, "reims:state-changed", true)
}
a.emitStateChanged()
return nil
}
+4 -5
View File
@@ -14,7 +14,6 @@ import (
"time"
"github.com/Nwflower/reims-go/internal/guesttools"
wailsRuntime "github.com/wailsapp/wails/v2/pkg/runtime"
)
const MaxHostDropFileBytes int64 = 2 << 30
@@ -184,8 +183,8 @@ func (a *App) handleHostDrop(vmKey, name string, req guesttools.HostDropRequest)
result.Delivered = append(result.Delivered, delivered)
}
a.emitVMLog(name, fmt.Sprintf("Host drop %s: delivered %d, skipped %d", result.DropID, len(result.Delivered), len(result.Skipped)))
if a.ctx != nil && len(result.Delivered) > 0 {
wailsRuntime.EventsEmit(a.ctx, "reims:host-drop", map[string]any{
if len(result.Delivered) > 0 {
a.emit("reims:host-drop", map[string]any{
"vm": name, "drop_id": result.DropID, "delivered": result.Delivered, "skipped": result.Skipped, "mode": result.Mode,
})
}
@@ -215,8 +214,8 @@ func (a *App) handleHostDropAck(vmKey, name string, ack guesttools.DropEventAck)
srv.RevokeDropShare(vmKey, ack.DropID)
}
a.emitVMLog(name, fmt.Sprintf("Host drop %s: %s (%s)", ack.DropID, ack.Status, ack.TargetKind))
if ack.Status != "cancelled" && a.ctx != nil {
wailsRuntime.EventsEmit(a.ctx, "reims:host-drop-ack", map[string]any{
if ack.Status != "cancelled" {
a.emit("reims:host-drop-ack", map[string]any{
"vm": name, "drop_id": ack.DropID, "status": ack.Status, "target_kind": ack.TargetKind,
"target_label": ack.TargetLabel, "placed_names": ack.PlacedNames, "error": ack.Error,
})
+3 -8
View File
@@ -7,7 +7,6 @@ import (
"github.com/Nwflower/reims-go/internal/dataroot"
"github.com/Nwflower/reims-go/internal/host"
"github.com/Nwflower/reims-go/internal/i18n"
wailsRuntime "github.com/wailsapp/wails/v2/pkg/runtime"
)
var (
@@ -28,10 +27,9 @@ func (a *App) SetEnableHypervisorSwitch(enabled bool) error {
if err != nil {
a.cfg.EnableHypervisorSwitch = prev
}
ctx := a.ctx
a.mu.Unlock()
if err == nil && ctx != nil {
wailsRuntime.EventsEmit(ctx, "reims:state-changed", true)
if err == nil {
a.emitStateChanged()
}
return err
}
@@ -56,7 +54,6 @@ func (a *App) setHypervisorBootInternal(enable bool) (bool, error) {
dataRoot := a.cfg.DataRoot
needsSetup := a.needsSetup
rootStatus := a.root
ctx := a.ctx
if rootStatus.ReadOnly {
a.mu.Unlock()
return false, dataroot.Error(loc, rootStatus)
@@ -124,9 +121,7 @@ func (a *App) setHypervisorBootInternal(enable bool) (bool, error) {
} else {
a.emitLog("host", "Updated Windows hypervisor boot configuration (next boot: "+pending+"); restart Windows manually to apply")
}
if ctx != nil {
wailsRuntime.EventsEmit(ctx, "reims:state-changed", true)
}
a.emitStateChanged()
return true, nil
}
+10 -33
View File
@@ -14,7 +14,6 @@ import (
"github.com/Nwflower/reims-go/internal/macos/reims"
"github.com/Nwflower/reims-go/internal/macos/startprep"
"github.com/Nwflower/reims-go/internal/vmstart"
wailsRuntime "github.com/wailsapp/wails/v2/pkg/runtime"
)
// isRecoveryModeActive reports whether d has an installer attached or an
@@ -58,20 +57,6 @@ func (a *App) pickCachedRecoveryInstaller() (string, error) {
return "", nil
}
func (a *App) isVMRunning(ctx context.Context, c *reims.Client, name string, d reims.VMDetail) bool {
if d.State == "running" {
return true
}
if list, err := c.List(ctx); err == nil {
for _, vm := range list {
if vm.Name == name && vm.State == "running" {
return true
}
}
}
return false
}
// EnterRecovery routes the macOS recovery action through the lifecycle service.
// The legacy path remains available for minimal embedding without a plugin manager.
func (a *App) EnterRecovery(name string) error {
@@ -99,7 +84,7 @@ func (a *App) EnterRecovery(name string) error {
a.emitVMLog(name, "Recovery mode enabled for "+name+" (pick Recovery in OpenCore boot menu)")
}
a.wakePoll()
a.emitLifecycleStateChanged()
a.emitStateChanged()
return nil
}
@@ -119,7 +104,7 @@ func (a *App) enterMacOSRecovery(name string) error {
w := vmstart.LineWriter(func(line string) { a.emitVMLog(name, line) })
ctx := context.Background()
if a.isVMRunning(ctx, c, name, d) {
if c.IsRunning(ctx, d) {
marker := startprep.ReadRecoveryMarker(d.Directory)
if marker != "on" {
startprep.WriteRecoveryMarker(d.Directory, "want")
@@ -143,9 +128,7 @@ func (a *App) enterMacOSRecovery(name string) error {
}
a.emitVMLog(name, "Recovery mode enabled for "+name+" (pick Recovery in OpenCore boot menu)")
}
if a.ctx != nil {
wailsRuntime.EventsEmit(a.ctx, "reims:state-changed", true)
}
a.emitStateChanged()
return nil
}
@@ -203,7 +186,7 @@ func (a *App) AttachInstaller(name, installerPath string) (string, error) {
if err != nil {
return "", err
}
if a.isVMRunning(ctx, c, name, d) {
if c.IsRunning(ctx, d) {
a.mu.Lock()
a.pendingChanges[vmKey(name)] = append(a.pendingChanges[vmKey(name)], PendingChange{
Field: "installer",
@@ -212,9 +195,7 @@ func (a *App) AttachInstaller(name, installerPath string) (string, error) {
})
a.mu.Unlock()
}
if a.ctx != nil {
wailsRuntime.EventsEmit(a.ctx, "reims:state-changed", true)
}
a.emitStateChanged()
return base, nil
}
@@ -329,7 +310,7 @@ func (a *App) FinishInstall(name string) error {
}
a.emitVMLog(name, "Exited recovery mode")
a.wakePoll()
a.emitLifecycleStateChanged()
a.emitStateChanged()
return nil
}
@@ -383,7 +364,7 @@ func (a *App) finishMacOSInstall(name string) error {
}
}
running := a.isVMRunning(ctx, c, name, d)
running := c.IsRunning(ctx, d)
marker := startprep.ReadRecoveryMarker(d.Directory)
if running {
var diffs []PendingChange
@@ -424,9 +405,7 @@ func (a *App) finishMacOSInstall(name string) error {
}
}
a.emitVMLog(name, "Exited recovery mode")
if a.ctx != nil {
wailsRuntime.EventsEmit(a.ctx, "reims:state-changed", true)
}
a.emitStateChanged()
return nil
}
@@ -471,7 +450,7 @@ func (a *App) UpgradeDiskToNVMe(name string) error {
if err != nil {
return err
}
if a.isVMRunning(ctx, c, name, d) {
if c.IsRunning(ctx, d) {
a.mu.Lock()
a.pendingChanges[vmKey(name)] = append(a.pendingChanges[vmKey(name)], PendingChange{
Field: "disk_controller",
@@ -480,8 +459,6 @@ func (a *App) UpgradeDiskToNVMe(name string) error {
})
a.mu.Unlock()
}
if a.ctx != nil {
wailsRuntime.EventsEmit(a.ctx, "reims:state-changed", true)
}
a.emitStateChanged()
return nil
}
+3 -3
View File
@@ -29,17 +29,17 @@ func TestLegacyExtraArgsAdoptedWithoutDuplication(t *testing.T) {
PluginID: builtin.IDGuestTools,
Args: []plugin.ArgFragment{{
PluginID: builtin.IDGuestTools, Key: "reimstools", Builtin: true, Priority: 80,
Tokens: plugin.SplitShellTokens(reims.MergeGuestToolsArgs("", `D:\Data\cache\tools.img`)),
Tokens: qmp.SplitArgs(reims.MergeGuestToolsArgs("", `D:\Data\cache\tools.img`)),
}},
},
{
PluginID: guest.ID,
Args: []plugin.ArgFragment{{
PluginID: guest.ID, Key: "reimshelp", Builtin: true, Priority: 85,
Tokens: plugin.SplitShellTokens(reims.MergeOfflineHelperArgs("", `D:\Data\cache\reimshelp.img`)),
Tokens: qmp.SplitArgs(reims.MergeOfflineHelperArgs("", `D:\Data\cache\reimshelp.img`)),
}, {
PluginID: guest.ID, Key: "win10-cold-reboot", Builtin: true, Priority: 95,
Tokens: plugin.SplitShellTokens(qmp.MergeWin10RebootUnixArgs("", `D:\Data\vms\mac\reims-go-reboot.sock`)),
Tokens: qmp.SplitArgs(qmp.MergeWin10RebootUnixArgs("", `D:\Data\vms\mac\reims-go-reboot.sock`)),
}},
},
}
+7 -14
View File
@@ -12,15 +12,8 @@ import (
"github.com/Nwflower/reims-go/internal/plugin"
"github.com/Nwflower/reims-go/internal/plugin/builtin"
"github.com/Nwflower/reims-go/internal/vmstart"
wailsRuntime "github.com/wailsapp/wails/v2/pkg/runtime"
)
func (a *App) emitLifecycleStateChanged() {
if a.ctx != nil {
wailsRuntime.EventsEmit(a.ctx, "reims:state-changed", true)
}
}
func (a *App) emitVMLogForDriver(driverID, name, line string) {
a.emitLog(vmKeyForDriver(driverID, name), line)
}
@@ -146,7 +139,7 @@ func (a *App) startResolvedVMLocked(ctx context.Context, svc interface {
a.transitions[key] = "starting"
delete(a.pendingChanges, key)
a.mu.Unlock()
a.emitLifecycleStateChanged()
a.emitStateChanged()
startAt := time.Now()
if ref.DriverID == driver.BuiltinReimsMacOSDriverID {
rep := host.Inspect(a.currentDataRoot())
@@ -160,7 +153,7 @@ func (a *App) startResolvedVMLocked(ctx context.Context, svc interface {
delete(a.transitions, key)
a.mu.Unlock()
a.emitVMLogForDriver(ref.DriverID, ref.Name, "Start error: "+err.Error())
a.emitLifecycleStateChanged()
a.emitStateChanged()
return err
}
if ref.DriverID == driver.BuiltinReimsMacOSDriverID {
@@ -175,7 +168,7 @@ func (a *App) startResolvedVMLocked(ctx context.Context, svc interface {
a.startVMMonitor(ref.Name, detail, startAt)
}
a.wakePoll()
a.emitLifecycleStateChanged()
a.emitStateChanged()
return nil
}
@@ -209,7 +202,7 @@ func (a *App) stopVMWithDriverCtx(ctx context.Context, driverID, name string, fo
a.mu.Lock()
a.transitions[key] = "stopping"
a.mu.Unlock()
a.emitLifecycleStateChanged()
a.emitStateChanged()
w := vmstart.LineWriter(func(line string) { a.emitVMLogForDriver(ref.DriverID, ref.Name, line) })
if err := svc.Stop(operationCtx, ref, force, w, w); err != nil {
a.mu.Lock()
@@ -224,7 +217,7 @@ func (a *App) stopVMWithDriverCtx(ctx context.Context, driverID, name string, fo
delete(a.pendingChanges, key)
a.mu.Unlock()
a.wakePoll()
a.emitLifecycleStateChanged()
a.emitStateChanged()
return nil
})
}
@@ -250,7 +243,7 @@ func (a *App) EjectInstallerWithDriver(driverID, name string) error {
})
if err == nil {
a.wakePoll()
a.emitLifecycleStateChanged()
a.emitStateChanged()
}
return err
}
@@ -378,7 +371,7 @@ func (a *App) DeleteVMWithDriver(driverID, name string, keepFiles bool) error {
gt.UnregisterVM(key)
}
a.wakePoll()
a.emitLifecycleStateChanged()
a.emitStateChanged()
return deleteErr
})
}
+11
View File
@@ -97,3 +97,14 @@ func populateSuspendDetail(d *reims.VMDetail) {
}
}
}
// GetVMMacOS returns the macOS release recorded when the VM was created. It is
// "" for VMs made from an existing disk or before this was recorded; the UI
// then guesses from the VM's name.
func (a *App) GetVMMacOS(name string) string {
dir := a.vmDirectory(name)
if dir == "" {
return ""
}
return reims.ReadReleaseRecord(dir)
}
+7 -8
View File
@@ -19,7 +19,6 @@ import (
"github.com/Nwflower/reims-go/internal/plugin/builtin"
"github.com/Nwflower/reims-go/internal/qmp"
"github.com/Nwflower/reims-go/internal/vmstart"
wailsRuntime "github.com/wailsapp/wails/v2/pkg/runtime"
)
const (
@@ -350,7 +349,7 @@ func (a *App) startMacOSVM(name string) error {
a.transitions[vmKey(name)] = "starting"
delete(a.pendingChanges, vmKey(name))
a.mu.Unlock()
wailsRuntime.EventsEmit(a.ctx, "reims:state-changed", true)
a.emitStateChanged()
startAt := time.Now()
a.emitStartSummary(name, vmInfoFromMacOSDetail(curDetail), rep, qmpAddr)
@@ -363,7 +362,7 @@ func (a *App) startMacOSVM(name string) error {
delete(a.transitions, vmKey(name))
a.mu.Unlock()
a.emitVMLog(name, "Start error: "+err.Error())
wailsRuntime.EventsEmit(a.ctx, "reims:state-changed", true)
a.emitStateChanged()
return err
}
if qmpAddr != "" && mgr == nil {
@@ -379,7 +378,7 @@ func (a *App) startMacOSVM(name string) error {
}
a.startVMMonitor(name, vmInfoFromMacOSDetail(curDetail), startAt)
a.wakePoll()
wailsRuntime.EventsEmit(a.ctx, "reims:state-changed", true)
a.emitStateChanged()
return nil
}
@@ -460,7 +459,7 @@ func (a *App) stopMacOSVMLocked(ctx context.Context, name string, force bool, c
DriverID: builtin.IDDriverReimsMacOS,
})
}
wailsRuntime.EventsEmit(a.ctx, "reims:state-changed", true)
a.emitStateChanged()
w := vmstart.LineWriter(func(line string) { a.emitVMLog(name, line) })
a.emitVMLog(name, fmt.Sprintf("Stopping %s (force=%v)...", name, force))
@@ -488,7 +487,7 @@ func (a *App) stopMacOSVMLocked(ctx context.Context, name string, force bool, c
})
}
a.wakePoll()
wailsRuntime.EventsEmit(a.ctx, "reims:state-changed", true)
a.emitStateChanged()
return nil
}
@@ -555,7 +554,7 @@ func (a *App) ejectMacOSInstaller(name string) error {
return err
}
a.emitVMLog(name, "Installer ejected.")
wailsRuntime.EventsEmit(a.ctx, "reims:state-changed", true)
a.emitStateChanged()
return nil
}
@@ -604,7 +603,7 @@ func (a *App) deleteMacOSVMLocked(ctx context.Context, name string, keepFiles bo
})
}
a.wakePoll()
wailsRuntime.EventsEmit(a.ctx, "reims:state-changed", true)
a.emitStateChanged()
return nil
}
-40
View File
@@ -1,40 +0,0 @@
package app
import (
"os"
"path/filepath"
"strings"
)
// vmMacOSFileName records which macOS release a VM was created with, for its
// icon. reims-ctl keeps no such field in vm.toml.
const vmMacOSFileName = ".reims-go-macos"
// GetVMMacOS returns the macOS release recorded when the VM was created: an
// installer version such as "26.7.3", or a codename such as "tahoe" for an
// online-recovery install. It is "" for VMs made from an existing disk or
// before this was recorded; the UI then guesses from the VM's name.
func (a *App) GetVMMacOS(name string) string {
dir := a.vmDirectory(name)
if dir == "" {
return ""
}
return readVMMacOS(dir)
}
func readVMMacOS(dir string) string {
b, err := os.ReadFile(filepath.Join(dir, vmMacOSFileName))
if err != nil {
return ""
}
return strings.TrimSpace(string(b))
}
// writeVMMacOS stores release next to vm.toml; an empty release writes nothing.
func writeVMMacOS(dir, release string) error {
release = strings.TrimSpace(strings.ReplaceAll(strings.ReplaceAll(release, "\r", ""), "\n", ""))
if dir == "" || release == "" {
return nil
}
return os.WriteFile(filepath.Join(dir, vmMacOSFileName), []byte(release+"\n"), 0o644)
}
-25
View File
@@ -1,25 +0,0 @@
package app
import "testing"
func TestVMMacOSRoundTrip(t *testing.T) {
dir := t.TempDir()
if got := readVMMacOS(dir); got != "" {
t.Fatalf("empty dir: got %q", got)
}
if err := writeVMMacOS(dir, ""); err != nil {
t.Fatal(err)
}
if got := readVMMacOS(dir); got != "" {
t.Fatalf("empty release wrote %q", got)
}
if err := writeVMMacOS(dir, " 26.7.3\r\n"); err != nil {
t.Fatal(err)
}
if got := readVMMacOS(dir); got != "26.7.3" {
t.Fatalf("got %q, want 26.7.3", got)
}
if err := writeVMMacOS("", "tahoe"); err != nil {
t.Fatalf("no dir should be a no-op, got %v", err)
}
}
+2 -5
View File
@@ -22,7 +22,6 @@ import (
"github.com/Nwflower/reims-go/internal/qmp"
rt "github.com/Nwflower/reims-go/internal/runtime"
"github.com/Nwflower/reims-go/internal/vmstart"
wailsRuntime "github.com/wailsapp/wails/v2/pkg/runtime"
)
// ToggleBorderless switches borderless fullscreen startup through the native macOS settings flow.
@@ -206,7 +205,7 @@ func (a *App) ApplyVMSettings(opts reims.SetOpts) (err error) {
}
}
a.emitVMLog(opts.Name, "Updated VM settings for "+opts.Name)
wailsRuntime.EventsEmit(a.ctx, "reims:state-changed", true)
a.emitStateChanged()
return nil
}
@@ -480,9 +479,7 @@ func (a *App) applyVMNetwork(parent context.Context, name, mode, uplink string)
} else if err := a.applyPacketNetwork(ctx, c, d, mode, selected, record); err != nil {
return VMNetworkSettings{}, err
}
if a.ctx != nil {
wailsRuntime.EventsEmit(a.ctx, "reims:state-changed", true)
}
a.emitStateChanged()
settings, err := a.GetVMNetworkSettings(name)
if err != nil {
a.emitLog(name, networkmsg.Text(a.locale(), "log.refresh_failed"))
+2 -5
View File
@@ -7,7 +7,6 @@ import (
"github.com/Nwflower/reims-go/internal/macos/reims"
"github.com/Nwflower/reims-go/internal/macos/startprep"
rt "github.com/Nwflower/reims-go/internal/runtime"
wailsRuntime "github.com/wailsapp/wails/v2/pkg/runtime"
)
// populateGuestLangDetail fills VMDetail.GuestLang from the VM's persisted
@@ -102,7 +101,7 @@ func (a *App) ApplyVMSMBIOS(name string, id opencore.SMBIOSIdentity) (opencore.S
return opencore.SMBIOSIdentity{}, err
}
defer release()
if a.isVMRunning(ctx, c, name, d) {
if c.IsRunning(ctx, d) {
return opencore.SMBIOSIdentity{}, fmt.Errorf("stop %s before updating its SMBIOS identity", name)
}
if d.State == "suspended" {
@@ -132,9 +131,7 @@ func (a *App) ApplyVMSMBIOS(name string, id opencore.SMBIOSIdentity) (opencore.S
}
// Never log Serial, MLB, UUID, or ROM into VM/app logs.
a.emitVMLog(name, fmt.Sprintf("Updated OpenCore SMBIOS identity (%s)", modelLabel))
if a.ctx != nil {
wailsRuntime.EventsEmit(a.ctx, "reims:state-changed", true)
}
a.emitStateChanged()
}
return updated, nil
}
+14 -25
View File
@@ -30,7 +30,6 @@ import (
rt "github.com/Nwflower/reims-go/internal/runtime"
"github.com/Nwflower/reims-go/internal/version"
"github.com/Nwflower/reims-go/internal/vmstart"
wailsRuntime "github.com/wailsapp/wails/v2/pkg/runtime"
)
// PluginUIContributions aggregates all active declarative plugin UI contributions
@@ -121,7 +120,7 @@ func (a *App) initPlugins() {
return err
}
a.wakePoll()
a.emitLifecycleStateChanged()
a.emitStateChanged()
return nil
})
mgr.Broker().SetVMExitHandler(func(string, string) { a.wakePoll() })
@@ -200,9 +199,7 @@ func (a *App) initPlugins() {
},
StopPacketBridges: a.closePacketBridges,
OnInstallGuidesChanged: func() {
if a.ctx != nil {
wailsRuntime.EventsEmit(a.ctx, "reims:state-changed", true)
}
a.emitStateChanged()
},
SyncInstallGuides: func() {
a.wakePoll()
@@ -236,9 +233,7 @@ func (a *App) initPlugins() {
a.syncClipboardPolicies()
a.syncLocales()
a.wakePoll()
if a.ctx != nil {
wailsRuntime.EventsEmit(a.ctx, "reims:state-changed", true)
}
a.emitStateChanged()
})
a.keymapMu.Lock()
@@ -537,9 +532,7 @@ func (a *App) onPluginSettingsChanged(pluginID, vmName string) {
}
}
}
if a.ctx != nil {
wailsRuntime.EventsEmit(a.ctx, "reims:state-changed", true)
}
a.emitStateChanged()
}
func clipboardPolicyFromMap(vals map[string]any) guesttools.ClipboardPolicy {
@@ -671,8 +664,8 @@ func (a *App) InstallPluginArchive(archivePath string) (*plugin.PluginInfo, erro
return nil, errors.New("plugin manager not initialized")
}
info, err := mgr.InstallLocalArchive(context.Background(), archivePath, plugin.PackageInstallOptions{})
if err == nil && a.ctx != nil {
wailsRuntime.EventsEmit(a.ctx, "reims:state-changed", true)
if err == nil {
a.emitStateChanged()
}
return info, err
}
@@ -685,8 +678,8 @@ func (a *App) LinkPluginDev(dir string) (*plugin.PluginInfo, error) {
return nil, errors.New("plugin manager not initialized")
}
info, err := mgr.LinkDev(context.Background(), dir)
if err == nil && a.ctx != nil {
wailsRuntime.EventsEmit(a.ctx, "reims:state-changed", true)
if err == nil {
a.emitStateChanged()
}
return info, err
}
@@ -825,8 +818,8 @@ func (a *App) SetActiveTheme(themeID, schemeID string) error {
return errors.New("plugin manager not initialized")
}
err := mgr.SetActiveTheme(themeID, schemeID)
if err == nil && a.ctx != nil {
wailsRuntime.EventsEmit(a.ctx, "reims:state-changed", true)
if err == nil {
a.emitStateChanged()
}
return err
}
@@ -921,9 +914,7 @@ func (a *App) CreateVMWithDriver(req driver.CreateRequest) error {
})
}
a.wakePoll()
if a.ctx != nil {
wailsRuntime.EventsEmit(a.ctx, "reims:state-changed", true)
}
a.emitStateChanged()
return nil
}
@@ -1139,9 +1130,7 @@ func (a *App) InstallMarketPlugin(pluginID string, includeAlpha bool) (*plugin.P
lastEmit time.Time
)
emit := func(p MarketInstallProgress) {
if a.ctx != nil {
wailsRuntime.EventsEmit(a.ctx, "reims:plugin-install", p)
}
a.emit("reims:plugin-install", p)
}
info, err := a.getPluginMarket().InstallFromMarket(context.Background(), mgr, pluginID, plugin.MarketInstallOptions{
IncludeAlpha: includeAlpha,
@@ -1165,8 +1154,8 @@ func (a *App) InstallMarketPlugin(pluginID string, includeAlpha bool) (*plugin.P
emit(MarketInstallProgress{ID: pluginID, Phase: ph, Done: done, Total: total})
},
})
if err == nil && a.ctx != nil {
wailsRuntime.EventsEmit(a.ctx, "reims:state-changed", true)
if err == nil {
a.emitStateChanged()
}
return info, err
}
+1 -3
View File
@@ -122,9 +122,7 @@ func (a *App) InstallRuntimeOnline(commit string) (string, error) {
a.emitLog("runtime", "Runtime install error: "+err.Error())
tasks.finish(id, "", err)
}
if a.ctx != nil {
wailsRuntime.EventsEmit(a.ctx, "reims:state-changed", true)
}
a.emitStateChanged()
}()
return id, nil
}
+1 -4
View File
@@ -16,7 +16,6 @@ import (
"github.com/Nwflower/reims-go/internal/host"
"github.com/Nwflower/reims-go/internal/i18n"
"github.com/Nwflower/reims-go/internal/version"
wailsRuntime "github.com/wailsapp/wails/v2/pkg/runtime"
)
// DataRootChoice is a suggested data folder on one drive.
@@ -150,9 +149,7 @@ func (a *App) CompleteSetup(dir string) error {
a.resetDataRootCaches()
a.reloadPlugins()
a.wakePoll()
if a.ctx != nil {
wailsRuntime.EventsEmit(a.ctx, "reims:state-changed", true)
}
a.emitStateChanged()
return nil
}
+1 -1
View File
@@ -68,6 +68,6 @@ func (a *App) runSnapshotOpWithDriver(driverID, name, operation, snapName, verb
}
a.emitVMLogForDriver(driverID, name, fmt.Sprintf("%s %q", verb, cleanSnap))
a.wakePoll()
a.emitLifecycleStateChanged()
a.emitStateChanged()
return nil
}
-7
View File
@@ -11,7 +11,6 @@ import (
"github.com/Nwflower/reims-go/internal/i18n"
rt "github.com/Nwflower/reims-go/internal/runtime"
"github.com/Nwflower/reims-go/internal/vmstart"
wailsRuntime "github.com/wailsapp/wails/v2/pkg/runtime"
)
// SuspendVM saves a VM's running state and closes its QEMU process.
@@ -297,11 +296,5 @@ func suspendProgressPercent(p driver.SuspendProgress) (int, bool) {
return pct, true
}
func (a *App) emitStateChanged() {
if a.ctx != nil {
wailsRuntime.EventsEmit(a.ctx, "reims:state-changed", true)
}
}
// Keep context import used cleanly for future cancellation hooks.
var _ context.Context
+1 -4
View File
@@ -16,7 +16,6 @@ import (
"github.com/Nwflower/reims-go/internal/host"
"github.com/Nwflower/reims-go/internal/vmstart"
wailsRuntime "github.com/wailsapp/wails/v2/pkg/runtime"
)
const (
@@ -367,9 +366,7 @@ func (r *rateMeter) add(done int64) float64 {
func (a *App) taskEmitter() func(Task) {
return func(t Task) {
if a.ctx != nil {
wailsRuntime.EventsEmit(a.ctx, "reims:task", t)
}
a.emit("reims:task", t)
}
}
+1 -1
View File
@@ -184,7 +184,7 @@ func (a *App) ToggleVMFullscreenWithDriver(driverID, name string) (bool, error)
return false, i18n.NewCodedError(loc, "E_FULLSCREEN_FAILED", "err.fullscreen_failed", vars, err)
}
a.emitVMLogForDriver(vm.DriverID, name, fmt.Sprintf("VM window full screen: %t", fullscreen))
a.emitLifecycleStateChanged()
a.emitStateChanged()
return fullscreen, nil
}
+1 -1
View File
@@ -147,7 +147,7 @@ func (a *App) probeUIHealth(ctx context.Context, reason string) {
if wailsRuntime.WindowIsMinimised(a.ctx) {
return
}
wailsRuntime.EventsEmit(a.ctx, "reims:ui-ping", pingSentAt.UnixMilli())
a.emit("reims:ui-ping", pingSentAt.UnixMilli())
timer := time.NewTimer(uiHealthPingTimeout)
defer timer.Stop()
+56
View File
@@ -0,0 +1,56 @@
package archtest
import (
"go/ast"
"os"
"regexp"
"strings"
"testing"
)
// TestFrontendEventsMatch keeps both ends of the window event contract in step:
// Go emits only through App.emit, and every event name used in Go is also used
// in the frontend's wails.ts, and the other way round.
func TestFrontendEventsMatch(t *testing.T) {
raw, err := os.ReadFile("../../frontend/src/wails.ts")
if err != nil {
t.Fatal(err)
}
frontend := map[string]bool{}
for _, m := range regexp.MustCompile(`'(reims:[a-z-]+)'`).FindAllStringSubmatch(string(raw), -1) {
frontend[m[1]] = true
}
if len(frontend) < 10 {
t.Fatalf("found only %d event names in wails.ts", len(frontend))
}
backend := map[string]bool{}
for _, s := range sources(t) {
if s.isTest() || !strings.HasPrefix(s.rel, "internal/") {
continue
}
ast.Inspect(s.file, func(n ast.Node) bool {
switch n := n.(type) {
case *ast.SelectorExpr:
if n.Sel.Name == "EventsEmit" && s.rel != "internal/app/events.go" {
t.Errorf("%s calls EventsEmit: use App.emit", s.rel)
}
case *ast.BasicLit:
if name := strings.Trim(n.Value, `"`); strings.HasPrefix(name, "reims:") {
backend[name] = true
}
}
return true
})
}
for name := range backend {
if !frontend[name] {
t.Errorf("event %q exists in Go but not in frontend/src/wails.ts", name)
}
}
for name := range frontend {
if !backend[name] {
t.Errorf("event %q exists in frontend/src/wails.ts but not in Go", name)
}
}
}
+3 -2
View File
@@ -108,7 +108,7 @@ func run(dataRoot, appVersion string, steps []Step, current int, now func() time
// A folder already stamped at this layout is left untouched; anything
// else (steps ran, no stamp yet, damaged stamp) gets a fresh stamp.
if stamp.DataVersion == current && readErr == nil && stampExists(dataRoot) {
if stamp.DataVersion == current && readErr == nil && HasStamp(dataRoot) {
return res, nil
}
res.To = current
@@ -137,7 +137,8 @@ func ReadStamp(dataRoot string) (Stamp, error) {
return s, nil
}
func stampExists(dataRoot string) bool {
// HasStamp reports whether dataRoot records its data version.
func HasStamp(dataRoot string) bool {
_, err := os.Stat(filepath.Join(dataRoot, StampFile))
return err == nil
}
+1 -6
View File
@@ -87,7 +87,7 @@ func open(dir, appVersion string, repair bool) Status {
case err == nil && stamp.DataVersion > datamigrate.CurrentVersion:
st.Version = stamp.DataVersion
return readOnly(st, ReasonNewer, "")
case err == nil && stamp.DataVersion == datamigrate.CurrentVersion && stampExists(dir):
case err == nil && stamp.DataVersion == datamigrate.CurrentVersion && datamigrate.HasStamp(dir):
st.Version = stamp.DataVersion
return st
}
@@ -128,11 +128,6 @@ func readOnly(st Status, reason Reason, detail string) Status {
return st
}
func stampExists(dir string) bool {
_, err := os.Stat(filepath.Join(dir, datamigrate.StampFile))
return err == nil
}
// Error explains why st cannot be written, for the GUI and the CLI alike. It
// is nil for a writable folder.
func Error(loc i18n.Locale, st Status) error {
+15
View File
@@ -0,0 +1,15 @@
package driver
import "testing"
func TestValidateSnapshotName(t *testing.T) {
if got, err := ValidateSnapshotName(" before-ota-26.2 "); err != nil || got != "before-ota-26.2" {
t.Fatalf("valid name failed: %q %v", got, err)
}
if _, err := ValidateSnapshotName(" "); err == nil {
t.Fatal("expected error for empty snapshot name")
}
if _, err := ValidateSnapshotName(`bad"quote`); err == nil {
t.Fatal("expected error for quote in snapshot name")
}
}
+8
View File
@@ -0,0 +1,8 @@
//go:build !windows
package host
import "os/exec"
// HideConsole does nothing: only Windows opens console windows.
func HideConsole(*exec.Cmd) {}
+13
View File
@@ -0,0 +1,13 @@
package host
import (
"os/exec"
"syscall"
"golang.org/x/sys/windows"
)
// HideConsole keeps a console program started by the GUI from opening a window.
func HideConsole(cmd *exec.Cmd) {
cmd.SysProcAttr = &syscall.SysProcAttr{HideWindow: true, CreationFlags: windows.CREATE_NO_WINDOW}
}
+17
View File
@@ -0,0 +1,17 @@
package host
import "testing"
func TestDiagnoseGPULog(t *testing.T) {
lost := "reims-vgpu: the rt platform's device on AMD Radeon (TM) Graphics (1002:15e7) was lost at vkQueueSubmit2 (ERROR_DEVICE_LOST)"
if code, detail := DiagnoseGPULog(lost); code != "gpu_device_lost" || detail == "" {
t.Fatalf("DiagnoseGPULog(lost) = (%q, %q), want gpu_device_lost", code, detail)
}
floor := "reims-vgpu: no physical device meets the floor (VK_ERROR_INCOMPATIBLE_DRIVER)"
if code, detail := DiagnoseGPULog(floor); code != "gpu_vulkan_floor" || detail == "" {
t.Fatalf("DiagnoseGPULog(floor) = (%q, %q), want gpu_vulkan_floor", code, detail)
}
if code, _ := DiagnoseGPULog("normal boot log line"); code != "" {
t.Fatalf("expected empty code for normal log, got %q", code)
}
}
+1 -11
View File
@@ -2,7 +2,6 @@ package guest
import (
"context"
"strings"
"github.com/Nwflower/reims-go/internal/driver"
"github.com/Nwflower/reims-go/internal/i18n"
@@ -140,7 +139,7 @@ func Definition(ver string, cb builtin.HostCallbacks, desired bool) plugin.Plugi
return nil, nil
}
caps, _ := p.HostFacts["runtime.capabilities"].([]string)
if whpxFallbackNeeded(p.HostFacts) && !hasCap(caps, "nested-virt-nonfatal") {
if whpxFallbackNeeded(p.HostFacts) && !plugin.HasCap(caps, "nested-virt-nonfatal") {
return plugin.PreflightResult{
Advices: []string{i18n.T(guestLocale(cb), "core.preflight.whpx_irqchip_advice")},
}, nil
@@ -182,12 +181,3 @@ func whpxFallbackNeeded(facts map[string]any) bool {
nestedOK, _ := facts["host.whpx_nested_virt"].(bool)
return !needsCold && irqAvail && !nestedOK
}
func hasCap(caps []string, want string) bool {
for _, c := range caps {
if strings.EqualFold(c, want) {
return true
}
}
return false
}
+2 -1
View File
@@ -15,6 +15,7 @@ import (
"strings"
"github.com/Nwflower/reims-go/internal/downloader"
"github.com/Nwflower/reims-go/internal/host"
)
func resolveOfflineRelease(releases []Release, version string) (Release, bool) {
@@ -77,7 +78,7 @@ func (c *Client) prepareOfflinePartWithUtil(ctx context.Context, version, partPa
defer cancel()
cmd := exec.CommandContext(prepCtx, c.Util, "--json", "offline-installer", version, "-o", c.InstallersDir)
configureCmd(cmd)
host.HideConsole(cmd)
cmd.Env = c.Env
cmd.Stdin = nil
var stderr bytes.Buffer
+2 -2
View File
@@ -118,7 +118,7 @@ func (c *Client) run(ctx context.Context, onUpdate func(Update), args ...string)
onUpdate = func(Update) {}
}
cmd := exec.CommandContext(ctx, c.Util, append([]string{"--json"}, args...)...)
configureCmd(cmd)
host.HideConsole(cmd)
cmd.Env = c.Env
cmd.Stdin = nil
var stderr bytes.Buffer
@@ -428,7 +428,7 @@ func (c *Client) DeleteCached(ctx context.Context, name string, stdout io.Writer
return fmt.Errorf("not a download name: %q", name)
}
cmd := exec.CommandContext(ctx, c.Ctl, "downloads", "delete", name, "--yes")
configureCmd(cmd)
host.HideConsole(cmd)
cmd.Env = c.Env
var out, errBuf bytes.Buffer
cmd.Stdout = &out
-7
View File
@@ -1,7 +0,0 @@
//go:build !windows
package installer
import "os/exec"
func configureCmd(*exec.Cmd) {}
-17
View File
@@ -1,17 +0,0 @@
//go:build windows
package installer
import (
"os/exec"
"syscall"
)
const createNoWindow = 0x08000000
func configureCmd(cmd *exec.Cmd) {
cmd.SysProcAttr = &syscall.SysProcAttr{
HideWindow: true,
CreationFlags: createNoWindow,
}
}
+1 -17
View File
@@ -22,22 +22,6 @@ import (
var _ driver.CloneDriver = (*ReimsMacOSDriver)(nil)
var _ driver.CloneResultDriver = (*ReimsMacOSDriver)(nil)
func readVMMacOS(dir string) string {
raw, err := os.ReadFile(filepath.Join(dir, ".reims-go-macos"))
if err != nil {
return ""
}
return strings.TrimSpace(string(raw))
}
func writeVMMacOS(dir, release string) error {
release = strings.TrimSpace(strings.NewReplacer("\r", "", "\n", "").Replace(release))
if dir == "" || release == "" {
return nil
}
return os.WriteFile(filepath.Join(dir, ".reims-go-macos"), []byte(release+"\n"), 0o644)
}
func (d *ReimsMacOSDriver) CloneCoWWithInfo(ctx context.Context, sourceName, cloneName string, stdout, stderr io.Writer) (driver.VMInfo, error) {
cloneName = strings.TrimSpace(cloneName)
if err := d.CloneCoW(ctx, sourceName, cloneName, stdout, stderr); err != nil {
@@ -155,7 +139,7 @@ func (d *ReimsMacOSDriver) CloneCoW(ctx context.Context, sourceName, cloneName s
_, _ = fmt.Fprintf(stdout, "Warning: could not apply clone language (%s): %v\n", src.GuestLang, prepErr)
}
}
if err := writeVMMacOS(cloned.Directory, readVMMacOS(src.Directory)); err != nil {
if err := reims.WriteReleaseRecord(cloned.Directory, reims.ReadReleaseRecord(src.Directory)); err != nil {
_, _ = fmt.Fprintf(stdout, "Warning: could not copy macOS release: %v\n", err)
}
if vmstart.HasSavedVMAffinity(src.Directory) {
+2 -2
View File
@@ -174,7 +174,7 @@ func (d *ReimsMacOSDriver) prepareOfflineHelper(cfg config.Config, cur reims.VMD
return fmt.Errorf("prepare offline install helper disk: %w", err)
}
in.Args = append(in.Args, plugin.ArgFragment{PluginID: d.opts.OwnerID, Key: keyOfflineHelper,
Tokens: plugin.SplitShellTokens(reims.MergeOfflineHelperArgs("", helperPath)), Builtin: true, Priority: 85})
Tokens: qmp.SplitArgs(reims.MergeOfflineHelperArgs("", helperPath)), Builtin: true, Priority: 85})
return nil
}
@@ -242,7 +242,7 @@ func (d *ReimsMacOSDriver) prepareColdReboot(cfg config.Config, name, vmDir stri
return fmt.Errorf("replace cold-reboot socket: %w", err)
}
in.Args = append(in.Args, plugin.ArgFragment{PluginID: d.opts.OwnerID, Key: keyWin10ColdReboot,
Tokens: plugin.SplitShellTokens(qmp.MergeWin10RebootUnixArgs("", sockPath)), Builtin: true, Priority: 95})
Tokens: qmp.SplitArgs(qmp.MergeWin10RebootUnixArgs("", sockPath)), Builtin: true, Priority: 95})
in.PostStart = append(in.PostStart, plugin.PostStartAction{PluginID: d.opts.OwnerID,
Kind: "qmp.watch_cold_reboot", Params: map[string]any{"qmp_addr": "unix:" + sockPath}})
return nil
+4 -18
View File
@@ -18,20 +18,6 @@ import (
var _ driver.SnapshotDriver = (*ReimsMacOSDriver)(nil)
var _ driver.DiskDriver = (*ReimsMacOSDriver)(nil)
func vmRunning(ctx context.Context, c *reims.Client, name string, d reims.VMDetail) bool {
if d.State == "running" {
return true
}
if list, err := c.List(ctx); err == nil {
for _, vm := range list {
if vm.Name == name && vm.State == "running" {
return true
}
}
}
return false
}
func (d *ReimsMacOSDriver) ListSnapshots(ctx context.Context, name string) ([]driver.DiskSnapshot, error) {
c, active, err := d.startClient()
if err != nil {
@@ -59,7 +45,7 @@ func (d *ReimsMacOSDriver) ListSnapshots(ctx context.Context, name string) ([]dr
}
func (d *ReimsMacOSDriver) RunSnapshot(ctx context.Context, name, operation, snapName string, stdout, stderr io.Writer) error {
clean, err := reims.ValidateSnapshotName(snapName)
clean, err := driver.ValidateSnapshotName(snapName)
if err != nil {
return err
}
@@ -76,7 +62,7 @@ func (d *ReimsMacOSDriver) RunSnapshot(ctx context.Context, name, operation, sna
return err
}
defer release()
if vmRunning(ctx, c, name, det) {
if c.IsRunning(ctx, det) {
return fmt.Errorf("stop %s before changing restore points", name)
}
if reims.HasSuspendState(det.Directory) {
@@ -108,7 +94,7 @@ func (d *ReimsMacOSDriver) ResizeDisk(ctx context.Context, name, newSize string,
return driver.DiskResizeResult{}, err
}
defer release()
if vmRunning(ctx, c, name, det) {
if c.IsRunning(ctx, det) {
return driver.DiskResizeResult{}, fmt.Errorf("stop %s before resizing its disk", name)
}
if reims.HasSuspendState(det.Directory) {
@@ -149,7 +135,7 @@ func (d *ReimsMacOSDriver) compactDiskWithOptions(ctx context.Context, name stri
return driver.DiskCompactResult{}, err
}
defer release()
if vmRunning(ctx, c, name, det) {
if c.IsRunning(ctx, det) {
return driver.DiskCompactResult{}, fmt.Errorf("stop %s before rewriting its disk", name)
}
if reims.HasSuspendState(det.Directory) {
+7 -5
View File
@@ -11,6 +11,8 @@ import (
"path/filepath"
"strings"
"unicode/utf16"
"github.com/Nwflower/reims-go/internal/host"
)
const (
@@ -286,10 +288,10 @@ type fat32FS struct {
}
type fatEntry struct {
name string
firstCluster uint32
size uint32
dirEntryOff uint64 // byte offset on disk of this 32-byte short directory entry
name string
firstCluster uint32
size uint32
dirEntryOff uint64 // byte offset on disk of this 32-byte short directory entry
}
func openFAT32(d diskIO, espStart uint64) (*fat32FS, error) {
@@ -745,7 +747,7 @@ func patchQcow2ViaRawWith(ctx context.Context, qcow2Path, qemuImgPath string, en
func runQemuImg(ctx context.Context, qemuImgPath string, env []string, args ...string) error {
cmd := exec.CommandContext(ctx, qemuImgPath, args...)
configureCmd(cmd)
host.HideConsole(cmd)
if len(env) > 0 {
cmd.Env = env
}
-7
View File
@@ -1,7 +0,0 @@
//go:build !windows
package opencore
import "os/exec"
func configureCmd(_ *exec.Cmd) {}
-12
View File
@@ -1,12 +0,0 @@
//go:build windows
package opencore
import (
"os/exec"
"syscall"
)
func configureCmd(cmd *exec.Cmd) {
cmd.SysProcAttr = &syscall.SysProcAttr{HideWindow: true}
}
+1 -6
View File
@@ -78,11 +78,6 @@ func IsWHPXNestedVirtError(output string) bool {
return strings.Contains(output, "WHPX: Failed to enable nested virtualization")
}
// DiagnoseGPULog inspects QEMU / reims-vgpu output for known Vulkan GPU
// compatibility or device-loss failures and returns a machine-readable code
// ("gpu_device_lost" | "gpu_vulkan_floor") and matching line excerpt.
func DiagnoseGPULog(output string) (code, detail string) { return host.DiagnoseGPULog(output) }
// HasKernelIrqchipArg reports whether extra-args already specifies a
// kernel-irqchip setting.
func HasKernelIrqchipArg(extraArgs string) bool {
@@ -230,7 +225,7 @@ func (c *Client) StartWithCompat(ctx context.Context, name string, stdout, stder
}
return fmt.Errorf("%s (%w)", msg, err)
}
if gpuCode, _ := DiagnoseGPULog(combined); gpuCode != "" {
if gpuCode, _ := host.DiagnoseGPULog(combined); gpuCode != "" {
msg := i18n.T(c.Locale, "err."+gpuCode)
if onNote != nil {
onNote(msg)
-14
View File
@@ -375,20 +375,6 @@ func TestIsWHPXNoAcceleratorError(t *testing.T) {
}
}
func TestDiagnoseGPULog(t *testing.T) {
lost := "reims-vgpu: the rt platform's device on AMD Radeon (TM) Graphics (1002:15e7) was lost at vkQueueSubmit2 (ERROR_DEVICE_LOST)"
if code, detail := DiagnoseGPULog(lost); code != "gpu_device_lost" || detail == "" {
t.Fatalf("DiagnoseGPULog(lost) = (%q, %q), want gpu_device_lost", code, detail)
}
floor := "reims-vgpu: no physical device meets the floor (VK_ERROR_INCOMPATIBLE_DRIVER)"
if code, detail := DiagnoseGPULog(floor); code != "gpu_vulkan_floor" || detail == "" {
t.Fatalf("DiagnoseGPULog(floor) = (%q, %q), want gpu_vulkan_floor", code, detail)
}
if code, _ := DiagnoseGPULog("normal boot log line"); code != "" {
t.Fatalf("expected empty code for normal log, got %q", code)
}
}
func TestMergeAndStripOfflineHelperArgs(t *testing.T) {
base := `-no-reboot -qmp tcp:127.0.0.1:45555,server=on,wait=off -machine kernel-irqchip=off`
merged := MergeOfflineHelperArgs(base, `D:\Data\reims-go\cache\reims-helper.img`)
+6 -6
View File
@@ -209,7 +209,7 @@ func ParseQCOW2CreateOptionsFromInfoJSON(raw []byte) (QCOW2CreateOptions, error)
// on diskPath and returns its qcow2 creation options.
func InspectQCOW2CreateOptions(ctx context.Context, qemuImgPath string, env []string, diskPath string) (QCOW2CreateOptions, error) {
cmd := exec.CommandContext(ctx, qemuImgPath, "info", "--force-share", "--output=json", diskPath)
configureCmd(cmd)
host.HideConsole(cmd)
cmd.Env = env
out, err := cmd.CombinedOutput()
if err != nil {
@@ -266,7 +266,7 @@ func ConvertDiskToQCOW2(ctx context.Context, qemuImgPath string, env []string, s
return err
}
cmd := exec.CommandContext(ctx, qemuImgPath, BuildConvertToQCOW2Args(srcPath, dstPath)...)
configureCmd(cmd)
host.HideConsole(cmd)
cmd.Env = env
if stdout != nil {
cmd.Stdout = stdout
@@ -298,7 +298,7 @@ func CreateCoWOverlay(ctx context.Context, qemuImgPath string, env []string, bac
return fmt.Errorf("inspect backing qcow2 options: %w", err)
}
cmd := exec.CommandContext(ctx, qemuImgPath, BuildCoWOverlayArgs(backingPath, overlayPath, opts)...)
configureCmd(cmd)
host.HideConsole(cmd)
cmd.Env = env
if stdout != nil {
cmd.Stdout = stdout
@@ -327,7 +327,7 @@ func ResizeDisk(ctx context.Context, qemuImgPath string, env []string, diskPath,
return DiskResizeResult{}, err
}
cmd := exec.CommandContext(ctx, qemuImgPath, BuildResizeDiskArgs(diskPath, arg)...)
configureCmd(cmd)
host.HideConsole(cmd)
cmd.Env = env
if stdout != nil {
cmd.Stdout = stdout
@@ -392,7 +392,7 @@ func CompactDisk(ctx context.Context, qemuImgPath string, env []string, diskPath
defer os.Remove(tmpPath)
cmd := exec.CommandContext(ctx, qemuImgPath, BuildCompactDiskArgs(diskPath, tmpPath, opts)...)
configureCmd(cmd)
host.HideConsole(cmd)
cmd.Env = env
if stdout != nil {
cmd.Stdout = stdout
@@ -406,7 +406,7 @@ func CompactDisk(ctx context.Context, qemuImgPath string, env []string, diskPath
// Verify integrity of the compacted image before touching the original.
chk := exec.CommandContext(ctx, qemuImgPath, "check", "-q", tmpPath)
configureCmd(chk)
host.HideConsole(chk)
chk.Env = env
if out, err := chk.CombinedOutput(); err != nil {
return DiskCompactResult{}, fmt.Errorf("compacted qcow2 integrity check failed: %w (%s)", err, strings.TrimSpace(string(out)))
+4 -35
View File
@@ -3,6 +3,8 @@ package reims
import (
"fmt"
"strings"
"github.com/Nwflower/reims-go/internal/qmp"
)
// IsOfflineInstallerPath reports whether an attached installer path is a
@@ -14,7 +16,7 @@ func IsOfflineInstallerPath(path string) bool {
// StripOfflineHelperArgs removes any reims-go managed offline helper USB disk
// arguments from QEMU extra-args while leaving all other arguments intact.
func StripOfflineHelperArgs(existing string) string {
tokens := splitShellTokens(existing)
tokens := qmp.SplitArgs(existing)
cleaned := make([]string, 0, len(tokens))
for i := 0; i < len(tokens); i++ {
tok := tokens[i]
@@ -57,7 +59,7 @@ func HasGuestToolsArgs(existing string) bool {
// StripGuestToolsArgs removes any reims-go managed REIMSTOOLS USB disk args.
func StripGuestToolsArgs(existing string) string {
tokens := splitShellTokens(existing)
tokens := qmp.SplitArgs(existing)
cleaned := make([]string, 0, len(tokens))
for i := 0; i < len(tokens); i++ {
tok := tokens[i]
@@ -90,36 +92,3 @@ func MergeGuestToolsArgs(existing, toolsImgPath string) string {
}
return base + " " + toolsArgs
}
func splitShellTokens(s string) []string {
var out []string
var cur strings.Builder
var quote byte
for i := 0; i < len(s); i++ {
c := s[i]
if quote != 0 {
cur.WriteByte(c)
if c == quote {
quote = 0
}
continue
}
if c == '\'' || c == '"' {
quote = c
cur.WriteByte(c)
continue
}
if c == ' ' || c == '\t' || c == '\n' || c == '\r' {
if cur.Len() > 0 {
out = append(out, cur.String())
cur.Reset()
}
continue
}
cur.WriteByte(c)
}
if cur.Len() > 0 {
out = append(out, cur.String())
}
return out
}
-7
View File
@@ -1,7 +0,0 @@
//go:build !windows
package reims
import "os/exec"
func configureCmd(cmd *exec.Cmd) {}
-17
View File
@@ -1,17 +0,0 @@
//go:build windows
package reims
import (
"os/exec"
"syscall"
)
const createNoWindow = 0x08000000
func configureCmd(cmd *exec.Cmd) {
cmd.SysProcAttr = &syscall.SysProcAttr{
HideWindow: true,
CreationFlags: createNoWindow,
}
}
+14 -1
View File
@@ -10,6 +10,7 @@ import (
"os/exec"
"path/filepath"
"regexp"
"slices"
"strconv"
"strings"
@@ -714,7 +715,7 @@ func ParseShow(name, text string) VMDetail {
func (c *Client) run(ctx context.Context, stdout, stderr io.Writer, args ...string) error {
cmd := exec.CommandContext(ctx, c.Binary, args...)
configureCmd(cmd)
host.HideConsole(cmd)
cmd.Env = c.Env
if stdout != nil {
cmd.Stdout = stdout
@@ -886,3 +887,15 @@ func (c *Client) Delete(ctx context.Context, name string, keepFiles bool, stdout
}
return c.deleteWithCoW(ctx, name, keepFiles, removeVM)
}
// IsRunning reports whether the VM runs, either in d or in a fresh list.
func (c *Client) IsRunning(ctx context.Context, d VMDetail) bool {
if d.State == "running" {
return true
}
list, err := c.List(ctx)
if err != nil {
return false
}
return slices.ContainsFunc(list, func(vm VMListItem) bool { return vm.Name == d.Name && vm.State == "running" })
}
+31
View File
@@ -0,0 +1,31 @@
package reims
import (
"os"
"path/filepath"
"strings"
)
// releaseRecordFile records which macOS release a VM was created with, for its
// icon. reims-ctl keeps no such field in vm.toml.
const releaseRecordFile = ".reims-go-macos"
// ReadReleaseRecord returns the macOS release recorded in dir: an installer
// version such as "26.7.3", or a codename such as "tahoe" for an
// online-recovery install. It is "" when none was recorded.
func ReadReleaseRecord(dir string) string {
b, err := os.ReadFile(filepath.Join(dir, releaseRecordFile))
if err != nil {
return ""
}
return strings.TrimSpace(string(b))
}
// WriteReleaseRecord stores release next to vm.toml; an empty release writes nothing.
func WriteReleaseRecord(dir, release string) error {
release = strings.TrimSpace(strings.NewReplacer("\r", "", "\n", "").Replace(release))
if dir == "" || release == "" {
return nil
}
return os.WriteFile(filepath.Join(dir, releaseRecordFile), []byte(release+"\n"), 0o644)
}
@@ -0,0 +1,25 @@
package reims
import "testing"
func TestReleaseRecordRoundTrip(t *testing.T) {
dir := t.TempDir()
if got := ReadReleaseRecord(dir); got != "" {
t.Fatalf("empty dir: got %q", got)
}
if err := WriteReleaseRecord(dir, ""); err != nil {
t.Fatal(err)
}
if got := ReadReleaseRecord(dir); got != "" {
t.Fatalf("empty release wrote %q", got)
}
if err := WriteReleaseRecord(dir, " 26.7.3\r\n"); err != nil {
t.Fatal(err)
}
if got := ReadReleaseRecord(dir); got != "26.7.3" {
t.Fatalf("got %q, want 26.7.3", got)
}
if err := WriteReleaseRecord("", "tahoe"); err != nil {
t.Fatalf("no dir should be a no-op, got %v", err)
}
}
+5 -2
View File
@@ -9,6 +9,9 @@ import (
"strings"
"sync"
"time"
"github.com/Nwflower/reims-go/internal/host"
"github.com/Nwflower/reims-go/internal/qmp"
)
// BuildSMBIOSType17Value formats the value token for `-smbios <val>` carrying
@@ -27,7 +30,7 @@ func BuildSMBIOSType17Value(speedMHz, memoryType int, includeMemoryType bool) st
// HasSMBIOSType17Arg reports whether extraArgs already contains a `-smbios`
// option targeting SMBIOS Type 17.
func HasSMBIOSType17Arg(extraArgs string) bool {
tokens := splitShellTokens(extraArgs)
tokens := qmp.SplitArgs(extraArgs)
for i := 0; i < len(tokens); i++ {
tok := tokens[i]
var val string
@@ -102,7 +105,7 @@ func ProbeQEMUSupportsSMBIOSMemoryType(qemuPath string, env []string) bool {
ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second)
defer cancel()
cmd := exec.CommandContext(ctx, qemuPath, "-smbios", "type=17,memory_type=26", "-version")
configureCmd(cmd)
host.HideConsole(cmd)
if len(env) > 0 {
cmd.Env = env
}
+4 -8
View File
@@ -11,6 +11,7 @@ import (
"strings"
"github.com/Nwflower/reims-go/internal/driver"
"github.com/Nwflower/reims-go/internal/host"
)
// DiskSnapshot describes one internal qcow2 snapshot returned by `qemu-img info --output=json`.
@@ -55,7 +56,7 @@ func ListDiskSnapshots(ctx context.Context, qemuImgPath string, env []string, di
return nil, fmt.Errorf("qemu-img not found in runtime (%s): %w", qemuImgPath, err)
}
cmd := exec.CommandContext(ctx, qemuImgPath, "info", "--output=json", diskPath)
configureCmd(cmd)
host.HideConsole(cmd)
cmd.Env = env
var stdout, stderr bytes.Buffer
cmd.Stdout = &stdout
@@ -77,23 +78,18 @@ func ListDiskSnapshots(ctx context.Context, qemuImgPath string, env []string, di
return snaps, nil
}
// ValidateSnapshotName checks that a snapshot tag is safe for `qemu-img snapshot`.
func ValidateSnapshotName(snapName string) (string, error) {
return driver.ValidateSnapshotName(snapName)
}
// RunDiskSnapshot executes `qemu-img snapshot <flag> <snapName> <diskPath>`
// where flag is "-c" (create), "-a" (apply/restore), or "-d" (delete).
func RunDiskSnapshot(ctx context.Context, qemuImgPath string, env []string, flag, snapName, diskPath string) error {
if _, err := os.Stat(qemuImgPath); err != nil {
return fmt.Errorf("qemu-img not found in runtime (%s): %w", qemuImgPath, err)
}
snapName, err := ValidateSnapshotName(snapName)
snapName, err := driver.ValidateSnapshotName(snapName)
if err != nil {
return err
}
cmd := exec.CommandContext(ctx, qemuImgPath, "snapshot", flag, snapName, diskPath)
configureCmd(cmd)
host.HideConsole(cmd)
cmd.Env = env
var stderr bytes.Buffer
cmd.Stderr = &stderr
+2 -1
View File
@@ -8,6 +8,7 @@ import (
"strings"
"time"
"github.com/Nwflower/reims-go/internal/qmp"
rt "github.com/Nwflower/reims-go/internal/runtime"
)
@@ -209,7 +210,7 @@ func shortRev(rev string) string {
// StripIncomingDeferArgs removes any `-incoming defer` / `-incoming=defer`
// arguments from QEMU extra-args while leaving all other arguments intact.
func StripIncomingDeferArgs(existing string) string {
tokens := splitShellTokens(existing)
tokens := qmp.SplitArgs(existing)
cleaned := make([]string, 0, len(tokens))
for i := 0; i < len(tokens); i++ {
tok := tokens[i]
+4 -12
View File
@@ -19,6 +19,7 @@ import (
"github.com/Nwflower/reims-go/internal/macos/reims"
"github.com/Nwflower/reims-go/internal/networkmsg"
"github.com/Nwflower/reims-go/internal/plugin"
"github.com/Nwflower/reims-go/internal/qmp"
"github.com/Nwflower/reims-go/internal/version"
)
@@ -69,15 +70,6 @@ type HostCallbacks struct {
GetSetting func(pluginID, vmName, key string) (any, bool)
}
func hasCap(caps []string, want string) bool {
for _, cap := range caps {
if strings.EqualFold(cap, want) {
return true
}
}
return false
}
func appVersion() string {
v := strings.TrimPrefix(strings.TrimSpace(version.Version), "v")
if v == "" || v == "dev" {
@@ -195,20 +187,20 @@ func defGuestTools(ver string, cb HostCallbacks, desiredFn func(string, bool) bo
s.StopManagementNetwork(p.VMName)
intent.ClearKeys = append(intent.ClearKeys, "guest-tools-network")
}
if hasCap(p.RuntimeCaps, "window-file-drop") {
if plugin.HasCap(p.RuntimeCaps, "window-file-drop") {
if token := s.HostDropToken(gtCfg.DriverID, p.VMName); token != "" {
intent.Env["REIMS_GO_DROP_URL"] = fmt.Sprintf("http://127.0.0.1:%d/v1/host-drop", port)
intent.Env["REIMS_GO_DROP_TOKEN"] = token
}
}
if sc.Registry().IsActive(IDInput) && hasCap(p.RuntimeCaps, "win32-unicode-input") {
if sc.Registry().IsActive(IDInput) && plugin.HasCap(p.RuntimeCaps, "win32-unicode-input") {
intent.Env["REIMS_GO_INPUT_URL"] = fmt.Sprintf("http://127.0.0.1:%d/v1/host-text", port)
intent.Env["REIMS_GO_INPUT_TOKEN"] = gtCfg.Token
}
}
if reims.HasGuestToolsArgs(p.ExtraArgs) && cb.GuestToolsImg != nil && err == nil {
imgPath := cb.GuestToolsImg(p.VMName)
tokens := plugin.SplitShellTokens(reims.MergeGuestToolsArgs("", imgPath))
tokens := qmp.SplitArgs(reims.MergeGuestToolsArgs("", imgPath))
intent.Args = append(intent.Args, plugin.ArgFragment{
PluginID: IDGuestTools,
Key: "reimstools",
+7
View File
@@ -3,7 +3,9 @@ package plugin
import (
"context"
"fmt"
"slices"
"sort"
"strings"
"sync"
"sync/atomic"
"time"
@@ -61,6 +63,11 @@ type BeforeCreateResult struct {
Patches map[string]any `json:"patches,omitempty"`
}
// HasCap reports whether a runtime declares the capability want.
func HasCap(caps []string, want string) bool {
return slices.ContainsFunc(caps, func(c string) bool { return strings.EqualFold(c, want) })
}
// BeforeStartPayload is passed to vm.beforeStart handlers.
type BeforeStartPayload struct {
VMName string `json:"vm_name"`
+4 -37
View File
@@ -11,6 +11,7 @@ import (
"strings"
"github.com/Nwflower/reims-go/internal/atomicfile"
"github.com/Nwflower/reims-go/internal/qmp"
)
const ArgLedgerFileName = ".reims-go-arg-ledger.json"
@@ -252,7 +253,7 @@ func validateSingleShellToken(tok string) error {
return fmt.Errorf("QEMU argument token %q contains unquoted whitespace or quotes", tok)
}
}
resplit := SplitShellTokens(tok)
resplit := qmp.SplitArgs(tok)
if len(resplit) != 1 || resplit[0] != tok {
return fmt.Errorf("QEMU argument token %q does not round-trip as a single token", tok)
}
@@ -386,7 +387,7 @@ func sanitizeEnvPrefix(pluginID string) string {
// UserExtraArgs returns the portion of currentExtraArgs that is NOT owned by
// any fragment currently recorded in ledger.
func UserExtraArgs(currentExtraArgs string, ledger *ArgLedger) string {
return strings.Join(stripOwnedTokens(SplitShellTokens(currentExtraArgs), ledger), " ")
return strings.Join(stripOwnedTokens(qmp.SplitArgs(currentExtraArgs), ledger), " ")
}
// ReconcileStartIntents strips previously owned fragments from currentExtraArgs
@@ -411,7 +412,7 @@ func reconcileStartIntents(currentExtraArgs string, ledger *ArgLedger, activePlu
ledger.Owners = map[string][]ArgFragment{}
}
userTokens := stripOwnedTokens(SplitShellTokens(currentExtraArgs), ledger)
userTokens := stripOwnedTokens(qmp.SplitArgs(currentExtraArgs), ledger)
if activePlugins != nil {
for pid := range ledger.Owners {
@@ -656,37 +657,3 @@ func unquoteShellToken(token string) string {
}
return token
}
// SplitShellTokens splits a QEMU extra-args string preserving quoted tokens.
func SplitShellTokens(s string) []string {
var out []string
var cur strings.Builder
var quote byte
for i := 0; i < len(s); i++ {
c := s[i]
if quote != 0 {
cur.WriteByte(c)
if c == quote {
quote = 0
}
continue
}
if c == '\'' || c == '"' {
quote = c
cur.WriteByte(c)
continue
}
if c == ' ' || c == '\t' || c == '\n' || c == '\r' {
if cur.Len() > 0 {
out = append(out, cur.String())
cur.Reset()
}
continue
}
cur.WriteByte(c)
}
if cur.Len() > 0 {
out = append(out, cur.String())
}
return out
}
+37
View File
@@ -0,0 +1,37 @@
package qmp
import "strings"
// SplitArgs splits a QEMU extra-args string and keeps quoted tokens whole.
func SplitArgs(s string) []string {
var out []string
var cur strings.Builder
var quote byte
for i := 0; i < len(s); i++ {
c := s[i]
if quote != 0 {
cur.WriteByte(c)
if c == quote {
quote = 0
}
continue
}
if c == '\'' || c == '"' {
quote = c
cur.WriteByte(c)
continue
}
if c == ' ' || c == '\t' || c == '\n' || c == '\r' {
if cur.Len() > 0 {
out = append(out, cur.String())
cur.Reset()
}
continue
}
cur.WriteByte(c)
}
if cur.Len() > 0 {
out = append(out, cur.String())
}
return out
}
+3 -7
View File
@@ -257,10 +257,6 @@ func absEvent(axis string, value int) map[string]any {
return map[string]any{"type": "abs", "data": map[string]any{"axis": axis, "value": value}}
}
func btnEvent(button string, down bool) map[string]any {
return map[string]any{"type": "btn", "data": map[string]any{"down": down, "button": button}}
}
func clampAbsCoord(norm float64) int {
switch {
case math.IsNaN(norm), math.IsInf(norm, 0), norm <= 0:
@@ -306,20 +302,20 @@ func leftClick(ctx context.Context, q Executor, clickHold time.Duration) error {
if err := ctx.Err(); err != nil {
return err
}
if err := send(btnEvent("left", true)); err != nil {
if err := send(mouseButtonEvent("left", true)); err != nil {
return err
}
btnDown := true
defer func() {
if btnDown {
_ = send(btnEvent("left", false))
_ = send(mouseButtonEvent("left", false))
}
}()
sleep(ctx, clickHold)
if err := ctx.Err(); err != nil {
return err
}
if err := send(btnEvent("left", false)); err != nil {
if err := send(mouseButtonEvent("left", false)); err != nil {
return err
}
btnDown = false
+3 -36
View File
@@ -46,7 +46,7 @@ func RebootSocketPath(vmDir, tmpDir, vmName string) string {
// (`-no-reboot` + `-qmp <managed>`) ONLY when a managed QMP target is present,
// preserving any user hand-written `-no-reboot` on hosts without managed QMP.
func StripLegacyWin10RebootArgs(existing string) string {
tokens := splitShellTokens(existing)
tokens := SplitArgs(existing)
hasManagedQMP := false
for i := 0; i < len(tokens); i++ {
if tokens[i] == "-qmp" && i+1 < len(tokens) && isManagedQMPTarget(tokens[i+1]) {
@@ -76,7 +76,7 @@ func StripLegacyWin10RebootArgs(existing string) string {
// `-qmp unix:<path>,server=on,wait=off` into existing extra_args while stripping
// any legacy managed TCP or Unix QMP arguments.
func MergeWin10RebootUnixArgs(existing, sockPath string) string {
tokens := splitShellTokens(existing)
tokens := SplitArgs(existing)
cleaned := make([]string, 0, len(tokens)+3)
for i := 0; i < len(tokens); i++ {
tok := tokens[i]
@@ -106,7 +106,7 @@ func win10RebootUnixTarget(sockPath string) string {
// HasWin10RebootUnixArgs checks for the private socket Reims-Go configured,
// without accepting other monitors declared in extra-args.
func HasWin10RebootUnixArgs(extraArgs, sockPath string) bool {
tokens := splitShellTokens(extraArgs)
tokens := SplitArgs(extraArgs)
want := win10RebootUnixTarget(sockPath)
var noReboot, socket bool
for i, token := range tokens {
@@ -134,39 +134,6 @@ func isManagedQMPTarget(arg string) bool {
return false
}
func splitShellTokens(s string) []string {
var out []string
var cur strings.Builder
var quote byte
for i := 0; i < len(s); i++ {
c := s[i]
if quote != 0 {
cur.WriteByte(c)
if c == quote {
quote = 0
}
continue
}
if c == '\'' || c == '"' {
quote = c
cur.WriteByte(c)
continue
}
if c == ' ' || c == '\t' || c == '\n' || c == '\r' {
if cur.Len() > 0 {
out = append(out, cur.String())
cur.Reset()
}
continue
}
cur.WriteByte(c)
}
if cur.Len() > 0 {
out = append(out, cur.String())
}
return out
}
// WatchShutdownReason waits for QEMU's SHUTDOWN event over QMP and returns its
// reason (e.g. "guest-reset", "guest-shutdown", "host-qmp-quit"), or "" on EOF.
func WatchShutdownReason(ctx context.Context, addr string) (string, error) {