Files
Reims-Go/internal/plugin/builtin/builtin.go
T
Nwflower 181c616909 feat(plugin,ui): consolidate builtin.core, enforce Guest Tools toggle, and add QQ group entry
- Merge essential builtins (driver, default theme, start prep, host workarounds) into always-on system plugin builtin.core, with state.json and arg-ledger migration plus app-scoped workaround settings honored by both GUI and CLI.
- Ensure disabling builtin.bridge.guest-tools stops the localhost bridge without being restarted by feature callers, fix guesttools.Server Start/Close race, and reflect the disabled state in VMPage and SettingsModal.
- Add QQ community group entry in About settings with Windows tencent:// protocol detection, cached invite redirect resolution, and copy-ID fallback.
- Update docs/plugin-architecture.md, Wails bindings, and i18n strings.
2026-11-29 09:54:51 -07:00

341 lines
12 KiB
Go
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
// Package builtin registers compiled-in Reims-Go extensions onto the unified
// plugin Registry (docs/plugin-architecture.md §3.2, §5.4). 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/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/plugin"
"github.com/Nwflower/reims-go/internal/version"
)
// Builtin plugin IDs (§3.2, §5.4). 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; the core plugin registers it.
IDDriverReimsMacOS = driver.BuiltinReimsMacOSDriverID
IDGuestTools = "builtin.bridge.guest-tools"
IDClipboard = "builtin.bridge.clipboard"
IDInput = "builtin.input"
)
// 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 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, cb),
defGuestTools(ver, cb, desiredFn),
defClipboard(ver, cb, desiredFn),
defInput(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 {
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 copied text and screenshots 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"},
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: "用 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
},
}
}