Files
Reims-Go/internal/plugin/builtin/builtin.go
T

773 lines
27 KiB
Go

// Package builtin registers compiled-in Reims-Go extensions onto the unified
// plugin Registry (docs/plugin-architecture.md §3.2, §5.4). Every builtin
// extension runs through the same reversible Scope, service dependency graph,
// and HookBus as external plugins so disabling any extension leaves zero residue.
package builtin
import (
"context"
"fmt"
"os"
"path/filepath"
"strings"
"github.com/Nwflower/reims-go/internal/config"
"github.com/Nwflower/reims-go/internal/driver"
"github.com/Nwflower/reims-go/internal/driver/reims"
"github.com/Nwflower/reims-go/internal/guesttools"
"github.com/Nwflower/reims-go/internal/host"
"github.com/Nwflower/reims-go/internal/installer"
"github.com/Nwflower/reims-go/internal/opencore"
"github.com/Nwflower/reims-go/internal/plugin"
"github.com/Nwflower/reims-go/internal/qmp"
rt "github.com/Nwflower/reims-go/internal/runtime"
"github.com/Nwflower/reims-go/internal/version"
"github.com/Nwflower/reims-go/internal/vmstart"
)
// Builtin plugin IDs (§3.2, §5.4).
const (
IDThemeDefault = "builtin.theme.default"
IDDriverReimsMacOS = driver.BuiltinReimsMacOSDriverID
IDGuestTools = "builtin.bridge.guest-tools"
IDClipboard = "builtin.bridge.clipboard"
IDInput = "builtin.input"
IDWin10ColdReboot = "builtin.compat.win10-cold-reboot"
IDWHPXFallback = "builtin.compat.whpx-fallback"
IDOfflineHelper = "builtin.prep.offline-helper"
IDRecoveryBoot = "builtin.prep.recovery-boot"
IDGuestLang = "builtin.prep.guest-lang"
)
// Service names provided by builtin extensions.
const (
ServiceGuestToolsTransport = "guest-tools.transport"
ServiceHostInput = "host.input"
)
// HostCallbacks connects builtin extensions to host runtime services without
// creating an import cycle with internal/app.
type HostCallbacks struct {
GetConfig func() config.Config
Log func(source, line string)
EnsureGuestTools func() (*guesttools.Server, int, error)
StopGuestTools func()
ValidateDriveConfig func(guesttools.VMConfig) guesttools.VMConfig
OnIMEText func(target host.IMETarget, text string)
StartColdReboot func(vmName, qmpAddr string)
CancelColdReboot func(vmName string)
VMSharedDir func(vmName string) string
GuestToolsImg func(vmName string) string
// GetSetting returns a saved plugin setting value (empty vmName = app scope).
GetSetting func(pluginID, vmName, key string) (any, bool)
}
func appVersion() string {
v := strings.TrimPrefix(strings.TrimSpace(version.Version), "v")
if v == "" || v == "dev" {
return "0.2.6"
}
return v
}
// RegisterAll registers all Phase 0 builtin extensions into reg.
// desiredFn optionally overrides defaultEnabled (e.g. from state.json).
func RegisterAll(reg *plugin.Registry, cb HostCallbacks, desiredFn func(id string, defaultEnabled bool) bool) error {
if desiredFn == nil {
desiredFn = func(_ string, def bool) bool { return def }
}
ver := appVersion()
defs := []plugin.PluginDef{
defThemeDefault(ver, desiredFn),
defDriverReimsMacOS(ver, cb, desiredFn),
defGuestTools(ver, cb, desiredFn),
defClipboard(ver, cb, desiredFn),
defInput(ver, cb, desiredFn),
defWin10ColdReboot(ver, cb, desiredFn),
defWHPXFallback(ver, cb, desiredFn),
defOfflineHelper(ver, cb, desiredFn),
defRecoveryBoot(ver, cb, desiredFn),
defGuestLang(ver, cb, desiredFn),
}
for _, d := range defs {
if err := reg.Register(d); err != nil {
return err
}
}
return nil
}
func defThemeDefault(ver string, desiredFn func(string, bool) bool) plugin.PluginDef {
return plugin.PluginDef{
Manifest: plugin.Manifest{
Schema: 1,
ID: IDThemeDefault,
Version: ver,
Name: plugin.LocalizedText{ZhCN: "默认浅色 / 深色主题", EnUS: "Default Light / Dark Theme"},
Description: plugin.LocalizedText{
ZhCN: "内置 macOS Tahoe 风格浅色与深色主题,零额外样式注入",
EnUS: "Built-in macOS Tahoe light and dark themes with zero extra CSS overhead",
},
Publisher: "Reims-Go",
License: "Apache-2.0",
DefaultEnabled: true,
Contributes: plugin.Contributes{
Themes: []plugin.ThemeContribution{{
ID: IDThemeDefault,
Name: plugin.LocalizedText{ZhCN: "默认主题", EnUS: "Default"},
Appearance: "both",
}},
},
},
Source: plugin.SourceBuiltin,
Trust: plugin.TrustOfficial,
Desired: desiredFn(IDThemeDefault, true),
}
}
func defDriverReimsMacOS(ver string, cb HostCallbacks, desiredFn func(string, bool) bool) plugin.PluginDef {
return plugin.PluginDef{
Manifest: plugin.Manifest{
Schema: 1,
ID: IDDriverReimsMacOS,
Version: ver,
Name: plugin.LocalizedText{ZhCN: "macOS 虚拟机驱动 (Reims vGPU)", EnUS: "macOS VM Driver (Reims vGPU)"},
Description: plugin.LocalizedText{
ZhCN: "内置 reims-ctl / reims-vgpu macOS 虚拟机驱动,支持 Metal Vulkan 加速、OpenCore 与快照",
EnUS: "Built-in reims-ctl / reims-vgpu macOS VM driver with Metal-to-Vulkan acceleration, OpenCore, and snapshots",
},
Publisher: "Reims-Go",
License: "Apache-2.0",
Permissions: []string{"driver:vm", "vm:control", "qmp:write"},
DefaultEnabled: true,
},
Source: plugin.SourceBuiltin,
Trust: plugin.TrustOfficial,
Desired: desiredFn(IDDriverReimsMacOS, true),
Activate: func(_ context.Context, sc *plugin.Scope) error {
drv := driver.NewReimsMacOSDriver(cb.GetConfig)
sc.Registry().RegisterGuestDriver(sc, IDDriverReimsMacOS, drv)
return nil
},
}
}
func defGuestTools(ver string, cb HostCallbacks, desiredFn func(string, bool) bool) plugin.PluginDef {
return plugin.PluginDef{
Manifest: plugin.Manifest{
Schema: 1,
ID: IDGuestTools,
Version: ver,
Name: plugin.LocalizedText{ZhCN: "Guest Tools 传输服务", EnUS: "Guest Tools Transport"},
Description: plugin.LocalizedText{
ZhCN: "提供本地回环鉴权宿客传输通道、REIMSTOOLS 辅助盘挂载、共享目录与防休眠支持",
EnUS: "Provides localhost token-authenticated host-guest transport, REIMSTOOLS helper disk, shared folders, and prevent-sleep",
},
Publisher: "Reims-Go",
License: "Apache-2.0",
Provides: []plugin.ServiceProvision{{Service: ServiceGuestToolsTransport, Version: "1.0.0"}},
Permissions: []string{"vm:intent", "fs:shared", "ui:slot"},
DefaultEnabled: true,
},
Source: plugin.SourceBuiltin,
Trust: plugin.TrustOfficial,
Desired: desiredFn(IDGuestTools, true),
Activate: func(_ context.Context, sc *plugin.Scope) error {
var srv *guesttools.Server
if cb.EnsureGuestTools != nil {
s, _, err := cb.EnsureGuestTools()
if err != nil {
return err
}
srv = s
} else {
srv = guesttools.NewTransportServer(nil)
}
sc.Provide(ServiceGuestToolsTransport, "1.0.0", srv)
sc.OnDispose(func() {
if cb.StopGuestTools != nil {
cb.StopGuestTools()
}
})
sc.Registry().RegisterVMCard(sc, plugin.VMCardContribution{
ID: "guest-tools-transport",
Title: plugin.LocalizedText{ZhCN: "宿客协作通道", EnUS: "Guest Tools Bridge"},
Value: plugin.LocalizedText{ZhCN: "已就绪", EnUS: "Ready"},
Badge: "ok",
When: "capability:guest_tools",
})
sc.Registry().Hooks().Subscribe(sc, plugin.HookRegistration{
Event: plugin.EventVMBeforeStart,
Builtin: true,
Handler: func(_ context.Context, raw any) (any, error) {
p, ok := raw.(plugin.BeforeStartPayload)
if !ok || p.VMDir == "" || p.DriverID != IDDriverReimsMacOS {
return nil, nil
}
if cb.EnsureGuestTools == nil {
return nil, nil
}
s, port, err := cb.EnsureGuestTools()
if err != nil || port <= 0 {
return nil, nil
}
sharedDir := ""
if cb.VMSharedDir != nil {
sharedDir = cb.VMSharedDir(p.VMName)
}
intent := plugin.StartIntent{
PluginID: IDGuestTools,
Env: map[string]string{},
}
gtCfg, err := guesttools.LoadOrCreateVMConfig(p.VMDir, p.VMName, sharedDir, port)
if err == nil && gtCfg.Token != "" {
if cb.ValidateDriveConfig != nil {
gtCfg = cb.ValidateDriveConfig(gtCfg)
}
s.RegisterVM(gtCfg)
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)
if bErr := guesttools.BuildToolsDiskImage(imgPath, gtCfg); bErr == nil {
tokens := plugin.SplitShellTokens(reims.MergeGuestToolsArgs("", imgPath))
intent.Args = append(intent.Args, plugin.ArgFragment{
PluginID: IDGuestTools,
Key: "reimstools",
Tokens: tokens,
Builtin: true,
Priority: 80,
})
} else {
intent.Warnings = append(intent.Warnings, "guest tools image skipped: "+bErr.Error())
}
} else if !reims.HasGuestToolsArgs(p.ExtraArgs) {
intent.ClearKeys = append(intent.ClearKeys, "reimstools")
}
return intent, nil
},
})
return nil
},
}
}
func defClipboard(ver string, cb HostCallbacks, desiredFn func(string, bool) bool) plugin.PluginDef {
minMB := 1.0
maxMB := 16.0
return plugin.PluginDef{
Manifest: plugin.Manifest{
Schema: 1,
ID: IDClipboard,
Version: ver,
Name: plugin.LocalizedText{ZhCN: "剪贴板互通", EnUS: "Clipboard Sync"},
Description: plugin.LocalizedText{
ZhCN: "在 Windows 宿主与 macOS 虚拟机之间同步文本与截图;支持按方向与大小限制即时开关",
EnUS: "Sync text and screenshots between Windows host and macOS VMs with per-VM direction and size controls",
},
Publisher: "Reims-Go",
License: "Apache-2.0",
Requires: []plugin.ServiceRequirement{{Service: ServiceGuestToolsTransport, Version: "^1.0.0"}},
Permissions: []string{"host:clipboard", "ui:slot"},
DefaultEnabled: true,
Settings: &plugin.SettingsSchema{
Title: plugin.LocalizedText{ZhCN: "剪贴板互通", EnUS: "Clipboard Sync"},
Group: "collaboration",
Scope: "vm",
Order: []string{"enabled", "direction", "sync_images", "max_image_mb"},
Properties: map[string]plugin.SettingProperty{
"enabled": {
Type: "boolean",
Title: plugin.LocalizedText{ZhCN: "启用剪贴板互通", EnUS: "Enable clipboard sync"},
Default: true,
Effect: "immediate",
Scope: "vm",
Group: "collaboration",
},
"direction": {
Type: "string",
Title: plugin.LocalizedText{ZhCN: "同步方向", EnUS: "Sync direction"},
Enum: []string{"bidirectional", "host-to-guest", "guest-to-host"},
EnumLabels: []plugin.LocalizedText{
{ZhCN: "双向同步", EnUS: "Bidirectional"},
{ZhCN: "仅宿主到虚拟机", EnUS: "Host to guest only"},
{ZhCN: "仅虚拟机到宿主", EnUS: "Guest to host only"},
},
Default: "bidirectional",
Effect: "immediate",
Scope: "vm",
Group: "collaboration",
},
"sync_images": {
Type: "boolean",
Title: plugin.LocalizedText{ZhCN: "同步剪贴板图片", EnUS: "Sync clipboard images"},
Default: true,
Effect: "immediate",
Scope: "vm",
Group: "collaboration",
},
"max_image_mb": {
Type: "integer",
Title: plugin.LocalizedText{ZhCN: "图片大小上限 (MB)", EnUS: "Max image size (MB)"},
Default: 16,
Minimum: &minMB,
Maximum: &maxMB,
Effect: "immediate",
Scope: "vm",
Group: "collaboration",
},
},
},
},
Source: plugin.SourceBuiltin,
Trust: plugin.TrustOfficial,
Desired: desiredFn(IDClipboard, true),
Activate: func(_ context.Context, sc *plugin.Scope) error {
rawSvc, ok := sc.Lookup(ServiceGuestToolsTransport)
if !ok {
return fmt.Errorf("required service %q not available", ServiceGuestToolsTransport)
}
srv, ok := rawSvc.(*guesttools.Server)
if !ok || srv == nil {
return fmt.Errorf("invalid %q service instance", ServiceGuestToolsTransport)
}
srv.SetClipboardActive(true)
sc.OnDispose(func() {
srv.SetClipboardActive(false)
})
sc.Registry().RegisterVMCard(sc, plugin.VMCardContribution{
ID: "clipboard-sync",
Title: plugin.LocalizedText{ZhCN: "剪贴板互通", EnUS: "Clipboard Sync"},
Value: plugin.LocalizedText{ZhCN: "已启用", EnUS: "Active"},
Badge: "ok",
When: "capability:guest_tools",
})
sc.Registry().RegisterDiagnostics(sc, plugin.DiagnosticsContribution{
ID: "clipboard-stats",
Title: plugin.LocalizedText{ZhCN: "剪贴板同步统计", EnUS: "Clipboard Sync Counters"},
}, func(_ context.Context, _ string) (plugin.DiagnosticsEntry, error) {
stats := srv.ClipboardDiagnostics()
// Privacy rule (§5.4): record counters and errors only, NEVER clipboard content.
return plugin.DiagnosticsEntry{
PluginID: IDClipboard,
Title: "Clipboard Sync Counters",
Data: map[string]any{
"active": stats.Active,
"watcher_running": stats.WatcherRunning,
"host_to_guest_count": stats.HostToGuestCount,
"guest_to_host_count": stats.GuestToHostCount,
"error_count": stats.ErrorCount,
},
}, nil
})
return nil
},
}
}
func defInput(ver string, cb HostCallbacks, desiredFn func(string, bool) bool) plugin.PluginDef {
return plugin.PluginDef{
Manifest: plugin.Manifest{
Schema: 1,
ID: IDInput,
Version: ver,
Name: plugin.LocalizedText{ZhCN: "宿主输入服务与 IME 桥接", EnUS: "Host Input Service & IME Bridge"},
Description: plugin.LocalizedText{
ZhCN: "管理远程输入法键入钩子与声明式鼠标输入过滤器,停用后立即卸载钩子线程",
EnUS: "Manages the remote IME keyboard hook and declarative mouse input filters; unloads hook threads on disable",
},
Publisher: "Reims-Go",
License: "Apache-2.0",
Provides: []plugin.ServiceProvision{{Service: ServiceHostInput, Version: "1.0.0"}},
Permissions: []string{"input:filter"},
DefaultEnabled: true,
},
Source: plugin.SourceBuiltin,
Trust: plugin.TrustOfficial,
Desired: desiredFn(IDInput, true),
Activate: func(_ context.Context, sc *plugin.Scope) error {
svc := host.NewInputService(cb.OnIMEText)
if cb.OnIMEText != nil {
if err := svc.EnableIME(true); err != nil && cb.Log != nil {
cb.Log("app", "Remote IME hook unavailable: "+err.Error())
}
}
sc.Provide(ServiceHostInput, "1.0.0", svc)
sc.OnDispose(func() {
svc.Close()
})
return nil
},
}
}
func defWin10ColdReboot(ver string, cb HostCallbacks, desiredFn func(string, bool) bool) plugin.PluginDef {
return plugin.PluginDef{
Manifest: plugin.Manifest{
Schema: 1,
ID: IDWin10ColdReboot,
Version: ver,
Name: plugin.LocalizedText{ZhCN: "Windows 10 冷重启补偿", EnUS: "Windows 10 Cold-Reboot Workaround"},
Description: plugin.LocalizedText{
ZhCN: "在缺少 WHvResetPartition 的 Windows 10 上通过独立 QMP 通道监听客体重启并自动重新拉起",
EnUS: "Uses an isolated QMP channel with -no-reboot on Windows 10 to restart guests cleanly in a new Hyper-V partition",
},
Publisher: "Reims-Go",
License: "Apache-2.0",
Permissions: []string{"vm:intent", "qmp:write"},
DefaultEnabled: true,
},
Source: plugin.SourceBuiltin,
Trust: plugin.TrustOfficial,
Desired: desiredFn(IDWin10ColdReboot, true),
Activate: func(_ context.Context, sc *plugin.Scope) error {
sc.Registry().Hooks().Subscribe(sc, plugin.HookRegistration{
Event: plugin.EventVMBeforeStart,
Builtin: true,
Handler: func(_ context.Context, raw any) (any, error) {
p, ok := raw.(plugin.BeforeStartPayload)
if !ok || p.DriverID != IDDriverReimsMacOS {
return nil, nil
}
needs, _ := p.HostFacts["host.needs_cold_reboot"].(bool)
if !needs {
return plugin.StartIntent{
PluginID: IDWin10ColdReboot,
ClearKeys: []string{"win10-cold-reboot"},
}, nil
}
tmpDir := ""
if cb.GetConfig != nil {
cfg := cb.GetConfig()
tmpDir = cfg.TempDir()
}
sockPath := qmp.RebootSocketPath(p.VMDir, tmpDir, p.VMName)
_ = os.MkdirAll(filepath.Dir(sockPath), 0o755)
_ = os.Remove(sockPath)
tokens := plugin.SplitShellTokens(qmp.MergeWin10RebootUnixArgs("", sockPath))
return plugin.StartIntent{
PluginID: IDWin10ColdReboot,
Args: []plugin.ArgFragment{{
PluginID: IDWin10ColdReboot,
Key: "win10-cold-reboot",
Tokens: tokens,
Builtin: true,
Priority: 95,
}},
PostStart: []plugin.PostStartAction{{
PluginID: IDWin10ColdReboot,
Kind: "qmp.watch_cold_reboot",
Params: map[string]any{"qmp_addr": "unix:" + sockPath},
}},
}, nil
},
})
sc.Registry().Hooks().Subscribe(sc, plugin.HookRegistration{
Event: plugin.EventVMAfterStart,
Builtin: true,
Handler: func(_ context.Context, raw any) (any, error) {
ev, ok := raw.(plugin.VMEventPayload)
if ok && ev.QMPAddr != "" && cb.StartColdReboot != nil {
cb.StartColdReboot(ev.VMName, ev.QMPAddr)
}
return nil, nil
},
})
sc.Registry().Hooks().Subscribe(sc, plugin.HookRegistration{
Event: plugin.EventVMAfterStop,
Builtin: true,
Handler: func(_ context.Context, raw any) (any, error) {
ev, ok := raw.(plugin.VMEventPayload)
if ok && cb.CancelColdReboot != nil {
cb.CancelColdReboot(ev.VMName)
}
return nil, nil
},
})
return nil
},
}
}
func defWHPXFallback(ver string, cb HostCallbacks, desiredFn func(string, bool) bool) plugin.PluginDef {
return plugin.PluginDef{
Manifest: plugin.Manifest{
Schema: 1,
ID: IDWHPXFallback,
Version: ver,
Name: plugin.LocalizedText{ZhCN: "WHPX 兼容降级", EnUS: "WHPX Compatibility Fallback"},
Description: plugin.LocalizedText{
ZhCN: "根据宿主嵌套虚拟化探测与运行时能力自动应用 kernel-irqchip=off 避免首次启动崩溃",
EnUS: "Automatically applies kernel-irqchip=off based on host nested-virt probes and runtime capabilities",
},
Publisher: "Reims-Go",
License: "Apache-2.0",
Permissions: []string{"vm:intent"},
DefaultEnabled: true,
},
Source: plugin.SourceBuiltin,
Trust: plugin.TrustOfficial,
Desired: desiredFn(IDWHPXFallback, true),
Activate: func(_ context.Context, sc *plugin.Scope) error {
sc.Registry().Hooks().Subscribe(sc, plugin.HookRegistration{
Event: plugin.EventHostPreflight,
Builtin: true,
Handler: func(_ context.Context, raw any) (any, error) {
p, ok := raw.(plugin.PreflightPayload)
if !ok {
return nil, nil
}
needsCold, _ := p.HostFacts["host.needs_cold_reboot"].(bool)
irqAvail, _ := p.HostFacts["host.whpx_irqchip"].(bool)
nestedOK, _ := p.HostFacts["host.whpx_nested_virt"].(bool)
hasCap := false
if caps, ok := p.HostFacts["runtime.capabilities"].([]string); ok {
for _, c := range caps {
if strings.EqualFold(c, "nested-virt-nonfatal") {
hasCap = true
break
}
}
}
if !needsCold && irqAvail && !nestedOK && !hasCap {
return plugin.PreflightResult{
Advices: []string{"Host lacks nested-virt property and runtime lacks nested-virt-nonfatal capability; kernel-irqchip=off will be auto-applied"},
}, nil
}
return nil, nil
},
})
sc.Registry().Hooks().Subscribe(sc, plugin.HookRegistration{
Event: plugin.EventVMBeforeStart,
Builtin: true,
Handler: func(_ context.Context, raw any) (any, error) {
p, ok := raw.(plugin.BeforeStartPayload)
if !ok || p.DriverID != IDDriverReimsMacOS {
return nil, nil
}
needsCold, _ := p.HostFacts["host.needs_cold_reboot"].(bool)
irqAvail, _ := p.HostFacts["host.whpx_irqchip"].(bool)
nestedOK, _ := p.HostFacts["host.whpx_nested_virt"].(bool)
if needsCold || !irqAvail || nestedOK {
return plugin.StartIntent{
PluginID: IDWHPXFallback,
ClearKeys: []string{"kernel-irqchip"},
}, nil
}
for _, c := range p.RuntimeCaps {
if strings.EqualFold(c, "nested-virt-nonfatal") {
return plugin.StartIntent{
PluginID: IDWHPXFallback,
ClearKeys: []string{"kernel-irqchip"},
}, nil
}
}
if reims.HasKernelIrqchipArg(p.ExtraArgs) {
return nil, nil
}
return plugin.StartIntent{
PluginID: IDWHPXFallback,
Args: []plugin.ArgFragment{{
PluginID: IDWHPXFallback,
Key: "kernel-irqchip",
Tokens: []string{"-machine", "kernel-irqchip=off"},
Builtin: true,
Priority: 90,
}},
Warnings: []string{"Host rejects nested-virtualization property; enabled kernel-irqchip=off automatically"},
}, nil
},
})
return nil
},
}
}
func defOfflineHelper(ver string, cb HostCallbacks, desiredFn func(string, bool) bool) plugin.PluginDef {
return plugin.PluginDef{
Manifest: plugin.Manifest{
Schema: 1,
ID: IDOfflineHelper,
Version: ver,
Name: plugin.LocalizedText{ZhCN: "离线安装辅助盘", EnUS: "Offline Installer Helper Disk"},
Description: plugin.LocalizedText{
ZhCN: "在挂载离线安装器时自动准备并注入 REIMSHELP 辅助盘,弹出安装盘后自动剥离",
EnUS: "Automatically prepares and attaches the REIMSHELP helper disk for offline installers and strips it on eject",
},
Publisher: "Reims-Go",
License: "Apache-2.0",
Permissions: []string{"vm:intent"},
DefaultEnabled: true,
},
Source: plugin.SourceBuiltin,
Trust: plugin.TrustOfficial,
Desired: desiredFn(IDOfflineHelper, true),
Activate: func(_ context.Context, sc *plugin.Scope) error {
sc.Registry().Hooks().Subscribe(sc, plugin.HookRegistration{
Event: plugin.EventVMBeforeStart,
Builtin: true,
Handler: func(_ context.Context, raw any) (any, error) {
p, ok := raw.(plugin.BeforeStartPayload)
if !ok || p.DriverID != IDDriverReimsMacOS {
return nil, nil
}
if p.HasInstaller && reims.IsOfflineInstallerPath(p.InstallerPath) && cb.GetConfig != nil {
cfg := cb.GetConfig()
helperPath, err := installer.EnsureOfflineHelperImage(cfg.XDGCacheDir(), p.InstallerPath)
if err != nil {
return plugin.StartIntent{
PluginID: IDOfflineHelper,
Warnings: []string{"offline install helper disk skipped: " + err.Error()},
}, nil
}
tokens := plugin.SplitShellTokens(reims.MergeOfflineHelperArgs("", helperPath))
return plugin.StartIntent{
PluginID: IDOfflineHelper,
Args: []plugin.ArgFragment{{
PluginID: IDOfflineHelper,
Key: "reimshelp",
Tokens: tokens,
Builtin: true,
Priority: 85,
}},
}, nil
}
return plugin.StartIntent{
PluginID: IDOfflineHelper,
ClearKeys: []string{"reimshelp"},
}, nil
},
})
return nil
},
}
}
func defRecoveryBoot(ver string, cb HostCallbacks, desiredFn func(string, bool) bool) plugin.PluginDef {
return plugin.PluginDef{
Manifest: plugin.Manifest{
Schema: 1,
ID: IDRecoveryBoot,
Version: ver,
Name: plugin.LocalizedText{ZhCN: "恢复模式引导切换", EnUS: "Recovery Boot Picker Sync"},
Description: plugin.LocalizedText{
ZhCN: "在虚拟机启动前根据标记自动更新 OpenCore 引导菜单以进入或退出恢复模式",
EnUS: "Updates OpenCore boot picker before start when entering or exiting macOS Recovery mode",
},
Publisher: "Reims-Go",
License: "Apache-2.0",
Permissions: []string{"vm:intent"},
DefaultEnabled: true,
},
Source: plugin.SourceBuiltin,
Trust: plugin.TrustOfficial,
Desired: desiredFn(IDRecoveryBoot, true),
Activate: func(_ context.Context, sc *plugin.Scope) error {
sc.Registry().Hooks().Subscribe(sc, plugin.HookRegistration{
Event: plugin.EventVMBeforeStart,
Builtin: true,
Handler: func(ctx context.Context, raw any) (any, error) {
p, ok := raw.(plugin.BeforeStartPayload)
if !ok || p.VMDir == "" || p.DriverID != IDDriverReimsMacOS || cb.GetConfig == nil {
return nil, nil
}
marker := vmstart.ReadRecoveryMarker(p.VMDir)
if marker != "want" && marker != "restore" {
return nil, nil
}
cfg := cb.GetConfig()
active, err := rt.ResolveActive(&cfg)
if err != nil || active == nil {
return nil, nil
}
c := reims.NewClient(&cfg, *active)
show := marker == "want"
nextMarker := ""
if show {
nextMarker = "on"
}
logFn := func(line string) {
if cb.Log != nil {
cb.Log(p.VMName, line)
}
}
w := vmstart.LineWriter(logFn)
if err := c.UpdateOpenCore(ctx, p.VMName, show, w, w); err != nil {
return plugin.StartIntent{
PluginID: IDRecoveryBoot,
Warnings: []string{"could not update OpenCore boot picker: " + err.Error()},
}, nil
}
vmstart.WriteRecoveryMarker(p.VMDir, nextMarker)
return nil, nil
},
})
return nil
},
}
}
func defGuestLang(ver string, cb HostCallbacks, desiredFn func(string, bool) bool) plugin.PluginDef {
return plugin.PluginDef{
Manifest: plugin.Manifest{
Schema: 1,
ID: IDGuestLang,
Version: ver,
Name: plugin.LocalizedText{ZhCN: "macOS 引导语言重放", EnUS: "macOS Boot Language Replay"},
Description: plugin.LocalizedText{
ZhCN: "在启动前与 OpenCore 重建后自动写入已保存的 prev-lang:kbd 客体语言偏好",
EnUS: "Replays the saved prev-lang:kbd language preference into OpenCore NVRAM before start",
},
Publisher: "Reims-Go",
License: "Apache-2.0",
Permissions: []string{"vm:intent"},
DefaultEnabled: true,
},
Source: plugin.SourceBuiltin,
Trust: plugin.TrustOfficial,
Desired: desiredFn(IDGuestLang, true),
Activate: func(_ context.Context, sc *plugin.Scope) error {
sc.Registry().Hooks().Subscribe(sc, plugin.HookRegistration{
Event: plugin.EventVMBeforeStart,
Builtin: true,
// Lower priority so it replays AFTER recovery-boot rebuilds OpenCore (§11.2).
Priority: -10,
Handler: func(ctx context.Context, raw any) (any, error) {
p, ok := raw.(plugin.BeforeStartPayload)
if !ok || p.VMDir == "" || p.DriverID != IDDriverReimsMacOS || cb.GetConfig == nil {
return nil, nil
}
saved := opencore.ReadSavedGuestLang(p.VMDir)
if saved == "" {
return nil, nil
}
ocPath := opencore.ResolveOpenCorePath(p.VMDir)
if ocPath == "" {
return nil, nil
}
cfg := cb.GetConfig()
active, err := rt.ResolveActive(&cfg)
if err != nil || active == nil {
return nil, nil
}
env := rt.BuildChildEnv(&cfg, *active)
if _, err := opencore.PatchImagePrevLang(ctx, ocPath, saved, active.QemuImgPath(), env); err != nil {
return plugin.StartIntent{
PluginID: IDGuestLang,
Warnings: []string{"could not apply macOS language to OpenCore: " + err.Error()},
}, nil
}
return nil, nil
},
})
return nil
},
}
}