Build Guest Tools images in the macOS driver after all start hooks pass, through a host callback rather than a new macOS-to-guesttools dependency. Add driver.OptimizationAdvisor, keep generic hardware evaluation in host, and move WHPX recommendations and tests into macosdriver for both the UI and diagnostics.
1150 lines
31 KiB
Go
1150 lines
31 KiB
Go
package app
|
|
|
|
import (
|
|
"context"
|
|
"errors"
|
|
"fmt"
|
|
"io"
|
|
"math"
|
|
"net/http"
|
|
"os"
|
|
"path/filepath"
|
|
"strings"
|
|
"sync"
|
|
"time"
|
|
|
|
"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"
|
|
vmlifecycle "github.com/Nwflower/reims-go/internal/lifecycle"
|
|
"github.com/Nwflower/reims-go/internal/macos/guest"
|
|
"github.com/Nwflower/reims-go/internal/macos/reims"
|
|
"github.com/Nwflower/reims-go/internal/plugin"
|
|
"github.com/Nwflower/reims-go/internal/plugin/builtin"
|
|
rt "github.com/Nwflower/reims-go/internal/runtime"
|
|
"github.com/Nwflower/reims-go/internal/version"
|
|
"github.com/Nwflower/reims-go/internal/vmstart"
|
|
wailsRuntime "github.com/wailsapp/wails/v2/pkg/runtime"
|
|
)
|
|
|
|
// PluginUIContributions aggregates all active declarative plugin UI contributions
|
|
// for the frontend in a single round-trip (§4.2, §10).
|
|
type PluginUIContributions struct {
|
|
SafeMode bool `json:"safe_mode"`
|
|
CrashDetected bool `json:"crash_detected"`
|
|
Menus []plugin.MenuContribution `json:"menus,omitempty"`
|
|
VMCards []plugin.VMCardContribution `json:"vm_cards,omitempty"`
|
|
SettingsPages []plugin.SettingsPageContribution `json:"settings_pages,omitempty"`
|
|
StatusItems []plugin.StatusItemContribution `json:"status_items,omitempty"`
|
|
Panels []plugin.PanelContribution `json:"panels,omitempty"`
|
|
VMTemplates []plugin.VMTemplateContribution `json:"vm_templates,omitempty"`
|
|
Themes []plugin.ThemeContribution `json:"themes,omitempty"`
|
|
Locales []plugin.ResolvedLocalePack `json:"locales,omitempty"`
|
|
RuntimeSources []plugin.RuntimeSourceContribution `json:"runtime_sources,omitempty"`
|
|
RuntimeKinds []rt.KindSpec `json:"runtime_kinds,omitempty"`
|
|
Drivers []driver.DriverSummary `json:"drivers,omitempty"`
|
|
AssetToken string `json:"asset_token,omitempty"`
|
|
}
|
|
|
|
func (a *App) initPlugins() {
|
|
// Plugins keep their state in the data folder. Before setup there is no
|
|
// chosen folder, and a read-only folder must not be written; the app runs
|
|
// without a plugin manager then (see startup).
|
|
if !a.dataRootUsable() {
|
|
return
|
|
}
|
|
a.mu.Lock()
|
|
dataRoot := a.cfg.DataRoot
|
|
safeMode := a.launch.SafeMode
|
|
a.mu.Unlock()
|
|
|
|
// Idempotent fallback for embedders that construct a Manager directly;
|
|
// normal startup already ran this as data layout v2 in dataroot.Open.
|
|
if err := guest.MigrateFiles(dataRoot); err != nil {
|
|
a.emitLog("plugin", "Could not migrate macOS guest state: "+err.Error())
|
|
return
|
|
}
|
|
mgr, err := plugin.NewManager(plugin.ManagerOptions{
|
|
DataRoot: dataRoot,
|
|
HostVersion: version.Version,
|
|
SafeMode: safeMode,
|
|
RedactFn: reims.RedactText,
|
|
LocaleFn: a.locale,
|
|
Logger: func(source, line string) {
|
|
a.emitLog(source, line)
|
|
},
|
|
SidecarDriverFactory: func(contrib plugin.GuestDriverContribution, sup *plugin.SidecarSupervisor) any {
|
|
return driver.NewSidecarDriver(contrib, sup)
|
|
},
|
|
OnSettingsChanged: func(pluginID, vmName string) {
|
|
a.onPluginSettingsChanged(pluginID, vmName)
|
|
},
|
|
})
|
|
if err != nil {
|
|
a.emitLog("plugin", "Plugin state warning: "+err.Error())
|
|
if mgr == nil {
|
|
return
|
|
}
|
|
}
|
|
|
|
kindReg := rt.NewKindRegistry()
|
|
drvRouter := driver.NewRouterWithDataRoot(mgr.Registry(), func() string {
|
|
a.mu.Lock()
|
|
defer a.mu.Unlock()
|
|
return a.cfg.DataRoot
|
|
})
|
|
|
|
mgr.Registry().SetInUseChecker(func(pluginID string) (bool, string, error) {
|
|
// Must not call Registry.Info/List here: both invoke this checker,
|
|
// which recursed until the goroutine stack overflowed at startup.
|
|
// Check all guest driver IDs declared by this plugin (even when disabled) plus pluginID itself.
|
|
seen := map[string]bool{}
|
|
candidates := append([]string{pluginID}, mgr.Registry().DeclaredDriverIDs(pluginID)...)
|
|
for _, did := range candidates {
|
|
if did == "" || seen[did] {
|
|
continue
|
|
}
|
|
seen[did] = true
|
|
if inUse, reason, err := drvRouter.CheckDriverInUse(context.Background(), did); err != nil || inUse {
|
|
return inUse, reason, err
|
|
}
|
|
}
|
|
return false, "", nil
|
|
})
|
|
|
|
mgr.Broker().SetNotifier(func(pluginID, title, body string) {
|
|
a.emitLog("plugin:"+pluginID, title+": "+body)
|
|
})
|
|
|
|
cb := builtin.HostCallbacks{
|
|
GetConfig: func() config.Config {
|
|
a.mu.Lock()
|
|
cp := *a.cfg
|
|
a.mu.Unlock()
|
|
return cp
|
|
},
|
|
Log: func(source, line string) {
|
|
a.emitLog(source, line)
|
|
},
|
|
EnsureGuestTools: func() (*guesttools.Server, int, error) {
|
|
srv, port, created, err := a.startGuestToolsServer()
|
|
if err == nil && created {
|
|
// A fresh server knows no VM tokens: at startup and when the
|
|
// plugin is switched back on, re-register configured VMs.
|
|
go a.registerVMsWithBridge(context.Background(), srv, port)
|
|
}
|
|
return srv, port, err
|
|
},
|
|
StopGuestTools: func() {
|
|
a.mu.Lock()
|
|
gt := a.guestTools
|
|
a.guestTools = nil
|
|
a.mu.Unlock()
|
|
if gt != nil {
|
|
shutCtx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
|
|
_ = gt.Close(shutCtx)
|
|
cancel()
|
|
}
|
|
},
|
|
ValidateDriveConfig: validatedDriveConfig,
|
|
OnIMEText: func(target host.IMETarget, text string) {
|
|
go a.injectRemoteText(target.VMName, target.VMDir, text)
|
|
},
|
|
StartColdReboot: func(vmName, qmpAddr string) {
|
|
a.watchWin10ColdReboot(vmName, qmpAddr)
|
|
},
|
|
CancelColdReboot: func(vmName string) {
|
|
a.cancelRebootWatcher(vmName)
|
|
},
|
|
VMSharedDir: func(vmName string) string {
|
|
return a.vmSharedDir(vmName)
|
|
},
|
|
GuestToolsImg: func(vmName string) string {
|
|
return a.guestToolsImagePath(vmName)
|
|
},
|
|
BuildGuestToolsImage: a.buildGuestToolsImage,
|
|
OnInstallGuidesChanged: func() {
|
|
if a.ctx != nil {
|
|
wailsRuntime.EventsEmit(a.ctx, "reims:state-changed", true)
|
|
}
|
|
},
|
|
SyncInstallGuides: func() {
|
|
a.wakePoll()
|
|
},
|
|
GetSetting: func(pluginID, vmName, key string) (any, bool) {
|
|
v, ok := mgr.GetSettings(pluginID, vmName, false)[key]
|
|
return v, ok
|
|
},
|
|
}
|
|
|
|
if err := builtin.RegisterAll(mgr.Registry(), cb, mgr.DesiredFor); err != nil {
|
|
a.emitLog("plugin", "Builtin extension register error: "+err.Error())
|
|
}
|
|
if err := guest.Register(mgr.Registry(), cb, mgr.DesiredFor); err != nil {
|
|
a.emitLog("plugin", "macOS guest plugin register error: "+err.Error())
|
|
}
|
|
if err := mgr.LoadExternal(); err != nil {
|
|
a.emitLog("plugin", "External plugin load warning: "+err.Error())
|
|
}
|
|
|
|
// Sync runtime kinds, input filters, clipboard policies, and locales whenever registry state changes.
|
|
mgr.Registry().OnChange(func() {
|
|
a.syncRuntimeKinds(kindReg, mgr.Registry())
|
|
a.syncInputFilters()
|
|
a.syncClipboardPolicies()
|
|
a.syncLocales()
|
|
if a.ctx != nil {
|
|
wailsRuntime.EventsEmit(a.ctx, "reims:state-changed", true)
|
|
}
|
|
})
|
|
|
|
a.mu.Lock()
|
|
a.pluginMgr = mgr
|
|
a.driverRouter = drvRouter
|
|
a.lifecycleSvc = vmlifecycle.New(mgr.Registry(), drvRouter, a.startHookPayload)
|
|
a.runtimeKinds = kindReg
|
|
a.mu.Unlock()
|
|
|
|
mgr.Registry().Reconcile(context.Background())
|
|
mgr.MarkBootComplete()
|
|
a.syncInputFilters()
|
|
a.syncClipboardPolicies()
|
|
a.syncLocales()
|
|
}
|
|
|
|
func (a *App) shutdownPlugins() {
|
|
a.mu.Lock()
|
|
mgr := a.pluginMgr
|
|
a.pluginMgr = nil
|
|
a.pluginMarket = nil
|
|
a.lifecycleSvc = nil
|
|
a.driverRouter = nil
|
|
a.mu.Unlock()
|
|
i18n.SetPluginCatalogs(nil)
|
|
if mgr != nil {
|
|
mgr.Close()
|
|
}
|
|
}
|
|
|
|
func (a *App) getPluginMarket() *plugin.MarketClient {
|
|
a.mu.Lock()
|
|
defer a.mu.Unlock()
|
|
if a.needsSetup {
|
|
// The first-run screen has not chosen a data folder yet (a.cfg holds
|
|
// only the default suggestion), so nothing may be cached or
|
|
// downloaded into it. A throwaway client keeps the index in memory;
|
|
// the first call after setup builds the real one.
|
|
return plugin.NewMarketClient(plugin.MarketClientOptions{HostVersion: version.Version})
|
|
}
|
|
if a.pluginMarket != nil {
|
|
return a.pluginMarket
|
|
}
|
|
dataRoot := ""
|
|
if a.cfg != nil {
|
|
dataRoot = a.cfg.DataRoot
|
|
}
|
|
a.pluginMarket = plugin.NewMarketClient(plugin.MarketClientOptions{
|
|
Layout: plugin.NewPluginsLayout(dataRoot),
|
|
HostVersion: version.Version,
|
|
})
|
|
return a.pluginMarket
|
|
}
|
|
|
|
// reloadPlugins tears down the existing Plugin Manager (if running) and
|
|
// re-initializes plugins and language packs against the current a.cfg.DataRoot.
|
|
func (a *App) reloadPlugins() {
|
|
a.mu.Lock()
|
|
hadPlugins := a.pluginMgr != nil
|
|
hasCtx := a.ctx != nil
|
|
ib := a.imeBridge
|
|
a.imeBridge = nil
|
|
a.mu.Unlock()
|
|
if ib != nil {
|
|
ib.Close()
|
|
}
|
|
if !hadPlugins && !hasCtx {
|
|
// Headless unit test without initialized app runtime: load static locale packs only.
|
|
a.mu.Lock()
|
|
dr := ""
|
|
if a.cfg != nil {
|
|
dr = a.cfg.DataRoot
|
|
}
|
|
a.mu.Unlock()
|
|
plugin.LoadStaticLocalePacks(dr)
|
|
return
|
|
}
|
|
a.shutdownPlugins()
|
|
a.initPlugins()
|
|
}
|
|
|
|
func (a *App) syncLocales() {
|
|
a.mu.Lock()
|
|
mgr := a.pluginMgr
|
|
a.mu.Unlock()
|
|
if mgr == nil {
|
|
i18n.SetPluginCatalogs(nil)
|
|
return
|
|
}
|
|
uiPacks, backendPacks := mgr.ResolvedLocalePacks()
|
|
if len(uiPacks) > 0 {
|
|
if backendPacks == nil {
|
|
backendPacks = make(map[i18n.Locale]i18n.PluginCatalog)
|
|
}
|
|
for _, up := range uiPacks {
|
|
if !up.HasUIMessages {
|
|
continue
|
|
}
|
|
loc := i18n.Locale(up.Locale)
|
|
if _, exists := backendPacks[loc]; !exists {
|
|
backendPacks[loc] = i18n.PluginCatalog{
|
|
Fallback: i18n.Locale(up.Fallback),
|
|
}
|
|
}
|
|
}
|
|
}
|
|
i18n.SetPluginCatalogs(backendPacks)
|
|
go mgr.NotifyLocaleChanged(mgr.CurrentLocale())
|
|
}
|
|
|
|
func (a *App) syncRuntimeKinds(kr *rt.KindRegistry, reg *plugin.Registry) {
|
|
if kr == nil || reg == nil {
|
|
return
|
|
}
|
|
activeKinds := map[string]bool{rt.DefaultKind: true}
|
|
for _, rk := range reg.RuntimeKinds() {
|
|
activeKinds[rk.Kind] = true
|
|
_ = kr.Register(rt.KindSpec{
|
|
Kind: rk.Kind,
|
|
Name: rk.Name,
|
|
NameZh: rk.Name.ZhCN,
|
|
NameEn: rk.Name.EnUS,
|
|
RequiredFiles: rk.RequiredFiles,
|
|
DefaultAPIVersion: rk.DefaultAPIVer,
|
|
PluginID: rk.PluginID,
|
|
})
|
|
}
|
|
for _, existing := range kr.List() {
|
|
if !existing.Builtin && !activeKinds[existing.Kind] {
|
|
kr.Unregister(existing.Kind, "")
|
|
}
|
|
}
|
|
}
|
|
|
|
func (a *App) getInputService() *host.InputService {
|
|
a.mu.Lock()
|
|
mgr := a.pluginMgr
|
|
a.mu.Unlock()
|
|
if mgr == nil {
|
|
return nil
|
|
}
|
|
raw, ok := mgr.Registry().LookupService(builtin.ServiceHostInput)
|
|
if !ok {
|
|
return nil
|
|
}
|
|
svc, _ := raw.(*host.InputService)
|
|
return svc
|
|
}
|
|
|
|
func (a *App) syncInputTargets(targets []host.IMETarget) {
|
|
if svc := a.getInputService(); svc != nil {
|
|
svc.SetTargets(targets)
|
|
}
|
|
}
|
|
|
|
func (a *App) syncInputFilters() {
|
|
a.mu.Lock()
|
|
mgr := a.pluginMgr
|
|
a.mu.Unlock()
|
|
if mgr == nil {
|
|
return
|
|
}
|
|
svc := a.getInputService()
|
|
if svc == nil {
|
|
return
|
|
}
|
|
contribs := mgr.Registry().InputFilters()
|
|
var rules []host.InputFilterRule
|
|
for _, flt := range contribs {
|
|
if flt.Event != "mouse_wheel" {
|
|
continue
|
|
}
|
|
settingKey := flt.SettingKey
|
|
if settingKey == "" {
|
|
settingKey = "enabled"
|
|
}
|
|
vmNames := mgr.ActiveVMNamesWithSetting(flt.PluginID, settingKey)
|
|
if len(vmNames) == 0 {
|
|
continue
|
|
}
|
|
for _, vmKey := range vmNames {
|
|
ref, ok := driver.ParseVMRef(vmKey)
|
|
if !ok {
|
|
ref = driver.NewVMRef("", vmKey)
|
|
}
|
|
vmName := ref.Name
|
|
vals := mgr.GetSettings(flt.PluginID, vmKey, false)
|
|
vert := true
|
|
if flt.VertKey != "" {
|
|
if v, ok := vals[flt.VertKey].(bool); ok {
|
|
vert = v
|
|
}
|
|
}
|
|
horiz := false
|
|
if flt.HorizKey != "" {
|
|
if h, ok := vals[flt.HorizKey].(bool); ok {
|
|
horiz = h
|
|
}
|
|
}
|
|
if !vert && !horiz {
|
|
continue
|
|
}
|
|
axis := flt.Axis
|
|
if flt.VertKey != "" || flt.HorizKey != "" {
|
|
// Explicit per-axis booleans govern; clear Axis so vertical=false is respected.
|
|
axis = ""
|
|
}
|
|
rules = append(rules, host.InputFilterRule{
|
|
ID: flt.ID + ":" + ref.Key(),
|
|
PluginID: flt.PluginID,
|
|
Event: flt.Event,
|
|
Axis: axis,
|
|
Transform: flt.Transform,
|
|
Scope: flt.Scope,
|
|
VMNames: map[string]bool{vmName: true},
|
|
Vertical: vert,
|
|
Horizontal: horiz,
|
|
})
|
|
}
|
|
}
|
|
svc.SetFilterRules(rules)
|
|
}
|
|
|
|
func (a *App) syncClipboardPolicies() {
|
|
a.mu.Lock()
|
|
mgr := a.pluginMgr
|
|
gt := a.guestTools
|
|
a.mu.Unlock()
|
|
if mgr == nil || gt == nil {
|
|
return
|
|
}
|
|
if !mgr.Registry().IsActive(builtin.IDClipboard) {
|
|
return
|
|
}
|
|
globalVals := mgr.GetSettings(builtin.IDClipboard, "", false)
|
|
gt.SetGlobalClipboardPolicy(clipboardPolicyFromMap(globalVals))
|
|
for vmKey, vmVals := range mgr.SavedVMSettingsForPlugin(builtin.IDClipboard) {
|
|
ref, ok := driver.ParseVMRef(vmKey)
|
|
if !ok {
|
|
ref = driver.NewVMRef("", vmKey)
|
|
}
|
|
pol := clipboardPolicyFromMap(vmVals)
|
|
gt.SetVMClipboardPolicy(ref.Key(), &pol)
|
|
}
|
|
}
|
|
|
|
func (a *App) onPluginSettingsChanged(pluginID, vmName string) {
|
|
a.syncInputFilters()
|
|
if pluginID == builtin.IDClipboard {
|
|
a.mu.Lock()
|
|
mgr := a.pluginMgr
|
|
gt := a.guestTools
|
|
a.mu.Unlock()
|
|
if mgr != nil && gt != nil {
|
|
vals := mgr.GetSettings(builtin.IDClipboard, vmName, false)
|
|
pol := clipboardPolicyFromMap(vals)
|
|
if vmName == "" {
|
|
gt.SetGlobalClipboardPolicy(pol)
|
|
} else {
|
|
ref, ok := driver.ParseVMRef(vmName)
|
|
if !ok {
|
|
ref = driver.NewVMRef("", vmName)
|
|
}
|
|
gt.SetVMClipboardPolicy(ref.Key(), &pol)
|
|
}
|
|
}
|
|
}
|
|
if pluginID == guest.ID && vmName == "" {
|
|
a.mu.Lock()
|
|
mgr := a.pluginMgr
|
|
a.mu.Unlock()
|
|
if mgr != nil {
|
|
wantGuide := guest.SettingOn(mgr.GetSettings(guest.ID, "", false), guest.SettingInstallGuide)
|
|
if wantGuide != a.installGuideEnabled() {
|
|
a.reloadPlugins()
|
|
}
|
|
}
|
|
}
|
|
if a.ctx != nil {
|
|
wailsRuntime.EventsEmit(a.ctx, "reims:state-changed", true)
|
|
}
|
|
}
|
|
|
|
func clipboardPolicyFromMap(vals map[string]any) guesttools.ClipboardPolicy {
|
|
p := guesttools.DefaultClipboardPolicy()
|
|
if v, ok := vals["enabled"].(bool); ok {
|
|
p.Enabled = v
|
|
}
|
|
if v, ok := vals["direction"].(string); ok && v != "" {
|
|
p.Direction = guesttools.ClipboardDirection(v)
|
|
}
|
|
if v, ok := vals["sync_images"].(bool); ok {
|
|
p.SyncImages = v
|
|
}
|
|
switch v := vals["max_image_mb"].(type) {
|
|
case float64:
|
|
if v > 0 && !math.IsNaN(v) && !math.IsInf(v, 0) {
|
|
mb := int(math.Round(v))
|
|
if mb < 1 {
|
|
mb = 1
|
|
}
|
|
if mb > 16 {
|
|
mb = 16
|
|
}
|
|
p.MaxImageBytes = mb << 20
|
|
}
|
|
case int:
|
|
if v > 0 {
|
|
if v > 16 {
|
|
v = 16
|
|
}
|
|
p.MaxImageBytes = v << 20
|
|
}
|
|
}
|
|
return p
|
|
}
|
|
|
|
// PluginAssetHandler returns the HTTP handler mounted on Wails AssetServer for
|
|
// `/plugin-assets/<runToken>/<pluginID>/<relPath>` (§7.3).
|
|
func (a *App) PluginAssetHandler() http.Handler {
|
|
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
|
if !strings.HasPrefix(r.URL.Path, "/plugin-assets/") {
|
|
http.NotFound(w, r)
|
|
return
|
|
}
|
|
a.mu.Lock()
|
|
mgr := a.pluginMgr
|
|
a.mu.Unlock()
|
|
if mgr == nil || mgr.Assets() == nil {
|
|
http.NotFound(w, r)
|
|
return
|
|
}
|
|
mgr.Assets().ServeHTTP(w, r)
|
|
})
|
|
}
|
|
|
|
func (a *App) emitPluginLogLine(vmName, source, line string) {
|
|
a.mu.Lock()
|
|
mgr := a.pluginMgr
|
|
a.mu.Unlock()
|
|
if mgr != nil {
|
|
mgr.Registry().Hooks().EmitLogLine(vmName, source, line)
|
|
}
|
|
}
|
|
|
|
func (a *App) collectPluginDiagnostics(ctx context.Context, vmName string) []plugin.DiagnosticsEntry {
|
|
a.mu.Lock()
|
|
mgr := a.pluginMgr
|
|
a.mu.Unlock()
|
|
if mgr == nil {
|
|
return nil
|
|
}
|
|
return mgr.Registry().CollectDiagnostics(ctx, vmName, reims.RedactText)
|
|
}
|
|
|
|
func buildHostFacts(rep host.Report, rtCaps []string) map[string]any {
|
|
gpuKind := "unknown"
|
|
if rep.RecommendedGPU != nil {
|
|
gpuKind = string(rep.RecommendedGPU.Kind)
|
|
}
|
|
return map[string]any{
|
|
"host.os": rep.OS,
|
|
"host.arch": rep.Arch,
|
|
"host.whpx": string(rep.WHPX),
|
|
"host.whpx_irqchip": rep.WHPXCaps.KernelIrqchipAvailable,
|
|
"host.whpx_nested_virt": rep.WHPXCaps.NestedVirtProperty,
|
|
"host.needs_cold_reboot": rep.NeedsColdRebootWorkaround,
|
|
"host.gpu_kind": gpuKind,
|
|
"runtime.capabilities": rtCaps,
|
|
}
|
|
}
|
|
|
|
// --- Wails-bound Plugin & Driver APIs (§10) ---
|
|
|
|
func (a *App) ListPlugins() []plugin.PluginInfo {
|
|
a.mu.Lock()
|
|
mgr := a.pluginMgr
|
|
a.mu.Unlock()
|
|
if mgr == nil {
|
|
return nil
|
|
}
|
|
return mgr.LocalizePluginInfos(mgr.Registry().List())
|
|
}
|
|
|
|
func (a *App) InstallPluginArchive(archivePath string) (*plugin.PluginInfo, error) {
|
|
a.mu.Lock()
|
|
mgr := a.pluginMgr
|
|
a.mu.Unlock()
|
|
if mgr == nil {
|
|
return nil, errors.New("plugin manager not initialized")
|
|
}
|
|
info, err := mgr.InstallLocalArchive(context.Background(), archivePath, plugin.PackageInstallOptions{})
|
|
if err == nil && a.ctx != nil {
|
|
wailsRuntime.EventsEmit(a.ctx, "reims:state-changed", true)
|
|
}
|
|
return info, err
|
|
}
|
|
|
|
func (a *App) LinkPluginDev(dir string) (*plugin.PluginInfo, error) {
|
|
a.mu.Lock()
|
|
mgr := a.pluginMgr
|
|
a.mu.Unlock()
|
|
if mgr == nil {
|
|
return nil, errors.New("plugin manager not initialized")
|
|
}
|
|
info, err := mgr.LinkDev(context.Background(), dir)
|
|
if err == nil && a.ctx != nil {
|
|
wailsRuntime.EventsEmit(a.ctx, "reims:state-changed", true)
|
|
}
|
|
return info, err
|
|
}
|
|
|
|
func (a *App) EnablePlugin(id string, approveHighRisk bool) error {
|
|
a.mu.Lock()
|
|
mgr := a.pluginMgr
|
|
a.mu.Unlock()
|
|
if mgr == nil {
|
|
return errors.New("plugin manager not initialized")
|
|
}
|
|
return mgr.Enable(context.Background(), id, approveHighRisk)
|
|
}
|
|
|
|
func (a *App) DisablePlugin(id string) error {
|
|
a.mu.Lock()
|
|
mgr := a.pluginMgr
|
|
a.mu.Unlock()
|
|
if mgr == nil {
|
|
return errors.New("plugin manager not initialized")
|
|
}
|
|
return mgr.Disable(context.Background(), id)
|
|
}
|
|
|
|
func (a *App) RemovePlugin(id string, purgeData bool) error {
|
|
a.mu.Lock()
|
|
mgr := a.pluginMgr
|
|
a.mu.Unlock()
|
|
if mgr == nil {
|
|
return errors.New("plugin manager not initialized")
|
|
}
|
|
return mgr.Remove(context.Background(), id, purgeData)
|
|
}
|
|
|
|
func (a *App) GetPluginSettings(pluginID, vmKey string) map[string]any {
|
|
a.mu.Lock()
|
|
mgr := a.pluginMgr
|
|
a.mu.Unlock()
|
|
if mgr == nil {
|
|
return map[string]any{}
|
|
}
|
|
return mgr.GetSettings(pluginID, vmKey, true)
|
|
}
|
|
|
|
func (a *App) SetPluginSettings(pluginID, vmKey string, values map[string]any) error {
|
|
a.mu.Lock()
|
|
mgr := a.pluginMgr
|
|
a.mu.Unlock()
|
|
if mgr == nil {
|
|
return errors.New("plugin manager not initialized")
|
|
}
|
|
return mgr.SetSettings(pluginID, vmKey, values)
|
|
}
|
|
|
|
func (a *App) GetVMPluginSettings(vmKey string) map[string]map[string]any {
|
|
a.mu.Lock()
|
|
mgr := a.pluginMgr
|
|
a.mu.Unlock()
|
|
if mgr == nil {
|
|
return map[string]map[string]any{}
|
|
}
|
|
return mgr.GetAllVMSettings(vmKey)
|
|
}
|
|
|
|
func (a *App) GetPluginUIContributions() PluginUIContributions {
|
|
a.mu.Lock()
|
|
mgr := a.pluginMgr
|
|
kr := a.runtimeKinds
|
|
dr := a.driverRouter
|
|
a.mu.Unlock()
|
|
if mgr == nil {
|
|
return PluginUIContributions{}
|
|
}
|
|
reg := mgr.Registry()
|
|
uiLocales, _ := mgr.ResolvedLocalePacks()
|
|
out := PluginUIContributions{
|
|
SafeMode: mgr.SafeMode(),
|
|
CrashDetected: mgr.CrashDetected(),
|
|
Menus: mgr.LocalizeMenus(reg.Menus("")),
|
|
VMCards: mgr.LocalizeVMCards(reg.VMCards()),
|
|
SettingsPages: mgr.LocalizeSettingsPages(reg.SettingsPages()),
|
|
StatusItems: mgr.LocalizeStatusItems(reg.StatusItems()),
|
|
Panels: mgr.LocalizePanels(reg.Panels("")),
|
|
VMTemplates: reg.VMTemplates(),
|
|
Themes: reg.Themes(),
|
|
Locales: uiLocales,
|
|
RuntimeSources: reg.RuntimeSources(),
|
|
AssetToken: mgr.Assets().Token(),
|
|
}
|
|
if kr != nil {
|
|
out.RuntimeKinds = kr.List()
|
|
}
|
|
if dr != nil {
|
|
out.Drivers = dr.Summaries()
|
|
}
|
|
return out
|
|
}
|
|
|
|
func (a *App) InvokePluginCommand(pluginID, commandID string, args map[string]any) (any, error) {
|
|
a.mu.Lock()
|
|
mgr := a.pluginMgr
|
|
a.mu.Unlock()
|
|
if mgr == nil {
|
|
return nil, errors.New("plugin manager not initialized")
|
|
}
|
|
return mgr.Registry().InvokeCommand(context.Background(), pluginID, commandID, args)
|
|
}
|
|
|
|
func (a *App) GetActiveTheme() plugin.ActiveThemePayload {
|
|
a.mu.Lock()
|
|
mgr := a.pluginMgr
|
|
a.mu.Unlock()
|
|
if mgr == nil {
|
|
return plugin.ActiveThemePayload{ThemeID: builtin.IDThemeDefault}
|
|
}
|
|
return mgr.ActiveThemePayload()
|
|
}
|
|
|
|
func (a *App) SetActiveTheme(themeID, schemeID string) error {
|
|
a.mu.Lock()
|
|
mgr := a.pluginMgr
|
|
a.mu.Unlock()
|
|
if mgr == nil {
|
|
return errors.New("plugin manager not initialized")
|
|
}
|
|
err := mgr.SetActiveTheme(themeID, schemeID)
|
|
if err == nil && a.ctx != nil {
|
|
wailsRuntime.EventsEmit(a.ctx, "reims:state-changed", true)
|
|
}
|
|
return err
|
|
}
|
|
|
|
func (a *App) SaveCustomThemeScheme(scheme plugin.CustomThemeScheme) error {
|
|
a.mu.Lock()
|
|
mgr := a.pluginMgr
|
|
a.mu.Unlock()
|
|
if mgr == nil {
|
|
return errors.New("plugin manager not initialized")
|
|
}
|
|
return mgr.SaveCustomThemeScheme(scheme)
|
|
}
|
|
|
|
func (a *App) DeleteCustomThemeScheme(schemeID string) error {
|
|
a.mu.Lock()
|
|
mgr := a.pluginMgr
|
|
a.mu.Unlock()
|
|
if mgr == nil {
|
|
return errors.New("plugin manager not initialized")
|
|
}
|
|
return mgr.DeleteCustomThemeScheme(schemeID)
|
|
}
|
|
|
|
func (a *App) ListDrivers() []driver.DriverSummary {
|
|
a.mu.Lock()
|
|
dr := a.driverRouter
|
|
a.mu.Unlock()
|
|
if dr == nil {
|
|
return nil
|
|
}
|
|
return dr.Summaries()
|
|
}
|
|
|
|
func (a *App) ListRuntimeKinds() []rt.KindSpec {
|
|
a.mu.Lock()
|
|
kr := a.runtimeKinds
|
|
a.mu.Unlock()
|
|
if kr == nil {
|
|
return rt.NewKindRegistry().List()
|
|
}
|
|
return kr.List()
|
|
}
|
|
|
|
func (a *App) CreateVMWithDriver(req driver.CreateRequest) error {
|
|
if err := a.requireWritableDataRoot(); err != nil {
|
|
return err
|
|
}
|
|
a.mu.Lock()
|
|
dr := a.driverRouter
|
|
mgr := a.pluginMgr
|
|
a.mu.Unlock()
|
|
if dr == nil {
|
|
return errors.New("driver router not initialized")
|
|
}
|
|
drv, err := dr.DriverByID(req.DriverID)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
ctx := context.Background()
|
|
if mgr != nil {
|
|
res := mgr.Registry().Hooks().DispatchBeforeCreate(ctx, plugin.BeforeCreatePayload{
|
|
VMName: req.Name,
|
|
DriverID: drv.ID(),
|
|
Options: req.Options,
|
|
})
|
|
if len(res.Errors) > 0 {
|
|
return errors.New(res.Errors[0])
|
|
}
|
|
if len(res.Patches) > 0 {
|
|
if req.Options == nil {
|
|
req.Options = map[string]any{}
|
|
}
|
|
for k, v := range res.Patches {
|
|
if _, exists := req.Options[k]; !exists {
|
|
req.Options[k] = v
|
|
}
|
|
}
|
|
}
|
|
}
|
|
if issues := drv.ValidateCreate(ctx, req); len(issues) > 0 {
|
|
return errors.New(issues[0].Message)
|
|
}
|
|
w := vmstart.LineWriter(func(line string) { a.emitLog(req.Name, line) })
|
|
if err := drv.Create(ctx, req, w, w); err != nil {
|
|
return err
|
|
}
|
|
if mgr != nil {
|
|
mgr.Registry().Hooks().DispatchObserve(plugin.EventVMAfterCreate, plugin.VMEventPayload{
|
|
VMName: req.Name,
|
|
DriverID: drv.ID(),
|
|
})
|
|
}
|
|
a.wakePoll()
|
|
if a.ctx != nil {
|
|
wailsRuntime.EventsEmit(a.ctx, "reims:state-changed", true)
|
|
}
|
|
return nil
|
|
}
|
|
|
|
func (a *App) ReadPluginLog(pluginID string) (string, error) {
|
|
a.mu.Lock()
|
|
mgr := a.pluginMgr
|
|
a.mu.Unlock()
|
|
if mgr == nil {
|
|
return "", nil
|
|
}
|
|
if pluginID == "" || strings.ContainsAny(pluginID, `/\`) || strings.Contains(pluginID, "..") {
|
|
return "", errors.New("invalid plugin id")
|
|
}
|
|
if _, ok := mgr.Registry().Info(pluginID); !ok {
|
|
return "", fmt.Errorf("plugin %q not found", pluginID)
|
|
}
|
|
logsDir := filepath.Clean(mgr.Layout().LogsDir())
|
|
logPath := filepath.Clean(mgr.Layout().LogPath(pluginID))
|
|
if !strings.HasPrefix(strings.ToLower(logPath), strings.ToLower(logsDir+string(os.PathSeparator))) {
|
|
return "", errors.New("invalid plugin log path")
|
|
}
|
|
f, err := os.Open(logPath)
|
|
if err != nil {
|
|
if errors.Is(err, os.ErrNotExist) {
|
|
return "", nil
|
|
}
|
|
return "", err
|
|
}
|
|
defer f.Close()
|
|
const maxLogReadBytes = 2 << 20
|
|
if st, statErr := f.Stat(); statErr == nil && st.Size() > maxLogReadBytes {
|
|
_, _ = f.Seek(st.Size()-maxLogReadBytes, io.SeekStart)
|
|
}
|
|
raw, err := io.ReadAll(io.LimitReader(f, maxLogReadBytes))
|
|
if err != nil {
|
|
return "", err
|
|
}
|
|
return reims.RedactText(string(raw)), nil
|
|
}
|
|
|
|
func (a *App) DoctorPlugin(pluginID string) []plugin.DoctorFinding {
|
|
a.mu.Lock()
|
|
mgr := a.pluginMgr
|
|
a.mu.Unlock()
|
|
if mgr == nil {
|
|
return nil
|
|
}
|
|
info, ok := mgr.Registry().Info(pluginID)
|
|
if !ok {
|
|
return []plugin.DoctorFinding{{
|
|
Severity: "error",
|
|
Check: "lookup",
|
|
Message: fmt.Sprintf("plugin %q not found", pluginID),
|
|
}}
|
|
}
|
|
if info.InstallDir == "" {
|
|
return []plugin.DoctorFinding{{
|
|
Severity: "ok",
|
|
Check: "builtin",
|
|
Message: fmt.Sprintf("%s@%s (%s)", info.ID, info.Version, info.State),
|
|
}}
|
|
}
|
|
return plugin.DoctorDirectory(info.InstallDir, version.Version, nil)
|
|
}
|
|
|
|
// InspectPluginArchive runs the unified static security scanner on a local .zip
|
|
// package before installing it so the UI can display hard blockers, capabilities,
|
|
// and L3 native execution notices.
|
|
func (a *App) InspectPluginArchive(archivePath string) (plugin.ScanReport, error) {
|
|
a.mu.Lock()
|
|
mgr := a.pluginMgr
|
|
dataRoot := ""
|
|
if a.cfg != nil {
|
|
dataRoot = a.cfg.DataRoot
|
|
}
|
|
a.mu.Unlock()
|
|
tmpDir := plugin.NewPluginsLayout(dataRoot).TmpDir()
|
|
if mgr != nil {
|
|
tmpDir = mgr.Layout().TmpDir()
|
|
}
|
|
return plugin.ScanArchive(archivePath, tmpDir, version.Version, plugin.ScanOptions{
|
|
Keyring: plugin.DefaultKeyring(),
|
|
})
|
|
}
|
|
|
|
// ScanInstalledPlugin runs the unified static risk report against an installed
|
|
// or dev-linked plugin directory.
|
|
func (a *App) ScanInstalledPlugin(pluginID string) (plugin.ScanReport, error) {
|
|
a.mu.Lock()
|
|
mgr := a.pluginMgr
|
|
a.mu.Unlock()
|
|
if mgr == nil {
|
|
return plugin.ScanReport{}, errors.New("plugin manager not initialized")
|
|
}
|
|
info, ok := mgr.Registry().Info(pluginID)
|
|
if !ok {
|
|
return plugin.ScanReport{}, fmt.Errorf("plugin %q not found", pluginID)
|
|
}
|
|
if info.InstallDir == "" {
|
|
return plugin.ScanReport{
|
|
PluginID: info.ID,
|
|
Version: info.Version,
|
|
Name: info.Name,
|
|
Tier: info.Tier,
|
|
Trust: info.Trust,
|
|
Publisher: info.Publisher,
|
|
License: info.License,
|
|
Passed: true,
|
|
Headline: plugin.LocalizedText{
|
|
ZhCN: "内置插件状态正常",
|
|
EnUS: "Built-in plugin is healthy",
|
|
},
|
|
}, nil
|
|
}
|
|
rep := plugin.ScanDirectory(info.InstallDir, version.Version, plugin.ScanOptions{
|
|
Keyring: plugin.DefaultKeyring(),
|
|
})
|
|
if info.Trust == plugin.TrustDev {
|
|
rep.Trust = plugin.TrustDev
|
|
}
|
|
return rep, nil
|
|
}
|
|
|
|
// BrowsePluginMarket lazily queries the remote/cached/fallback plugin market
|
|
// index (never called at app startup, §8.1, §9).
|
|
func (a *App) BrowsePluginMarket(query, kind string, includeAlpha, forceRefresh bool) plugin.MarketBrowseResult {
|
|
a.mu.Lock()
|
|
mgr := a.pluginMgr
|
|
a.mu.Unlock()
|
|
var installed []plugin.PluginInfo
|
|
if mgr != nil {
|
|
installed = mgr.Registry().List()
|
|
}
|
|
return a.getPluginMarket().Browse(context.Background(), installed, plugin.MarketBrowseOptions{
|
|
Query: query,
|
|
Kind: kind,
|
|
IncludeAlpha: includeAlpha,
|
|
ForceRefresh: forceRefresh,
|
|
})
|
|
}
|
|
|
|
// PeekPluginMarket returns the market from memory, disk cache or the embedded
|
|
// fallback with no network I/O, so the page can paint before
|
|
// BrowsePluginMarket revalidates.
|
|
func (a *App) PeekPluginMarket(query, kind string) plugin.MarketBrowseResult {
|
|
a.mu.Lock()
|
|
mgr := a.pluginMgr
|
|
a.mu.Unlock()
|
|
var installed []plugin.PluginInfo
|
|
if mgr != nil {
|
|
installed = mgr.Registry().List()
|
|
}
|
|
return a.getPluginMarket().Peek(installed, plugin.MarketBrowseOptions{Query: query, Kind: kind})
|
|
}
|
|
|
|
// SuggestLanguagePack looks up the market once for a language pack matching
|
|
// the OS language, for the first-run screen to offer. It is the one market
|
|
// request made without the user opening the market (§8.1), and returns nil
|
|
// when a built-in language already covers the OS language, the market is
|
|
// unreachable or turned off, or nothing matches.
|
|
func (a *App) SuggestLanguagePack() *plugin.MarketCatalogItem {
|
|
tag := i18n.DetectOSLocaleTag()
|
|
if builtinCoversLocale(string(tag)) {
|
|
return nil
|
|
}
|
|
a.mu.Lock()
|
|
mgr := a.pluginMgr
|
|
a.mu.Unlock()
|
|
var installed []plugin.PluginInfo
|
|
if mgr != nil {
|
|
installed = mgr.Registry().List()
|
|
}
|
|
ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second)
|
|
defer cancel()
|
|
return a.getPluginMarket().SuggestLocalePack(ctx, installed, string(tag))
|
|
}
|
|
|
|
// builtinCoversLocale reports whether the built-in zh-CN or en-US catalogs
|
|
// already serve tag well enough that a language pack adds nothing.
|
|
func builtinCoversLocale(tag string) bool {
|
|
s := strings.ToLower(strings.TrimSpace(tag))
|
|
if s == "" || s == "en" || strings.HasPrefix(s, "en-") {
|
|
return true
|
|
}
|
|
switch s {
|
|
case "zh", "zh-cn", "zh-sg", "zh-hans", "zh-hans-cn", "zh-hans-sg":
|
|
return true
|
|
}
|
|
return false
|
|
}
|
|
|
|
// MarketInstallProgress is emitted as "reims:plugin-install" while
|
|
// InstallMarketPlugin runs. Total is 0 when the size is unknown.
|
|
type MarketInstallProgress struct {
|
|
ID string `json:"id"`
|
|
Phase string `json:"phase"` // "download" | "install"
|
|
Done int64 `json:"done"`
|
|
Total int64 `json:"total"`
|
|
}
|
|
|
|
// InstallMarketPlugin downloads, verifies SHA-256, static-scans, and installs
|
|
// a plugin from the market index.
|
|
func (a *App) InstallMarketPlugin(pluginID string, includeAlpha bool) (*plugin.PluginInfo, error) {
|
|
a.mu.Lock()
|
|
mgr := a.pluginMgr
|
|
a.mu.Unlock()
|
|
if mgr == nil {
|
|
return nil, errors.New("plugin manager not initialized")
|
|
}
|
|
var (
|
|
progMu sync.Mutex
|
|
phase = plugin.MarketPhaseDownload
|
|
lastEmit time.Time
|
|
)
|
|
emit := func(p MarketInstallProgress) {
|
|
if a.ctx != nil {
|
|
wailsRuntime.EventsEmit(a.ctx, "reims:plugin-install", p)
|
|
}
|
|
}
|
|
info, err := a.getPluginMarket().InstallFromMarket(context.Background(), mgr, pluginID, plugin.MarketInstallOptions{
|
|
IncludeAlpha: includeAlpha,
|
|
OnPhase: func(ph string) {
|
|
progMu.Lock()
|
|
phase = ph
|
|
progMu.Unlock()
|
|
emit(MarketInstallProgress{ID: pluginID, Phase: ph})
|
|
},
|
|
OnProgress: func(done, total int64) {
|
|
progMu.Lock()
|
|
// ~12 updates a second is smooth enough; always send the last one.
|
|
now := time.Now()
|
|
if now.Sub(lastEmit) < 80*time.Millisecond && (total <= 0 || done < total) {
|
|
progMu.Unlock()
|
|
return
|
|
}
|
|
lastEmit = now
|
|
ph := phase
|
|
progMu.Unlock()
|
|
emit(MarketInstallProgress{ID: pluginID, Phase: ph, Done: done, Total: total})
|
|
},
|
|
})
|
|
if err == nil && a.ctx != nil {
|
|
wailsRuntime.EventsEmit(a.ctx, "reims:state-changed", true)
|
|
}
|
|
return info, err
|
|
}
|
|
|
|
// PanelBridgeCall handles permission-checked, rate-limited, redacted Host API
|
|
// reads from sandboxed L4 iframe panels (§7.3).
|
|
func (a *App) PanelBridgeCall(pluginID, method string, params map[string]any) (any, error) {
|
|
a.mu.Lock()
|
|
mgr := a.pluginMgr
|
|
a.mu.Unlock()
|
|
if mgr == nil {
|
|
return nil, errors.New("plugin manager not initialized")
|
|
}
|
|
hasPanel := false
|
|
for _, p := range mgr.Registry().Panels("") {
|
|
if p.PluginID == pluginID {
|
|
hasPanel = true
|
|
break
|
|
}
|
|
}
|
|
if !hasPanel {
|
|
return nil, fmt.Errorf("plugin %q has no active panel", pluginID)
|
|
}
|
|
switch method {
|
|
case "i18n.getBundle":
|
|
if err := mgr.Broker().AllowRate(pluginID); err != nil {
|
|
return nil, err
|
|
}
|
|
eff := mgr.CurrentLocale()
|
|
msgs := mgr.PluginL10nBundle(pluginID, eff)
|
|
if msgs == nil {
|
|
msgs = map[string]string{}
|
|
}
|
|
return map[string]any{
|
|
"locale": string(eff),
|
|
"dir": i18n.DirOf(eff),
|
|
"messages": msgs,
|
|
}, nil
|
|
case "vm.list":
|
|
if err := mgr.Broker().Authorize(pluginID, "vm:read"); err != nil {
|
|
return nil, err
|
|
}
|
|
vms, err := a.polledVMs(context.Background())
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
out := make([]map[string]any, 0, len(vms))
|
|
for _, v := range vms {
|
|
out = append(out, map[string]any{
|
|
"name": v.Name,
|
|
"state": v.State,
|
|
})
|
|
}
|
|
return out, nil
|
|
case "notify":
|
|
title, _ := params["title"].(string)
|
|
body, _ := params["body"].(string)
|
|
if err := mgr.Broker().Notify(pluginID, title, body); err != nil {
|
|
return nil, err
|
|
}
|
|
return map[string]any{"ok": true}, nil
|
|
case "command.invoke":
|
|
if err := mgr.Broker().Authorize(pluginID, "ui:slot"); err != nil {
|
|
return nil, err
|
|
}
|
|
cmdID, _ := params["command"].(string)
|
|
cmdArgs, _ := params["args"].(map[string]any)
|
|
mgr.Broker().Audit(pluginID, "PANEL_CMD", cmdID)
|
|
return mgr.Registry().InvokeCommand(context.Background(), pluginID, cmdID, cmdArgs)
|
|
default:
|
|
return nil, fmt.Errorf("panel bridge method %q is not allowed", method)
|
|
}
|
|
}
|