Files
zerorigin-toolbox/internal/config/config.go
T
zerorigin2019 0a1c1e82ea chore: 初始化仓库(零源工具箱 0.1.0 基线)
- Go 主进程 cmd/zerorigin(托盘常驻 + 触发器/规则/动作引擎)
- Wails v3 设置进程 cmd/settings(独立 module)
- 监督进程 cmd/watchdog(-supervise 异常重启)
- 构建脚本 build.bat / NSIS 安装包 deploy/、便携版 portable/
- 架构与 MVP 计划文档 docs/、阶段 0-4 验收记录 deploy/acceptance-0-4.md
2026-08-05 00:42:45 +08:00

291 lines
8.8 KiB
Go

// Package config 负责配置模型、默认值、加载、保存、校验与迁移。
// 阶段 4 完整版:大小限制、损坏恢复(.bak)、原子保存、版本迁移、热重载监听。
package config
import (
"encoding/json"
"errors"
"fmt"
"os"
"path/filepath"
)
// MaxConfigSize 为配置文件大小上限。
const MaxConfigSize = 1 << 20 // 1MB
// CurrentVersion 为当前配置格式版本。
const CurrentVersion = 1
// 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"`
Theme string `json:"theme"`
LogLevel string `json:"log_level"`
}
// Rule 为一条规则:触发器 + 条件(MVP 仅空)+ 动作链。
type Rule struct {
ID string `json:"id"`
Name string `json:"name"`
Enabled bool `json:"enabled"`
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: 1,
Global: GlobalConfig{
Enabled: true,
Theme: "system",
LogLevel: "info",
},
Rules: []Rule{
{
ID: "desktop-left-bottom",
Name: "左下角切换虚拟桌面",
Enabled: 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,
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{}}},
CooldownMs: 50,
},
{
ID: "volume-top-wheel-down",
Name: "顶部边缘滚轮减小音量",
Enabled: 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{}}},
CooldownMs: 50,
},
{
ID: "hotkey-switch-desktop",
Name: "示例:Ctrl+Alt+D 切换桌面(默认关闭)",
Enabled: false,
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,
},
},
}
}
// 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)
}
// 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)
}
}
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
}