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>
482 lines
18 KiB
Go
482 lines
18 KiB
Go
// Package builtin registers compiled-in Reims-Go extensions onto the unified
|
||
// plugin Registry (see docs/plugin-architecture.md). Every builtin
|
||
// runs through the same reversible Scope, service dependency graph and HookBus
|
||
// as external plugins. The core (core.go) is always on; disabling any optional
|
||
// extension leaves zero residue.
|
||
package builtin
|
||
|
||
import (
|
||
"context"
|
||
"fmt"
|
||
"strings"
|
||
|
||
"github.com/Nwflower/reims-go/internal/appwindow"
|
||
"github.com/Nwflower/reims-go/internal/config"
|
||
"github.com/Nwflower/reims-go/internal/driver"
|
||
"github.com/Nwflower/reims-go/internal/guesttools"
|
||
"github.com/Nwflower/reims-go/internal/host"
|
||
"github.com/Nwflower/reims-go/internal/i18n"
|
||
"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"
|
||
)
|
||
|
||
// Builtin plugin IDs. IDCore lives in core.go.
|
||
const (
|
||
// IDThemeDefault is the default theme's contribution ID; the core plugin
|
||
// contributes it.
|
||
IDThemeDefault = "builtin.theme.default"
|
||
// IDDriverReimsMacOS is the guest driver ID of the reims macOS driver,
|
||
// recorded in VM ownership markers; internal/macos/guest registers it.
|
||
IDDriverReimsMacOS = driver.BuiltinReimsMacOSDriverID
|
||
IDGuestTools = "builtin.bridge.guest-tools"
|
||
IDClipboard = "builtin.bridge.clipboard"
|
||
IDInput = "builtin.input"
|
||
IDNpcapBridge = "builtin.network.npcap"
|
||
IDComputerUse = "builtin.computer-use"
|
||
)
|
||
|
||
// Service names provided by builtin extensions.
|
||
const (
|
||
ServiceGuestToolsTransport = "guest-tools.transport"
|
||
ServiceHostInput = "host.input"
|
||
ServiceNpcapBridge = "network.npcap"
|
||
ServiceComputerUse = "computer-use.console"
|
||
)
|
||
|
||
// 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()
|
||
LoadAndRegisterGuestTools func(*guesttools.Server, int, string, string) (guesttools.VMConfig, error)
|
||
OnIMEText func(target host.IMETarget, text string)
|
||
StartColdReboot func(vmName, qmpAddr string)
|
||
CancelColdReboot func(vmName string)
|
||
GuestToolsImg func(vmName string) string
|
||
BuildGuestToolsImage func(vmName, vmDir string) error
|
||
OpenAppWindow func(context.Context, *appwindow.Sessions, *guesttools.Server, ComputerUseService, string) error
|
||
PrepareVMNetwork func(context.Context, string, bool) (func(), error)
|
||
// 返回取消并等待本次恢复任务结束的清理函数,由插件 scope 先于通道释放执行。
|
||
RestorePacketBridges func(context.Context) func()
|
||
StopPacketBridges func()
|
||
OnInstallGuidesChanged func()
|
||
SyncInstallGuides func()
|
||
// 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.12"
|
||
}
|
||
return v
|
||
}
|
||
|
||
// RegisterAll registers the core and the optional 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{
|
||
defCore(ver),
|
||
defGuestTools(ver, cb, desiredFn),
|
||
defClipboard(ver, cb, desiredFn),
|
||
defInput(ver, cb, desiredFn),
|
||
defNpcapBridge(ver, cb, desiredFn),
|
||
defComputerUse(ver, desiredFn),
|
||
defAppWindow(ver, cb, desiredFn),
|
||
defDownloaderParallel(ver, cb, desiredFn),
|
||
}
|
||
for _, d := range defs {
|
||
if err := reg.Register(d); err != nil {
|
||
return err
|
||
}
|
||
}
|
||
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: "宿主与虚拟机之间的通信通道,支撑共享文件夹和防休眠",
|
||
EnUS: "Host–guest channel behind shared folders and keep-awake",
|
||
},
|
||
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 || cb.LoadAndRegisterGuestTools == nil {
|
||
return nil, nil
|
||
}
|
||
s, port, err := cb.EnsureGuestTools()
|
||
if err != nil || port <= 0 {
|
||
return nil, nil
|
||
}
|
||
intent := plugin.StartIntent{
|
||
PluginID: IDGuestTools,
|
||
Env: map[string]string{},
|
||
}
|
||
gtCfg, err := cb.LoadAndRegisterGuestTools(s, port, p.VMDir, p.VMName)
|
||
if err == nil && gtCfg.Token != "" {
|
||
rec, _ := reims.ReadNetworkRecord(p.VMDir)
|
||
netEnabled, _ := reims.ReadVMNetworkEnabled(p.VMDir)
|
||
mode := reims.EffectiveNetworkMode(netEnabled, p.ExtraArgs, rec)
|
||
if mode == "bridge" && sc.Registry().IsActive(IDNpcapBridge) {
|
||
loc := i18n.Auto
|
||
if cb.GetConfig != nil {
|
||
loc = cb.GetConfig().Locale
|
||
}
|
||
tokens, argsErr := reims.GuestToolsNetworkUnixArgs(p.VMDir, gtCfg.ManagementOutSock, gtCfg.ManagementInSock)
|
||
if argsErr != nil {
|
||
return nil, networkmsg.Localize(argsErr, loc)
|
||
}
|
||
intent.Args = append(intent.Args, plugin.ArgFragment{PluginID: IDGuestTools, Key: "guest-tools-network", Tokens: tokens, Builtin: true, Priority: 79})
|
||
} else {
|
||
s.StopManagementNetwork(p.VMName)
|
||
intent.ClearKeys = append(intent.ClearKeys, "guest-tools-network")
|
||
}
|
||
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) && 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 := qmp.SplitArgs(reims.MergeGuestToolsArgs("", imgPath))
|
||
intent.Args = append(intent.Args, plugin.ArgFragment{
|
||
PluginID: IDGuestTools,
|
||
Key: "reimstools",
|
||
Tokens: tokens,
|
||
Builtin: true,
|
||
Priority: 80,
|
||
})
|
||
} 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
|
||
minFileMB := float64(guesttools.MinClipboardMaxFileMB)
|
||
maxFileMB := float64(guesttools.MaxClipboardMaxFileMB)
|
||
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 copied text, screenshots, and files between Windows and macOS",
|
||
},
|
||
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", "sync_files", "max_file_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",
|
||
},
|
||
"sync_files": {
|
||
Type: "boolean",
|
||
Title: plugin.LocalizedText{ZhCN: "同步剪贴板文件", EnUS: "Sync clipboard files"},
|
||
Default: true,
|
||
Effect: "immediate",
|
||
Scope: "both",
|
||
Group: "collaboration",
|
||
},
|
||
"max_file_mb": {
|
||
Type: "integer",
|
||
Title: plugin.LocalizedText{ZhCN: "文件传输上限 (MB)", EnUS: "File transfer limit (MB)"},
|
||
Description: plugin.LocalizedText{
|
||
ZhCN: "限制从 macOS 粘贴到 Windows 或共享挂载不可用时的单次传输总大小。",
|
||
EnUS: "Limits the total size per paste from macOS to Windows or when the shared mount is unavailable.",
|
||
},
|
||
Default: guesttools.DefaultClipboardPolicy().MaxFileBytes >> 20,
|
||
Minimum: &minFileMB,
|
||
Maximum: &maxFileMB,
|
||
Effect: "immediate",
|
||
Scope: "both",
|
||
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: 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,
|
||
"host_to_guest_files_applied_count": stats.HostToGuestFilesAppliedCount,
|
||
"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: "用 Windows 输入法直接向虚拟机输入文字",
|
||
EnUS: "Type into the VM directly with the Windows IME",
|
||
},
|
||
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 defNpcapBridge(ver string, cb HostCallbacks, desiredFn func(string, bool) bool) plugin.PluginDef {
|
||
return plugin.PluginDef{
|
||
Manifest: plugin.Manifest{
|
||
Schema: 1,
|
||
ID: IDNpcapBridge,
|
||
Version: ver,
|
||
Name: plugin.LocalizedText{ZhCN: "Npcap 网络桥接", EnUS: "Npcap Network Bridge"},
|
||
Description: plugin.LocalizedText{
|
||
ZhCN: "通过 Npcap 为虚拟机提供独立物理出口桥接与运行中切换出口",
|
||
EnUS: "Per-VM physical uplink bridging and live uplink switching via Npcap",
|
||
},
|
||
Publisher: "Reims-Go",
|
||
License: "Apache-2.0",
|
||
Provides: []plugin.ServiceProvision{{Service: ServiceNpcapBridge, Version: "1.0.0"}},
|
||
Permissions: []string{"vm:intent"},
|
||
DefaultEnabled: true,
|
||
},
|
||
Source: plugin.SourceBuiltin,
|
||
Trust: plugin.TrustOfficial,
|
||
Desired: desiredFn(IDNpcapBridge, true),
|
||
Activate: func(ctx context.Context, sc *plugin.Scope) error {
|
||
sc.Provide(ServiceNpcapBridge, "1.0.0", struct{}{})
|
||
sc.OnDispose(func() {
|
||
if cb.StopPacketBridges != nil {
|
||
cb.StopPacketBridges()
|
||
}
|
||
})
|
||
if cb.RestorePacketBridges != nil {
|
||
// 激活请求结束不取消常驻任务;任务生命周期由本插件 scope 管理。
|
||
sc.OnDispose(cb.RestorePacketBridges(context.WithoutCancel(ctx)))
|
||
}
|
||
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
|
||
}
|
||
intent := plugin.StartIntent{PluginID: IDNpcapBridge}
|
||
rec, err := reims.ReadNetworkRecord(p.VMDir)
|
||
if err != nil || rec.Corrupt || rec.Pending {
|
||
return intent, nil
|
||
}
|
||
netEnabled, _ := reims.ReadVMNetworkEnabled(p.VMDir)
|
||
mode := reims.EffectiveNetworkMode(netEnabled, p.ExtraArgs, rec)
|
||
if mode != "bridge" || rec.UplinkGUID == "" {
|
||
intent.ClearKeys = append(intent.ClearKeys, "bridge-network", "npcap-bridge")
|
||
return intent, nil
|
||
}
|
||
mac, err := reims.ReadVMNetworkMAC(p.VMDir)
|
||
if err != nil {
|
||
return nil, err
|
||
}
|
||
tmpDir := ""
|
||
if cb.GetConfig != nil {
|
||
cfg := cb.GetConfig()
|
||
tmpDir = cfg.TempDir()
|
||
}
|
||
sockPath := rec.SocketPath
|
||
if sockPath == "" {
|
||
sockPath = reims.VMUnixSocketPath(p.VMDir, tmpDir, p.VMName, "bridge.sock")
|
||
}
|
||
tokens, err := reims.PacketBridgeUnixTokens(mac, sockPath)
|
||
if err != nil {
|
||
return nil, err
|
||
}
|
||
// 键名按字典序排在 guest-tools-network 之前,确保带固定 addr=0x3 的主网卡先于管理网卡声明,避免被抢占 PCI 3 号槽位。
|
||
intent.ClearKeys = append(intent.ClearKeys, "npcap-bridge")
|
||
intent.Args = append(intent.Args, plugin.ArgFragment{
|
||
PluginID: IDNpcapBridge,
|
||
Key: "bridge-network",
|
||
Tokens: tokens,
|
||
Builtin: true,
|
||
Priority: 78,
|
||
})
|
||
return intent, nil
|
||
},
|
||
})
|
||
return nil
|
||
},
|
||
}
|
||
}
|