// Package config 负责配置模型、默认值、加载、保存、校验与迁移。 // 阶段 4 完整版:大小限制、损坏恢复(.bak)、原子保存、版本迁移、热重载监听。 package config import ( "encoding/json" "errors" "fmt" "os" "path/filepath" ) // MaxConfigSize 为配置文件大小上限。 const MaxConfigSize = 1 << 20 // 1MB // CurrentVersion 为当前配置格式版本。 // v2:滚轮音量按"格"生效(steps 提升到 4、冷却清零),并新增屏幕底部 // 滚轮调亮度规则。 // v3:全局新增 notify(调节时是否弹出桌面通知,默认开启;音量/静音的 // 自动通知默认关闭,见动作参数 toast)。 // v4:每条规则新增 notify(该规则是否弹通知,默认开启),global.notify // 仍作为总开关。 const CurrentVersion = 5 // ErrCorrupted 表示配置损坏、已备份并恢复为默认配置(可继续运行)。 var ErrCorrupted = errors.New("config corrupted, recovered from default") // ErrUnsupportedVersion 表示配置版本无法迁移、已备份并恢复为默认(可继续运行)。 var ErrUnsupportedVersion = errors.New("unsupported config version, recovered from default") // Config 为配置根结构(版本 1)。 type Config struct { Version int `json:"version"` Global GlobalConfig `json:"global"` Rules []Rule `json:"rules"` } // GlobalConfig 为全局设置。 type GlobalConfig struct { Enabled bool `json:"enabled"` Notify bool `json:"notify"` // 调节音量/亮度时是否弹桌面通知 Theme string `json:"theme"` LogLevel string `json:"log_level"` OSD OSDConfig `json:"osd"` // 调节提示条的位置 } // OSDConfig 为调节提示条(音量/亮度胶囊)的位置设置。 // // Position 为 "top" / "bottom" / "left" / "right":前两者在水平方向居中, // 后两者在垂直方向居中;Margin 为该边与显示器工作区边缘的距离(DIP)。 type OSDConfig struct { Position string `json:"position"` Margin int `json:"margin"` } // 提示条位置的合法取值。 const ( OSDPositionTop = "top" OSDPositionBottom = "bottom" OSDPositionLeft = "left" OSDPositionRight = "right" ) // DefaultOSD 返回提示条位置的默认值:底部居中、距底边 64 DIP。 func DefaultOSD() OSDConfig { return OSDConfig{Position: OSDPositionBottom, Margin: 64} } // OSDMaxMargin 为提示条与屏幕边缘距离的上限(DIP);实际显示时会再按 // 显示器工作区尺寸钳制,保证胶囊不会跑到屏幕外。 const OSDMaxMargin = 1000 // OSDMarginValid 报告提示条边距是否在允许范围内。 func (o OSDConfig) OSDMarginValid() bool { return o.Margin >= 0 && o.Margin <= OSDMaxMargin } // OSDPositionValid 报告提示条位置字符串是否合法(空值视为默认底部)。 func (o OSDConfig) OSDPositionValid() bool { switch o.Position { case "", OSDPositionTop, OSDPositionBottom, OSDPositionLeft, OSDPositionRight: return true } return false } // Rule 为一条规则:触发器 + 条件(MVP 仅空)+ 动作链。 type Rule struct { ID string `json:"id"` Name string `json:"name"` Enabled bool `json:"enabled"` // Notify 控制本规则触发时是否弹右下角系统通知;调节提示条不受影响。 // 与 global.notify 是"与"关系:两者都开启才弹通知。 Notify bool `json:"notify"` Priority int `json:"priority"` Trigger TriggerConfig `json:"trigger"` Conditions []ConditionConfig `json:"conditions,omitempty"` Actions []ActionConfig `json:"actions"` CooldownMs int `json:"cooldown_ms"` // Fullscreen 全屏行为:"" / "ignore"(默认,全屏前台窗口时忽略本规则) // / "allow"(豁免,全屏时仍触发)。 Fullscreen string `json:"fullscreen,omitempty"` } // TriggerConfig 为触发器配置。JSON 采用扁平形式: // // {"type": "mouse_corner", "corner": "bottom_left", "screen": "all"} // // "type" 之外的字段全部收集进 Params,供具体触发器解析。 type TriggerConfig struct { Type string `json:"type"` Params map[string]any `json:"-"` } // UnmarshalJSON 将扁平 JSON 拆分为 Type 与 Params。 func (t *TriggerConfig) UnmarshalJSON(b []byte) error { var raw map[string]json.RawMessage if err := json.Unmarshal(b, &raw); err != nil { return err } if v, ok := raw["type"]; ok { if err := json.Unmarshal(v, &t.Type); err != nil { return err } delete(raw, "type") } t.Params = make(map[string]any, len(raw)) for k, v := range raw { var x any if err := json.Unmarshal(v, &x); err != nil { return err } t.Params[k] = x } return nil } // MarshalJSON 将 Type 与 Params 展平回写,保证 JSON 往返对称。 func (t TriggerConfig) MarshalJSON() ([]byte, error) { m := make(map[string]any, len(t.Params)+1) for k, v := range t.Params { m[k] = v } m["type"] = t.Type return json.Marshal(m) } // ConditionConfig 为条件配置。MVP 阶段仅接受空列表。 type ConditionConfig struct { Type string `json:"type"` Params map[string]any `json:"params"` } // ActionConfig 为动作配置。 type ActionConfig struct { Type string `json:"type"` Params map[string]any `json:"params"` } // Default 返回内置默认配置(虚拟桌面/音量/亮度/快捷键示例规则)。 func Default() *Config { return &Config{ Version: CurrentVersion, Global: GlobalConfig{ Enabled: true, Notify: true, Theme: "system", LogLevel: "info", OSD: DefaultOSD(), }, Rules: []Rule{ { ID: "desktop-left-bottom", Name: "左下角切换虚拟桌面", Enabled: true, Notify: true, Priority: 100, Trigger: TriggerConfig{Type: "mouse_corner", Params: map[string]any{"corner": "bottom_left", "screen": "all", "threshold_px": 32}}, Actions: []ActionConfig{{Type: "switch_virtual_desktop", Params: map[string]any{"mode": "alternate"}}}, CooldownMs: 800, }, { ID: "volume-top-wheel-up", Name: "顶部边缘滚轮增大音量", Enabled: true, Notify: true, Priority: 100, Trigger: TriggerConfig{Type: "mouse_edge_wheel", Params: map[string]any{"edge": "top", "direction": "up", "threshold_px": 32}}, Actions: []ActionConfig{{Type: "volume_up", Params: map[string]any{"steps": 4}}}, CooldownMs: 0, }, { ID: "volume-top-wheel-down", Name: "顶部边缘滚轮减小音量", Enabled: true, Notify: true, Priority: 100, Trigger: TriggerConfig{Type: "mouse_edge_wheel", Params: map[string]any{"edge": "top", "direction": "down", "threshold_px": 32}}, Actions: []ActionConfig{{Type: "volume_down", Params: map[string]any{"steps": 4}}}, CooldownMs: 0, }, { ID: "hotkey-switch-desktop", Name: "示例:Ctrl+Alt+D 切换桌面(默认关闭)", Enabled: false, Notify: true, Priority: 50, Trigger: TriggerConfig{Type: "hotkey", Params: map[string]any{"hotkey": "ctrl+alt+d"}}, Actions: []ActionConfig{{Type: "switch_virtual_desktop", Params: map[string]any{"mode": "alternate"}}}, CooldownMs: 400, }, defaultBrightnessRule("up"), defaultBrightnessRule("down"), }, } } // defaultBrightnessRule 构造屏幕底部边缘滚轮调亮/调暗规则。 func defaultBrightnessRule(dir string) Rule { actionType, label := "brightness_up", "调亮" if dir == "down" { actionType, label = "brightness_down", "调暗" } return Rule{ ID: "brightness-bottom-wheel-" + dir, Name: "屏幕底部滚轮" + label, Enabled: true, Notify: true, Priority: 100, Trigger: TriggerConfig{Type: "mouse_edge_wheel", Params: map[string]any{"edge": "bottom", "direction": dir, "threshold_px": 32}}, Actions: []ActionConfig{{Type: actionType, Params: map[string]any{"steps": 5}}}, // 滚轮事件按"格"上报,冷却清零才能让快速连滚每一格都生效; // 动作层有合并队列兜底,不会因为 DDC 慢而堆积。 CooldownMs: 0, Fullscreen: "ignore", } } // AppDataDir 返回应用数据目录。 // 便携模式:exe 同目录存在 config.json 时,配置/日志跟随 exe 目录 // (绿色便携版);否则使用 %LOCALAPPDATA%\ZerOriginTool(安装版默认)。 func AppDataDir() (string, error) { if dir, ok := portableDir(); ok { return dir, nil } if d := os.Getenv("LOCALAPPDATA"); d != "" { return filepath.Join(d, "ZerOriginTool"), nil } d, err := os.UserConfigDir() if err != nil { return "", fmt.Errorf("resolve user config dir: %w", err) } return filepath.Join(d, "ZerOriginTool"), nil } // portableDir 检测便携模式:exe 同目录存在 config.json 时返回该目录。 func portableDir() (string, bool) { exe, err := os.Executable() if err != nil { return "", false } dir := filepath.Dir(exe) if _, err := os.Stat(filepath.Join(dir, "config.json")); err == nil { return dir, true } return "", false } // Path 返回配置文件路径。 func Path() (string, error) { dir, err := AppDataDir() if err != nil { return "", err } return filepath.Join(dir, "config.json"), nil } // Load 读取配置:文件不存在时生成默认;损坏或无法迁移时备份为 // config.json.bak、恢复默认配置,并以 ErrCorrupted/ErrUnsupportedVersion // 包装的错误返回(调用方应记录日志后继续运行)。 func Load() (*Config, error) { path, err := Path() if err != nil { return nil, err } return loadAt(path) } // Validate 校验全局设置,返回可直接展示给用户的问题描述。 // 加载、热重载与保存都会调用;有问题时调用方应回退到默认值而不是拒绝加载。 func (c *Config) Validate() []string { var out []string if !c.Global.OSD.OSDPositionValid() { out = append(out, fmt.Sprintf("提示条位置 %q 无效(应为 top/bottom/left/right)", c.Global.OSD.Position)) } if !c.Global.OSD.OSDMarginValid() { out = append(out, fmt.Sprintf("提示条边距 %d 超出范围(0–%d)", c.Global.OSD.Margin, OSDMaxMargin)) } return out } // Normalize 修正可以自动修复的全局设置(目前是提示条位置与边距), // 返回被修正的字段数。加载与热重载都会调用,保证运行期一定拿到合法值; // 与 osd.SetPosition 的归一化重复是刻意的双保险(配置层负责持久化数据)。 func (c *Config) Normalize() int { fixed := 0 if !c.Global.OSD.OSDPositionValid() { c.Global.OSD.Position = OSDPositionBottom fixed++ } if c.Global.OSD.Position == "" { c.Global.OSD.Position = OSDPositionBottom } if !c.Global.OSD.OSDMarginValid() { if c.Global.OSD.Margin < 0 { c.Global.OSD.Margin = 0 } else { c.Global.OSD.Margin = OSDMaxMargin } fixed++ } return fixed } // loadAt 在指定路径上执行完整加载流程(测试可注入临时路径)。 func loadAt(path string) (*Config, error) { fi, err := os.Stat(path) if err != nil { if os.IsNotExist(err) { return createDefault(path) } return nil, fmt.Errorf("stat config: %w", err) } if fi.Size() > MaxConfigSize { backup(path) return createDefault(path, fmt.Errorf("%w: size %d exceeds %d", ErrCorrupted, fi.Size(), MaxConfigSize)) } data, err := os.ReadFile(path) if err != nil { return nil, fmt.Errorf("read config: %w", err) } var cfg Config if err := json.Unmarshal(data, &cfg); err != nil { backup(path) return createDefault(path, fmt.Errorf("%w: %v", ErrCorrupted, err)) } // 版本迁移(v1 为当前版本,框架先行)。 if cfg.Version != CurrentVersion { migrated, err := migrate(&cfg) if err != nil { backup(path) return createDefault(path, fmt.Errorf("%w: %v", ErrUnsupportedVersion, err)) } cfg = *migrated if err := Save(path, &cfg); err != nil { return nil, fmt.Errorf("save migrated config: %w", err) } } // 手工改坏的全局设置就地修正(不写盘),避免非法值传到运行期。 cfg.Normalize() return &cfg, nil } // createDefault 生成默认配置并原子写入;wrap 非 nil 时作为返回错误附加。 func createDefault(path string, wrap ...error) (*Config, error) { cfg := Default() if err := Save(path, cfg); err != nil { return nil, fmt.Errorf("write default config: %w", err) } if len(wrap) > 0 && wrap[0] != nil { return cfg, wrap[0] } return cfg, nil } // backup 将现有配置文件改名为 .bak(覆盖旧备份)。 func backup(path string) { _ = os.Rename(path, path+".bak") } // Save 原子保存配置:写入同目录临时文件,关闭后原子替换原文件。 // 任何失败都不会破坏旧配置。 func Save(path string, cfg *Config) error { if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil { return err } tmp, err := os.CreateTemp(filepath.Dir(path), "config-*.tmp") if err != nil { return fmt.Errorf("create temp: %w", err) } defer os.Remove(tmp.Name()) // 失败路径清理 data, err := json.MarshalIndent(cfg, "", " ") if err != nil { tmp.Close() return err } if _, err := tmp.Write(data); err != nil { tmp.Close() return fmt.Errorf("write temp: %w", err) } if err := tmp.Close(); err != nil { return fmt.Errorf("close temp: %w", err) } if err := os.Rename(tmp.Name(), path); err != nil { return fmt.Errorf("replace config: %w", err) } return nil }