Added configuration change notification service

This commit is contained in:
2025-06-04 02:34:05 +08:00
parent 5381e4ba17
commit d9745ac7d1
21 changed files with 1579 additions and 406 deletions

View File

@@ -5,7 +5,6 @@ import (
"fmt"
"os"
"path/filepath"
"strings"
"sync"
"time"
"voidraft/internal/models"
@@ -21,12 +20,8 @@ type ConfigService struct {
logger *log.LoggerService // 日志服务
mu sync.RWMutex // 读写锁
// 热键配置变更回调
hotkeyChangeCallback func(enable bool, hotkey *models.HotkeyCombo) error
// 热键变更防抖
hotkeyNotificationTimer *time.Timer
hotkeyNotificationMu sync.Mutex
// 配置通知服务
notificationService *ConfigNotificationService
}
// ConfigError 配置错误
@@ -52,184 +47,6 @@ func (e *ConfigError) Is(target error) bool {
return ok
}
// ConfigLimits 配置限制定义
type ConfigLimits struct {
FontSizeMin int
FontSizeMax int
TabSizeMin int
TabSizeMax int
}
// getConfigLimits 获取配置限制
func getConfigLimits() ConfigLimits {
return ConfigLimits{
FontSizeMin: 12,
FontSizeMax: 28,
TabSizeMin: 2,
TabSizeMax: 8,
}
}
// validateAndFixValue 验证并修正配置值
func (cs *ConfigService) validateAndFixValue(key string, value interface{}) (interface{}, bool) {
limits := getConfigLimits()
fixed := false
switch key {
case "editing.font_size":
if intVal, ok := value.(int); ok {
if intVal < limits.FontSizeMin {
cs.logger.Warning("Config: Font size too small, fixing", "original", intVal, "fixed", limits.FontSizeMin)
return limits.FontSizeMin, true
}
if intVal > limits.FontSizeMax {
cs.logger.Warning("Config: Font size too large, fixing", "original", intVal, "fixed", limits.FontSizeMax)
return limits.FontSizeMax, true
}
}
case "editing.tab_size":
if intVal, ok := value.(int); ok {
if intVal < limits.TabSizeMin {
cs.logger.Warning("Config: Tab size too small, fixing", "original", intVal, "fixed", limits.TabSizeMin)
return limits.TabSizeMin, true
}
if intVal > limits.TabSizeMax {
cs.logger.Warning("Config: Tab size too large, fixing", "original", intVal, "fixed", limits.TabSizeMax)
return limits.TabSizeMax, true
}
}
case "editing.tab_type":
if strVal, ok := value.(string); ok {
validTypes := []string{string(models.TabTypeSpaces), string(models.TabTypeTab)}
isValid := false
for _, validType := range validTypes {
if strVal == validType {
isValid = true
break
}
}
if !isValid {
cs.logger.Warning("Config: Invalid tab type, fixing", "original", strVal, "fixed", string(models.TabTypeSpaces))
return string(models.TabTypeSpaces), true
}
}
case "appearance.language":
if strVal, ok := value.(string); ok {
validLanguages := []string{string(models.LangZhCN), string(models.LangEnUS)}
isValid := false
for _, validLang := range validLanguages {
if strVal == validLang {
isValid = true
break
}
}
if !isValid {
cs.logger.Warning("Config: Invalid language, fixing", "original", strVal, "fixed", string(models.LangZhCN))
return string(models.LangZhCN), true
}
}
case "editing.auto_save_delay":
if intVal, ok := value.(int); ok {
if intVal < 1000 {
cs.logger.Warning("Config: Auto save delay too small, fixing", "original", intVal, "fixed", 1000)
return 1000, true
}
if intVal > 30000 {
cs.logger.Warning("Config: Auto save delay too large, fixing", "original", intVal, "fixed", 30000)
return 30000, true
}
}
case "editing.change_threshold":
if intVal, ok := value.(int); ok {
if intVal < 10 {
cs.logger.Warning("Config: Change threshold too small, fixing", "original", intVal, "fixed", 10)
return 10, true
}
if intVal > 10000 {
cs.logger.Warning("Config: Change threshold too large, fixing", "original", intVal, "fixed", 10000)
return 10000, true
}
}
case "editing.min_save_interval":
if intVal, ok := value.(int); ok {
if intVal < 100 {
cs.logger.Warning("Config: Min save interval too small, fixing", "original", intVal, "fixed", 100)
return 100, true
}
if intVal > 10000 {
cs.logger.Warning("Config: Min save interval too large, fixing", "original", intVal, "fixed", 10000)
return 10000, true
}
}
}
return value, fixed
}
// validateAllConfig 验证并修正所有配置
func (cs *ConfigService) validateAllConfig() error {
hasChanges := false
// 获取当前配置
var config models.AppConfig
if err := cs.viper.Unmarshal(&config); err != nil {
return &ConfigError{Operation: "unmarshal_for_validation", Err: err}
}
// 验证编辑器配置
if fixedValue, fixed := cs.validateAndFixValue("editing.font_size", config.Editing.FontSize); fixed {
cs.viper.Set("editing.font_size", fixedValue)
hasChanges = true
}
if fixedValue, fixed := cs.validateAndFixValue("editing.tab_size", config.Editing.TabSize); fixed {
cs.viper.Set("editing.tab_size", fixedValue)
hasChanges = true
}
if fixedValue, fixed := cs.validateAndFixValue("editing.tab_type", string(config.Editing.TabType)); fixed {
cs.viper.Set("editing.tab_type", fixedValue)
hasChanges = true
}
if fixedValue, fixed := cs.validateAndFixValue("appearance.language", string(config.Appearance.Language)); fixed {
cs.viper.Set("appearance.language", fixedValue)
hasChanges = true
}
// 验证保存选项配置
if fixedValue, fixed := cs.validateAndFixValue("editing.auto_save_delay", config.Editing.AutoSaveDelay); fixed {
cs.viper.Set("editing.auto_save_delay", fixedValue)
hasChanges = true
}
if fixedValue, fixed := cs.validateAndFixValue("editing.change_threshold", config.Editing.ChangeThreshold); fixed {
cs.viper.Set("editing.change_threshold", fixedValue)
hasChanges = true
}
if fixedValue, fixed := cs.validateAndFixValue("editing.min_save_interval", config.Editing.MinSaveInterval); fixed {
cs.viper.Set("editing.min_save_interval", fixedValue)
hasChanges = true
}
// 如果有修正,保存配置
if hasChanges {
if err := cs.viper.WriteConfig(); err != nil {
return &ConfigError{Operation: "save_validated_config", Err: err}
}
cs.logger.Info("Config: Configuration validated and fixed")
}
return nil
}
// NewConfigService 创建新的配置服务实例
func NewConfigService(logger *log.LoggerService) *ConfigService {
// 设置日志服务
@@ -268,16 +85,14 @@ func NewConfigService(logger *log.LoggerService) *ConfigService {
logger: logger,
}
// 初始化配置通知服务
service.notificationService = NewConfigNotificationService(v, logger)
// 初始化配置
if err := service.initConfig(); err != nil {
service.logger.Error("Config: Failed to initialize config", "error", err)
}
// 验证并修正配置
if err := service.validateAllConfig(); err != nil {
service.logger.Error("Config: Failed to validate config", "error", err)
}
// 启动配置文件监听
service.startWatching()
@@ -290,7 +105,9 @@ func setDefaults(v *viper.Viper) {
// 通用设置默认值
v.SetDefault("general.always_on_top", defaultConfig.General.AlwaysOnTop)
v.SetDefault("general.data_path", defaultConfig.General.DataPath)
v.SetDefault("general.default_data_path", defaultConfig.General.DefaultDataPath)
v.SetDefault("general.use_custom_data_path", defaultConfig.General.UseCustomDataPath)
v.SetDefault("general.custom_data_path", defaultConfig.General.CustomDataPath)
v.SetDefault("general.enable_global_hotkey", defaultConfig.General.EnableGlobalHotkey)
v.SetDefault("general.global_hotkey.ctrl", defaultConfig.General.GlobalHotkey.Ctrl)
v.SetDefault("general.global_hotkey.shift", defaultConfig.General.GlobalHotkey.Shift)
@@ -371,11 +188,9 @@ func (cs *ConfigService) startWatching() {
// 设置配置变化回调
cs.viper.OnConfigChange(func(e fsnotify.Event) {
cs.logger.Info("Config: Config file changed", "file", e.Name, "operation", e.Op.String())
// 注释掉自动更新时间戳,避免无限循环
// err := cs.Set("metadata.last_updated", time.Now())
// if err != nil {
// cs.logger.Error("Config: Failed to update last_updated field", "error", err)
// }
// 使用配置通知服务检查所有已注册的配置变更
cs.notificationService.CheckConfigChanges()
})
// 启动配置文件监听
@@ -400,33 +215,14 @@ func (cs *ConfigService) GetConfig() (*models.AppConfig, error) {
func (cs *ConfigService) Set(key string, value interface{}) error {
cs.mu.Lock()
defer cs.mu.Unlock()
// 验证并修正配置值
validatedValue, wasFixed := cs.validateAndFixValue(key, value)
// 设置验证后的值
cs.viper.Set(key, validatedValue)
cs.viper.Set(key, value)
// 使用 WriteConfig 写入配置文件(会触发文件监听)
if err := cs.viper.WriteConfig(); err != nil {
return &ConfigError{Operation: "set_config", Err: err}
}
if wasFixed {
cs.logger.Debug("Config: Successfully set config with validation", "key", key, "original", value, "fixed", validatedValue)
} else {
cs.logger.Debug("Config: Successfully set config", "key", key, "value", value)
}
// 检查是否是热键相关配置
if cs.isHotkeyRelatedKey(key) {
cs.logger.Info("Config: Detected hotkey configuration change", "key", key, "value", value)
// 释放锁后通知,避免死锁
go func() {
cs.notifyHotkeyChange()
}()
}
return nil
}
@@ -455,75 +251,11 @@ func (cs *ConfigService) ResetConfig() error {
}
// SetHotkeyChangeCallback 设置热键配置变更回调
func (cs *ConfigService) SetHotkeyChangeCallback(callback func(enable bool, hotkey *models.HotkeyCombo) error) {
func (cs *ConfigService) SetHotkeyChangeCallback(callback func(enable bool, hotkey *models.HotkeyCombo) error) error {
cs.mu.Lock()
defer cs.mu.Unlock()
cs.hotkeyChangeCallback = callback
}
// notifyHotkeyChange 通知热键配置变更
func (cs *ConfigService) notifyHotkeyChange() {
if cs.hotkeyChangeCallback == nil {
return
}
cs.hotkeyNotificationMu.Lock()
defer cs.hotkeyNotificationMu.Unlock()
// 取消之前的定时器
if cs.hotkeyNotificationTimer != nil {
cs.hotkeyNotificationTimer.Stop()
}
// 设置新的防抖定时器200ms延迟
cs.hotkeyNotificationTimer = time.AfterFunc(200*time.Millisecond, func() {
cs.logger.Debug("Config: Executing hotkey change notification after debounce")
// 获取当前热键配置
config, err := cs.GetConfig()
if err != nil {
cs.logger.Error("Config: Failed to get config for hotkey notification", "error", err)
return
}
cs.logger.Debug("Config: Notifying hotkey service of configuration change",
"enable", config.General.EnableGlobalHotkey,
"ctrl", config.General.GlobalHotkey.Ctrl,
"shift", config.General.GlobalHotkey.Shift,
"alt", config.General.GlobalHotkey.Alt,
"win", config.General.GlobalHotkey.Win,
"key", config.General.GlobalHotkey.Key)
// 异步通知热键服务
go func() {
err := cs.hotkeyChangeCallback(config.General.EnableGlobalHotkey, &config.General.GlobalHotkey)
if err != nil {
cs.logger.Error("Config: Failed to notify hotkey change", "error", err)
} else {
cs.logger.Debug("Config: Successfully notified hotkey change")
}
}()
})
cs.logger.Debug("Config: Hotkey change notification scheduled with debounce")
}
// isHotkeyRelatedKey 检查是否是热键相关的配置键
func (cs *ConfigService) isHotkeyRelatedKey(key string) bool {
hotkeyKeys := []string{
"general.enable_global_hotkey",
"general.global_hotkey",
"general.global_hotkey.ctrl",
"general.global_hotkey.shift",
"general.global_hotkey.alt",
"general.global_hotkey.win",
"general.global_hotkey.key",
}
for _, hotkeyKey := range hotkeyKeys {
if strings.HasPrefix(key, hotkeyKey) || key == hotkeyKey {
return true
}
}
return false
// 创建热键监听器并注册
hotkeyListener := CreateHotkeyListener(callback)
return cs.notificationService.RegisterListener(hotkeyListener)
}