Merge pull request #174 from Nwflower/feat/clipboard-plugin-settings

feat(plugin): move clipboard sync settings to plugin configuration
This commit is contained in:
千川白浪 authored and GitHub committed 2026-12-04 23:09:18 +08:00
commit 5aca93a862
9 files changed
+383 -44

No files matched your search

@@ -0,0 +1,7 @@
{
"group": "improvements",
"order": 0,
"authors": ["Nwflower"],
"zh": "将「剪贴板互通」的全部配置项从虚拟机设置迁移到插件页的插件配置中统一管理,并在升级时按显式关闭与更严格限制优先的规则自动迁移旧的单虚拟机配置。",
"en": "Move all Clipboard Sync settings from VM settings into the plugin configuration on the Plugins page, automatically migrating legacy per-VM settings on upgrade with explicit-off and stricter limits taking precedence."
}
+37 -19
View File
@@ -79,7 +79,7 @@ func TestGuestToolsBridgeFollowsPluginSwitch(t *testing.T) {
}
}
func TestClipboardFileSettingsInheritAndOverrideGlobalDefaults(t *testing.T) {
func TestClipboardSettingsApplyGloballyFromPluginConfig(t *testing.T) {
srv := guesttools.NewTransportServer(nil)
cfg := config.Default()
cfg.DataRoot = t.TempDir()
@@ -106,33 +106,51 @@ func TestClipboardFileSettingsInheritAndOverrideGlobalDefaults(t *testing.T) {
t.Fatal("clipboard plugin did not activate")
}
info, ok := mgr.Registry().Info(builtin.IDClipboard)
if !ok || info.Settings == nil {
t.Fatal("clipboard plugin missing settings schema")
}
if info.Settings.Scope != "app" {
t.Fatalf("clipboard schema scope = %q, want app", info.Settings.Scope)
}
for key, prop := range info.Settings.Properties {
if prop.Scope != "app" {
t.Fatalf("clipboard setting %q scope = %q, want app", key, prop.Scope)
}
}
vm := driver.NewVMRef("", "mac").Key()
peer := driver.NewVMRef("", "peer").Key()
set := func(vmKey string, vals map[string]any) {
t.Helper()
if err := a.SetPluginSettings(builtin.IDClipboard, vmKey, vals); err != nil {
t.Fatal(err)
}
}
set(vm, map[string]any{"sync_images": false, "direction": "host-to-guest"})
set("", map[string]any{"sync_files": false, "max_file_mb": 64})
policy := srv.EffectiveClipboardPolicy(vm)
if !policy.Enabled || policy.SyncFiles || policy.MaxFileBytes != 64<<20 ||
policy.SyncImages || policy.Direction != guesttools.ClipboardHostToGuest {
t.Fatalf("global file defaults or existing VM policies lost: %+v", policy)
}
settings := a.GetVMPluginSettings(vm)[builtin.IDClipboard]
if settings["sync_files"] != false || settings["max_file_mb"] != 64 {
t.Fatalf("VM settings should display inherited values, got %v", settings)
// Stale per-VM entries saved before moving clipboard settings to plugin scope
// must not override the plugin-level configuration.
set(vm, map[string]any{"enabled": false, "direction": "guest-to-host", "max_file_mb": 256})
set("", map[string]any{
"enabled": true,
"direction": "host-to-guest",
"sync_images": false,
"max_image_mb": 8,
"sync_files": false,
"max_file_mb": 64,
})
for _, target := range []string{vm, peer} {
policy := srv.EffectiveClipboardPolicy(target)
if !policy.Enabled || policy.Direction != guesttools.ClipboardHostToGuest ||
policy.SyncImages || policy.MaxImageBytes != 8<<20 ||
policy.SyncFiles || policy.MaxFileBytes != 64<<20 {
t.Fatalf("VM %q policy did not match plugin config: %+v", target, policy)
}
}
set(vm, map[string]any{"max_file_mb": 256})
set("", map[string]any{"sync_files": true, "max_file_mb": 32})
policy = srv.EffectiveClipboardPolicy(vm)
if !policy.SyncFiles || policy.MaxFileBytes != 256<<20 {
t.Fatalf("VM must inherit the new toggle and retain its own limit, got %+v", policy)
}
if peer := srv.EffectiveClipboardPolicy(driver.NewVMRef("", "peer").Key()); !peer.SyncFiles || peer.MaxFileBytes != 32<<20 {
t.Fatalf("unconfigured VM should use global defaults, got %+v", peer)
set("", map[string]any{"enabled": false, "sync_files": true, "max_file_mb": 32})
if policy := srv.EffectiveClipboardPolicy(vm); policy.Enabled || !policy.SyncFiles || policy.MaxFileBytes != 32<<20 {
t.Fatalf("updated plugin config did not apply immediately: %+v", policy)
}
}
-8
View File
@@ -500,14 +500,6 @@ func (a *App) syncClipboardPolicies() {
}
globalVals := mgr.GetSettings(builtin.IDClipboard, "", false)
gt.SetGlobalClipboardPolicy(clipboardPolicyFromMap(globalVals))
for vmKey := range mgr.SavedVMSettingsForPlugin(builtin.IDClipboard) {
ref, ok := driver.ParseVMRef(vmKey)
if !ok {
ref = driver.NewVMRef("", vmKey)
}
pol := clipboardPolicyFromMap(mgr.GetSettings(builtin.IDClipboard, vmKey, false))
gt.SetVMClipboardPolicy(ref.Key(), &pol)
}
}
func (a *App) onPluginSettingsChanged(pluginID, vmName string) {
+175
View File
@@ -0,0 +1,175 @@
package datamigrate
import (
"math"
"github.com/Nwflower/reims-go/internal/plugin"
"github.com/Nwflower/reims-go/internal/plugin/builtin"
)
const (
clipDirHostToGuest = 1 << 0
clipDirGuestToHost = 1 << 1
clipDirBoth = clipDirHostToGuest | clipDirGuestToHost
)
// migrateClipboardSettings moves legacy per-VM clipboard settings into the
// plugin's app-scoped settings using restrictive-first merge rules and clears
// the obsolete VMSettings map.
func migrateClipboardSettings(dataRoot string) error {
store := plugin.NewStateStore(plugin.NewPluginsLayout(dataRoot).Root)
st, err := store.Load()
if err != nil {
return err
}
if !migrateClipboardSettingsState(st) {
return nil
}
return store.Save(st)
}
func migrateClipboardSettingsState(st *plugin.StateFile) bool {
if st == nil || st.Plugins == nil {
return false
}
rec := st.Plugins[builtin.IDClipboard]
if rec == nil || len(rec.VMSettings) == 0 {
return false
}
app := rec.AppSettings
ensureApp := func() map[string]any {
if app == nil {
app = map[string]any{}
rec.AppSettings = app
}
return app
}
// Booleans: explicit false in either AppSettings or any VMSettings wins.
for _, key := range []string{"enabled", "sync_images", "sync_files"} {
if appVal, ok := app[key].(bool); ok && !appVal {
continue
}
hasFalse := false
hasTrue := false
for _, vmVals := range rec.VMSettings {
v, ok := vmVals[key].(bool)
if !ok {
continue
}
if !v {
hasFalse = true
} else {
hasTrue = true
}
}
if hasFalse {
ensureApp()[key] = false
} else if hasTrue {
if _, exists := app[key]; !exists {
ensureApp()[key] = true
}
}
}
// Direction: take the intersection of allowed directions across AppSettings
// and all VMSettings. If two VMs restrict to disjoint directions, disable
// sync rather than silently re-enabling a blocked direction.
dirMask := clipDirBoth
hasDir := false
if s, ok := app["direction"].(string); ok {
if m, valid := parseClipDirectionMask(s); valid {
dirMask &= m
hasDir = true
}
}
for _, vmVals := range rec.VMSettings {
s, ok := vmVals["direction"].(string)
if !ok {
continue
}
if m, valid := parseClipDirectionMask(s); valid {
dirMask &= m
hasDir = true
}
}
if hasDir {
if dirStr, ok := formatClipDirectionMask(dirMask); ok {
ensureApp()["direction"] = dirStr
} else {
ensureApp()["enabled"] = false
}
}
// Size limits: smallest explicit positive value wins.
for _, key := range []string{"max_image_mb", "max_file_mb"} {
best := 0
hasLimit := false
if v, ok := positiveIntSetting(app[key]); ok {
best = v
hasLimit = true
}
for _, vmVals := range rec.VMSettings {
if v, ok := positiveIntSetting(vmVals[key]); ok {
if !hasLimit || v < best {
best = v
hasLimit = true
}
}
}
if hasLimit {
ensureApp()[key] = best
}
}
rec.VMSettings = nil
return true
}
func parseClipDirectionMask(dir string) (int, bool) {
switch dir {
case "bidirectional":
return clipDirBoth, true
case "host-to-guest":
return clipDirHostToGuest, true
case "guest-to-host":
return clipDirGuestToHost, true
default:
return 0, false
}
}
func formatClipDirectionMask(mask int) (string, bool) {
switch mask {
case clipDirBoth:
return "bidirectional", true
case clipDirHostToGuest:
return "host-to-guest", true
case clipDirGuestToHost:
return "guest-to-host", true
default:
return "", false
}
}
func positiveIntSetting(raw any) (int, bool) {
switch v := raw.(type) {
case int:
if v > 0 {
return v, true
}
case int64:
if v > 0 {
return int(v), true
}
case float64:
if v > 0 && !math.IsNaN(v) && !math.IsInf(v, 0) {
n := int(math.Round(v))
if n > 0 {
return n, true
}
}
}
return 0, false
}
@@ -0,0 +1,153 @@
package datamigrate
import (
"os"
"testing"
"github.com/Nwflower/reims-go/internal/plugin"
"github.com/Nwflower/reims-go/internal/plugin/builtin"
)
func TestClipboardSettingsUpgradeFromV3Fixture(t *testing.T) {
root := t.TempDir()
if err := writeStamp(root, Stamp{DataVersion: 3, WrittenBy: "0.2.13"}); err != nil {
t.Fatal(err)
}
store := plugin.NewStateStore(plugin.NewPluginsLayout(root).Root)
if err := store.Save(&plugin.StateFile{
Plugins: map[string]*plugin.PluginRecord{
builtin.IDClipboard: {
ID: builtin.IDClipboard,
Enabled: true,
AppSettings: map[string]any{
"sync_files": true,
"max_file_mb": 128,
},
VMSettings: map[string]map[string]any{
"reims-macos:mac-a": {
"enabled": false,
"direction": "host-to-guest",
"sync_images": false,
"max_image_mb": 4,
"max_file_mb": 64,
},
"reims-macos:mac-b": {
"enabled": true,
"direction": "bidirectional",
"sync_images": true,
"max_image_mb": 12,
"sync_files": false,
},
},
},
},
}); err != nil {
t.Fatal(err)
}
original, err := os.ReadFile(store.Path())
if err != nil {
t.Fatal(err)
}
res, err := Run(root, "dev")
if err != nil || res.From != 3 || res.To != CurrentVersion {
t.Fatalf("Run = %+v, err=%v", res, err)
}
backup, err := os.ReadFile(store.Path() + ".bak")
if err != nil || string(backup) != string(original) {
t.Fatalf("backup did not preserve pre-upgrade state.json: err=%v", err)
}
st, err := store.Load()
if err != nil {
t.Fatal(err)
}
rec := st.Plugins[builtin.IDClipboard]
if rec == nil {
t.Fatal("clipboard plugin record missing")
}
if len(rec.VMSettings) != 0 {
t.Fatalf("legacy VMSettings were not cleared: %+v", rec.VMSettings)
}
if rec.AppSettings["enabled"] != false {
t.Fatalf("enabled = %v, want false", rec.AppSettings["enabled"])
}
if rec.AppSettings["direction"] != "host-to-guest" {
t.Fatalf("direction = %v, want host-to-guest", rec.AppSettings["direction"])
}
if rec.AppSettings["sync_images"] != false {
t.Fatalf("sync_images = %v, want false", rec.AppSettings["sync_images"])
}
if rec.AppSettings["max_image_mb"] != float64(4) {
t.Fatalf("max_image_mb = %v, want 4", rec.AppSettings["max_image_mb"])
}
if rec.AppSettings["sync_files"] != false {
t.Fatalf("sync_files = %v, want false", rec.AppSettings["sync_files"])
}
if rec.AppSettings["max_file_mb"] != float64(64) {
t.Fatalf("max_file_mb = %v, want 64", rec.AppSettings["max_file_mb"])
}
// Idempotent on second Run.
before, _ := os.ReadFile(store.Path())
res2, err := Run(root, "dev")
if err != nil || len(res2.Applied) != 0 {
t.Fatalf("second Run = %+v, err=%v", res2, err)
}
after, _ := os.ReadFile(store.Path())
if string(before) != string(after) {
t.Fatal("second Run modified state.json")
}
}
func TestClipboardSettingsMigrationDisjointDirectionsDisableSync(t *testing.T) {
st := &plugin.StateFile{
Plugins: map[string]*plugin.PluginRecord{
builtin.IDClipboard: {
ID: builtin.IDClipboard,
Enabled: true,
VMSettings: map[string]map[string]any{
"reims-macos:mac-a": {"direction": "host-to-guest"},
"reims-macos:mac-b": {"direction": "guest-to-host"},
},
},
},
}
if !migrateClipboardSettingsState(st) {
t.Fatal("expected state change")
}
rec := st.Plugins[builtin.IDClipboard]
if rec.AppSettings["enabled"] != false {
t.Fatalf("disjoint directions should disable sync, got enabled=%v", rec.AppSettings["enabled"])
}
if len(rec.VMSettings) != 0 {
t.Fatalf("VMSettings not cleared: %+v", rec.VMSettings)
}
}
func TestClipboardSettingsMigrationPreservesDisabledPluginAndNoOp(t *testing.T) {
st := &plugin.StateFile{
Plugins: map[string]*plugin.PluginRecord{
builtin.IDClipboard: {
ID: builtin.IDClipboard,
Enabled: false,
VMSettings: map[string]map[string]any{
"reims-macos:mac": {"direction": "guest-to-host", "max_image_mb": float64(8)},
},
},
},
}
if !migrateClipboardSettingsState(st) {
t.Fatal("expected state change")
}
rec := st.Plugins[builtin.IDClipboard]
if rec.Enabled {
t.Fatal("disabled plugin was silently enabled")
}
if rec.AppSettings["direction"] != "guest-to-host" || rec.AppSettings["max_image_mb"] != 8 {
t.Fatalf("unexpected migrated settings: %+v", rec.AppSettings)
}
if migrateClipboardSettingsState(st) {
t.Fatal("second migration pass should be a no-op")
}
}
+2 -1
View File
@@ -20,7 +20,7 @@ const StampFile = ".reims-go-data.json"
// CurrentVersion is the data layout this build writes. Bump it together
// with a new Step.
const CurrentVersion = 3
const CurrentVersion = 4
// Stamp is the content of StampFile.
type Stamp struct {
@@ -41,6 +41,7 @@ type Step struct {
var steps = []Step{
{To: 1, Name: "vm-owner-markers", Run: backfillOwnerMarkers},
{To: 3, Name: "guest-vmref-metadata", Run: migrateGuestAndVMRef},
{To: 4, Name: "clipboard-plugin-settings", Run: migrateClipboardSettings},
}
// Result reports what Run did.
+1 -1
View File
@@ -48,7 +48,7 @@ func TestRunStampsAndMarksLegacyVMs(t *testing.T) {
if err != nil {
t.Fatalf("Run: %v", err)
}
if res.From != 0 || res.To != CurrentVersion || !reflect.DeepEqual(res.Applied, []string{"vm-owner-markers", "guest-vmref-metadata"}) {
if res.From != 0 || res.To != CurrentVersion || !reflect.DeepEqual(res.Applied, []string{"vm-owner-markers", "guest-vmref-metadata", "clipboard-plugin-settings"}) {
t.Fatalf("result = %+v", res)
}
if got := marker(t, legacy); got != driver.BuiltinReimsMacOSDriverID {
+1 -1
View File
@@ -25,7 +25,7 @@ func TestV3MigratesVMSettingsToVMRefKeys(t *testing.T) {
t.Fatal(err)
}
res, err := Run(root, "dev")
if err != nil || res.From != 2 || res.To != 3 {
if err != nil || res.From != 2 || res.To != CurrentVersion {
t.Fatalf("Run = %+v, %v", res, err)
}
st, err := store.Load()
+7 -14
View File
@@ -243,8 +243,7 @@ func defClipboard(ver string, desiredFn func(string, bool) bool) plugin.PluginDe
DefaultEnabled: true,
Settings: &plugin.SettingsSchema{
Title: plugin.LocalizedText{ZhCN: "剪贴板互通", EnUS: "Clipboard Sync"},
Group: "collaboration",
Scope: "vm",
Scope: "app",
Order: []string{"enabled", "direction", "sync_images", "max_image_mb", "sync_files", "max_file_mb"},
Properties: map[string]plugin.SettingProperty{
"enabled": {
@@ -252,8 +251,7 @@ func defClipboard(ver string, desiredFn func(string, bool) bool) plugin.PluginDe
Title: plugin.LocalizedText{ZhCN: "启用剪贴板互通", EnUS: "Enable clipboard sync"},
Default: true,
Effect: "immediate",
Scope: "vm",
Group: "collaboration",
Scope: "app",
},
"direction": {
Type: "string",
@@ -266,16 +264,14 @@ func defClipboard(ver string, desiredFn func(string, bool) bool) plugin.PluginDe
},
Default: "bidirectional",
Effect: "immediate",
Scope: "vm",
Group: "collaboration",
Scope: "app",
},
"sync_images": {
Type: "boolean",
Title: plugin.LocalizedText{ZhCN: "同步剪贴板图片", EnUS: "Sync clipboard images"},
Default: true,
Effect: "immediate",
Scope: "vm",
Group: "collaboration",
Scope: "app",
},
"max_image_mb": {
Type: "integer",
@@ -284,16 +280,14 @@ func defClipboard(ver string, desiredFn func(string, bool) bool) plugin.PluginDe
Minimum: &minMB,
Maximum: &maxMB,
Effect: "immediate",
Scope: "vm",
Group: "collaboration",
Scope: "app",
},
"sync_files": {
Type: "boolean",
Title: plugin.LocalizedText{ZhCN: "同步剪贴板文件", EnUS: "Sync clipboard files"},
Default: true,
Effect: "immediate",
Scope: "both",
Group: "collaboration",
Scope: "app",
},
"max_file_mb": {
Type: "integer",
@@ -306,8 +300,7 @@ func defClipboard(ver string, desiredFn func(string, bool) bool) plugin.PluginDe
Minimum: &minFileMB,
Maximum: &maxFileMB,
Effect: "immediate",
Scope: "both",
Group: "collaboration",
Scope: "app",
},
},
},