package app import ( "context" "errors" "fmt" "strings" "sync" "time" "github.com/Nwflower/reims-go/internal/driver" "github.com/Nwflower/reims-go/internal/host" "github.com/Nwflower/reims-go/internal/vmstart" ) type VMDisplayStatus struct { TargetDisplay string `json:"target_display"` EffectiveDisplay string `json:"effective_display"` FallbackToPrimary bool `json:"fallback_to_primary"` Connected bool `json:"connected"` Displays []host.DisplayInfo `json:"displays"` DisplayPresets []host.DisplayPreset `json:"display_presets"` FullscreenHiDPI bool `json:"fullscreen_hidpi"` HiDPIAdvice string `json:"hidpi_advice"` Running bool `json:"running"` AppliedLive bool `json:"applied_live"` MoveError string `json:"move_error,omitempty"` } type vmDisplayHost struct { displays func() []host.DisplayInfo move func(pid uint32, displayName string, borderless bool) (bool, error) // moveTree places the window of a VM whose processes are pids; nil means the // host's own implementation. moveTree func(pids []uint32, displayName string, borderless bool) (bool, error) } func (h vmDisplayHost) moveProcessTree(pids []uint32, displayName string, borderless bool) (bool, error) { if h.moveTree != nil { return h.moveTree(pids, displayName, borderless) } return host.MoveProcessTreeWindowToDisplay(pids, displayName, borderless) } type vmDisplayPlacement struct { sync.Mutex moveEpoch uint64 } func (a *App) vmDisplayPlacement(ref driver.VMRef) *vmDisplayPlacement { placement, _ := a.displayPlacements.LoadOrStore(ref.Key(), &vmDisplayPlacement{}) return placement.(*vmDisplayPlacement) } func buildVMDisplayStatus(vm driver.VMInfo, cfg vmstart.VMDisplayConfig, displays []host.DisplayInfo) VMDisplayStatus { target, fallback := vmstart.ResolveTargetDisplay(cfg, displays) if displays == nil { displays = []host.DisplayInfo{} } presets, _ := host.RecommendDisplayPresets(target) status := VMDisplayStatus{ TargetDisplay: cfg.TargetDisplay, FallbackToPrimary: fallback, Connected: target != nil && !fallback, Displays: displays, DisplayPresets: presets, FullscreenHiDPI: host.FullscreenStartsHiDPI(target), HiDPIAdvice: host.HiDPIAdvice(target, presets), Running: vm.State == "running", } if target != nil { status.EffectiveDisplay = target.Name } return status } func (a *App) GetVMDisplay(driverID, name string) (VMDisplayStatus, error) { vm, err := a.resolveVMInfo(driverID, name) if err != nil { return VMDisplayStatus{}, err } return buildVMDisplayStatus(vm, vmstart.ReadVMDisplay(vm.Directory), a.displayHost.displays()), nil } func (a *App) SetVMDisplay(driverID, name, targetDisplay string) (VMDisplayStatus, error) { if err := a.requireWritableDataRoot(); err != nil { return VMDisplayStatus{}, err } vm, err := a.resolveVMInfo(driverID, name) if err != nil { return VMDisplayStatus{}, err } placement := a.vmDisplayPlacement(vm.Ref()) placement.Lock() defer placement.Unlock() displays := a.displayHost.displays() cfg := vmstart.VMDisplayConfig{TargetDisplay: vmstart.NormalizeTargetDisplay(targetDisplay)} status := buildVMDisplayStatus(vm, cfg, displays) if status.FallbackToPrimary && !strings.EqualFold(cfg.TargetDisplay, vmstart.ReadVMDisplay(vm.Directory).TargetDisplay) { return VMDisplayStatus{}, fmt.Errorf("%w: %q is not connected", host.ErrDisplayNotFound, cfg.TargetDisplay) } if _, err := vmstart.SaveVMDisplay(vm.Directory, cfg); err != nil { return VMDisplayStatus{}, err } defer a.emitStateChanged() if !status.Running || len(displays) == 0 { return status, nil } if status.FallbackToPrimary { a.emitVMLogForDriver(vm.DriverID, vm.Name, displayFallbackLog(cfg.TargetDisplay)) } if driver.IsHosted(vm.Capabilities) { // The driver owns a hosted VM's display; only the choice is saved. return status, nil } pid := 0 if vm.PID != nil { pid = *vm.PID } managed := a.brokerRunsVM(vm.DriverID, vm.Name) if pid <= 0 && !managed { ctx := a.baseCtx() pid, err = a.displayVMPID(ctx, vm.Ref()) if err == nil && pid <= 0 { pid, err = a.liveDisplayVMPID(ctx, vm.Ref()) } if err != nil { status.MoveError = "Could not find VM display process: " + err.Error() a.emitVMLogForDriver(vm.DriverID, vm.Name, status.MoveError) return status, nil } } if pid <= 0 && !managed { a.emitVMLogForDriver(vm.DriverID, vm.Name, "Display window not ready. The display selection will apply on next start.") return status, nil } // Use the window's current mode, which the user may have toggled since startup. var moved bool if pids := a.vmProcessPIDs(vm.Ref(), pid); managed || len(pids) > 1 { moved, err = a.displayHost.moveProcessTree(pids, status.EffectiveDisplay, false) } else { moved, err = a.displayHost.move(uint32(pid), status.EffectiveDisplay, false) } switch { case errors.Is(err, host.ErrDisplayWindowNotFound): a.emitVMLogForDriver(vm.DriverID, vm.Name, "Display window not ready. The display selection will apply on next start.") return status, nil case err != nil: status.MoveError = "Could not move VM display: " + err.Error() a.emitVMLogForDriver(vm.DriverID, vm.Name, status.MoveError) case moved: status.AppliedLive = true placement.moveEpoch++ a.emitVMLogForDriver(vm.DriverID, vm.Name, fmt.Sprintf("Moved VM window to display %q.", status.EffectiveDisplay)) } return status, nil } func displayFallbackLog(target string) string { return fmt.Sprintf("Display %q is disconnected. Using the primary display.", target) } func (a *App) displayVMPID(ctx context.Context, ref driver.VMRef) (int, error) { vms, err := a.polledVMs(ctx) if err != nil { return 0, err } return runningDisplayPID(vms, ref), nil } func runningDisplayPID(vms []driver.VMListItem, ref driver.VMRef) int { for _, vm := range vms { if driver.NewVMRef(vm.DriverID, vm.Name) == ref && vm.State == "running" && vm.PID != nil { return *vm.PID } } return 0 } func (a *App) liveDisplayVMPID(ctx context.Context, ref driver.VMRef) (int, error) { a.mu.Lock() router := a.driverRouter a.mu.Unlock() if router == nil { vms, err := a.listVMsInternal(ctx) return runningDisplayPID(vms, ref), err } d, err := router.DriverByID(ref.DriverID) if err != nil { return 0, err } vms, err := d.List(ctx) if err != nil { return 0, err } for _, vm := range vms { if driver.NewVMRef(ref.DriverID, vm.Name) == ref && vm.State == "running" && vm.PID != nil { return *vm.PID, nil } } return 0, nil } func (a *App) positionVMDisplayOnStart(ctx context.Context, vm driver.VMInfo, ticks <-chan time.Time, probePID func(context.Context) (int, error)) { placement := a.vmDisplayPlacement(vm.Ref()) placement.Lock() epoch := placement.moveEpoch placement.Unlock() log := func(line string) { a.emitVMLogForDriver(vm.DriverID, vm.Name, line) } cfg := vmstart.ReadVMDisplay(vm.Directory) if cfg.TargetDisplay == "" { return } borderless := vmInfoBool(vm, "borderless") for { select { case <-ctx.Done(): return case <-ticks: if ctx.Err() != nil { return } } pid, err := probePID(ctx) if ctx.Err() != nil { return } if err != nil { log("Could not find VM display process: " + err.Error()) return } if pid <= 0 { continue } // A settings change may have saved and applied a new target while we waited. placement.Lock() if placement.moveEpoch != epoch || ctx.Err() != nil { placement.Unlock() return } cfg := vmstart.ReadVMDisplay(vm.Directory) if cfg.TargetDisplay == "" { placement.Unlock() return } target, fallback := vmstart.ResolveTargetDisplay(cfg, a.displayHost.displays()) if target == nil { placement.Unlock() return } moved, err := a.displayHost.move(uint32(pid), target.Name, borderless) placement.Unlock() switch { case errors.Is(err, host.ErrDisplayWindowNotFound), errors.Is(err, host.ErrDisplayNotFound): // The window or monitor may have changed since enumeration. continue case err != nil: log("Could not move VM display: " + err.Error()) case moved: if fallback { log(displayFallbackLog(cfg.TargetDisplay)) } log(fmt.Sprintf("Moved VM window to display %q.", target.Name)) } return } }