package cli import ( "context" "encoding/json" "errors" "fmt" "os" "os/signal" "path/filepath" "time" "github.com/Nwflower/reims-go/internal/config" "github.com/Nwflower/reims-go/internal/host" "github.com/Nwflower/reims-go/internal/i18n" "github.com/Nwflower/reims-go/internal/plugin" "github.com/Nwflower/reims-go/internal/plugin/builtin" "github.com/Nwflower/reims-go/internal/vmstart" ) // startHandoffTimeout bounds how long `vm start` waits for the window to // report back. Preparation can rebuild the OpenCore image before QEMU starts. const startHandoffTimeout = 5 * time.Minute // startVM checks the VM can start, then hands it to the desktop window: the // one already running, or a new one in the tray (`--background`). The window // runs the GUI's StartVM, so a VM started from the command line gets Guest // Tools and the Win10 cold-reboot watcher too; both need a process that stays // up after this command exits. // // viaWindow is false when --data-root points elsewhere than the window's // data root could; the VM then starts here, without those two. func startVM(ctx context.Context, cfg *config.Config, prep *vmstart.Prep, name string, viaWindow bool) error { rep := host.Inspect(cfg.DataRoot) d, err := prep.Client.Show(ctx, name) if err != nil { return err } if d.State == "running" { // Preparation rewrites extra-args and the OpenCore image; never under a live VM. return fmt.Errorf("%s", i18n.T(cfg.Locale, "vm.already_running", name)) } if err := prep.CheckWHPX(rep); err != nil { return err } if err := prep.CheckMemory(d.Memory, rep); err != nil { return err } if viaWindow && windowHandoffWorks { return startInWindow(ctx, cfg, name) } // Honour the core plugin's WHPX setting, as the window does. st := plugin.ReadState(cfg.DataRoot) prep.SkipWHPXFallback = !builtin.CoreSettingOnInState(st, builtin.SettingWHPXFallback) prep.Prepare(ctx, name, rep, &d) if err := prep.Client.StartWithCompat(ctx, name, os.Stdout, os.Stderr, func(msg string) { fmt.Fprintln(os.Stderr, msg) }); err != nil { return err } vms, err := prep.Client.List(ctx) if err != nil { return nil } for _, vm := range vms { if vm.Name == name && vm.State == "running" && vm.PID != nil && *vm.PID > 0 { vmDir := vm.Dir if vmDir == "" { vmDir = d.Directory } if line, _ := vmstart.ApplyVMAffinity(cfg.Locale, rep, vmDir, cfg.AutoPinPCores, *vm.PID, d.CPUs, false); line != "" { fmt.Fprintln(os.Stderr, line) } } } return nil } func startInWindow(ctx context.Context, cfg *config.Config, name string) error { if err := os.MkdirAll(cfg.TempDir(), 0o755); err != nil { return err } result := filepath.Join(cfg.TempDir(), fmt.Sprintf("cli-start-%d.json", time.Now().UnixNano())) w := WindowArgs{StartVM: name, StartResult: result} if hwnd := findWindow(); hwnd != 0 { fmt.Fprintln(os.Stderr, i18n.M(cfg.Locale, "cli.start.handing_to_window", i18n.Vars{"name": name})) if err := sendToWindow(hwnd, w.Args()); err != nil { return err } } else { w.Background = true fmt.Fprintln(os.Stderr, i18n.M(cfg.Locale, "cli.start.spawning_tray", i18n.Vars{"name": name})) if err := spawnWindow(w.Args()); err != nil { return err } } ctx, stop := signal.NotifyContext(ctx, os.Interrupt) defer stop() res, err := waitStartResult(ctx, result, startHandoffTimeout) switch { case errors.Is(err, context.Canceled): return fmt.Errorf("%s", i18n.M(cfg.Locale, "cli.start.canceled", i18n.Vars{"name": name})) case errors.Is(err, context.DeadlineExceeded): return fmt.Errorf("%s", i18n.M(cfg.Locale, "cli.start.timeout", i18n.Vars{"name": name, "timeout": startHandoffTimeout})) case err != nil: return err } if !res.OK { return errors.New(res.Error) } // Guest Tools only connects once macOS is up and its agent runs, so say // what this process can know: who now looks after the VM. fmt.Println(i18n.M(cfg.Locale, "cli.start.managed_ok", i18n.Vars{"name": name})) return nil } // waitStartResult polls for the window's StartResult file and removes it. // The window writes it with a rename, so any file seen is complete. func waitStartResult(ctx context.Context, path string, timeout time.Duration) (StartResult, error) { ctx, cancel := context.WithTimeout(ctx, timeout) defer cancel() tick := time.NewTicker(250 * time.Millisecond) defer tick.Stop() for { if b, err := os.ReadFile(path); err == nil { _ = os.Remove(path) var res StartResult if err := json.Unmarshal(b, &res); err != nil { return StartResult{}, fmt.Errorf("unreadable start result %s: %w", path, err) } return res, nil } select { case <-ctx.Done(): return StartResult{}, ctx.Err() case <-tick.C: } } } // WriteStartResult is the window's side of waitStartResult. func WriteStartResult(path string, startErr error) error { res := StartResult{OK: startErr == nil} if startErr != nil { res.Error = startErr.Error() } b, err := json.Marshal(res) if err != nil { return err } part := path + ".part" if err := os.WriteFile(part, b, 0o644); err != nil { return err } return os.Rename(part, path) }