🎨 Optimize code
This commit is contained in:
@@ -127,8 +127,10 @@ int isHotkeyRegistered() {
|
||||
import "C"
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
"time"
|
||||
"unsafe"
|
||||
"voidraft/internal/models"
|
||||
@@ -142,12 +144,14 @@ type HotkeyService struct {
|
||||
logger *log.LoggerService
|
||||
configService *ConfigService
|
||||
app *application.App
|
||||
|
||||
mu sync.RWMutex
|
||||
isRegistered bool
|
||||
currentHotkey *models.HotkeyCombo
|
||||
stopChan chan struct{}
|
||||
wg sync.WaitGroup
|
||||
running bool
|
||||
isRegistered atomic.Bool
|
||||
|
||||
ctx context.Context
|
||||
cancel context.CancelFunc
|
||||
wg sync.WaitGroup
|
||||
}
|
||||
|
||||
// HotkeyError 热键错误
|
||||
@@ -158,25 +162,25 @@ type HotkeyError struct {
|
||||
|
||||
// Error 实现error接口
|
||||
func (e *HotkeyError) Error() string {
|
||||
return fmt.Sprintf("hotkey error during %s: %v", e.Operation, e.Err)
|
||||
return fmt.Sprintf("hotkey %s: %v", e.Operation, e.Err)
|
||||
}
|
||||
|
||||
// Unwrap 获取原始错误
|
||||
func (e *HotkeyError) Unwrap() error {
|
||||
return e.Err
|
||||
}
|
||||
|
||||
// NewHotkeyService 创建新的热键服务实例
|
||||
// NewHotkeyService 创建热键服务实例
|
||||
func NewHotkeyService(configService *ConfigService, logger *log.LoggerService) *HotkeyService {
|
||||
if logger == nil {
|
||||
logger = log.New()
|
||||
}
|
||||
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
return &HotkeyService{
|
||||
logger: logger,
|
||||
configService: configService,
|
||||
isRegistered: false,
|
||||
running: false,
|
||||
ctx: ctx,
|
||||
cancel: cancel,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -184,91 +188,73 @@ func NewHotkeyService(configService *ConfigService, logger *log.LoggerService) *
|
||||
func (hs *HotkeyService) Initialize(app *application.App) error {
|
||||
hs.app = app
|
||||
|
||||
// 初始化X11显示
|
||||
if int(C.initX11Display()) == 0 {
|
||||
return &HotkeyError{Operation: "init_x11", Err: fmt.Errorf("failed to initialize X11 display")}
|
||||
return &HotkeyError{"init_x11", fmt.Errorf("failed to initialize X11 display")}
|
||||
}
|
||||
|
||||
// 加载并应用当前配置
|
||||
config, err := hs.configService.GetConfig()
|
||||
if err != nil {
|
||||
return &HotkeyError{Operation: "load_config", Err: err}
|
||||
return &HotkeyError{"load_config", err}
|
||||
}
|
||||
|
||||
if config.General.EnableGlobalHotkey {
|
||||
err = hs.RegisterHotkey(&config.General.GlobalHotkey)
|
||||
if err != nil {
|
||||
hs.logger.Error("Hotkey: Failed to register hotkey on startup", "error", err)
|
||||
if err := hs.RegisterHotkey(&config.General.GlobalHotkey); err != nil {
|
||||
hs.logger.Error("failed to register startup hotkey", "error", err)
|
||||
}
|
||||
}
|
||||
|
||||
hs.logger.Info("Hotkey: Linux service initialized")
|
||||
return nil
|
||||
}
|
||||
|
||||
// RegisterHotkey 注册全局热键
|
||||
func (hs *HotkeyService) RegisterHotkey(hotkey *models.HotkeyCombo) error {
|
||||
if !hs.isValidHotkey(hotkey) {
|
||||
return &HotkeyError{"validate", fmt.Errorf("invalid hotkey combination")}
|
||||
}
|
||||
|
||||
hs.mu.Lock()
|
||||
defer hs.mu.Unlock()
|
||||
|
||||
// 先取消注册现有热键
|
||||
if hs.isRegistered {
|
||||
hs.logger.Info("Hotkey: Unregistering existing hotkey before registering new one")
|
||||
err := hs.unregisterHotkeyInternal()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
// 取消现有热键
|
||||
if hs.isRegistered.Load() {
|
||||
hs.unregisterInternal()
|
||||
}
|
||||
|
||||
// 验证热键组合
|
||||
if !hs.isValidHotkey(hotkey) {
|
||||
return &HotkeyError{Operation: "validate_hotkey", Err: fmt.Errorf("invalid hotkey combination")}
|
||||
}
|
||||
|
||||
hs.logger.Info("Hotkey: Registering global hotkey on Linux",
|
||||
"ctrl", hotkey.Ctrl,
|
||||
"shift", hotkey.Shift,
|
||||
"alt", hotkey.Alt,
|
||||
"win", hotkey.Win,
|
||||
"key", hotkey.Key)
|
||||
|
||||
// 转换键码和修饰符
|
||||
keyCode := hs.keyToX11KeyCode(hotkey.Key)
|
||||
if keyCode == 0 {
|
||||
return &HotkeyError{Operation: "convert_key", Err: fmt.Errorf("unsupported key: %s", hotkey.Key)}
|
||||
return &HotkeyError{"convert_key", fmt.Errorf("unsupported key: %s", hotkey.Key)}
|
||||
}
|
||||
|
||||
modifiers := hs.buildX11Modifiers(hotkey)
|
||||
|
||||
// 调用C函数注册热键
|
||||
result := int(C.registerGlobalHotkey(C.int(keyCode), C.uint(modifiers)))
|
||||
if result == 0 {
|
||||
return &HotkeyError{Operation: "register_hotkey", Err: fmt.Errorf("failed to register hotkey")}
|
||||
return &HotkeyError{"register", fmt.Errorf("failed to register hotkey")}
|
||||
}
|
||||
|
||||
// 创建ready channel等待goroutine启动完成
|
||||
readyChan := make(chan struct{})
|
||||
|
||||
// 确保 stopChan 是新的
|
||||
hs.stopChan = make(chan struct{})
|
||||
// 启动监听器
|
||||
ctx, cancel := context.WithCancel(hs.ctx)
|
||||
hs.wg.Add(1)
|
||||
go hs.hotkeyListener(hotkey, readyChan)
|
||||
|
||||
// 等待监听器启动完成,设置超时避免无限等待
|
||||
ready := make(chan error, 1)
|
||||
go hs.hotkeyListener(ctx, ready)
|
||||
|
||||
// 等待启动完成
|
||||
select {
|
||||
case <-readyChan:
|
||||
// 监听器启动完成
|
||||
case <-time.After(1 * time.Second):
|
||||
// 超时处理
|
||||
hs.logger.Warning("Hotkey: Timeout waiting for listener to start")
|
||||
return &HotkeyError{Operation: "start_listener", Err: fmt.Errorf("timeout waiting for hotkey listener to start")}
|
||||
case err := <-ready:
|
||||
if err != nil {
|
||||
cancel()
|
||||
return &HotkeyError{"start_listener", err}
|
||||
}
|
||||
case <-time.After(time.Second):
|
||||
cancel()
|
||||
return &HotkeyError{"start_listener", fmt.Errorf("timeout")}
|
||||
}
|
||||
|
||||
hs.currentHotkey = hotkey
|
||||
hs.isRegistered = true
|
||||
hs.running = true
|
||||
hs.isRegistered.Store(true)
|
||||
hs.cancel = cancel
|
||||
|
||||
hs.logger.Info("Hotkey: Successfully registered global hotkey on Linux")
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -276,130 +262,70 @@ func (hs *HotkeyService) RegisterHotkey(hotkey *models.HotkeyCombo) error {
|
||||
func (hs *HotkeyService) UnregisterHotkey() error {
|
||||
hs.mu.Lock()
|
||||
defer hs.mu.Unlock()
|
||||
|
||||
return hs.unregisterHotkeyInternal()
|
||||
return hs.unregisterInternal()
|
||||
}
|
||||
|
||||
// unregisterHotkeyInternal 内部取消注册方法(无锁)
|
||||
func (hs *HotkeyService) unregisterHotkeyInternal() error {
|
||||
if !hs.isRegistered {
|
||||
hs.logger.Debug("Hotkey: No hotkey registered, skipping unregister")
|
||||
// unregisterInternal 内部取消注册(无锁)
|
||||
func (hs *HotkeyService) unregisterInternal() error {
|
||||
if !hs.isRegistered.Load() {
|
||||
return nil
|
||||
}
|
||||
|
||||
hs.logger.Info("Hotkey: Unregistering global hotkey on Linux")
|
||||
|
||||
// 停止监听
|
||||
if hs.stopChan != nil {
|
||||
close(hs.stopChan)
|
||||
hs.logger.Debug("Hotkey: Waiting for listener goroutine to stop")
|
||||
if hs.cancel != nil {
|
||||
hs.cancel()
|
||||
hs.wg.Wait()
|
||||
hs.logger.Debug("Hotkey: Listener goroutine stopped")
|
||||
}
|
||||
|
||||
// 调用C函数取消注册热键
|
||||
result := int(C.unregisterGlobalHotkey())
|
||||
if result == 0 {
|
||||
return &HotkeyError{Operation: "unregister_hotkey", Err: fmt.Errorf("failed to unregister hotkey")}
|
||||
return &HotkeyError{"unregister", fmt.Errorf("failed to unregister hotkey")}
|
||||
}
|
||||
|
||||
// 重置状态
|
||||
hs.currentHotkey = nil
|
||||
hs.isRegistered = false
|
||||
hs.running = false
|
||||
hs.stopChan = nil
|
||||
|
||||
hs.logger.Info("Hotkey: Successfully unregistered global hotkey on Linux")
|
||||
hs.isRegistered.Store(false)
|
||||
return nil
|
||||
}
|
||||
|
||||
// UpdateHotkey 更新热键配置
|
||||
func (hs *HotkeyService) UpdateHotkey(enable bool, hotkey *models.HotkeyCombo) error {
|
||||
hs.logger.Info("Hotkey: === UpdateHotkey called (Linux) ===",
|
||||
"enable", enable,
|
||||
"ctrl", hotkey.Ctrl,
|
||||
"shift", hotkey.Shift,
|
||||
"alt", hotkey.Alt,
|
||||
"win", hotkey.Win,
|
||||
"key", hotkey.Key)
|
||||
|
||||
if enable {
|
||||
// 启用热键:直接注册新热键(RegisterHotkey 会处理取消旧热键)
|
||||
err := hs.RegisterHotkey(hotkey)
|
||||
if err != nil {
|
||||
hs.logger.Error("Hotkey: Failed to register new hotkey", "error", err)
|
||||
return err
|
||||
}
|
||||
hs.logger.Info("Hotkey: Successfully updated and registered new hotkey on Linux")
|
||||
return nil
|
||||
} else {
|
||||
// 禁用热键:取消注册
|
||||
err := hs.UnregisterHotkey()
|
||||
if err != nil {
|
||||
hs.logger.Error("Hotkey: Failed to unregister hotkey", "error", err)
|
||||
return err
|
||||
}
|
||||
hs.logger.Info("Hotkey: Successfully disabled hotkey on Linux")
|
||||
return nil
|
||||
return hs.RegisterHotkey(hotkey)
|
||||
}
|
||||
return hs.UnregisterHotkey()
|
||||
}
|
||||
|
||||
// ToggleWindow 切换窗口显示/隐藏
|
||||
func (hs *HotkeyService) ToggleWindow() {
|
||||
if hs.app == nil {
|
||||
hs.logger.Warning("Hotkey: App is nil, cannot toggle")
|
||||
return
|
||||
}
|
||||
|
||||
// 发送事件到前端,让前端处理窗口切换
|
||||
hs.app.EmitEvent("hotkey:toggle-window", nil)
|
||||
hs.logger.Debug("Hotkey: Emitted toggle window event (Linux)")
|
||||
}
|
||||
|
||||
// hotkeyListener 热键监听器goroutine
|
||||
func (hs *HotkeyService) hotkeyListener(hotkey *models.HotkeyCombo, readyChan chan struct{}) {
|
||||
// hotkeyListener 热键监听器
|
||||
func (hs *HotkeyService) hotkeyListener(ctx context.Context, ready chan<- error) {
|
||||
defer hs.wg.Done()
|
||||
|
||||
hs.logger.Debug("Hotkey: Starting Linux X11 hotkey listener")
|
||||
|
||||
// 检查间隔(100ms)
|
||||
ticker := time.NewTicker(100 * time.Millisecond)
|
||||
defer ticker.Stop()
|
||||
|
||||
// 标记是否已经发送ready信号,确保只发送一次
|
||||
readySent := false
|
||||
ready <- nil // 标记准备就绪
|
||||
|
||||
for {
|
||||
select {
|
||||
case <-hs.stopChan:
|
||||
hs.logger.Debug("Hotkey: Stopping Linux X11 hotkey listener")
|
||||
if !readySent {
|
||||
close(readyChan)
|
||||
}
|
||||
case <-ctx.Done():
|
||||
return
|
||||
case <-ticker.C:
|
||||
// 第一次循环时发送ready信号,表示监听器已经准备就绪
|
||||
if !readySent {
|
||||
close(readyChan)
|
||||
readySent = true
|
||||
hs.logger.Debug("Hotkey: Listener ready signal sent")
|
||||
}
|
||||
|
||||
// 检查热键事件
|
||||
if int(C.checkHotkeyEvent()) == 1 {
|
||||
hs.logger.Debug("Hotkey: Global hotkey triggered via Linux X11")
|
||||
hs.ToggleWindow()
|
||||
hs.toggleWindow()
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// keyToX11KeyCode 将键名转换为X11键码
|
||||
// toggleWindow 切换窗口
|
||||
func (hs *HotkeyService) toggleWindow() {
|
||||
if hs.app != nil {
|
||||
hs.app.EmitEvent("hotkey:toggle-window", nil)
|
||||
}
|
||||
}
|
||||
|
||||
// keyToX11KeyCode 键名转X11键码
|
||||
func (hs *HotkeyService) keyToX11KeyCode(key string) int {
|
||||
// 将Go字符串转换为C字符串
|
||||
cKey := C.CString(key)
|
||||
defer C.free(unsafe.Pointer(cKey))
|
||||
|
||||
return int(C.getX11Keycode(cKey))
|
||||
}
|
||||
|
||||
@@ -423,27 +349,19 @@ func (hs *HotkeyService) buildX11Modifiers(hotkey *models.HotkeyCombo) uint {
|
||||
return modifiers
|
||||
}
|
||||
|
||||
// isValidHotkey 验证热键组合是否有效
|
||||
// isValidHotkey 验证热键组合
|
||||
func (hs *HotkeyService) isValidHotkey(hotkey *models.HotkeyCombo) bool {
|
||||
if hotkey == nil {
|
||||
if hotkey == nil || hotkey.Key == "" {
|
||||
return false
|
||||
}
|
||||
|
||||
// 必须有主键
|
||||
if hotkey.Key == "" {
|
||||
return false
|
||||
}
|
||||
|
||||
// 必须至少有一个修饰键
|
||||
// 至少需要一个修饰键
|
||||
if !hotkey.Ctrl && !hotkey.Shift && !hotkey.Alt && !hotkey.Win {
|
||||
return false
|
||||
}
|
||||
|
||||
// 验证主键是否在有效范围内
|
||||
return hs.keyToX11KeyCode(hotkey.Key) != 0
|
||||
}
|
||||
|
||||
// GetCurrentHotkey 获取当前注册的热键
|
||||
// GetCurrentHotkey 获取当前热键
|
||||
func (hs *HotkeyService) GetCurrentHotkey() *models.HotkeyCombo {
|
||||
hs.mu.RLock()
|
||||
defer hs.mu.RUnlock()
|
||||
@@ -452,7 +370,6 @@ func (hs *HotkeyService) GetCurrentHotkey() *models.HotkeyCombo {
|
||||
return nil
|
||||
}
|
||||
|
||||
// 返回副本避免并发问题
|
||||
return &models.HotkeyCombo{
|
||||
Ctrl: hs.currentHotkey.Ctrl,
|
||||
Shift: hs.currentHotkey.Shift,
|
||||
@@ -462,28 +379,15 @@ func (hs *HotkeyService) GetCurrentHotkey() *models.HotkeyCombo {
|
||||
}
|
||||
}
|
||||
|
||||
// IsRegistered 检查是否已注册热键
|
||||
// IsRegistered 检查是否已注册
|
||||
func (hs *HotkeyService) IsRegistered() bool {
|
||||
hs.mu.RLock()
|
||||
defer hs.mu.RUnlock()
|
||||
return hs.isRegistered
|
||||
return hs.isRegistered.Load()
|
||||
}
|
||||
|
||||
// ServiceShutdown 关闭热键服务
|
||||
// ServiceShutdown 关闭服务
|
||||
func (hs *HotkeyService) ServiceShutdown() error {
|
||||
hs.mu.Lock()
|
||||
defer hs.mu.Unlock()
|
||||
|
||||
if hs.isRegistered {
|
||||
err := hs.unregisterHotkeyInternal()
|
||||
if err != nil {
|
||||
hs.logger.Error("Hotkey: Failed to unregister hotkey on shutdown", "error", err)
|
||||
}
|
||||
}
|
||||
|
||||
// 关闭X11显示
|
||||
hs.cancel()
|
||||
hs.wg.Wait()
|
||||
C.closeX11Display()
|
||||
|
||||
hs.logger.Info("Hotkey: Linux service shutdown completed")
|
||||
return nil
|
||||
}
|
||||
|
Reference in New Issue
Block a user