package plugin import ( "encoding/json" "maps" "os" "path/filepath" "slices" "sort" "strings" "github.com/Nwflower/reims-go/internal/i18n" ) // ResolvedLocalePacks loads and merges all active plugin locale contributions // and per-plugin l10n bundles into frontend UI packs and backend/CLI catalogs. // Returns nil in safe mode. func (m *Manager) ResolvedLocalePacks() ([]ResolvedLocalePack, map[i18n.Locale]i18n.PluginCatalog) { if m.safeMode { return nil, nil } contribs := m.registry.Locales() m.mu.RLock() dirs := maps.Clone(m.installDirs) m.mu.RUnlock() type mergedPack struct { pack ResolvedLocalePack seenPID map[string]bool backend map[string]string } byLocale := make(map[string]*mergedPack) ensurePack := func(canon i18n.Locale) *mergedPack { key := string(canon) mp := byLocale[key] if mp == nil { mp = &mergedPack{ pack: ResolvedLocalePack{ Locale: key, Fallback: string(i18n.DefaultFallback(canon)), Messages: make(map[string]string), }, seenPID: make(map[string]bool), backend: make(map[string]string), } byLocale[key] = mp } return mp } setPluginMsg := func(mp *mergedPack, targetPID, k, v string, overwrite bool) { if targetPID == "" || k == "" || v == "" { return } if mp.pack.PluginMessages == nil { mp.pack.PluginMessages = make(map[string]map[string]string) } pm := mp.pack.PluginMessages[targetPID] if pm == nil { pm = make(map[string]string) mp.pack.PluginMessages[targetPID] = pm } if !overwrite { if _, exists := pm[k]; exists { return } } pm[k] = v } // 1. Collect private `/.json` bundles from active/degraded functional plugins (underlay). // Use ActivePluginIDs() rather than List() so we never trigger inUseChecker / Sidecar wake-ups // while Registry.Reconcile holds reconcileMu. activeIDs := m.registry.ActivePluginIDs() sortedActiveIDs := make([]string, 0, len(activeIDs)) for pid := range activeIDs { sortedActiveIDs = append(sortedActiveIDs, pid) } sort.Strings(sortedActiveIDs) for _, pid := range sortedActiveIDs { man, ok := m.registry.ManifestOf(pid) if !ok { continue } for _, file := range l10nFiles(dirs[pid], man.L10n) { loaded, err := loadLocaleJSONFile(dirs[pid], file.rel) if err != nil || len(loaded) == 0 { continue } mp := ensurePack(file.locale) for k, v := range loaded { setPluginMsg(mp, pid, k, v, true) } } } // 2. Layer active Language Pack contributions (sorted deterministically by TrustRank -> Priority -> PluginID). uiDomains := []string{"core", "vm", "wizard", "settings", "plugins", "macosGlossary", "macos-glossary"} for _, lc := range contribs { canon, ok := i18n.ParseLocale(lc.Locale) if !ok { continue } privileged := isPrivilegedLocaleTrustRank(lc.TrustRank) if !privileged && (canon == i18n.ZhCN || canon == i18n.EnUS) { // Community/unprivileged language packs may not hijack built-in host catalogs. continue } mp := ensurePack(canon) if lbl := strings.TrimSpace(lc.Label); lbl != "" { mp.pack.Label = lbl } if fb := strings.TrimSpace(lc.Fallback); fb != "" { if cfb, ok := i18n.ParseLocale(fb); ok { mp.pack.Fallback = string(cfb) } } installDir := dirs[lc.PluginID] mergeLocaleFile(mp.pack.Messages, installDir, lc.File) for _, dom := range uiDomains { mergeLocaleFile(mp.pack.Messages, installDir, lc.Files[dom]) } mergeMessages(mp.pack.Messages, lc.Messages) mergeBackendMessages(mp.backend, installDir, lc) // Resolve bundled WOFF2 WebFonts via AssetServer. if installDir != "" && m.assets != nil && len(lc.Fonts) > 0 { for _, f := range lc.Fonts { if strings.TrimSpace(f.Family) == "" || !strings.EqualFold(filepath.Ext(strings.TrimSpace(f.File)), ".woff2") { continue } if full, err := safeJoin(installDir, f.File); err == nil && verifyWOFF2Header(full) == nil { mp.pack.Fonts = append(mp.pack.Fonts, ResolvedLocaleFont{ Family: f.Family, URL: m.assets.AssetURL(lc.PluginID, f.File), Weight: f.Weight, Style: f.Style, UnicodeRange: f.UnicodeRange, }) } } } // Layer cross-plugin message overrides onto PluginMessages[targetID]. // Unprivileged community packs may only fill in missing keys, never overwrite // a target plugin's own messages. for targetID, ov := range lc.PluginOverrides { if installDir != "" && strings.TrimSpace(ov.MessagesFile) != "" { if loaded, err := loadLocaleJSONFile(installDir, ov.MessagesFile); err == nil { for k, v := range loaded { setPluginMsg(mp, targetID, k, v, privileged) } } } for k, v := range ov.Messages { setPluginMsg(mp, targetID, k, v, privileged) } } if lc.PluginID != "" && !mp.seenPID[lc.PluginID] { mp.seenPID[lc.PluginID] = true mp.pack.PluginIDs = append(mp.pack.PluginIDs, lc.PluginID) } } if len(byLocale) == 0 { return nil, nil } uiPacks := make([]ResolvedLocalePack, 0, len(byLocale)) backendPacks := make(map[i18n.Locale]i18n.PluginCatalog, len(byLocale)) for key, mp := range byLocale { if mp.pack.Label == "" { mp.pack.Label = defaultLocaleLabel(key) } sort.Strings(mp.pack.PluginIDs) if len(mp.pack.Messages) > 0 { mp.pack.HasUIMessages = true } else { mp.pack.Messages = nil } uiPacks = append(uiPacks, mp.pack) if len(mp.backend) > 0 { backendPacks[i18n.Locale(key)] = i18n.PluginCatalog{ Fallback: i18n.Locale(mp.pack.Fallback), Messages: mp.backend, } } } sort.Slice(uiPacks, func(i, j int) bool { return uiPacks[i].Locale < uiPacks[j].Locale }) if len(backendPacks) == 0 { backendPacks = nil } return uiPacks, backendPacks } type resolvedManifestOverride struct { locale string privileged bool ov PluginManifestOverride } func applyLocalizedOverride(lt *LocalizedText, locale, val string, privileged bool) { if privileged { lt.Set(locale, val) } else { lt.SetIfEmpty(locale, val) } } func (m *Manager) activeManifestOverrides() map[string][]resolvedManifestOverride { if m == nil || m.safeMode { return nil } contribs := m.registry.Locales() if len(contribs) == 0 { return nil } m.mu.RLock() dirs := maps.Clone(m.installDirs) m.mu.RUnlock() var out map[string][]resolvedManifestOverride for _, lc := range contribs { if len(lc.PluginOverrides) == 0 { continue } canon, ok := i18n.ParseLocale(lc.Locale) if !ok { continue } privileged := isPrivilegedLocaleTrustRank(lc.TrustRank) if !privileged && (canon == i18n.ZhCN || canon == i18n.EnUS) { continue } packDir := dirs[lc.PluginID] for targetID, po := range lc.PluginOverrides { var merged PluginManifestOverride hasAny := false if packDir != "" && strings.TrimSpace(po.ManifestFile) != "" { if loaded, err := loadPluginManifestOverrideFile(packDir, po.ManifestFile); err == nil && loaded != nil { merged = *loaded hasAny = true } } if po.Manifest != nil { if po.Manifest.Name != "" { merged.Name = po.Manifest.Name } if po.Manifest.Description != "" { merged.Description = po.Manifest.Description } if len(po.Manifest.Fields) > 0 { if merged.Fields == nil { merged.Fields = make(map[string]string, len(po.Manifest.Fields)) } for fk, fv := range po.Manifest.Fields { merged.Fields[fk] = fv } } hasAny = true } if !hasAny { continue } if out == nil { out = make(map[string][]resolvedManifestOverride) } out[targetID] = append(out[targetID], resolvedManifestOverride{ locale: string(canon), privileged: privileged, ov: merged, }) } } return out } func cloneLocalizedText(lt LocalizedText) LocalizedText { out := LocalizedText{ZhCN: lt.ZhCN, EnUS: lt.EnUS} if len(lt.Extra) > 0 { out.Extra = make(map[string]string, len(lt.Extra)) for k, v := range lt.Extra { out.Extra[k] = v } } return out } func cloneSettingsSchemaWithOverrides(sc *SettingsSchema, list []resolvedManifestOverride) *SettingsSchema { if sc == nil { return nil } cp := *sc cp.Title = cloneLocalizedText(sc.Title) if len(sc.Properties) > 0 { cp.Properties = make(map[string]SettingProperty, len(sc.Properties)) for pk, prop := range sc.Properties { pcp := prop pcp.Title = cloneLocalizedText(prop.Title) pcp.Description = cloneLocalizedText(prop.Description) cp.Properties[pk] = pcp } } for _, r := range list { if v := r.ov.Fields["settings.title"]; v != "" { applyLocalizedOverride(&cp.Title, r.locale, v, r.privileged) } for pk, prop := range cp.Properties { changed := false if v := firstNonEmptyField(r.ov.Fields, "setting."+pk+".title", pk+".title"); v != "" { applyLocalizedOverride(&prop.Title, r.locale, v, r.privileged) changed = true } if v := firstNonEmptyField(r.ov.Fields, "setting."+pk+".description", pk+".description"); v != "" { applyLocalizedOverride(&prop.Description, r.locale, v, r.privileged) changed = true } if changed { cp.Properties[pk] = prop } } } return &cp } func firstNonEmptyField(fields map[string]string, keys ...string) string { if len(fields) == 0 { return "" } for _, k := range keys { if v := strings.TrimSpace(fields[k]); v != "" { return v } } return "" } // LocalizePluginInfos returns a copy of infos enriched with any active Language Pack // `pluginOverrides` translations for plugin Name, Description, and SettingsSchema. func (m *Manager) LocalizePluginInfos(infos []PluginInfo) []PluginInfo { ovs := m.activeManifestOverrides() if len(ovs) == 0 || len(infos) == 0 { return infos } out := make([]PluginInfo, len(infos)) for i, info := range infos { cp := info if list := ovs[info.ID]; len(list) > 0 { cp.Name = cloneLocalizedText(info.Name) cp.Description = cloneLocalizedText(info.Description) for _, r := range list { if r.ov.Name != "" { applyLocalizedOverride(&cp.Name, r.locale, r.ov.Name, r.privileged) } if r.ov.Description != "" { applyLocalizedOverride(&cp.Description, r.locale, r.ov.Description, r.privileged) } } cp.Settings = cloneSettingsSchemaWithOverrides(info.Settings, list) } out[i] = cp } return out } // overridableText is a contribution text that a Language Pack may replace, and // the override fields that do so, in order of preference. type overridableText struct { text *LocalizedText keys []string } // localizeContributions returns a copy of items with the active Language Pack // overrides applied to the texts that texts lists for each item. func localizeContributions[T any](m *Manager, items []T, texts func(*T) (pluginID string, list []overridableText)) []T { ovs := m.activeManifestOverrides() if len(ovs) == 0 || len(items) == 0 { return items } out := slices.Clone(items) for i := range out { pluginID, list := texts(&out[i]) for _, t := range list { if len(ovs[pluginID]) > 0 { *t.text = cloneLocalizedText(*t.text) } for _, r := range ovs[pluginID] { if v := firstNonEmptyField(r.ov.Fields, t.keys...); v != "" { applyLocalizedOverride(t.text, r.locale, v, r.privileged) } } } } return out } // LocalizeMenus applies Language Pack overrides to menu titles. func (m *Manager) LocalizeMenus(items []MenuContribution) []MenuContribution { return localizeContributions(m, items, func(c *MenuContribution) (string, []overridableText) { return c.PluginID, []overridableText{{&c.Title, []string{"menu." + c.ID + ".title", "command." + c.Command + ".title"}}} }) } // LocalizePanels applies Language Pack overrides to panel titles. func (m *Manager) LocalizePanels(items []PanelContribution) []PanelContribution { return localizeContributions(m, items, func(c *PanelContribution) (string, []overridableText) { return c.PluginID, []overridableText{{&c.Title, []string{"panel." + c.ID + ".title"}}} }) } // LocalizeViews applies Language Pack overrides to view titles. func (m *Manager) LocalizeViews(items []ViewContribution) []ViewContribution { return localizeContributions(m, items, func(c *ViewContribution) (string, []overridableText) { return c.PluginID, []overridableText{{&c.Title, []string{"view." + c.ID + ".title"}}} }) } // LocalizeImageSources applies Language Pack overrides to image source titles and descriptions. func (m *Manager) LocalizeImageSources(items []ImageSourceContribution) []ImageSourceContribution { return localizeContributions(m, items, func(c *ImageSourceContribution) (string, []overridableText) { return c.PluginID, []overridableText{ {&c.Title, []string{"imageSource." + c.ID + ".title"}}, {&c.Description, []string{"imageSource." + c.ID + ".description"}}, } }) } // LocalizeVMCards applies Language Pack overrides to VM card titles and values. func (m *Manager) LocalizeVMCards(items []VMCardContribution) []VMCardContribution { return localizeContributions(m, items, func(c *VMCardContribution) (string, []overridableText) { return c.PluginID, []overridableText{ {&c.Title, []string{"vmCard." + c.ID + ".title"}}, {&c.Value, []string{"vmCard." + c.ID + ".value"}}, } }) } // LocalizeSettingsPages applies Language Pack overrides to settings page titles. func (m *Manager) LocalizeSettingsPages(items []SettingsPageContribution) []SettingsPageContribution { return localizeContributions(m, items, func(c *SettingsPageContribution) (string, []overridableText) { return c.PluginID, []overridableText{{&c.Title, []string{"settingsPage." + c.ID + ".title"}}} }) } // LocalizeStatusItems applies Language Pack overrides to status item texts and tooltips. func (m *Manager) LocalizeStatusItems(items []StatusItemContribution) []StatusItemContribution { return localizeContributions(m, items, func(c *StatusItemContribution) (string, []overridableText) { return c.PluginID, []overridableText{ {&c.Text, []string{"statusItem." + c.ID + ".text"}}, {&c.Tooltip, []string{"statusItem." + c.ID + ".tooltip"}}, } }) } // CurrentLocale returns the active effective host locale for plugin operations. func (m *Manager) CurrentLocale() i18n.Locale { if m != nil && m.opts.LocaleFn != nil { return i18n.EffectiveLocale(m.opts.LocaleFn()) } return i18n.Detect() } // PluginL10nBundle builds the merged private localization dictionary for pluginID // in loc, layering the plugin's own `/.json` files underneath any // active Language Pack `pluginOverrides[pluginID]` entries along FallbackChain(loc). func (m *Manager) PluginL10nBundle(pluginID string, loc i18n.Locale) map[string]string { if m == nil || pluginID == "" || m.safeMode { return nil } cacheKey := pluginID + "\x00" + string(loc) m.mu.RLock() gen := m.l10nGen if cached, ok := m.l10nCache[cacheKey]; ok { m.mu.RUnlock() if len(cached) == 0 { return nil } return maps.Clone(cached) } selfDir := m.installDirs[pluginID] dirs := maps.Clone(m.installDirs) m.mu.RUnlock() chain := i18n.FallbackChain(loc) out := make(map[string]string) selfLocaleFiles := make(map[string]string) if man, ok := m.registry.ManifestOf(pluginID); ok { for _, file := range l10nFiles(selfDir, man.L10n) { if _, exists := selfLocaleFiles[string(file.locale)]; !exists { selfLocaleFiles[string(file.locale)] = file.rel } } } contribs := m.registry.Locales() // Walk fallback chain from least specific to most specific so higher-priority hops win. for idx := len(chain) - 1; idx >= 0; idx-- { step := string(chain[idx]) selfKeysThisStep := make(map[string]bool) if rel, ok := selfLocaleFiles[step]; ok { if loaded, err := loadLocaleJSONFile(selfDir, rel); err == nil { for k, v := range loaded { if k != "" && v != "" { out[k] = v selfKeysThisStep[k] = true } } } } for _, lc := range contribs { if lc.Locale != step { continue } privileged := isPrivilegedLocaleTrustRank(lc.TrustRank) if !privileged && (step == string(i18n.ZhCN) || step == string(i18n.EnUS)) { continue } ov, ok := lc.PluginOverrides[pluginID] if !ok { continue } applyMsg := func(k, v string) { if k == "" || v == "" { return } if !privileged && selfKeysThisStep[k] { return } out[k] = v } packDir := dirs[lc.PluginID] if packDir != "" && strings.TrimSpace(ov.MessagesFile) != "" { if loaded, err := loadLocaleJSONFile(packDir, ov.MessagesFile); err == nil { for k, v := range loaded { applyMsg(k, v) } } } for k, v := range ov.Messages { applyMsg(k, v) } } } m.mu.Lock() if m.l10nGen == gen { if len(m.l10nCache) >= 512 { clear(m.l10nCache) } if len(out) == 0 { m.l10nCache[cacheKey] = nil } else { m.l10nCache[cacheKey] = maps.Clone(out) } } m.mu.Unlock() if len(out) == 0 { return nil } return out } // NotifyLocaleChanged broadcasts `plugin/localeChanged` to all currently running // L3 Sidecar processes without waking sleeping Sidecars. func (m *Manager) NotifyLocaleChanged(eff i18n.Locale) { if m == nil { return } m.mu.RLock() sups := maps.Clone(m.supervisors) m.mu.RUnlock() if len(sups) == 0 { return } chain := i18n.FallbackChain(eff) strChain := make([]string, len(chain)) for i, c := range chain { strChain[i] = string(c) } for pid, sup := range sups { if sup.PID() == 0 { continue } sup.NotifyIfRunning("plugin/localeChanged", map[string]any{ "locale": string(eff), "fallbackChain": strChain, "l10nBundle": m.PluginL10nBundle(pid, eff), }) } } func defaultLocaleLabel(code string) string { switch code { case string(i18n.ZhCN): return "简体中文" case string(i18n.EnUS): return "English" default: return code } } func isPrivilegedLocaleTrustRank(rank int) bool { return rank == 10 || rank == 20 || rank >= 50 } func localeTrustRank(source SourceKind, trust TrustLevel) int { switch { case source == SourceBuiltin: return 10 case source == SourceBundled: return 20 case trust == TrustCommunity: return 30 case trust == TrustVerified: return 40 case trust == TrustOfficial: return 50 case source == SourceDevLink || trust == TrustDev: return 60 default: return 30 } } func mergeMessages(dst, src map[string]string) { for k, v := range src { if k != "" && v != "" { dst[k] = v } } } // mergeLocaleFile merges the messages in dir/rel into dst. A missing or // invalid file adds nothing; the plugin scanner reports those. func mergeLocaleFile(dst map[string]string, dir, rel string) { rel = strings.TrimSpace(rel) if dir == "" || rel == "" { return } if loaded, err := loadLocaleJSONFile(dir, rel); err == nil { mergeMessages(dst, loaded) } } // mergeBackendMessages merges the Go-side messages of one language pack. // Later sources win: domain files, the backend file, then inline messages. func mergeBackendMessages(dst map[string]string, dir string, lc LocaleContribution) { for _, dom := range []string{"native", "macosGlossary", "macos-glossary", "core"} { mergeLocaleFile(dst, dir, lc.Files[dom]) } mergeLocaleFile(dst, dir, lc.BackendFile) mergeMessages(dst, lc.Backend) } // l10nFile is one `/.json` message file of a plugin. type l10nFile struct { locale i18n.Locale rel string } // l10nFiles lists the private message files a plugin ships in its l10n folder. func l10nFiles(pluginDir, l10n string) []l10nFile { l10n = strings.Trim(strings.TrimSpace(l10n), "/") if pluginDir == "" || l10n == "" { return nil } full, err := safeJoin(pluginDir, l10n) if err != nil { return nil } entries, err := os.ReadDir(full) if err != nil { return nil } var files []l10nFile for _, ent := range entries { if ent.IsDir() || !strings.HasSuffix(strings.ToLower(ent.Name()), ".json") { continue } tag := strings.TrimSuffix(ent.Name(), filepath.Ext(ent.Name())) if canon, ok := i18n.ParseLocale(tag); ok { files = append(files, l10nFile{locale: canon, rel: l10n + "/" + ent.Name()}) } } return files } // LoadStaticLocalePacks performs an ultra-fast (< 2ms), side-effect-free scan of // enabled plugins under dataRoot to populate backend/CLI language packs without // starting any L3 Sidecars, AssetServer, or service dependency reconciliation. func LoadStaticLocalePacks(dataRoot string) map[i18n.Locale]i18n.PluginCatalog { if strings.TrimSpace(dataRoot) == "" { i18n.SetPluginCatalogs(nil) return nil } layout := NewPluginsLayout(dataRoot) if DidLastStartupCrash(layout.Root) { i18n.SetPluginCatalogs(nil) return nil } st, err := NewStateStore(layout.Root).Load() if err != nil || st == nil || len(st.Plugins) == 0 { i18n.SetPluginCatalogs(nil) return nil } type staticCandidate struct { id string dir string rec *PluginRecord rank int } var candidates []staticCandidate for id, rec := range st.Plugins { if rec == nil || !rec.Enabled || rec.Source == SourceBuiltin || rec.Source == SourceBundled { continue } var dir string if rec.Source == SourceDevLink { if !st.DeveloperMode || strings.TrimSpace(rec.DevPath) == "" { continue } dir = rec.DevPath } else { if rec.Version == "" || !reReverseDomainID.MatchString(id) { continue } if _, err := ParseSemVer(rec.Version); err != nil { continue } safeDir, err := safeJoin(layout.PkgsDir(), id+"/"+rec.Version) if err != nil { continue } dir = safeDir } candidates = append(candidates, staticCandidate{ id: id, dir: dir, rec: rec, rank: localeTrustRank(rec.Source, rec.Trust), }) } sort.Slice(candidates, func(i, j int) bool { if candidates[i].rank != candidates[j].rank { return candidates[i].rank < candidates[j].rank } return candidates[i].id < candidates[j].id }) type staticLocaleItem struct { canon i18n.Locale rank int id string dir string lc LocaleContribution } var items []staticLocaleItem for _, c := range candidates { raw, err := os.ReadFile(filepath.Join(c.dir, "plugin.json")) if err != nil { continue } var man Manifest if json.Unmarshal(raw, &man) != nil || len(man.Contributes.Locales) == 0 { continue } if c.id != "" && man.ID != c.id { continue } trust := c.rec.Trust if trust == "" { trust = TrustCommunity } if c.rec.Source == SourceDevLink { trust = TrustDev } _, _, entryHash, err := resolveManifestEntry(man, c.dir, false) if err != nil { continue } if computeNeedsApproval(man, trust, c.rec.ApprovedPermissions, c.rec.ApprovedEntryHash, entryHash) { continue } for _, lc := range man.Contributes.Locales { canon, ok := i18n.ParseLocale(lc.Locale) if !ok { continue } items = append(items, staticLocaleItem{ canon: canon, rank: c.rank, id: c.id, dir: c.dir, lc: lc, }) } } sort.Slice(items, func(i, j int) bool { if items[i].canon != items[j].canon { return items[i].canon < items[j].canon } if items[i].rank != items[j].rank { return items[i].rank < items[j].rank } if items[i].lc.Priority != items[j].lc.Priority { return items[i].lc.Priority < items[j].lc.Priority } return items[i].id < items[j].id }) packs := make(map[i18n.Locale]i18n.PluginCatalog) for _, it := range items { canon := it.canon if !isPrivilegedLocaleTrustRank(it.rank) && (canon == i18n.ZhCN || canon == i18n.EnUS) { continue } lc := it.lc cur, exists := packs[canon] if !exists { cur = i18n.PluginCatalog{ Fallback: i18n.DefaultFallback(canon), Messages: make(map[string]string), } } if fb, ok := i18n.ParseLocale(lc.Fallback); ok { cur.Fallback = fb } mergeBackendMessages(cur.Messages, it.dir, lc) if len(cur.Messages) > 0 { packs[canon] = cur } } i18n.SetPluginCatalogs(packs) return packs }