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
This commit is contained in:
commit
0a1c1e82ea
188 files changed
+19926
No files matched your search
@@ -0,0 +1,103 @@
|
||||
// Package action 定义动作接口、参数 Schema 与注册表。
|
||||
// 动作不得自行修改规则配置;参数必须先 Validate 再 Execute;
|
||||
// 任何动作失败都不能导致主进程退出(由引擎层 recover 兜底)。
|
||||
package action
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"log/slog"
|
||||
"sync"
|
||||
)
|
||||
|
||||
// logger 为动作诊断日志(由 app 注入)。高频路径只打采样日志。
|
||||
var logger = slog.Default()
|
||||
|
||||
// SetLogger 注入动作诊断日志器。
|
||||
func SetLogger(l *slog.Logger) {
|
||||
if l != nil {
|
||||
logger = l
|
||||
}
|
||||
}
|
||||
|
||||
// ParamSpec 描述一个动作参数。
|
||||
type ParamSpec struct {
|
||||
Name string
|
||||
Type string // "string" | "int" | "bool"
|
||||
Required bool
|
||||
Default any
|
||||
}
|
||||
|
||||
// ActionSchema 描述动作的参数契约(供校验与未来 UI 使用)。
|
||||
type ActionSchema struct {
|
||||
Params []ParamSpec
|
||||
}
|
||||
|
||||
// Action 为动作接口。
|
||||
type Action interface {
|
||||
ID() string
|
||||
Name() string
|
||||
Schema() ActionSchema
|
||||
Validate(params map[string]any) error
|
||||
Execute(ctx context.Context, params map[string]any) error
|
||||
}
|
||||
|
||||
// Factory 根据配置参数构造动作实例。
|
||||
type Factory func() Action
|
||||
|
||||
var (
|
||||
registryMu sync.RWMutex
|
||||
registry = map[string]Factory{}
|
||||
)
|
||||
|
||||
// Register 注册动作工厂。重复注册同一 ID 会 panic(编程错误)。
|
||||
func Register(id string, f Factory) {
|
||||
registryMu.Lock()
|
||||
defer registryMu.Unlock()
|
||||
if _, ok := registry[id]; ok {
|
||||
panic(fmt.Sprintf("action %q already registered", id))
|
||||
}
|
||||
registry[id] = f
|
||||
}
|
||||
|
||||
// New 按 ID 构造动作实例。
|
||||
func New(id string) (Action, error) {
|
||||
registryMu.RLock()
|
||||
f, ok := registry[id]
|
||||
registryMu.RUnlock()
|
||||
if !ok {
|
||||
return nil, fmt.Errorf("unknown action type %q", id)
|
||||
}
|
||||
return f(), nil
|
||||
}
|
||||
|
||||
// Known 报告动作 ID 是否已注册。
|
||||
func Known(id string) bool {
|
||||
registryMu.RLock()
|
||||
defer registryMu.RUnlock()
|
||||
_, ok := registry[id]
|
||||
return ok
|
||||
}
|
||||
|
||||
// GetString 从参数 map 读取字符串参数。
|
||||
func GetString(params map[string]any, name string) string {
|
||||
s, _ := params[name].(string)
|
||||
return s
|
||||
}
|
||||
|
||||
// GetInt 从参数 map 读取整数参数(JSON 数字解析为 float64)。
|
||||
func GetInt(params map[string]any, name string) int {
|
||||
switch v := params[name].(type) {
|
||||
case float64:
|
||||
return int(v)
|
||||
case int:
|
||||
return v
|
||||
}
|
||||
return 0
|
||||
}
|
||||
|
||||
// GetBool 从参数 map 读取布尔参数。
|
||||
func GetBool(params map[string]any, name string) bool {
|
||||
b, _ := params[name].(bool)
|
||||
return b
|
||||
}
|
||||
@@ -0,0 +1,138 @@
|
||||
package action
|
||||
|
||||
import (
|
||||
"context"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func TestRegistry(t *testing.T) {
|
||||
for _, id := range []string{
|
||||
"switch_virtual_desktop", "volume_up", "volume_down",
|
||||
"toggle_mute", "show_notification", "delay",
|
||||
} {
|
||||
if !Known(id) {
|
||||
t.Errorf("builtin action %q not registered", id)
|
||||
}
|
||||
}
|
||||
if Known("no_such_action") {
|
||||
t.Error("unknown action reported as known")
|
||||
}
|
||||
if _, err := New("no_such_action"); err == nil {
|
||||
t.Error("New(unknown) should fail")
|
||||
}
|
||||
}
|
||||
|
||||
func TestSwitchDesktopValidate(t *testing.T) {
|
||||
a, _ := New("switch_virtual_desktop")
|
||||
// 有状态动作必须是单例:alternate 往返方向跨执行保持。
|
||||
b, _ := New("switch_virtual_desktop")
|
||||
if a != b {
|
||||
t.Error("switch_virtual_desktop should be a singleton (alternate state)")
|
||||
}
|
||||
for _, mode := range []string{"alternate", "left", "right"} {
|
||||
if err := a.Validate(map[string]any{"mode": mode}); err != nil {
|
||||
t.Errorf("mode %q should pass: %v", mode, err)
|
||||
}
|
||||
}
|
||||
if err := a.Validate(map[string]any{"mode": "up"}); err == nil {
|
||||
t.Error("invalid mode should fail")
|
||||
}
|
||||
if err := a.Validate(map[string]any{}); err == nil {
|
||||
t.Error("missing mode should fail")
|
||||
}
|
||||
// method 参数校验
|
||||
for _, m := range []string{"com", "taskview", "hotkey", ""} {
|
||||
if err := a.Validate(map[string]any{"mode": "left", "method": m}); err != nil {
|
||||
t.Errorf("method %q should pass: %v", m, err)
|
||||
}
|
||||
}
|
||||
if err := a.Validate(map[string]any{"mode": "left", "method": "cli"}); err == nil {
|
||||
t.Error("invalid method should fail")
|
||||
}
|
||||
if err := a.Validate(map[string]any{"mode": "left", "taskview_delay_ms": -1}); err == nil {
|
||||
t.Error("negative delay should fail")
|
||||
}
|
||||
}
|
||||
|
||||
func TestVolumeValidate(t *testing.T) {
|
||||
up, _ := New("volume_up")
|
||||
if err := up.Validate(map[string]any{}); err != nil {
|
||||
t.Errorf("empty params should pass: %v", err)
|
||||
}
|
||||
if err := up.Validate(map[string]any{"steps": -1}); err == nil {
|
||||
t.Error("negative steps should fail")
|
||||
}
|
||||
if err := up.Validate(map[string]any{"steps": 3}); err != nil {
|
||||
t.Errorf("positive steps should pass: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestNotificationValidate(t *testing.T) {
|
||||
a, _ := New("show_notification")
|
||||
if err := a.Validate(map[string]any{}); err == nil {
|
||||
t.Error("missing title/text should fail")
|
||||
}
|
||||
if err := a.Validate(map[string]any{"title": "t", "text": "x"}); err != nil {
|
||||
t.Errorf("valid params should pass: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestDelay(t *testing.T) {
|
||||
a, _ := New("delay")
|
||||
if err := a.Validate(map[string]any{"ms": -1}); err == nil {
|
||||
t.Error("negative ms should fail")
|
||||
}
|
||||
start := time.Now()
|
||||
if err := a.Execute(context.Background(), map[string]any{"ms": 30}); err != nil {
|
||||
t.Fatalf("execute: %v", err)
|
||||
}
|
||||
if elapsed := time.Since(start); elapsed < 25*time.Millisecond {
|
||||
t.Errorf("delay too short: %v", elapsed)
|
||||
}
|
||||
|
||||
// 取消传播
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
cancel()
|
||||
if err := a.Execute(ctx, map[string]any{"ms": 5000}); err == nil {
|
||||
t.Error("cancelled ctx should return error")
|
||||
}
|
||||
}
|
||||
|
||||
func TestLaunchApplicationValidate(t *testing.T) {
|
||||
a, _ := New("launch_application")
|
||||
if err := a.Validate(map[string]any{}); err == nil {
|
||||
t.Error("missing path should fail")
|
||||
}
|
||||
if err := a.Validate(map[string]any{"path": "notepad.exe"}); err == nil {
|
||||
t.Error("relative path should fail")
|
||||
}
|
||||
if err := a.Validate(map[string]any{"path": filepath.Join(t.TempDir(), "nope.exe")}); err == nil {
|
||||
t.Error("nonexistent path should fail")
|
||||
}
|
||||
// 绝对路径 + 存在的文件(用测试二进制自身)
|
||||
exe, err := os.Executable()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := a.Validate(map[string]any{"path": exe}); err != nil {
|
||||
t.Errorf("existing abs path should pass: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestOpenURLValidate(t *testing.T) {
|
||||
a, _ := New("open_url")
|
||||
if err := a.Validate(map[string]any{"url": "https://example.com"}); err != nil {
|
||||
t.Errorf("https should pass: %v", err)
|
||||
}
|
||||
if err := a.Validate(map[string]any{"url": "http://example.com"}); err != nil {
|
||||
t.Errorf("http should pass: %v", err)
|
||||
}
|
||||
for _, bad := range []string{"", "file:///etc/passwd", "cmd://x", "javascript:alert(1)", "not a url"} {
|
||||
if err := a.Validate(map[string]any{"url": bad}); err == nil {
|
||||
t.Errorf("url %q should fail", bad)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
package action
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"time"
|
||||
)
|
||||
|
||||
func init() {
|
||||
Register("delay", func() Action { return &delayAction{} })
|
||||
}
|
||||
|
||||
// delayAction 延迟指定毫秒数(响应 context 取消)。
|
||||
type delayAction struct{}
|
||||
|
||||
func (a *delayAction) ID() string { return "delay" }
|
||||
func (a *delayAction) Name() string { return "延迟" }
|
||||
|
||||
func (a *delayAction) Schema() ActionSchema {
|
||||
return ActionSchema{Params: []ParamSpec{
|
||||
{Name: "ms", Type: "int", Required: true},
|
||||
}}
|
||||
}
|
||||
|
||||
func (a *delayAction) Validate(params map[string]any) error {
|
||||
if ms := GetInt(params, "ms"); ms < 0 {
|
||||
return fmt.Errorf("delay: ms must be >= 0")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (a *delayAction) Execute(ctx context.Context, params map[string]any) error {
|
||||
ms := GetInt(params, "ms")
|
||||
timer := time.NewTimer(time.Duration(ms) * time.Millisecond)
|
||||
defer timer.Stop()
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return ctx.Err()
|
||||
case <-timer.C:
|
||||
return nil
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,88 @@
|
||||
package action
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
pwin "zerorigin/internal/platform/windows"
|
||||
)
|
||||
|
||||
func init() {
|
||||
// 单例:alternate 模式的往返方向状态必须跨执行保持
|
||||
//(引擎每次执行都通过工厂获取实例,非单例会丢失状态)。
|
||||
Register("switch_virtual_desktop", func() Action { return switchDesktopShared })
|
||||
}
|
||||
|
||||
// switchDesktopShared 为共享的切换桌面动作实例。
|
||||
var switchDesktopShared = &switchDesktopAction{}
|
||||
|
||||
// switchDesktopAction 切换虚拟桌面。
|
||||
// mode: alternate(往返)/ left / right。
|
||||
// method: com(默认,COM 直调,无快捷键依赖)/ taskview(Win+Tab 导航)/ hotkey(Win+Ctrl+方向键,
|
||||
// 仅当系统快捷键未被占用时可用)。com 失败时自动回退 taskview。
|
||||
type switchDesktopAction struct {
|
||||
mu sync.Mutex
|
||||
next int32 // alternate 模式下上次切换方向,用于往返
|
||||
}
|
||||
|
||||
func (a *switchDesktopAction) ID() string { return "switch_virtual_desktop" }
|
||||
func (a *switchDesktopAction) Name() string { return "切换虚拟桌面" }
|
||||
|
||||
func (a *switchDesktopAction) Schema() ActionSchema {
|
||||
return ActionSchema{Params: []ParamSpec{
|
||||
{Name: "mode", Type: "string", Required: true, Default: "alternate"},
|
||||
{Name: "method", Type: "string", Required: false, Default: "com"},
|
||||
{Name: "taskview_delay_ms", Type: "int", Required: false, Default: 400},
|
||||
}}
|
||||
}
|
||||
|
||||
func (a *switchDesktopAction) Validate(params map[string]any) error {
|
||||
mode := GetString(params, "mode")
|
||||
switch mode {
|
||||
case "alternate", "left", "right":
|
||||
default:
|
||||
return fmt.Errorf("switch_virtual_desktop: invalid mode %q (want alternate|left|right)", mode)
|
||||
}
|
||||
method := GetString(params, "method")
|
||||
switch method {
|
||||
case "", "com", "taskview", "hotkey":
|
||||
default:
|
||||
return fmt.Errorf("switch_virtual_desktop: invalid method %q (want com|taskview|hotkey)", method)
|
||||
}
|
||||
if d := GetInt(params, "taskview_delay_ms"); d < 0 {
|
||||
return fmt.Errorf("switch_virtual_desktop: taskview_delay_ms must be >= 0")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (a *switchDesktopAction) Execute(ctx context.Context, params map[string]any) error {
|
||||
mode := GetString(params, "mode")
|
||||
var dir int32
|
||||
switch mode {
|
||||
case "left":
|
||||
dir = -1
|
||||
case "right":
|
||||
dir = 1
|
||||
default: // alternate
|
||||
a.mu.Lock()
|
||||
dir = a.next
|
||||
if dir == 0 {
|
||||
dir = 1 // 首次默认向右
|
||||
}
|
||||
a.next = -dir
|
||||
a.mu.Unlock()
|
||||
}
|
||||
switch GetString(params, "method") {
|
||||
case "hotkey":
|
||||
return pwin.SwitchVirtualDesktop(dir)
|
||||
case "taskview":
|
||||
return pwin.SwitchDesktopViaTaskView(dir, time.Duration(GetInt(params, "taskview_delay_ms"))*time.Millisecond)
|
||||
default: // com:COM 直调,失败回退 taskview
|
||||
if err := pwin.SwitchDesktopCOM(dir); err == nil {
|
||||
return nil
|
||||
}
|
||||
return pwin.SwitchDesktopViaTaskView(dir, time.Duration(GetInt(params, "taskview_delay_ms"))*time.Millisecond)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,65 @@
|
||||
package action
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"os"
|
||||
|
||||
pwin "zerorigin/internal/platform/windows"
|
||||
)
|
||||
|
||||
func init() {
|
||||
Register("launch_application", func() Action { return &launchAction{} })
|
||||
}
|
||||
|
||||
// launchAction 启动指定程序。
|
||||
// 安全约束(架构文档 §9.2):路径必须为绝对路径且文件存在;
|
||||
// 不使用 shell 拼接;结果与错误均记录,不记录敏感参数。
|
||||
type launchAction struct{}
|
||||
|
||||
func (a *launchAction) ID() string { return "launch_application" }
|
||||
func (a *launchAction) Name() string { return "启动程序" }
|
||||
|
||||
func (a *launchAction) Schema() ActionSchema {
|
||||
return ActionSchema{Params: []ParamSpec{
|
||||
{Name: "path", Type: "string", Required: true},
|
||||
{Name: "args", Type: "string", Required: false, Default: ""},
|
||||
}}
|
||||
}
|
||||
|
||||
func (a *launchAction) Validate(params map[string]any) error {
|
||||
path := GetString(params, "path")
|
||||
if path == "" {
|
||||
return fmt.Errorf("launch_application: missing param \"path\"")
|
||||
}
|
||||
if !filepathIsAbs(path) {
|
||||
return fmt.Errorf("launch_application: path must be absolute: %q", path)
|
||||
}
|
||||
fi, err := os.Stat(path)
|
||||
if err != nil {
|
||||
return fmt.Errorf("launch_application: %q: %v", path, err)
|
||||
}
|
||||
if fi.IsDir() {
|
||||
return fmt.Errorf("launch_application: %q is a directory, want executable", path)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (a *launchAction) Execute(ctx context.Context, params map[string]any) error {
|
||||
path := GetString(params, "path")
|
||||
args := GetString(params, "args")
|
||||
return pwin.OpenPathWithArgs(path, args)
|
||||
}
|
||||
|
||||
// filepathIsAbs 判断路径是否绝对路径(避免引入 filepath 包仅为此一处)。
|
||||
func filepathIsAbs(p string) bool {
|
||||
if len(p) >= 2 {
|
||||
if p[1] == ':' && (p[0] >= 'A' && p[0] <= 'Z' || p[0] >= 'a' && p[0] <= 'z') {
|
||||
return true // C:\... / c:\...
|
||||
}
|
||||
if p[0] == '\\' && p[1] == '\\' {
|
||||
return true // \\server\share
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
package action
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
|
||||
pwin "zerorigin/internal/platform/windows"
|
||||
)
|
||||
|
||||
func init() {
|
||||
Register("show_notification", func() Action { return ¬ificationAction{} })
|
||||
}
|
||||
|
||||
// notificationAction 显示系统托盘气泡通知。
|
||||
type notificationAction struct{}
|
||||
|
||||
func (a *notificationAction) ID() string { return "show_notification" }
|
||||
func (a *notificationAction) Name() string { return "显示通知" }
|
||||
|
||||
func (a *notificationAction) Schema() ActionSchema {
|
||||
return ActionSchema{Params: []ParamSpec{
|
||||
{Name: "title", Type: "string", Required: true},
|
||||
{Name: "text", Type: "string", Required: true},
|
||||
}}
|
||||
}
|
||||
|
||||
func (a *notificationAction) Validate(params map[string]any) error {
|
||||
if GetString(params, "title") == "" {
|
||||
return fmt.Errorf("show_notification: missing param \"title\"")
|
||||
}
|
||||
if GetString(params, "text") == "" {
|
||||
return fmt.Errorf("show_notification: missing param \"text\"")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (a *notificationAction) Execute(ctx context.Context, params map[string]any) error {
|
||||
return pwin.ShowBalloon(GetString(params, "title"), GetString(params, "text"))
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
package action
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"net/url"
|
||||
"strings"
|
||||
|
||||
pwin "zerorigin/internal/platform/windows"
|
||||
)
|
||||
|
||||
func init() {
|
||||
Register("open_url", func() Action { return &openURLAction{} })
|
||||
}
|
||||
|
||||
// openURLAction 用系统默认浏览器打开 URL。
|
||||
type openURLAction struct{}
|
||||
|
||||
func (a *openURLAction) ID() string { return "open_url" }
|
||||
func (a *openURLAction) Name() string { return "打开链接" }
|
||||
|
||||
func (a *openURLAction) Schema() ActionSchema {
|
||||
return ActionSchema{Params: []ParamSpec{
|
||||
{Name: "url", Type: "string", Required: true},
|
||||
}}
|
||||
}
|
||||
|
||||
func (a *openURLAction) Validate(params map[string]any) error {
|
||||
raw := GetString(params, "url")
|
||||
if raw == "" {
|
||||
return fmt.Errorf("open_url: missing param \"url\"")
|
||||
}
|
||||
u, err := url.Parse(raw)
|
||||
if err != nil {
|
||||
return fmt.Errorf("open_url: invalid url: %v", err)
|
||||
}
|
||||
// 仅允许 http/https,避免被用作本地文件/协议注入。
|
||||
switch strings.ToLower(u.Scheme) {
|
||||
case "http", "https":
|
||||
default:
|
||||
return fmt.Errorf("open_url: unsupported scheme %q (want http/https)", u.Scheme)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (a *openURLAction) Execute(ctx context.Context, params map[string]any) error {
|
||||
return pwin.OpenPath(GetString(params, "url"))
|
||||
}
|
||||
@@ -0,0 +1,195 @@
|
||||
package action
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
pwin "zerorigin/internal/platform/windows"
|
||||
)
|
||||
|
||||
func init() {
|
||||
Register("volume_up", func() Action { return &volumeStepAction{dir: 1} })
|
||||
Register("volume_down", func() Action { return &volumeStepAction{dir: -1} })
|
||||
Register("toggle_mute", func() Action { return &muteAction{} })
|
||||
}
|
||||
|
||||
// volumeStepAction 音量步进。
|
||||
// steps: 百分比步进(默认 1 = ±1%)。
|
||||
// method: media(默认,SendInput 媒体键 VK_VOLUME_UP/DOWN,由系统 Shell 处理:
|
||||
//
|
||||
// Win11 显示完整 OSD(设备名+滑块+数字+应用入口)且立即生效)/
|
||||
//
|
||||
// com(IAudioEndpointVolume 直调,精确百分比,但 OSD 简化、个别设备无效)/
|
||||
// hotkey(media 的别名,兼容旧配置)。
|
||||
//
|
||||
// 背景:COM 直调返回 S_OK 且读回验证通过,但 Win11 音频服务未将其视为
|
||||
// "系统级音量调节"→ OSD 简化为最小版,且若默认端点与应用实际聆听设备
|
||||
// 不一致则听感无变化。媒体键走系统 Shell 路径,无此问题。
|
||||
type volumeStepAction struct {
|
||||
dir int32
|
||||
}
|
||||
|
||||
func (a *volumeStepAction) ID() string {
|
||||
if a.dir > 0 {
|
||||
return "volume_up"
|
||||
}
|
||||
return "volume_down"
|
||||
}
|
||||
func (a *volumeStepAction) Name() string {
|
||||
if a.dir > 0 {
|
||||
return "音量增大"
|
||||
}
|
||||
return "音量减小"
|
||||
}
|
||||
|
||||
func (a *volumeStepAction) Schema() ActionSchema {
|
||||
return ActionSchema{Params: []ParamSpec{
|
||||
{Name: "steps", Type: "int", Required: false, Default: 1},
|
||||
{Name: "method", Type: "string", Required: false, Default: "media"},
|
||||
}}
|
||||
}
|
||||
|
||||
func (a *volumeStepAction) Validate(params map[string]any) error {
|
||||
if steps := GetInt(params, "steps"); steps < 0 {
|
||||
return fmt.Errorf("volume: steps must be >= 0")
|
||||
}
|
||||
// 校验原始值(不能先归一化:否则非法值会被 volumeMethod 兜底成 media 而漏检)。
|
||||
switch GetString(params, "method") {
|
||||
case "", "media", "com", "hotkey":
|
||||
default:
|
||||
return fmt.Errorf("volume: invalid method %q (want media|com|hotkey)", GetString(params, "method"))
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (a *volumeStepAction) Execute(ctx context.Context, params map[string]any) error {
|
||||
steps := GetInt(params, "steps")
|
||||
if steps <= 0 {
|
||||
steps = 1
|
||||
}
|
||||
delta := a.dir * int32(steps)
|
||||
if volumeMethod(GetString(params, "method")) == "com" {
|
||||
// COM 直调(精确百分比,用户显式选择);失败时记录原因并回退媒体键。
|
||||
if err := pwin.VolumeAdjustPercent(delta); err == nil {
|
||||
// 诊断读回:确认程序视角下音量确实变化(区分"程序没改到"与"改的不是聆听设备")。
|
||||
if after, err2 := pwin.GetMasterVolumePercent(); err2 == nil {
|
||||
logger.Debug("volume adjusted", "action", a.ID(), "after_percent", after)
|
||||
notifyVolume(after, volumeStepKind(a.dir))
|
||||
}
|
||||
return nil
|
||||
} else {
|
||||
logger.Warn("volume COM failed, falling back to media key", "action", a.ID(), "err", err)
|
||||
}
|
||||
}
|
||||
// 媒体键路径(默认):由系统 Shell 处理 → 完整 OSD + 立即生效。
|
||||
n := volumeStepCount(delta)
|
||||
for i := 0; i < n; i++ {
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return ctx.Err()
|
||||
default:
|
||||
}
|
||||
if err := pwin.VolumeStep(delta); err != nil {
|
||||
return err
|
||||
}
|
||||
// 连续按键留出间隔,避免系统吞掉相邻的相同按键事件。
|
||||
if i < n-1 {
|
||||
time.Sleep(30 * time.Millisecond)
|
||||
}
|
||||
}
|
||||
// 调节成功后弹出系统 Toast 显示当前音量(带去抖,见 volumeToastDebounce.go)。
|
||||
// 媒体键由系统 Shell 异步应用,稍候再读回,避免 Toast 显示切换前的旧值。
|
||||
time.Sleep(60 * time.Millisecond)
|
||||
if after, err := pwin.GetMasterVolumePercent(); err == nil {
|
||||
notifyVolume(after, volumeStepKind(a.dir))
|
||||
} else {
|
||||
logger.Debug("volume toast: read volume failed", "err", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// volumeStepKind 返回音量调节方向标签(供 Toast 内容使用)。
|
||||
func volumeStepKind(dir int32) string {
|
||||
if dir > 0 {
|
||||
return "up"
|
||||
}
|
||||
return "down"
|
||||
}
|
||||
|
||||
// muteAction 静音切换。
|
||||
type muteAction struct{}
|
||||
|
||||
func (a *muteAction) ID() string { return "toggle_mute" }
|
||||
func (a *muteAction) Name() string { return "静音切换" }
|
||||
|
||||
func (a *muteAction) Schema() ActionSchema {
|
||||
return ActionSchema{Params: []ParamSpec{
|
||||
{Name: "method", Type: "string", Required: false, Default: "media"},
|
||||
}}
|
||||
}
|
||||
|
||||
func (a *muteAction) Validate(params map[string]any) error {
|
||||
switch GetString(params, "method") {
|
||||
case "", "media", "com", "hotkey":
|
||||
return nil
|
||||
}
|
||||
return fmt.Errorf("toggle_mute: invalid method %q (want media|com|hotkey)", GetString(params, "method"))
|
||||
}
|
||||
|
||||
func (a *muteAction) Execute(ctx context.Context, params map[string]any) error {
|
||||
if volumeMethod(GetString(params, "method")) == "com" {
|
||||
// COM 直调(精确,用户显式选择);失败时记录原因并回退媒体键。
|
||||
if err := pwin.ToggleMuteCOM(); err == nil {
|
||||
notifyMuteResult()
|
||||
return nil
|
||||
} else {
|
||||
logger.Warn("mute COM failed, falling back to media key", "err", err)
|
||||
}
|
||||
}
|
||||
if err := pwin.VolumeMute(); err != nil {
|
||||
return err
|
||||
}
|
||||
notifyMuteResult()
|
||||
return nil
|
||||
}
|
||||
|
||||
// notifyMuteResult 读回当前静音状态并弹出系统 Toast(去抖由 notifyVolume 处理)。
|
||||
// 媒体键由 Shell 异步处理,先短暂等待再读回,避免读到切换前状态。
|
||||
func notifyMuteResult() {
|
||||
time.Sleep(80 * time.Millisecond)
|
||||
for i := 0; i < 3; i++ {
|
||||
muted, err := pwin.GetMuteState()
|
||||
if err == nil {
|
||||
if muted {
|
||||
notifyVolume(0, "mute")
|
||||
} else {
|
||||
notifyVolume(0, "unmute")
|
||||
}
|
||||
return
|
||||
}
|
||||
time.Sleep(40 * time.Millisecond)
|
||||
}
|
||||
logger.Debug("volume toast: read mute state failed")
|
||||
notifyVolume(0, "mute_unknown")
|
||||
}
|
||||
|
||||
// volumeMethod 归一化 method 参数:""(默认)→ media;hotkey 是 media 的别名。
|
||||
// 非法值同样归一化为 media(Validate 会先行拦截,此处仅为兜底)。
|
||||
func volumeMethod(raw string) string {
|
||||
switch raw {
|
||||
case "", "media", "hotkey":
|
||||
return "media"
|
||||
case "com":
|
||||
return "com"
|
||||
}
|
||||
return "media"
|
||||
}
|
||||
|
||||
// volumeStepCount 返回媒体键路径需要发送的按键次数(delta 的绝对值)。
|
||||
func volumeStepCount(delta int32) int {
|
||||
if delta < 0 {
|
||||
return int(-delta)
|
||||
}
|
||||
return int(delta)
|
||||
}
|
||||
@@ -0,0 +1,106 @@
|
||||
package action
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"runtime"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
pwin "zerorigin/internal/platform/windows"
|
||||
)
|
||||
|
||||
// 音量 Toast 去抖实现:快速连按时合并为最后一次显示,
|
||||
// 避免 Win11 系统 OSD 数字太小/消失太快时 Toast 弹窗闪烁。
|
||||
//
|
||||
// 行为(默认窗口 500ms):
|
||||
// - 首次调用 → 启动计时器,记录待显示内容;
|
||||
// - 窗口内再次调用 → 取消旧计时器,更新待显示内容,重启计时器;
|
||||
// - 计时器到期 → 只显示合并后的最终内容(最后一次的状态)。
|
||||
//
|
||||
// 因此单次按键会在 ~500ms 后弹一个 Toast;连按 5 次只在最后一次后
|
||||
// 500ms 弹 1 个 Toast。
|
||||
|
||||
// volumeToastDebounceWindow 音量 Toast 去抖窗口(测试可替换)。
|
||||
var volumeToastDebounceWindow = 500 * time.Millisecond
|
||||
|
||||
const (
|
||||
// volumeToastTitle 音量调节 Toast 标题。
|
||||
volumeToastTitle = "音量调节"
|
||||
// volumeToastMuteTitle 静音 Toast 标题。
|
||||
volumeToastMuteTitle = "静音"
|
||||
)
|
||||
|
||||
// showBalloonFunc 底层系统通知函数(变量便于测试注入替换)。
|
||||
var showBalloonFunc = pwin.ShowBalloon
|
||||
|
||||
// toastContent 待显示的 Toast 内容。
|
||||
type toastContent struct {
|
||||
title string
|
||||
text string
|
||||
}
|
||||
|
||||
var (
|
||||
toastMu sync.Mutex
|
||||
toastTimer *time.Timer
|
||||
toastNext *toastContent
|
||||
)
|
||||
|
||||
// notifyVolume 在音量/静音动作成功后显示系统 Toast(默认 500ms 去抖合并)。
|
||||
// level: 调节后的音量百分比(仅 up/down 使用;静音动作传 0,文本不依赖 level)。
|
||||
// kind: up | down | mute | unmute | mute_unknown。
|
||||
func notifyVolume(level int, kind string) {
|
||||
var title, text string
|
||||
switch kind {
|
||||
case "up", "down":
|
||||
title, text = volumeToastTitle, fmt.Sprintf("音量: %d%%", level)
|
||||
case "mute":
|
||||
title, text = volumeToastMuteTitle, "已静音"
|
||||
case "unmute":
|
||||
title, text = volumeToastMuteTitle, "未静音"
|
||||
default:
|
||||
title, text = volumeToastMuteTitle, "静音已切换"
|
||||
}
|
||||
scheduleToast(title, text)
|
||||
}
|
||||
|
||||
// scheduleToast 去抖调度:窗口内多次调用只显示最后一次内容。
|
||||
func scheduleToast(title, text string) {
|
||||
toastMu.Lock()
|
||||
defer toastMu.Unlock()
|
||||
|
||||
toastNext = &toastContent{title: title, text: text}
|
||||
if toastTimer != nil {
|
||||
toastTimer.Stop()
|
||||
}
|
||||
toastTimer = time.AfterFunc(volumeToastDebounceWindow, flushToast)
|
||||
}
|
||||
|
||||
// flushToast 计时器到期:显示合并后的最终内容并清空待显示状态。
|
||||
// ⚠️ 运行在 time.AfterFunc 的 goroutine 中,无上层 recover:
|
||||
// panic 会直接拖垮整个进程(Go panic 崩溃不产生任何系统记录)。
|
||||
// 因此这里必须兜底:recover 后记录崩溃到 crash.log,不中断进程。
|
||||
func flushToast() {
|
||||
defer func() {
|
||||
if r := recover(); r != nil {
|
||||
pwin.LogGoPanic("volumeToast.flushToast", r, debugStackBuf())
|
||||
}
|
||||
}()
|
||||
toastMu.Lock()
|
||||
next := toastNext
|
||||
toastNext = nil
|
||||
toastMu.Unlock()
|
||||
|
||||
if next == nil {
|
||||
return
|
||||
}
|
||||
if err := showBalloonFunc(next.title, next.text); err != nil {
|
||||
logger.Warn("volume toast failed", "err", err)
|
||||
}
|
||||
}
|
||||
|
||||
// debugStackBuf 返回当前 goroutine 堆栈(崩溃取证用)。
|
||||
func debugStackBuf() []byte {
|
||||
buf := make([]byte, 32<<10)
|
||||
n := runtime.Stack(buf, false)
|
||||
return buf[:n]
|
||||
}
|
||||
@@ -0,0 +1,139 @@
|
||||
package action
|
||||
|
||||
import (
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
// resetToastForTest 清空去抖状态,避免测试间相互影响。
|
||||
func resetToastForTest() {
|
||||
toastMu.Lock()
|
||||
defer toastMu.Unlock()
|
||||
if toastTimer != nil {
|
||||
toastTimer.Stop()
|
||||
toastTimer = nil
|
||||
}
|
||||
toastNext = nil
|
||||
}
|
||||
|
||||
// swapToastForTest 替换去抖窗口与底层通知函数,返回还原函数。
|
||||
func swapToastForTest(window time.Duration, fn func(title, text string) error) func() {
|
||||
oldWindow := volumeToastDebounceWindow
|
||||
oldFunc := showBalloonFunc
|
||||
volumeToastDebounceWindow = window
|
||||
showBalloonFunc = fn
|
||||
return func() {
|
||||
volumeToastDebounceWindow = oldWindow
|
||||
showBalloonFunc = oldFunc
|
||||
}
|
||||
}
|
||||
|
||||
// TestVolumeToastDebounce 验证去抖:窗口内 5 次调用只触发 1 次底层通知,
|
||||
// 且显示的是最后一次(合并后)的内容;窗口之外的新调用再触发 1 次。
|
||||
func TestVolumeToastDebounce(t *testing.T) {
|
||||
var (
|
||||
mu sync.Mutex
|
||||
calls int
|
||||
gotText string
|
||||
)
|
||||
restore := swapToastForTest(30*time.Millisecond, func(title, text string) error {
|
||||
mu.Lock()
|
||||
calls++
|
||||
gotText = text
|
||||
mu.Unlock()
|
||||
return nil
|
||||
})
|
||||
defer restore()
|
||||
resetToastForTest()
|
||||
defer resetToastForTest()
|
||||
|
||||
// 瞬间连按 5 次(远小于 30ms 窗口,必然合并为 1 次)。
|
||||
for i := 0; i < 5; i++ {
|
||||
notifyVolume(40+i, "up")
|
||||
}
|
||||
|
||||
// 等待远超窗口,合并后的最后一次触发应只发生一次。
|
||||
time.Sleep(150 * time.Millisecond)
|
||||
mu.Lock()
|
||||
if calls != 1 {
|
||||
mu.Unlock()
|
||||
t.Fatalf("5 calls within window -> %d underlying calls, want 1", calls)
|
||||
}
|
||||
if gotText != "音量: 44%" {
|
||||
t.Errorf("merged text = %q, want %q", gotText, "音量: 44%")
|
||||
}
|
||||
mu.Unlock()
|
||||
|
||||
// 窗口之外的新一轮调用应再次触发一次(且不被上一轮干扰)。
|
||||
notifyVolume(50, "down")
|
||||
time.Sleep(150 * time.Millisecond)
|
||||
mu.Lock()
|
||||
if calls != 2 {
|
||||
mu.Unlock()
|
||||
t.Fatalf("second round should trigger 1 more call, got %d total", calls)
|
||||
}
|
||||
mu.Unlock()
|
||||
}
|
||||
|
||||
// TestVolumeToastText 验证音量调节 Toast 文本格式("音量: 40%")。
|
||||
func TestVolumeToastText(t *testing.T) {
|
||||
var (
|
||||
mu sync.Mutex
|
||||
gotTitle string
|
||||
gotText string
|
||||
)
|
||||
restore := swapToastForTest(10*time.Millisecond, func(title, text string) error {
|
||||
mu.Lock()
|
||||
gotTitle, gotText = title, text
|
||||
mu.Unlock()
|
||||
return nil
|
||||
})
|
||||
defer restore()
|
||||
resetToastForTest()
|
||||
defer resetToastForTest()
|
||||
|
||||
notifyVolume(40, "up")
|
||||
time.Sleep(80 * time.Millisecond)
|
||||
mu.Lock()
|
||||
defer mu.Unlock()
|
||||
if gotText != "音量: 40%" {
|
||||
t.Errorf("volume up text = %q, want %q", gotText, "音量: 40%")
|
||||
}
|
||||
if gotTitle != volumeToastTitle {
|
||||
t.Errorf("volume up title = %q, want %q", gotTitle, volumeToastTitle)
|
||||
}
|
||||
}
|
||||
|
||||
// TestVolumeToastMuteText 验证静音 Toast 文本("已静音"/"未静音")。
|
||||
func TestVolumeToastMuteText(t *testing.T) {
|
||||
var (
|
||||
mu sync.Mutex
|
||||
gotText string
|
||||
)
|
||||
restore := swapToastForTest(10*time.Millisecond, func(title, text string) error {
|
||||
mu.Lock()
|
||||
gotText = text
|
||||
mu.Unlock()
|
||||
return nil
|
||||
})
|
||||
defer restore()
|
||||
resetToastForTest()
|
||||
defer resetToastForTest()
|
||||
|
||||
notifyVolume(0, "mute")
|
||||
time.Sleep(80 * time.Millisecond)
|
||||
mu.Lock()
|
||||
if gotText != "已静音" {
|
||||
t.Errorf("mute text = %q, want %q", gotText, "已静音")
|
||||
}
|
||||
mu.Unlock()
|
||||
|
||||
notifyVolume(0, "unmute")
|
||||
time.Sleep(80 * time.Millisecond)
|
||||
mu.Lock()
|
||||
if gotText != "未静音" {
|
||||
t.Errorf("unmute text = %q, want %q", gotText, "未静音")
|
||||
}
|
||||
mu.Unlock()
|
||||
}
|
||||
@@ -0,0 +1,73 @@
|
||||
package action
|
||||
|
||||
import "testing"
|
||||
|
||||
// TestVolumeMethodSelection 验证 method 参数归一化与校验:
|
||||
// 默认("")→ media;hotkey 为 media 别名;com 保留为精确选项。
|
||||
func TestVolumeMethodSelection(t *testing.T) {
|
||||
cases := []struct {
|
||||
in string
|
||||
want string
|
||||
}{
|
||||
{"", "media"},
|
||||
{"media", "media"},
|
||||
{"hotkey", "media"},
|
||||
{"com", "com"},
|
||||
{"bogus", "media"}, // Validate 拦截前的兜底
|
||||
}
|
||||
for _, c := range cases {
|
||||
if got := volumeMethod(c.in); got != c.want {
|
||||
t.Errorf("volumeMethod(%q) = %q, want %q", c.in, got, c.want)
|
||||
}
|
||||
}
|
||||
|
||||
for _, id := range []string{"volume_up", "volume_down", "toggle_mute"} {
|
||||
a, err := New(id)
|
||||
if err != nil {
|
||||
t.Fatalf("New(%q): %v", id, err)
|
||||
}
|
||||
for _, m := range []string{"", "media", "com", "hotkey"} {
|
||||
if err := a.Validate(map[string]any{"method": m}); err != nil {
|
||||
t.Errorf("%s method %q should pass: %v", id, m, err)
|
||||
}
|
||||
}
|
||||
if err := a.Validate(map[string]any{"method": "cli"}); err == nil {
|
||||
t.Errorf("%s invalid method should fail", id)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// TestVolumeStepCount 验证媒体键路径按键次数 = |delta|。
|
||||
func TestVolumeStepCount(t *testing.T) {
|
||||
cases := []struct {
|
||||
delta int32
|
||||
want int
|
||||
}{
|
||||
{1, 1},
|
||||
{3, 3},
|
||||
{-1, 1},
|
||||
{-5, 5},
|
||||
{0, 0},
|
||||
}
|
||||
for _, c := range cases {
|
||||
if got := volumeStepCount(c.delta); got != c.want {
|
||||
t.Errorf("volumeStepCount(%d) = %d, want %d", c.delta, got, c.want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// TestVolumeSchemaDefaultMedia 回归:schema 默认值必须为 media(方案A的落点)。
|
||||
func TestVolumeSchemaDefaultMedia(t *testing.T) {
|
||||
up, _ := New("volume_up")
|
||||
for _, p := range up.Schema().Params {
|
||||
if p.Name == "method" && p.Default != "media" {
|
||||
t.Errorf("volume_up method default = %v, want media", p.Default)
|
||||
}
|
||||
}
|
||||
mu, _ := New("toggle_mute")
|
||||
for _, p := range mu.Schema().Params {
|
||||
if p.Name == "method" && p.Default != "media" {
|
||||
t.Errorf("toggle_mute method default = %v, want media", p.Default)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,211 @@
|
||||
// Package app 负责主进程运行时组装与生命周期管理。
|
||||
// 阶段 3:单实例 → 配置 → 规则引擎 → 触发器(去重)→ 托盘 → 优雅退出。
|
||||
package app
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"log/slog"
|
||||
"os"
|
||||
"os/exec"
|
||||
"path/filepath"
|
||||
"syscall"
|
||||
"time"
|
||||
|
||||
"zerorigin/internal/action"
|
||||
"zerorigin/internal/config"
|
||||
"zerorigin/internal/logging"
|
||||
"zerorigin/internal/platform/windows"
|
||||
"zerorigin/internal/rule"
|
||||
"zerorigin/internal/tray"
|
||||
"zerorigin/internal/trigger"
|
||||
)
|
||||
|
||||
// Run 组装并运行主进程,阻塞直到托盘退出。返回 nil 表示正常退出。
|
||||
// levelVar 用于在加载配置后按 log_level 调整日志级别。
|
||||
func Run(logger *slog.Logger, levelVar *slog.LevelVar) error {
|
||||
// 0. 崩溃捕获(必须在一切业务初始化之前安装):
|
||||
// 原生异常 → crash.log;Go panic → recover 兜底写 crash.log。
|
||||
appDataDir, _ := config.AppDataDir()
|
||||
windows.InstallCrashGuard(filepath.Join(appDataDir, "logs", "crash.log"))
|
||||
// 心跳 + 内存看门狗:每 5s 写 heartbeat.json(进程消失后精确对齐时间线);
|
||||
// WorkingSet 超 500MB 告警。
|
||||
stopHeartbeat := windows.StartHeartbeat(logger, filepath.Join(appDataDir, "logs"), 5*time.Second, 500)
|
||||
defer stopHeartbeat()
|
||||
|
||||
// 1. 单实例
|
||||
si, err := windows.AcquireSingleInstance()
|
||||
if err != nil {
|
||||
if errors.Is(err, windows.ErrAlreadyRunning) {
|
||||
windows.ShowMessageBox("ZerOriginTool", "ZerOriginTool 已在运行。")
|
||||
}
|
||||
return err
|
||||
}
|
||||
defer si.Release()
|
||||
logger.Info("single instance acquired")
|
||||
|
||||
// 0.5 监督进程:主进程异常死亡时由 watchdog -supervise 自动重启(常驻保障)。
|
||||
// 监督进程自身有单实例互斥,重复启动无副作用;缺失时静默跳过。
|
||||
spawnSupervisor(logger)
|
||||
|
||||
// 2. 配置:损坏/版本不可迁移时自动恢复默认并继续运行。
|
||||
cfg, err := config.Load()
|
||||
if err != nil {
|
||||
if errors.Is(err, config.ErrCorrupted) || errors.Is(err, config.ErrUnsupportedVersion) {
|
||||
logger.Warn("config recovered to default", "err", err)
|
||||
} else {
|
||||
return err
|
||||
}
|
||||
}
|
||||
logger.Info("config loaded", "version", cfg.Version, "rules", len(cfg.Rules), "enabled", cfg.Global.Enabled)
|
||||
levelVar.Set(logging.ParseLevel(cfg.Global.LogLevel))
|
||||
|
||||
// 3. 规则引擎:先于触发器就绪,保证事件不丢失。
|
||||
engine := rule.New(logger, action.New)
|
||||
trigger.SetLogger(logger)
|
||||
action.SetLogger(logger)
|
||||
windows.SetNotifyLogger(logger)
|
||||
// 全屏抑制:前台全屏窗口时默认忽略规则(allow 规则豁免)。
|
||||
fsWatcher := windows.NewFullscreenWatcher()
|
||||
fsWatcher.Start()
|
||||
engine.SetFullscreenProvider(fsWatcher.IsFullscreen)
|
||||
snap := rule.BuildSnapshot(cfg, action.New)
|
||||
engine.SetSnapshot(snap)
|
||||
logger.Info("rules loaded", "active", len(snap.Rules), "bad", snap.BadCount)
|
||||
|
||||
// 3.1 配置热重载:文件变更 → 重新加载 → 校验 → 原子替换快照。
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
defer cancel()
|
||||
configPath, _ := config.Path()
|
||||
go config.Watch(ctx, configPath, time.Second, func() {
|
||||
reloaded, err := config.Load()
|
||||
if err != nil {
|
||||
logger.Warn("config reload skipped", "err", err) // 保留旧快照
|
||||
return
|
||||
}
|
||||
ns := rule.BuildSnapshot(reloaded, action.New)
|
||||
engine.SetSnapshot(ns)
|
||||
logger.Info("config reloaded", "active", len(ns.Rules), "bad", ns.BadCount)
|
||||
})
|
||||
|
||||
// 4. 触发器:按 (type + params) 去重实例化,事件汇入引擎。
|
||||
started := make(map[string]trigger.Trigger)
|
||||
for _, r := range snap.Rules {
|
||||
if !r.Enabled {
|
||||
continue // 禁用规则不启动触发器
|
||||
}
|
||||
key := rule.TriggerKey(r.Trigger)
|
||||
if _, ok := started[key]; ok {
|
||||
continue
|
||||
}
|
||||
tr, err := trigger.New(r.Trigger.Type, r.Trigger.Params)
|
||||
if err != nil {
|
||||
logger.Error("trigger instantiate failed", "type", r.Trigger.Type, "err", err)
|
||||
continue
|
||||
}
|
||||
if err := tr.Start(ctx, func(ev trigger.Event) { engine.HandleEvent(ev) }); err != nil {
|
||||
logger.Error("trigger start failed", "type", r.Trigger.Type, "err", err)
|
||||
continue
|
||||
}
|
||||
started[key] = tr
|
||||
logger.Info("trigger started", "type", r.Trigger.Type)
|
||||
}
|
||||
if len(started) == 0 {
|
||||
logger.Warn("no triggers started; check rule configuration")
|
||||
}
|
||||
|
||||
// 5. 托盘(阻塞直到退出)。
|
||||
tray.Run(tray.Callbacks{
|
||||
OnQuit: func() {},
|
||||
OnOpenSettings: func() { openSettings(logger) },
|
||||
OnOpenConfigFile: func() { _ = windows.OpenPath(configPath) },
|
||||
OnOpenConfigDir: func() { _ = windows.OpenPath(appDataDir) },
|
||||
AutoStart: windows.IsAutoStartEnabled(),
|
||||
OnToggleEnabled: func(enabled bool) bool {
|
||||
// 持久化到配置并立即替换快照(不等待热重载轮询)。
|
||||
reloaded, err := config.Load()
|
||||
if err != nil {
|
||||
logger.Warn("toggle enabled: load config failed", "err", err)
|
||||
return false
|
||||
}
|
||||
reloaded.Global.Enabled = enabled
|
||||
if err := config.Save(configPath, reloaded); err != nil {
|
||||
logger.Warn("toggle enabled: save failed", "err", err)
|
||||
return false
|
||||
}
|
||||
ns := rule.BuildSnapshot(reloaded, action.New)
|
||||
engine.SetSnapshot(ns)
|
||||
logger.Info("global enabled updated", "enabled", enabled)
|
||||
return true
|
||||
},
|
||||
OnToggleAutoStart: func(enabled bool) bool {
|
||||
if err := windows.SetAutoStart(enabled); err != nil {
|
||||
logger.Warn("toggle auto start failed", "enabled", enabled, "err", err)
|
||||
return false
|
||||
}
|
||||
return true
|
||||
},
|
||||
}, logger, func() {
|
||||
// 优雅退出:先停事件流,再卸载钩子,最后等动作链结束。
|
||||
cancel()
|
||||
fsWatcher.Stop()
|
||||
for _, tr := range started {
|
||||
if err := tr.Stop(); err != nil {
|
||||
logger.Warn("trigger stop failed", "type", tr.ID(), "err", err)
|
||||
}
|
||||
}
|
||||
engine.Wait()
|
||||
logger.Info("runtime stopped", "triggers", len(started))
|
||||
})
|
||||
logger.Info("application exited")
|
||||
return nil
|
||||
}
|
||||
|
||||
// settingsExeName 为设置进程可执行文件名(与主进程同目录)。
|
||||
const settingsExeName = "ZerOriginTool-Settings.exe"
|
||||
|
||||
// watchdogExeName 为监督进程可执行文件名(与主进程同目录)。
|
||||
const watchdogExeName = "watchdog.exe"
|
||||
|
||||
// createNoWindow 为 CreateProcess 的 CREATE_NO_WINDOW 标志:分离启动不闪控制台。
|
||||
const createNoWindow = 0x08000000
|
||||
|
||||
// spawnSupervisor 启动监督进程(watchdog -supervise):主进程异常死亡时自动重启。
|
||||
// 监督进程有单实例互斥,重复启动会被其自身静默丢弃;exe 缺失时静默跳过。
|
||||
func spawnSupervisor(logger *slog.Logger) {
|
||||
exe, err := os.Executable()
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
wd := filepath.Join(filepath.Dir(exe), watchdogExeName)
|
||||
if _, err := os.Stat(wd); err != nil {
|
||||
return
|
||||
}
|
||||
cmd := exec.Command(wd, "-supervise")
|
||||
cmd.SysProcAttr = &syscall.SysProcAttr{CreationFlags: createNoWindow}
|
||||
if err := cmd.Start(); err != nil {
|
||||
logger.Warn("supervisor start failed", "err", err)
|
||||
return
|
||||
}
|
||||
_ = cmd.Process.Release()
|
||||
logger.Info("supervisor started", "path", wd)
|
||||
}
|
||||
|
||||
// openSettings 启动设置进程。查找与主进程同目录的 Settings.exe;
|
||||
// 缺失或启动失败时提示(架构文档 §8.1:设置进程缺失/启动失败必须有明确提示)。
|
||||
func openSettings(logger *slog.Logger) {
|
||||
exe, err := os.Executable()
|
||||
if err != nil {
|
||||
logger.Error("open settings: resolve exe path", "err", err)
|
||||
return
|
||||
}
|
||||
settingsPath := filepath.Join(filepath.Dir(exe), settingsExeName)
|
||||
if _, err := os.Stat(settingsPath); err != nil {
|
||||
windows.ShowMessageBox("ZerOriginTool", "未找到设置程序(ZerOriginTool-Settings.exe)。\n请确认它与主程序放在同一目录。")
|
||||
return
|
||||
}
|
||||
if err := windows.OpenPath(settingsPath); err != nil {
|
||||
logger.Error("open settings failed", "err", err)
|
||||
windows.ShowMessageBox("ZerOriginTool", "启动设置程序失败。\n\n"+err.Error())
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,290 @@
|
||||
// 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
|
||||
}
|
||||
@@ -0,0 +1,99 @@
|
||||
package config
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"testing"
|
||||
)
|
||||
|
||||
// TestDefaultConfig 验证默认配置包含两条内置规则且字段正确。
|
||||
func TestDefaultConfig(t *testing.T) {
|
||||
cfg := Default()
|
||||
if cfg.Version != 1 {
|
||||
t.Fatalf("version = %d, want 1", cfg.Version)
|
||||
}
|
||||
if !cfg.Global.Enabled {
|
||||
t.Fatal("global.enabled should be true")
|
||||
}
|
||||
if len(cfg.Rules) != 4 {
|
||||
t.Fatalf("rules = %d, want 4", len(cfg.Rules))
|
||||
}
|
||||
r0 := cfg.Rules[0]
|
||||
if r0.ID != "desktop-left-bottom" || r0.Trigger.Type != "mouse_corner" {
|
||||
t.Fatalf("rule 0 unexpected: %+v", r0)
|
||||
}
|
||||
if len(r0.Actions) != 1 || r0.Actions[0].Type != "switch_virtual_desktop" {
|
||||
t.Fatalf("rule 0 actions unexpected: %+v", r0.Actions)
|
||||
}
|
||||
if r0.CooldownMs != 800 {
|
||||
t.Fatalf("rule 0 cooldown = %d, want 800", r0.CooldownMs)
|
||||
}
|
||||
// 音量规则按方向分流(up/down 各一条,动作不互相抵消)
|
||||
r1, r2 := cfg.Rules[1], cfg.Rules[2]
|
||||
if r1.Trigger.Params["direction"] != "up" || r1.Actions[0].Type != "volume_up" {
|
||||
t.Fatalf("rule 1 unexpected: %+v", r1)
|
||||
}
|
||||
if r2.Trigger.Params["direction"] != "down" || r2.Actions[0].Type != "volume_down" {
|
||||
t.Fatalf("rule 2 unexpected: %+v", r2)
|
||||
}
|
||||
if len(r1.Actions) != 1 || len(r2.Actions) != 1 {
|
||||
t.Fatalf("volume rules should have exactly 1 action each")
|
||||
}
|
||||
// 示例 hotkey 规则默认关闭
|
||||
if r3 := cfg.Rules[3]; r3.ID != "hotkey-switch-desktop" || r3.Enabled || r3.Trigger.Type != "hotkey" {
|
||||
t.Fatalf("rule 3 unexpected: %+v", r3)
|
||||
}
|
||||
}
|
||||
|
||||
// TestTriggerConfigFlatJSON 验证扁平 JSON 被拆分为 Type + Params。
|
||||
func TestTriggerConfigFlatJSON(t *testing.T) {
|
||||
var tc TriggerConfig
|
||||
if err := json.Unmarshal([]byte(`{"type":"mouse_corner","corner":"bottom_left","screen":"all","threshold_px":8}`), &tc); err != nil {
|
||||
t.Fatalf("unmarshal: %v", err)
|
||||
}
|
||||
if tc.Type != "mouse_corner" {
|
||||
t.Fatalf("type = %q, want mouse_corner", tc.Type)
|
||||
}
|
||||
if got := tc.Params["corner"]; got != "bottom_left" {
|
||||
t.Fatalf("corner = %v, want bottom_left", got)
|
||||
}
|
||||
if got := tc.Params["threshold_px"]; got != float64(8) {
|
||||
t.Fatalf("threshold_px = %v, want 8", got)
|
||||
}
|
||||
if _, ok := tc.Params["type"]; ok {
|
||||
t.Fatal("type should not remain in Params")
|
||||
}
|
||||
}
|
||||
|
||||
// TestTriggerConfigMissingType 验证缺 type 时 Unmarshal 不报错但 Type 为空。
|
||||
func TestTriggerConfigMissingType(t *testing.T) {
|
||||
var tc TriggerConfig
|
||||
if err := json.Unmarshal([]byte(`{"corner":"top_left"}`), &tc); err != nil {
|
||||
t.Fatalf("unmarshal: %v", err)
|
||||
}
|
||||
if tc.Type != "" {
|
||||
t.Fatalf("type = %q, want empty", tc.Type)
|
||||
}
|
||||
if len(tc.Params) != 1 {
|
||||
t.Fatalf("params = %v, want 1 entry", tc.Params)
|
||||
}
|
||||
}
|
||||
|
||||
// TestTriggerConfigRoundTrip 验证扁平 JSON 往返对称(Marshal 不丢参数)。
|
||||
func TestTriggerConfigRoundTrip(t *testing.T) {
|
||||
src := `{"type":"mouse_corner","corner":"bottom_left","screen":"all","threshold_px":8}`
|
||||
var tc TriggerConfig
|
||||
if err := json.Unmarshal([]byte(src), &tc); err != nil {
|
||||
t.Fatalf("unmarshal: %v", err)
|
||||
}
|
||||
out, err := json.Marshal(&tc)
|
||||
if err != nil {
|
||||
t.Fatalf("marshal: %v", err)
|
||||
}
|
||||
var back TriggerConfig
|
||||
if err := json.Unmarshal(out, &back); err != nil {
|
||||
t.Fatalf("unmarshal round trip: %v", err)
|
||||
}
|
||||
if back.Type != "mouse_corner" || back.Params["corner"] != "bottom_left" || back.Params["screen"] != "all" {
|
||||
t.Fatalf("round trip lost data: %s -> %s", src, out)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
package config
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"sync"
|
||||
)
|
||||
|
||||
// Migration 将配置从 from 版本迁移到 from+1。
|
||||
// 迁移必须可测试,失败时调用方负责备份与默认恢复。
|
||||
type Migration func(cfg *Config) (*Config, error)
|
||||
|
||||
var (
|
||||
migrationsMu sync.RWMutex
|
||||
migrations = map[int]Migration{}
|
||||
)
|
||||
|
||||
// RegisterMigration 注册从版本 from 到 from+1 的迁移。
|
||||
// 重复注册同一版本会 panic(编程错误)。
|
||||
func RegisterMigration(from int, m Migration) {
|
||||
migrationsMu.Lock()
|
||||
defer migrationsMu.Unlock()
|
||||
if _, ok := migrations[from]; ok {
|
||||
panic(fmt.Sprintf("migration from version %d already registered", from))
|
||||
}
|
||||
migrations[from] = m
|
||||
}
|
||||
|
||||
// migrate 将配置逐级迁移到 CurrentVersion;未来版本视为不可迁移。
|
||||
func migrate(cfg *Config) (*Config, error) {
|
||||
if cfg.Version > CurrentVersion {
|
||||
return nil, fmt.Errorf("config version %d is newer than supported %d", cfg.Version, CurrentVersion)
|
||||
}
|
||||
for cfg.Version < CurrentVersion {
|
||||
migrationsMu.RLock()
|
||||
m, ok := migrations[cfg.Version]
|
||||
migrationsMu.RUnlock()
|
||||
if !ok {
|
||||
return nil, fmt.Errorf("no migration from version %d to %d", cfg.Version, CurrentVersion)
|
||||
}
|
||||
next, err := m(cfg)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("migrate v%d: %w", cfg.Version, err)
|
||||
}
|
||||
cfg = next
|
||||
}
|
||||
return cfg, nil
|
||||
}
|
||||
@@ -0,0 +1,174 @@
|
||||
package config
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
// tmpConfig 创建临时配置文件并返回路径。
|
||||
func tmpConfig(t *testing.T, content string) string {
|
||||
t.Helper()
|
||||
dir := t.TempDir()
|
||||
p := filepath.Join(dir, "config.json")
|
||||
if content != "" {
|
||||
if err := os.WriteFile(p, []byte(content), 0o644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
return p
|
||||
}
|
||||
|
||||
func TestLoadCreatesDefaultWhenMissing(t *testing.T) {
|
||||
p := tmpConfig(t, "")
|
||||
cfg, err := loadAt(p)
|
||||
if err != nil {
|
||||
t.Fatalf("load: %v", err)
|
||||
}
|
||||
if len(cfg.Rules) != 4 {
|
||||
t.Fatalf("rules = %d, want 4", len(cfg.Rules))
|
||||
}
|
||||
if _, err := os.Stat(p); err != nil {
|
||||
t.Fatalf("default config not written: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestLoadCorruptedRecoversWithBackup(t *testing.T) {
|
||||
p := tmpConfig(t, `{"version": 1, "this is not valid json`)
|
||||
cfg, err := loadAt(p)
|
||||
if !errors.Is(err, ErrCorrupted) {
|
||||
t.Fatalf("err = %v, want ErrCorrupted", err)
|
||||
}
|
||||
if cfg == nil || len(cfg.Rules) != 4 {
|
||||
t.Fatalf("should recover to default config, got %+v", cfg)
|
||||
}
|
||||
if _, err := os.Stat(p + ".bak"); err != nil {
|
||||
t.Fatalf("backup file missing: %v", err)
|
||||
}
|
||||
// 原文件应被默认配置替换(可再次解析)
|
||||
if _, err := loadAt(p); err != nil {
|
||||
t.Fatalf("recovered config should load cleanly: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestLoadOversizeRecovers(t *testing.T) {
|
||||
big := `{"version":1,"rules":[]}` + strings.Repeat(" ", MaxConfigSize+1)
|
||||
p := tmpConfig(t, big)
|
||||
cfg, err := loadAt(p)
|
||||
if !errors.Is(err, ErrCorrupted) {
|
||||
t.Fatalf("err = %v, want ErrCorrupted", err)
|
||||
}
|
||||
if cfg == nil {
|
||||
t.Fatal("nil config")
|
||||
}
|
||||
}
|
||||
|
||||
func TestSaveAtomic(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
p := filepath.Join(dir, "config.json")
|
||||
cfg := Default()
|
||||
if err := Save(p, cfg); err != nil {
|
||||
t.Fatalf("save: %v", err)
|
||||
}
|
||||
loaded, err := loadAt(p)
|
||||
if err != nil {
|
||||
t.Fatalf("load saved: %v", err)
|
||||
}
|
||||
if loaded.Version != 1 || len(loaded.Rules) != 4 {
|
||||
t.Fatalf("saved content wrong: %+v", loaded)
|
||||
}
|
||||
// 无临时文件残留
|
||||
entries, _ := os.ReadDir(dir)
|
||||
for _, e := range entries {
|
||||
if strings.Contains(e.Name(), ".tmp") {
|
||||
t.Fatalf("temp file left behind: %s", e.Name())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestSaveFailureDoesNotBreakOldConfig(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
p := filepath.Join(dir, "config.json")
|
||||
cfg := Default()
|
||||
if err := Save(p, cfg); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
before, _ := os.ReadFile(p)
|
||||
// 保存到非法路径(父目录不存在且无法创建为文件):使用目录作为目标
|
||||
badPath := filepath.Join(dir, "sub", "nested", "config.json")
|
||||
// 用同名文件占位目录:先创建目录结构使 Save 的 MkdirAll 成功但 Rename 到目录失败
|
||||
if err := os.MkdirAll(badPath, 0o755); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := Save(badPath, cfg); err == nil {
|
||||
t.Fatal("save to directory should fail")
|
||||
}
|
||||
after, _ := os.ReadFile(p)
|
||||
if string(before) != string(after) {
|
||||
t.Fatal("old config was modified by failed save")
|
||||
}
|
||||
}
|
||||
|
||||
func TestMigrationFramework(t *testing.T) {
|
||||
RegisterMigration(0, func(cfg *Config) (*Config, error) {
|
||||
cfg.Version = 1
|
||||
return cfg, nil
|
||||
})
|
||||
p := tmpConfig(t, `{"version":0,"global":{"enabled":true,"theme":"system","log_level":"info"},"rules":[]}`)
|
||||
cfg, err := loadAt(p)
|
||||
if err != nil {
|
||||
t.Fatalf("load with migration: %v", err)
|
||||
}
|
||||
if cfg.Version != 1 {
|
||||
t.Fatalf("version = %d, want 1 after migration", cfg.Version)
|
||||
}
|
||||
// 迁移结果应已保存
|
||||
data, _ := os.ReadFile(p)
|
||||
if !strings.Contains(string(data), `"version": 1`) {
|
||||
t.Fatalf("migrated config not persisted: %s", data)
|
||||
}
|
||||
}
|
||||
|
||||
func TestMigrationUnsupportedRecovers(t *testing.T) {
|
||||
p := tmpConfig(t, `{"version":99,"rules":[]}`)
|
||||
_, err := loadAt(p)
|
||||
if !errors.Is(err, ErrUnsupportedVersion) {
|
||||
t.Fatalf("err = %v, want ErrUnsupportedVersion", err)
|
||||
}
|
||||
if _, err := os.Stat(p + ".bak"); err != nil {
|
||||
t.Fatalf("backup missing: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestWatchDetectsChange(t *testing.T) {
|
||||
p := tmpConfig(t, `{"version":1,"rules":[]}`)
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
defer cancel()
|
||||
|
||||
var mu, calls int
|
||||
done := make(chan struct{})
|
||||
onChange := func() {
|
||||
mu++
|
||||
calls = mu
|
||||
select {
|
||||
case done <- struct{}{}:
|
||||
default:
|
||||
}
|
||||
}
|
||||
go Watch(ctx, p, 30*time.Millisecond, onChange)
|
||||
|
||||
time.Sleep(80 * time.Millisecond) // 基线建立
|
||||
os.WriteFile(p, []byte(`{"version":1,"rules":[]}`), 0o644)
|
||||
select {
|
||||
case <-done:
|
||||
case <-time.After(2 * time.Second):
|
||||
t.Fatal("onChange not called after file modification")
|
||||
}
|
||||
if calls < 1 {
|
||||
t.Fatalf("calls = %d, want >= 1", calls)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
package config
|
||||
|
||||
import (
|
||||
"context"
|
||||
"os"
|
||||
"time"
|
||||
)
|
||||
|
||||
// Watch 轮询配置文件变更(mtime + size),变化时调用 onChange。
|
||||
// 首次扫描只记录基线不回调;onChange 在独立 goroutine 中执行。
|
||||
// 文件暂时不可见(如编辑器替换写入窗口)时跳过本轮。
|
||||
func Watch(ctx context.Context, path string, interval time.Duration, onChange func()) {
|
||||
var lastMod time.Time
|
||||
var lastSize int64
|
||||
initialized := false
|
||||
|
||||
ticker := time.NewTicker(interval)
|
||||
defer ticker.Stop()
|
||||
for {
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return
|
||||
case <-ticker.C:
|
||||
fi, err := os.Stat(path)
|
||||
if err != nil {
|
||||
continue // 文件不可见:跳过
|
||||
}
|
||||
if !initialized {
|
||||
lastMod, lastSize = fi.ModTime(), fi.Size()
|
||||
initialized = true
|
||||
continue
|
||||
}
|
||||
if fi.ModTime() != lastMod || fi.Size() != lastSize {
|
||||
lastMod, lastSize = fi.ModTime(), fi.Size()
|
||||
onChange()
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,73 @@
|
||||
// Package logging 初始化 slog 日志,输出到
|
||||
// %LOCALAPPDATA%\ZerOriginTool\logs\app.log。
|
||||
// 文件超过 5MB 时在启动时轮转为 app.log.old。
|
||||
package logging
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"io"
|
||||
"log/slog"
|
||||
"os"
|
||||
"path/filepath"
|
||||
)
|
||||
|
||||
const (
|
||||
// MaxLogSize 为单文件日志大小上限(5MB)。
|
||||
MaxLogSize = 5 << 20
|
||||
logDir = "logs"
|
||||
logFile = "app.log"
|
||||
)
|
||||
|
||||
// Init 初始化日志并返回 logger。level 通过 *slog.LevelVar 动态可调(对应配置 log_level)。
|
||||
// 高频事件路径不得逐条调用该 logger,必须采样或计数后聚合记录。
|
||||
func Init(appDataDir string, level *slog.LevelVar) (*slog.Logger, error) {
|
||||
dir := filepath.Join(appDataDir, logDir)
|
||||
if err := os.MkdirAll(dir, 0o755); err != nil {
|
||||
return nil, fmt.Errorf("create log dir: %w", err)
|
||||
}
|
||||
path := filepath.Join(dir, logFile)
|
||||
if err := rotateIfNeeded(path); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
f, err := os.OpenFile(path, os.O_CREATE|os.O_APPEND|os.O_WRONLY, 0o644)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("open log file: %w", err)
|
||||
}
|
||||
// 只写文件:主进程为托盘常驻程序,无控制台输出。
|
||||
h := slog.NewTextHandler(io.Writer(f), &slog.HandlerOptions{Level: level})
|
||||
return slog.New(h), nil
|
||||
}
|
||||
|
||||
// ParseLevel 将配置中的 log_level 字符串解析为 slog 级别。
|
||||
// 无法识别时返回 Info 级别(保守默认)。
|
||||
func ParseLevel(s string) slog.Level {
|
||||
switch s {
|
||||
case "debug":
|
||||
return slog.LevelDebug
|
||||
case "warn":
|
||||
return slog.LevelWarn
|
||||
case "error":
|
||||
return slog.LevelError
|
||||
default:
|
||||
return slog.LevelInfo
|
||||
}
|
||||
}
|
||||
|
||||
// rotateIfNeeded 在文件超过大小上限时将其重命名为 .old(覆盖旧轮转文件)。
|
||||
// 重命名失败不致命:仅记录到 stderr,继续使用原文件。
|
||||
func rotateIfNeeded(path string) error {
|
||||
fi, err := os.Stat(path)
|
||||
if err != nil {
|
||||
if os.IsNotExist(err) {
|
||||
return nil
|
||||
}
|
||||
return fmt.Errorf("stat log file: %w", err)
|
||||
}
|
||||
if fi.Size() <= MaxLogSize {
|
||||
return nil
|
||||
}
|
||||
if err := os.Rename(path, path+".old"); err != nil {
|
||||
fmt.Fprintf(os.Stderr, "rotate log: %v\n", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,236 @@
|
||||
/*
|
||||
Package systray is a cross-platform Go library to place an icon and menu in the notification area.
|
||||
*/
|
||||
package systray
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"runtime"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
|
||||
"github.com/getlantern/golog"
|
||||
)
|
||||
|
||||
var (
|
||||
log = golog.LoggerFor("systray")
|
||||
|
||||
systrayReady func()
|
||||
systrayExit func()
|
||||
menuItems = make(map[uint32]*MenuItem)
|
||||
menuItemsLock sync.RWMutex
|
||||
|
||||
currentID = uint32(0)
|
||||
quitOnce sync.Once
|
||||
)
|
||||
|
||||
func init() {
|
||||
runtime.LockOSThread()
|
||||
}
|
||||
|
||||
// MenuItem is used to keep track each menu item of systray.
|
||||
// Don't create it directly, use the one systray.AddMenuItem() returned
|
||||
type MenuItem struct {
|
||||
// ClickedCh is the channel which will be notified when the menu item is clicked
|
||||
ClickedCh chan struct{}
|
||||
|
||||
// id uniquely identify a menu item, not supposed to be modified
|
||||
id uint32
|
||||
// title is the text shown on menu item
|
||||
title string
|
||||
// tooltip is the text shown when pointing to menu item
|
||||
tooltip string
|
||||
// disabled menu item is grayed out and has no effect when clicked
|
||||
disabled bool
|
||||
// checked menu item has a tick before the title
|
||||
checked bool
|
||||
// has the menu item a checkbox (Linux)
|
||||
isCheckable bool
|
||||
// parent item, for sub menus
|
||||
parent *MenuItem
|
||||
}
|
||||
|
||||
func (item *MenuItem) String() string {
|
||||
if item.parent == nil {
|
||||
return fmt.Sprintf("MenuItem[%d, %q]", item.id, item.title)
|
||||
}
|
||||
return fmt.Sprintf("MenuItem[%d, parent %d, %q]", item.id, item.parent.id, item.title)
|
||||
}
|
||||
|
||||
// newMenuItem returns a populated MenuItem object
|
||||
func newMenuItem(title string, tooltip string, parent *MenuItem) *MenuItem {
|
||||
return &MenuItem{
|
||||
ClickedCh: make(chan struct{}),
|
||||
id: atomic.AddUint32(¤tID, 1),
|
||||
title: title,
|
||||
tooltip: tooltip,
|
||||
disabled: false,
|
||||
checked: false,
|
||||
isCheckable: false,
|
||||
parent: parent,
|
||||
}
|
||||
}
|
||||
|
||||
// Run initializes GUI and starts the event loop, then invokes the onReady
|
||||
// callback. It blocks until systray.Quit() is called.
|
||||
func Run(onReady func(), onExit func()) {
|
||||
Register(onReady, onExit)
|
||||
nativeLoop()
|
||||
}
|
||||
|
||||
// Register initializes GUI and registers the callbacks but relies on the
|
||||
// caller to run the event loop somewhere else. It's useful if the program
|
||||
// needs to show other UI elements, for example, webview.
|
||||
// To overcome some OS weirdness, On macOS versions before Catalina, calling
|
||||
// this does exactly the same as Run().
|
||||
func Register(onReady func(), onExit func()) {
|
||||
if onReady == nil {
|
||||
systrayReady = func() {}
|
||||
} else {
|
||||
// Run onReady on separate goroutine to avoid blocking event loop
|
||||
readyCh := make(chan interface{})
|
||||
go func() {
|
||||
<-readyCh
|
||||
onReady()
|
||||
}()
|
||||
systrayReady = func() {
|
||||
close(readyCh)
|
||||
}
|
||||
}
|
||||
// unlike onReady, onExit runs in the event loop to make sure it has time to
|
||||
// finish before the process terminates
|
||||
if onExit == nil {
|
||||
onExit = func() {}
|
||||
}
|
||||
systrayExit = onExit
|
||||
registerSystray()
|
||||
}
|
||||
|
||||
// Quit the systray
|
||||
func Quit() {
|
||||
quitOnce.Do(quit)
|
||||
}
|
||||
|
||||
// AddMenuItem adds a menu item with the designated title and tooltip.
|
||||
// It can be safely invoked from different goroutines.
|
||||
// Created menu items are checkable on Windows and OSX by default. For Linux you have to use AddMenuItemCheckbox
|
||||
func AddMenuItem(title string, tooltip string) *MenuItem {
|
||||
item := newMenuItem(title, tooltip, nil)
|
||||
item.update()
|
||||
return item
|
||||
}
|
||||
|
||||
// AddMenuItemCheckbox adds a menu item with the designated title and tooltip and a checkbox for Linux.
|
||||
// It can be safely invoked from different goroutines.
|
||||
// On Windows and OSX this is the same as calling AddMenuItem
|
||||
func AddMenuItemCheckbox(title string, tooltip string, checked bool) *MenuItem {
|
||||
item := newMenuItem(title, tooltip, nil)
|
||||
item.isCheckable = true
|
||||
item.checked = checked
|
||||
item.update()
|
||||
return item
|
||||
}
|
||||
|
||||
// AddSeparator adds a separator bar to the menu
|
||||
func AddSeparator() {
|
||||
addSeparator(atomic.AddUint32(¤tID, 1))
|
||||
}
|
||||
|
||||
// AddSubMenuItem adds a nested sub-menu item with the designated title and tooltip.
|
||||
// It can be safely invoked from different goroutines.
|
||||
// Created menu items are checkable on Windows and OSX by default. For Linux you have to use AddSubMenuItemCheckbox
|
||||
func (item *MenuItem) AddSubMenuItem(title string, tooltip string) *MenuItem {
|
||||
child := newMenuItem(title, tooltip, item)
|
||||
child.update()
|
||||
return child
|
||||
}
|
||||
|
||||
// AddSubMenuItemCheckbox adds a nested sub-menu item with the designated title and tooltip and a checkbox for Linux.
|
||||
// It can be safely invoked from different goroutines.
|
||||
// On Windows and OSX this is the same as calling AddSubMenuItem
|
||||
func (item *MenuItem) AddSubMenuItemCheckbox(title string, tooltip string, checked bool) *MenuItem {
|
||||
child := newMenuItem(title, tooltip, item)
|
||||
child.isCheckable = true
|
||||
child.checked = checked
|
||||
child.update()
|
||||
return child
|
||||
}
|
||||
|
||||
// SetTitle set the text to display on a menu item
|
||||
func (item *MenuItem) SetTitle(title string) {
|
||||
item.title = title
|
||||
item.update()
|
||||
}
|
||||
|
||||
// SetTooltip set the tooltip to show when mouse hover
|
||||
func (item *MenuItem) SetTooltip(tooltip string) {
|
||||
item.tooltip = tooltip
|
||||
item.update()
|
||||
}
|
||||
|
||||
// Disabled checks if the menu item is disabled
|
||||
func (item *MenuItem) Disabled() bool {
|
||||
return item.disabled
|
||||
}
|
||||
|
||||
// Enable a menu item regardless if it's previously enabled or not
|
||||
func (item *MenuItem) Enable() {
|
||||
item.disabled = false
|
||||
item.update()
|
||||
}
|
||||
|
||||
// Disable a menu item regardless if it's previously disabled or not
|
||||
func (item *MenuItem) Disable() {
|
||||
item.disabled = true
|
||||
item.update()
|
||||
}
|
||||
|
||||
// Hide hides a menu item
|
||||
func (item *MenuItem) Hide() {
|
||||
hideMenuItem(item)
|
||||
}
|
||||
|
||||
// Show shows a previously hidden menu item
|
||||
func (item *MenuItem) Show() {
|
||||
showMenuItem(item)
|
||||
}
|
||||
|
||||
// Checked returns if the menu item has a check mark
|
||||
func (item *MenuItem) Checked() bool {
|
||||
return item.checked
|
||||
}
|
||||
|
||||
// Check a menu item regardless if it's previously checked or not
|
||||
func (item *MenuItem) Check() {
|
||||
item.checked = true
|
||||
item.update()
|
||||
}
|
||||
|
||||
// Uncheck a menu item regardless if it's previously unchecked or not
|
||||
func (item *MenuItem) Uncheck() {
|
||||
item.checked = false
|
||||
item.update()
|
||||
}
|
||||
|
||||
// update propagates changes on a menu item to systray
|
||||
func (item *MenuItem) update() {
|
||||
menuItemsLock.Lock()
|
||||
menuItems[item.id] = item
|
||||
menuItemsLock.Unlock()
|
||||
addOrUpdateMenuItem(item)
|
||||
}
|
||||
|
||||
func systrayMenuItemSelected(id uint32) {
|
||||
menuItemsLock.RLock()
|
||||
item, ok := menuItems[id]
|
||||
menuItemsLock.RUnlock()
|
||||
if !ok {
|
||||
log.Errorf("No menu item with ID %v", id)
|
||||
return
|
||||
}
|
||||
select {
|
||||
case item.ClickedCh <- struct{}{}:
|
||||
// in case no one waiting for the channel
|
||||
default:
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,107 @@
|
||||
// +build !windows
|
||||
// go:build !windows
|
||||
|
||||
package systray
|
||||
|
||||
// #include "systray.h"
|
||||
import "C"
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"unsafe"
|
||||
)
|
||||
|
||||
func registerSystray() {
|
||||
C.registerSystray()
|
||||
}
|
||||
|
||||
func nativeLoop() {
|
||||
C.nativeLoop()
|
||||
}
|
||||
|
||||
func quit() {
|
||||
C.quit()
|
||||
}
|
||||
|
||||
// SetIcon sets the systray icon.
|
||||
// iconBytes should be the content of .ico for windows and .ico/.jpg/.png
|
||||
// for other platforms.
|
||||
func SetIcon(iconBytes []byte) {
|
||||
cstr := (*C.char)(unsafe.Pointer(&iconBytes[0]))
|
||||
C.setIcon(cstr, (C.int)(len(iconBytes)), false)
|
||||
}
|
||||
|
||||
// SetTitle sets the systray title, only available on Mac and Linux.
|
||||
func SetTitle(title string) {
|
||||
C.setTitle(C.CString(title))
|
||||
}
|
||||
|
||||
// SetTooltip sets the systray tooltip to display on mouse hover of the tray icon,
|
||||
// only available on Mac and Windows.
|
||||
func SetTooltip(tooltip string) {
|
||||
C.setTooltip(C.CString(tooltip))
|
||||
}
|
||||
|
||||
// SetBalloon 仅 Windows 支持,其他平台返回错误。
|
||||
func SetBalloon(title, text string) error {
|
||||
return errors.New("SetBalloon: only supported on Windows")
|
||||
}
|
||||
|
||||
func addOrUpdateMenuItem(item *MenuItem) {
|
||||
var disabled C.short
|
||||
if item.disabled {
|
||||
disabled = 1
|
||||
}
|
||||
var checked C.short
|
||||
if item.checked {
|
||||
checked = 1
|
||||
}
|
||||
var isCheckable C.short
|
||||
if item.isCheckable {
|
||||
isCheckable = 1
|
||||
}
|
||||
var parentID uint32 = 0
|
||||
if item.parent != nil {
|
||||
parentID = item.parent.id
|
||||
}
|
||||
C.add_or_update_menu_item(
|
||||
C.int(item.id),
|
||||
C.int(parentID),
|
||||
C.CString(item.title),
|
||||
C.CString(item.tooltip),
|
||||
disabled,
|
||||
checked,
|
||||
isCheckable,
|
||||
)
|
||||
}
|
||||
|
||||
func addSeparator(id uint32) {
|
||||
C.add_separator(C.int(id))
|
||||
}
|
||||
|
||||
func hideMenuItem(item *MenuItem) {
|
||||
C.hide_menu_item(
|
||||
C.int(item.id),
|
||||
)
|
||||
}
|
||||
|
||||
func showMenuItem(item *MenuItem) {
|
||||
C.show_menu_item(
|
||||
C.int(item.id),
|
||||
)
|
||||
}
|
||||
|
||||
//export systray_ready
|
||||
func systray_ready() {
|
||||
systrayReady()
|
||||
}
|
||||
|
||||
//export systray_on_exit
|
||||
func systray_on_exit() {
|
||||
systrayExit()
|
||||
}
|
||||
|
||||
//export systray_menu_item_selected
|
||||
func systray_menu_item_selected(cID C.int) {
|
||||
systrayMenuItemSelected(uint32(cID))
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,51 @@
|
||||
package windows
|
||||
|
||||
import (
|
||||
"os"
|
||||
|
||||
"golang.org/x/sys/windows/registry"
|
||||
)
|
||||
|
||||
// 开机自启:写入当前用户的 Run 注册表项(不修改 HKLM,架构文档 §9.1 约束)。
|
||||
|
||||
const (
|
||||
autoStartKey = `Software\Microsoft\Windows\CurrentVersion\Run`
|
||||
autoStartValue = "ZerOriginTool"
|
||||
)
|
||||
|
||||
// IsAutoStartEnabled 报告开机自启是否已启用。
|
||||
func IsAutoStartEnabled() bool {
|
||||
k, err := registry.OpenKey(registry.CURRENT_USER, autoStartKey, registry.QUERY_VALUE)
|
||||
if err != nil {
|
||||
return false
|
||||
}
|
||||
defer k.Close()
|
||||
_, _, err = k.GetStringValue(autoStartValue)
|
||||
return err == nil
|
||||
}
|
||||
|
||||
// SetAutoStart 启用/禁用开机自启。使用 exe 的绝对路径。
|
||||
func SetAutoStart(enabled bool) error {
|
||||
if !enabled {
|
||||
return disableAutoStart()
|
||||
}
|
||||
exe, err := os.Executable()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
k, err := registry.OpenKey(registry.CURRENT_USER, autoStartKey, registry.SET_VALUE)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer k.Close()
|
||||
return k.SetStringValue(autoStartValue, exe)
|
||||
}
|
||||
|
||||
func disableAutoStart() error {
|
||||
k, err := registry.OpenKey(registry.CURRENT_USER, autoStartKey, registry.SET_VALUE)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer k.Close()
|
||||
return k.DeleteValue(autoStartValue)
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
package windows
|
||||
|
||||
import (
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
// TestBenchSwitchDesktopCOM 测量 SwitchDesktopCOM 单次耗时(诊断用,非断言)。
|
||||
func TestBenchSwitchDesktopCOM(t *testing.T) {
|
||||
procCoInitializeEx.Call(0, coinitMultithreaded)
|
||||
defer procCoUninitialize.Call()
|
||||
|
||||
ids0, _, err := queryDesktopState()
|
||||
if err != nil || len(ids0) < 2 {
|
||||
t.Skipf("need >= 2 desktops: %v", err)
|
||||
}
|
||||
for i := 0; i < 3; i++ {
|
||||
s := time.Now()
|
||||
if err := SwitchDesktopCOM(1); err != nil {
|
||||
t.Fatalf("switch: %v", err)
|
||||
}
|
||||
t.Logf("SwitchDesktopCOM(1) 第%d次耗时: %v", i+1, time.Since(s))
|
||||
time.Sleep(200 * time.Millisecond)
|
||||
s = time.Now()
|
||||
if err := SwitchDesktopCOM(-1); err != nil {
|
||||
t.Fatalf("switch back: %v", err)
|
||||
}
|
||||
t.Logf("SwitchDesktopCOM(-1) 第%d次耗时: %v", i+1, time.Since(s))
|
||||
time.Sleep(200 * time.Millisecond)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,90 @@
|
||||
package windows
|
||||
|
||||
import (
|
||||
"golang.org/x/sys/windows"
|
||||
)
|
||||
|
||||
// MonitorRect 为单个显示器的虚拟屏幕矩形(主显示器左上角为原点)。
|
||||
type MonitorRect struct {
|
||||
Left, Top, Right, Bottom int32
|
||||
}
|
||||
|
||||
// MonitorRects 枚举所有显示器(含多显示器)的屏幕矩形。
|
||||
func MonitorRects() ([]MonitorRect, error) {
|
||||
var rects []MonitorRect
|
||||
err := enumDisplayMonitors(func(r rect) bool {
|
||||
rects = append(rects, MonitorRect{Left: r.Left, Top: r.Top, Right: r.Right, Bottom: r.Bottom})
|
||||
return true
|
||||
})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if len(rects) == 0 {
|
||||
return nil, windows.ERROR_NO_MORE_ITEMS
|
||||
}
|
||||
return rects, nil
|
||||
}
|
||||
|
||||
// PrimaryMonitorRect 返回主显示器矩形(原点在 (0,0))。
|
||||
func PrimaryMonitorRect() MonitorRect {
|
||||
return MonitorRect{
|
||||
Left: 0,
|
||||
Top: 0,
|
||||
Right: getSystemMetrics(0), // SM_CXSCREEN
|
||||
Bottom: getSystemMetrics(1), // SM_CYSCREEN
|
||||
}
|
||||
}
|
||||
|
||||
// CornerHit 判定点 (x, y) 是否落在任一屏幕的指定角落阈值区域内。
|
||||
// corner 取值:top_left / top_right / bottom_left / bottom_right。
|
||||
// 纯函数,便于单元测试。
|
||||
func CornerHit(rects []MonitorRect, x, y, threshold int32, corner string) bool {
|
||||
for _, r := range rects {
|
||||
switch corner {
|
||||
case "top_left":
|
||||
if x >= r.Left && x <= r.Left+threshold && y >= r.Top && y <= r.Top+threshold {
|
||||
return true
|
||||
}
|
||||
case "top_right":
|
||||
if x <= r.Right && x >= r.Right-threshold && y >= r.Top && y <= r.Top+threshold {
|
||||
return true
|
||||
}
|
||||
case "bottom_left":
|
||||
if x >= r.Left && x <= r.Left+threshold && y <= r.Bottom && y >= r.Bottom-threshold {
|
||||
return true
|
||||
}
|
||||
case "bottom_right":
|
||||
if x <= r.Right && x >= r.Right-threshold && y <= r.Bottom && y >= r.Bottom-threshold {
|
||||
return true
|
||||
}
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// EdgeHit 判定点 (x, y) 是否落在任一屏幕的指定边缘阈值区域内。
|
||||
// edge 取值:top / bottom / left / right。
|
||||
// 纯函数,便于单元测试。
|
||||
func EdgeHit(rects []MonitorRect, x, y, threshold int32, edge string) bool {
|
||||
for _, r := range rects {
|
||||
switch edge {
|
||||
case "top":
|
||||
if y >= r.Top && y <= r.Top+threshold && x >= r.Left && x <= r.Right {
|
||||
return true
|
||||
}
|
||||
case "bottom":
|
||||
if y <= r.Bottom && y >= r.Bottom-threshold && x >= r.Left && x <= r.Right {
|
||||
return true
|
||||
}
|
||||
case "left":
|
||||
if x >= r.Left && x <= r.Left+threshold && y >= r.Top && y <= r.Bottom {
|
||||
return true
|
||||
}
|
||||
case "right":
|
||||
if x <= r.Right && x >= r.Right-threshold && y >= r.Top && y <= r.Bottom {
|
||||
return true
|
||||
}
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
@@ -0,0 +1,66 @@
|
||||
package windows
|
||||
|
||||
import "testing"
|
||||
|
||||
// 多显示器场景:主屏 (0,0)-(1920,1080),右侧副屏 (1920,0)-(3840,1080)。
|
||||
var multiRects = []MonitorRect{
|
||||
{Left: 0, Top: 0, Right: 1920, Bottom: 1080},
|
||||
{Left: 1920, Top: 0, Right: 3840, Bottom: 1080},
|
||||
}
|
||||
|
||||
func TestCornerHit(t *testing.T) {
|
||||
cases := []struct {
|
||||
name string
|
||||
x, y int32
|
||||
corner string
|
||||
want bool
|
||||
}{
|
||||
{"主屏左上", 2, 2, "top_left", true},
|
||||
{"主屏左上阈值边界", 8, 8, "top_left", true},
|
||||
{"主屏左上阈值外", 9, 9, "top_left", false},
|
||||
{"主屏右上", 1919, 0, "top_right", true},
|
||||
{"副屏右上", 3839, 0, "top_right", true},
|
||||
{"副屏右下", 3839, 1079, "bottom_right", true},
|
||||
{"副屏左下", 1920, 1079, "bottom_left", true},
|
||||
{"屏幕中间不命中", 960, 540, "bottom_left", false},
|
||||
{"角落匹配错误", 2, 2, "bottom_left", false},
|
||||
}
|
||||
for _, c := range cases {
|
||||
if got := CornerHit(multiRects, c.x, c.y, 8, c.corner); got != c.want {
|
||||
t.Errorf("%s: CornerHit(%d,%d,%s) = %v, want %v", c.name, c.x, c.y, c.corner, got, c.want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestEdgeHit(t *testing.T) {
|
||||
cases := []struct {
|
||||
name string
|
||||
x, y int32
|
||||
edge string
|
||||
want bool
|
||||
}{
|
||||
{"主屏顶部", 500, 3, "top", true},
|
||||
{"副屏顶部", 2000, 7, "top", true},
|
||||
{"顶部阈值外", 500, 100, "top", false},
|
||||
{"主屏左侧", 3, 500, "left", true},
|
||||
{"副屏左侧(与主屏接缝处)", 1920, 500, "left", true},
|
||||
{"主屏底部", 500, 1077, "bottom", true},
|
||||
{"右侧屏右缘", 3839, 500, "right", true},
|
||||
{"屏幕上方之外", 500, -5, "top", false},
|
||||
}
|
||||
for _, c := range cases {
|
||||
if got := EdgeHit(multiRects, c.x, c.y, 8, c.edge); got != c.want {
|
||||
t.Errorf("%s: EdgeHit(%d,%d,%s) = %v, want %v", c.name, c.x, c.y, c.edge, got, c.want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestPrimaryMonitorRect(t *testing.T) {
|
||||
r := PrimaryMonitorRect()
|
||||
if r.Left != 0 || r.Top != 0 {
|
||||
t.Fatalf("primary rect origin = (%d,%d), want (0,0)", r.Left, r.Top)
|
||||
}
|
||||
if r.Right <= 0 || r.Bottom <= 0 {
|
||||
t.Fatalf("primary rect size invalid: %+v", r)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,183 @@
|
||||
package windows
|
||||
|
||||
// crashguard.go — 进程级崩溃捕获(取证)。
|
||||
//
|
||||
// 目标:主进程是托盘常驻程序(-H windowsgui,无控制台)。一旦发生
|
||||
// 未被 recover 的 Go panic,或 C 层原生异常(access violation 等),
|
||||
// 进程会静默消失,无任何证据。本模块提供三道防线:
|
||||
//
|
||||
// 1. AddVectoredExceptionHandler(VEH):捕获原生异常(access violation、
|
||||
// illegal instruction、stack overflow 等),将异常代码/地址写入崩溃日志。
|
||||
// ⚠️ 必须用 VEH 而非 SetUnhandledExceptionFilter:Go runtime 在 Windows
|
||||
// 上会安装自己的异常处理链,SetUnhandledExceptionFilter 可能永不被调用。
|
||||
// 2. crash.log 与 app.log / heartbeat 配合,可在进程消失后判定死因:
|
||||
// 有崩溃记录 → 自身崩溃;无崩溃记录且心跳停止但无 bye → 被外部强杀。
|
||||
// 3. Go panic(runtime panic,不触发 VEH)→ 必须靠各 goroutine 的
|
||||
// defer recover 调用 LogGoPanic 记录(见各调用点)。
|
||||
import (
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
"syscall"
|
||||
"time"
|
||||
"unsafe"
|
||||
)
|
||||
|
||||
var (
|
||||
crashKernel32 = syscall.NewLazyDLL("kernel32.dll")
|
||||
procSetUnhandledExceptionFilter2 = crashKernel32.NewProc("SetUnhandledExceptionFilter")
|
||||
procAddVectoredExceptionHandler = crashKernel32.NewProc("AddVectoredExceptionHandler")
|
||||
procCreateFileW2 = crashKernel32.NewProc("CreateFileW")
|
||||
procWriteFile2 = crashKernel32.NewProc("WriteFile")
|
||||
procCloseHandle2 = crashKernel32.NewProc("CloseHandle")
|
||||
procGetCurrentProcessId2 = crashKernel32.NewProc("GetCurrentProcessId")
|
||||
procSetFilePointer = crashKernel32.NewProc("SetFilePointer")
|
||||
)
|
||||
|
||||
// EXCEPTION_CONTINUE_SEARCH:不吞异常,继续查找处理程序(进程最终退出)。
|
||||
const exceptionContinueSearch = 0x80000001
|
||||
|
||||
// exceptionRecord 对应 EXCEPTION_RECORD(仅取所需字段,保持布局兼容)。
|
||||
type exceptionRecord struct {
|
||||
code uint32
|
||||
flags uint32
|
||||
outerRecord uintptr
|
||||
addr uintptr
|
||||
numParams uint32
|
||||
params [15]uintptr
|
||||
}
|
||||
|
||||
// exceptionPointers 对应 EXCEPTION_POINTERS。
|
||||
type exceptionPointers struct {
|
||||
record *exceptionRecord
|
||||
ctx uintptr
|
||||
}
|
||||
|
||||
var (
|
||||
crashGuardInstalled atomic.Bool
|
||||
crashLogPathVal string
|
||||
crashCallbackPtr uintptr // 回调指针必须保持存活(GC 安全)
|
||||
crashVehPtr uintptr
|
||||
crashMu sync.Mutex
|
||||
)
|
||||
|
||||
// InstallCrashGuard 安装崩溃捕获。logPath 为崩溃日志文件路径
|
||||
// (如 %LOCALAPPDATA%\ZerOriginTool\logs\crash.log)。幂等。
|
||||
func InstallCrashGuard(logPath string) {
|
||||
if crashGuardInstalled.Swap(true) {
|
||||
return
|
||||
}
|
||||
if logPath == "" {
|
||||
return
|
||||
}
|
||||
if err := os.MkdirAll(filepath.Dir(logPath), 0o755); err != nil {
|
||||
return
|
||||
}
|
||||
crashLogPathVal = logPath
|
||||
// VEH(首选):Go runtime 安装自己的异常链会覆盖 SetUnhandledExceptionFilter,
|
||||
// VEH 是链式的、可共存,且先于 SEH 触发。
|
||||
crashVehPtr = syscall.NewCallback(vehHandler)
|
||||
procAddVectoredExceptionHandler.Call(1, crashVehPtr)
|
||||
// SEH 兜底(部分场景仍有效)。
|
||||
crashCallbackPtr = syscall.NewCallback(crashHandler)
|
||||
procSetUnhandledExceptionFilter2.Call(crashCallbackPtr)
|
||||
}
|
||||
|
||||
// vehHandler 为 AddVectoredExceptionHandler 回调(LONG CALLBACK)。
|
||||
// 记录异常后返回 EXCEPTION_CONTINUE_SEARCH,交给后续处理(含 Go runtime 与默认流程)。
|
||||
func vehHandler(ep uintptr) uintptr {
|
||||
defer func() { _ = recover() }() // 尽力而为,绝不让记录动作再次崩溃
|
||||
code := uint32(0)
|
||||
addr := uintptr(0)
|
||||
if ep != 0 {
|
||||
rec := (*exceptionPointers)(unsafe.Pointer(ep))
|
||||
if rec != nil && rec.record != nil {
|
||||
code = rec.record.code
|
||||
addr = rec.record.addr
|
||||
}
|
||||
}
|
||||
// 只记录"会终止进程"的严重异常码,减少 Go runtime 正常处理异常时的噪音。
|
||||
switch code {
|
||||
case 0xC0000005, // access violation
|
||||
0xC000001D, // illegal instruction
|
||||
0xC00000FD, // stack overflow
|
||||
0xC0000096, // privileged instruction
|
||||
0xC0000008, // invalid handle
|
||||
0xC000013A, // ctrl+C (console)
|
||||
0xC0000142, // DLL init failed
|
||||
0xC0000409, // fail fast
|
||||
0xE06D7363: // MSVC C++ exception
|
||||
pid, _, _ := procGetCurrentProcessId2.Call()
|
||||
line := fmt.Sprintf("native-crash code=0x%08X addr=0x%X pid=%d ts=%s\n",
|
||||
code, addr, uint32(pid), time.Now().Format("2006-01-02T15:04:05.000-07:00"))
|
||||
appendCrashLog(line)
|
||||
}
|
||||
return exceptionContinueSearch
|
||||
}
|
||||
|
||||
// crashHandler 为 SetUnhandledExceptionFilter 回调(LONG CALLBACK)。
|
||||
// 记录异常信息后返回 EXCEPTION_CONTINUE_SEARCH,让系统走默认崩溃流程。
|
||||
func crashHandler(ep uintptr) uintptr {
|
||||
defer func() { _ = recover() }() // 尽力而为,绝不让记录动作再次崩溃
|
||||
|
||||
code := uint32(0)
|
||||
addr := uintptr(0)
|
||||
if ep != 0 {
|
||||
rec := (*exceptionPointers)(unsafe.Pointer(ep))
|
||||
if rec != nil && rec.record != nil {
|
||||
code = rec.record.code
|
||||
addr = rec.record.addr
|
||||
}
|
||||
}
|
||||
pid, _, _ := procGetCurrentProcessId2.Call()
|
||||
line := fmt.Sprintf("native-crash code=0x%08X addr=0x%X pid=%d ts=%s\n",
|
||||
code, addr, uint32(pid), time.Now().Format("2006-01-02T15:04:05.000-07:00"))
|
||||
appendCrashLog(line)
|
||||
return exceptionContinueSearch
|
||||
}
|
||||
|
||||
// LogGoPanic 供各 goroutine 的 recover 兜底调用:把 Go panic 信息写入崩溃日志。
|
||||
func LogGoPanic(where string, r any, stack []byte) {
|
||||
defer func() { _ = recover() }()
|
||||
line := fmt.Sprintf("go-panic %s value=%v pid=%d ts=%s\n%s\n",
|
||||
where, r, os.Getpid(), time.Now().Format("2006-01-02T15:04:05.000-07:00"), stack)
|
||||
appendCrashLog(line)
|
||||
}
|
||||
|
||||
// CrashLogPath 返回崩溃日志路径(未安装时为 "")。
|
||||
func CrashLogPath() string {
|
||||
return crashLogPathVal
|
||||
}
|
||||
|
||||
// appendCrashLog 追加一行到崩溃日志(纯 Win32 写入,崩溃线程上避免 Go 文件层)。
|
||||
func appendCrashLog(line string) {
|
||||
crashMu.Lock()
|
||||
defer crashMu.Unlock()
|
||||
if crashLogPathVal == "" {
|
||||
return
|
||||
}
|
||||
p, err := syscall.UTF16PtrFromString(crashLogPathVal)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
// CREATE_ALWAYS(2) | OPEN_ALWAYS(4):使用 OPEN_ALWAYS 追加。
|
||||
h, _, _ := procCreateFileW2.Call(
|
||||
uintptr(unsafe.Pointer(p)),
|
||||
0xC0000000, // GENERIC_READ | GENERIC_WRITE
|
||||
0x00000001, // FILE_SHARE_READ
|
||||
0,
|
||||
0x00000004, // OPEN_ALWAYS
|
||||
0x00000080, // FILE_ATTRIBUTE_NORMAL
|
||||
0)
|
||||
if h == 0 || h == ^uintptr(0) {
|
||||
return
|
||||
}
|
||||
// 定位到文件尾:SetFilePointer 与 GetFileSize 组合。
|
||||
procSetFilePointer.Call(h, 0, 0, 2) // FILE_END
|
||||
b := []byte(line)
|
||||
var written uint32
|
||||
procWriteFile2.Call(h, uintptr(unsafe.Pointer(&b[0])), uintptr(len(b)), uintptr(unsafe.Pointer(&written)), 0)
|
||||
procCloseHandle2.Call(h)
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
package windows
|
||||
|
||||
import (
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
// TestSwitchDesktopCOMCrossGoroutine 模拟真实触发模式:每次切换由
|
||||
// 独立 goroutine(可能不同 OS 线程)发起,复现"第一次成功第二次崩溃"。
|
||||
func TestSwitchDesktopCOMCrossGoroutine(t *testing.T) {
|
||||
if testing.Short() {
|
||||
t.Skip("short mode")
|
||||
}
|
||||
// 先初始化缓存(模拟程序长期运行后首次触发)
|
||||
procCoInitializeEx.Call(0, coinitMultithreaded)
|
||||
procCoUninitialize.Call()
|
||||
|
||||
for i := 0; i < 4; i++ {
|
||||
dir := int32(1)
|
||||
if i%2 == 1 {
|
||||
dir = -1
|
||||
}
|
||||
done := make(chan error, 1)
|
||||
go func() {
|
||||
done <- SwitchDesktopCOM(dir)
|
||||
}()
|
||||
select {
|
||||
case err := <-done:
|
||||
if err != nil {
|
||||
t.Logf("第%d次切换返回错误: %v", i+1, err)
|
||||
}
|
||||
case <-time.After(5 * time.Second):
|
||||
t.Fatalf("第%d次切换超时", i+1)
|
||||
}
|
||||
time.Sleep(300 * time.Millisecond)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,148 @@
|
||||
package windows
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"time"
|
||||
"unsafe"
|
||||
)
|
||||
|
||||
// 虚拟键码。
|
||||
const (
|
||||
vkLWin = 0x5B
|
||||
vkCtrl = 0x11
|
||||
vkLeft = 0x25
|
||||
vkRight = 0x27
|
||||
vkReturn = 0x0D
|
||||
vkTab = 0x09
|
||||
vkVolUp = 0xAF
|
||||
vkVolDown = 0xAE
|
||||
vkVolMute = 0xAD
|
||||
)
|
||||
|
||||
const (
|
||||
inputKeyboard = 1
|
||||
keyeventfKeyUp = 0x0002
|
||||
)
|
||||
|
||||
var (
|
||||
procSendInput = user32Hook.NewProc("SendInput")
|
||||
)
|
||||
|
||||
// KEYBDINPUT / INPUT 对应 Win32 结构(x64)。
|
||||
// 注意:C 的 INPUT 为 { DWORD type; union { MOUSEINPUT; KEYBDINPUT; HARDWAREINPUT } },
|
||||
// union 按最大成员 MOUSEINPUT(32 字节)对齐,因此 x64 下 sizeof(INPUT) = 40。
|
||||
type KEYBDINPUT struct {
|
||||
wVk uint16
|
||||
wScan uint16
|
||||
dwFlags uint32
|
||||
time uint32
|
||||
dwExtraInfo uintptr
|
||||
}
|
||||
|
||||
type INPUT struct {
|
||||
Type uint32
|
||||
_ uint32 // 对齐填充
|
||||
Ki KEYBDINPUT // union 起始(24 字节)
|
||||
_ [8]byte // union 补齐至 MOUSEINPUT 大小(32 字节)
|
||||
}
|
||||
|
||||
type keyState struct {
|
||||
vk uint16
|
||||
up bool
|
||||
}
|
||||
|
||||
// sendKeys 通过 SendInput 模拟按键序列(按下与抬起)。
|
||||
func sendKeys(states []keyState) error {
|
||||
if len(states) == 0 {
|
||||
return nil
|
||||
}
|
||||
ins := make([]INPUT, 0, len(states))
|
||||
for _, s := range states {
|
||||
flags := uint32(0)
|
||||
if s.up {
|
||||
flags |= keyeventfKeyUp
|
||||
}
|
||||
ins = append(ins, INPUT{Type: inputKeyboard, Ki: KEYBDINPUT{wVk: s.vk, dwFlags: flags}})
|
||||
}
|
||||
r, _, err := procSendInput.Call(
|
||||
uintptr(len(ins)),
|
||||
uintptr(unsafe.Pointer(&ins[0])),
|
||||
unsafe.Sizeof(INPUT{}),
|
||||
)
|
||||
if r != uintptr(len(ins)) {
|
||||
return fmt.Errorf("send input: injected %d of %d: %v", r, len(ins), err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// SwitchVirtualDesktop 模拟 Win+Ctrl+左/右 切换虚拟桌面。
|
||||
// dir < 0 切向左,dir > 0 切向右。
|
||||
//
|
||||
// 注意:Win+Ctrl 组合可能被输入法/其他软件注册为全局热键(如语音输入),
|
||||
// 此时注入该组合会误触第三方功能。优先使用 SwitchDesktopViaTaskView。
|
||||
func SwitchVirtualDesktop(dir int32) error {
|
||||
var key uint16 = vkRight
|
||||
if dir < 0 {
|
||||
key = vkLeft
|
||||
}
|
||||
return sendKeys([]keyState{
|
||||
{vk: vkLWin},
|
||||
{vk: vkCtrl},
|
||||
{vk: key},
|
||||
{vk: key, up: true},
|
||||
{vk: vkCtrl, up: true},
|
||||
{vk: vkLWin, up: true},
|
||||
})
|
||||
}
|
||||
|
||||
// DefaultTaskViewDelay 为 Win+Tab 打开任务视图后等待动画就绪的默认时长。
|
||||
const DefaultTaskViewDelay = 400 * time.Millisecond
|
||||
|
||||
// SwitchDesktopViaTaskView 通过任务视图导航切换虚拟桌面:
|
||||
// Win+Tab 打开任务视图 → 方向键选择相邻桌面 → Enter 确认。
|
||||
// 不依赖 Win+Ctrl 组合,避免与输入法全局热键冲突。
|
||||
// delay 为任务视图打开后的等待时长(<0 时使用默认值)。
|
||||
func SwitchDesktopViaTaskView(dir int32, delay time.Duration) error {
|
||||
if delay < 0 {
|
||||
delay = DefaultTaskViewDelay
|
||||
}
|
||||
var key uint16 = vkRight
|
||||
if dir < 0 {
|
||||
key = vkLeft
|
||||
}
|
||||
// 1. Win+Tab 打开任务视图
|
||||
if err := sendKeys([]keyState{
|
||||
{vk: vkLWin},
|
||||
{vk: vkTab},
|
||||
{vk: vkTab, up: true},
|
||||
{vk: vkLWin, up: true},
|
||||
}); err != nil {
|
||||
return err
|
||||
}
|
||||
// 2. 等待任务视图打开
|
||||
time.Sleep(delay)
|
||||
// 3. 方向键选择相邻桌面
|
||||
if err := sendKeys([]keyState{{vk: key}, {vk: key, up: true}}); err != nil {
|
||||
return err
|
||||
}
|
||||
time.Sleep(50 * time.Millisecond)
|
||||
// 4. Enter 确认切换
|
||||
if err := sendKeys([]keyState{{vk: vkReturn}, {vk: vkReturn, up: true}}); err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// VolumeStep 模拟媒体音量键步进。delta > 0 增大,delta < 0 减小。
|
||||
func VolumeStep(delta int32) error {
|
||||
var vk uint16 = vkVolUp
|
||||
if delta < 0 {
|
||||
vk = vkVolDown
|
||||
}
|
||||
return sendKeys([]keyState{{vk: vk}, {vk: vk, up: true}})
|
||||
}
|
||||
|
||||
// VolumeMute 模拟静音键。
|
||||
func VolumeMute() error {
|
||||
return sendKeys([]keyState{{vk: vkVolMute}, {vk: vkVolMute, up: true}})
|
||||
}
|
||||
@@ -0,0 +1,168 @@
|
||||
package windows
|
||||
|
||||
import (
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
"time"
|
||||
"unsafe"
|
||||
)
|
||||
|
||||
// 全屏检测:前台窗口矩形覆盖其所在显示器面积 ≥ 阈值即视为全屏。
|
||||
// 覆盖独占全屏(DXGI exclusive)、无边框全屏、全屏视频等场景。
|
||||
|
||||
// FullscreenCoverageThreshold 为全屏判定的最小覆盖比例。
|
||||
const FullscreenCoverageThreshold = 0.95
|
||||
|
||||
var (
|
||||
procGetForegroundWindow = user32Hook.NewProc("GetForegroundWindow")
|
||||
procGetWindowRect = user32Hook.NewProc("GetWindowRect")
|
||||
procIsZoomed = user32Hook.NewProc("IsZoomed")
|
||||
)
|
||||
|
||||
// IsFullscreenRect 判定窗口矩形是否覆盖屏幕矩形达到阈值(纯函数,可测)。
|
||||
// coverage = 交集面积 / 屏幕面积。
|
||||
func IsFullscreenRect(win, screen MonitorRect, threshold float64) bool {
|
||||
if threshold <= 0 {
|
||||
threshold = FullscreenCoverageThreshold
|
||||
}
|
||||
// 交集
|
||||
left := max32(win.Left, screen.Left)
|
||||
top := max32(win.Top, screen.Top)
|
||||
right := min32(win.Right, screen.Right)
|
||||
bottom := min32(win.Bottom, screen.Bottom)
|
||||
if right <= left || bottom <= top {
|
||||
return false
|
||||
}
|
||||
inter := float64(right-left) * float64(bottom-top)
|
||||
screenArea := float64(screen.Right-screen.Left) * float64(screen.Bottom-screen.Top)
|
||||
if screenArea <= 0 {
|
||||
return false
|
||||
}
|
||||
return inter/screenArea >= threshold
|
||||
}
|
||||
|
||||
func max32(a, b int32) int32 {
|
||||
if a > b {
|
||||
return a
|
||||
}
|
||||
return b
|
||||
}
|
||||
func min32(a, b int32) int32 {
|
||||
if a < b {
|
||||
return a
|
||||
}
|
||||
return b
|
||||
}
|
||||
|
||||
// rectFromWin 读取前台窗口矩形(虚拟屏幕坐标)。
|
||||
func rectFromWin(hwnd uintptr) (MonitorRect, bool) {
|
||||
var r rect
|
||||
hr, _, _ := procGetWindowRect.Call(hwnd, uintptr(unsafe.Pointer(&r)))
|
||||
if hr == 0 {
|
||||
return MonitorRect{}, false
|
||||
}
|
||||
return MonitorRect{Left: r.Left, Top: r.Top, Right: r.Right, Bottom: r.Bottom}, true
|
||||
}
|
||||
|
||||
// foregroundFullscreen 检测当前前台窗口是否全屏。
|
||||
// 无前台窗口或检测失败返回 false(不误抑制)。
|
||||
func foregroundFullscreen() bool {
|
||||
hwnd, _, _ := procGetForegroundWindow.Call()
|
||||
if hwnd == 0 {
|
||||
return false
|
||||
}
|
||||
// 最大化窗口不是全屏:任务栏可见时最大化窗口覆盖工作区 ≈96%,
|
||||
// 仅靠覆盖率阈值(95%)会把浏览器等普通最大化窗口误判为全屏,
|
||||
// 导致规则被错误抑制(角落/边缘功能失效)。用 IsZoomed 排除
|
||||
// 带 WS_MAXIMIZE 样式的窗口;真全屏窗口(游戏独占/无边框、
|
||||
// 全屏视频)没有该样式,不受影响。
|
||||
z, _, _ := procIsZoomed.Call(hwnd)
|
||||
if z != 0 {
|
||||
return false
|
||||
}
|
||||
win, ok := rectFromWin(hwnd)
|
||||
if !ok {
|
||||
return false
|
||||
}
|
||||
rects, err := MonitorRects()
|
||||
if err != nil || len(rects) == 0 {
|
||||
return false
|
||||
}
|
||||
// 前台窗口可能跨显示器:取与其交集最大的显示器。
|
||||
best := rects[0]
|
||||
bestOverlap := int64(-1)
|
||||
for _, r := range rects {
|
||||
left := max32(win.Left, r.Left)
|
||||
top := max32(win.Top, r.Top)
|
||||
right := min32(win.Right, r.Right)
|
||||
bottom := min32(win.Bottom, r.Bottom)
|
||||
if right > left && bottom > top {
|
||||
ov := int64(right-left) * int64(bottom-top)
|
||||
if ov > bestOverlap {
|
||||
bestOverlap = ov
|
||||
best = r
|
||||
}
|
||||
}
|
||||
}
|
||||
return IsFullscreenRect(win, best, FullscreenCoverageThreshold)
|
||||
}
|
||||
|
||||
// FullscreenWatcher 轮询前台窗口全屏状态,事件路径零额外 Win32 调用。
|
||||
type FullscreenWatcher struct {
|
||||
value atomic.Bool
|
||||
mu sync.Mutex
|
||||
started bool
|
||||
stop chan struct{}
|
||||
done chan struct{}
|
||||
interval time.Duration
|
||||
}
|
||||
|
||||
// NewFullscreenWatcher 创建全屏状态轮询器(默认 300ms)。
|
||||
func NewFullscreenWatcher() *FullscreenWatcher {
|
||||
return &FullscreenWatcher{interval: 300 * time.Millisecond}
|
||||
}
|
||||
|
||||
// Start 启动轮询 goroutine。幂等。
|
||||
func (w *FullscreenWatcher) Start() {
|
||||
w.mu.Lock()
|
||||
defer w.mu.Unlock()
|
||||
if w.started {
|
||||
return
|
||||
}
|
||||
w.started = true
|
||||
w.stop = make(chan struct{})
|
||||
w.done = make(chan struct{})
|
||||
go w.loop()
|
||||
}
|
||||
|
||||
// Stop 停止轮询并等待退出。幂等。
|
||||
func (w *FullscreenWatcher) Stop() {
|
||||
w.mu.Lock()
|
||||
if !w.started {
|
||||
w.mu.Unlock()
|
||||
return
|
||||
}
|
||||
w.started = false
|
||||
close(w.stop)
|
||||
w.mu.Unlock()
|
||||
<-w.done
|
||||
}
|
||||
|
||||
// IsFullscreen 返回最近一次检测的全屏状态(原子读,事件路径使用)。
|
||||
func (w *FullscreenWatcher) IsFullscreen() bool {
|
||||
return w.value.Load()
|
||||
}
|
||||
|
||||
func (w *FullscreenWatcher) loop() {
|
||||
defer close(w.done)
|
||||
ticker := time.NewTicker(w.interval)
|
||||
defer ticker.Stop()
|
||||
for {
|
||||
select {
|
||||
case <-w.stop:
|
||||
return
|
||||
case <-ticker.C:
|
||||
w.value.Store(foregroundFullscreen())
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,53 @@
|
||||
package windows
|
||||
|
||||
import (
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
// TestIsFullscreenRect 验证覆盖判定边界(94%/95%/96%、无交集、跨屏)。
|
||||
func TestIsFullscreenRect(t *testing.T) {
|
||||
screen := MonitorRect{Left: 0, Top: 0, Right: 1920, Bottom: 1080}
|
||||
cases := []struct {
|
||||
name string
|
||||
win MonitorRect
|
||||
want bool
|
||||
}{
|
||||
{"完全覆盖", MonitorRect{0, 0, 1920, 1080}, true},
|
||||
{"无边框全屏", MonitorRect{0, 0, 1920, 1080}, true},
|
||||
{"任务栏遮挡(94%)", MonitorRect{0, 0, 1920, 1015}, false}, // 1015/1080 ≈ 93.9%
|
||||
{"任务栏遮挡(96%)", MonitorRect{0, 0, 1920, 1040}, true}, // 1040/1080 ≈ 96.3%
|
||||
{"普通窗口", MonitorRect{100, 100, 1200, 800}, false},
|
||||
{"无交集", MonitorRect{3000, 3000, 4000, 4000}, false},
|
||||
{"覆盖95%临界", MonitorRect{0, 0, 1920, 1026}, true}, // 1026/1080 = 95.0%
|
||||
}
|
||||
for _, c := range cases {
|
||||
if got := IsFullscreenRect(c.win, screen, 0); got != c.want {
|
||||
t.Errorf("%s: IsFullscreenRect = %v, want %v", c.name, got, c.want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// TestIsFullscreenRectMultiMonitor 验证跨屏窗口按交集最大屏幕判定。
|
||||
func TestIsFullscreenRectMultiMonitor(t *testing.T) {
|
||||
screen := MonitorRect{Left: 1920, Top: 0, Right: 3840, Bottom: 1080}
|
||||
win := MonitorRect{Left: 1900, Top: 0, Right: 3840, Bottom: 1080} // 几乎全盖副屏
|
||||
if !IsFullscreenRect(win, screen, 0) {
|
||||
t.Fatal("near-fullscreen on secondary monitor should be true")
|
||||
}
|
||||
}
|
||||
|
||||
// TestFullscreenWatcherLifecycle 验证轮询器 Start/Stop 幂等与状态可读。
|
||||
func TestFullscreenWatcherLifecycle(t *testing.T) {
|
||||
w := NewFullscreenWatcher()
|
||||
w.Start()
|
||||
w.Start() // 幂等
|
||||
time.Sleep(100 * time.Millisecond)
|
||||
_ = w.IsFullscreen() // 可读(值不校验:取决于会话前台窗口)
|
||||
w.Stop()
|
||||
w.Stop() // 幂等
|
||||
// 重启
|
||||
w.Start()
|
||||
time.Sleep(50 * time.Millisecond)
|
||||
w.Stop()
|
||||
}
|
||||
@@ -0,0 +1,142 @@
|
||||
package windows
|
||||
|
||||
// heartbeat.go — 进程心跳与内存观测。
|
||||
//
|
||||
// 心跳文件(%LOCALAPPDATA%\ZerOriginTool\logs\heartbeat.json)每 30 秒
|
||||
// 原子更新一次,记录 PID / 时间 / 内存 / 运行时长。进程消失后结合三类
|
||||
// 证据判定死因:
|
||||
//
|
||||
// - heartbeat 停在 T,app.log 无 "bye",crash.log 有记录 → 自身崩溃
|
||||
// - heartbeat 停在 T,app.log 无 "bye",crash.log 无记录 → 被外部强杀
|
||||
// - app.log 有 "bye" → 正常退出
|
||||
//
|
||||
// 内存看门狗:每次心跳顺带检查 WorkingSet,超过阈值写 WARN 日志,
|
||||
// 用于提前发现内存泄漏趋势。
|
||||
import (
|
||||
"encoding/json"
|
||||
"log/slog"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"runtime"
|
||||
"sync"
|
||||
"syscall"
|
||||
"time"
|
||||
"unsafe"
|
||||
)
|
||||
|
||||
var (
|
||||
heartbeatPsapi = syscall.NewLazyDLL("psapi.dll")
|
||||
procGetProcessMemoryInfo = heartbeatPsapi.NewProc("GetProcessMemoryInfo")
|
||||
|
||||
heartbeatKernel32 = syscall.NewLazyDLL("kernel32.dll")
|
||||
procGetCurrentProcess = heartbeatKernel32.NewProc("GetCurrentProcess")
|
||||
)
|
||||
|
||||
// processMemoryCounters 对应 PROCESS_MEMORY_COUNTERS(仅取所需字段)。
|
||||
type processMemoryCounters struct {
|
||||
cb uint32
|
||||
pageFaultCount uint32
|
||||
peakWorkingSetSize uintptr
|
||||
workingSetSize uintptr
|
||||
quotaPeakPagedPoolUsage uintptr
|
||||
quotaPagedPoolUsage uintptr
|
||||
quotaPeakNonPagedPoolUsage uintptr
|
||||
quotaNonPagedPoolUsage uintptr
|
||||
pagefileUsage uintptr
|
||||
peakPagefileUsage uintptr
|
||||
}
|
||||
|
||||
// SelfWorkingSetMB 返回当前进程 WorkingSet(MB)。失败返回 0。
|
||||
func SelfWorkingSetMB() int64 {
|
||||
h, _, _ := procGetCurrentProcess.Call()
|
||||
if h == 0 {
|
||||
return 0
|
||||
}
|
||||
var mc processMemoryCounters
|
||||
mc.cb = uint32(unsafe.Sizeof(mc))
|
||||
r, _, _ := procGetProcessMemoryInfo.Call(h, uintptr(unsafe.Pointer(&mc)), uintptr(mc.cb))
|
||||
if r == 0 {
|
||||
return 0
|
||||
}
|
||||
return int64(mc.workingSetSize) / (1024 * 1024)
|
||||
}
|
||||
|
||||
// heartbeatEntry 为心跳文件内容(JSON,便于后续脚本分析)。
|
||||
type heartbeatEntry struct {
|
||||
PID int `json:"pid"`
|
||||
TS string `json:"ts"`
|
||||
UptimeS int64 `json:"uptime_s"`
|
||||
MemMB int64 `json:"mem_mb"`
|
||||
}
|
||||
|
||||
// StartHeartbeat 启动心跳 goroutine:interval 周期写心跳文件,超过
|
||||
// memLimitMB 时写 WARN 日志(memLimitMB <= 0 表示不检查)。
|
||||
// 返回 stop 函数(幂等)。
|
||||
func StartHeartbeat(logger *slog.Logger, logsDir string, interval time.Duration, memLimitMB int64) (stop func()) {
|
||||
if logger == nil {
|
||||
logger = slog.Default()
|
||||
}
|
||||
if interval <= 0 {
|
||||
interval = 30 * time.Second
|
||||
}
|
||||
path := filepath.Join(logsDir, "heartbeat.json")
|
||||
start := time.Now()
|
||||
|
||||
done := make(chan struct{})
|
||||
var once sync.Once
|
||||
go func() {
|
||||
defer func() {
|
||||
if r := recover(); r != nil {
|
||||
LogGoPanic("heartbeat", r, debugStack())
|
||||
}
|
||||
}()
|
||||
ticker := time.NewTicker(interval)
|
||||
defer ticker.Stop()
|
||||
writeHeartbeat(logger, path, start) // 启动即写一次
|
||||
for {
|
||||
select {
|
||||
case <-done:
|
||||
return
|
||||
case <-ticker.C:
|
||||
mem := SelfWorkingSetMB()
|
||||
if memLimitMB > 0 && mem > memLimitMB {
|
||||
logger.Warn("memory watchdog", "working_set_mb", mem, "limit_mb", memLimitMB)
|
||||
}
|
||||
writeHeartbeat(logger, path, start)
|
||||
}
|
||||
}
|
||||
}()
|
||||
return func() {
|
||||
once.Do(func() { close(done) })
|
||||
}
|
||||
}
|
||||
|
||||
func writeHeartbeat(logger *slog.Logger, path string, start time.Time) {
|
||||
e := heartbeatEntry{
|
||||
PID: os.Getpid(),
|
||||
TS: time.Now().Format("2006-01-02T15:04:05.000-07:00"),
|
||||
UptimeS: int64(time.Since(start).Seconds()),
|
||||
MemMB: SelfWorkingSetMB(),
|
||||
}
|
||||
b, err := json.Marshal(e)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
// 原子替换:写临时文件再 rename,避免读端看到半写内容。
|
||||
tmp := path + ".tmp"
|
||||
if err := os.WriteFile(tmp, b, 0o644); err != nil {
|
||||
logger.Debug("heartbeat write failed", "err", err)
|
||||
return
|
||||
}
|
||||
if err := os.Rename(tmp, path); err != nil {
|
||||
// rename 失败(如杀软锁文件):保留临时文件内容即可,不致命。
|
||||
_ = os.Remove(tmp)
|
||||
}
|
||||
}
|
||||
|
||||
// debugStack 返回当前 goroutine 堆栈(心跳/崩溃记录用,避免 import cycle)。
|
||||
func debugStack() []byte {
|
||||
buf := make([]byte, 32<<10)
|
||||
n := runtime.Stack(buf, false)
|
||||
return buf[:n]
|
||||
}
|
||||
@@ -0,0 +1,186 @@
|
||||
package windows
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"runtime"
|
||||
"sync"
|
||||
"syscall"
|
||||
"time"
|
||||
"unsafe"
|
||||
|
||||
"golang.org/x/sys/windows"
|
||||
)
|
||||
|
||||
// 低级鼠标钩子常量。
|
||||
const (
|
||||
whMouseLL = 14
|
||||
// WmMouseMove / WmMouseWheel 为导出消息号,供触发器使用。
|
||||
WmMouseMove = 0x0200
|
||||
WmMouseWheel = 0x020A
|
||||
wmQuit = 0x0012
|
||||
)
|
||||
|
||||
var (
|
||||
user32Hook = syscall.NewLazyDLL("user32.dll")
|
||||
procSetWindowsHookExW = user32Hook.NewProc("SetWindowsHookExW")
|
||||
procCallNextHookEx = user32Hook.NewProc("CallNextHookEx")
|
||||
procUnhookWindowsHookEx = user32Hook.NewProc("UnhookWindowsHookEx")
|
||||
)
|
||||
|
||||
// POINT 与 MSLLHOOKSTRUCT 对应 Win32 结构(仅取所需字段)。
|
||||
type POINT struct {
|
||||
X, Y int32
|
||||
}
|
||||
|
||||
type MSLLHOOKSTRUCT struct {
|
||||
pt POINT
|
||||
mouseData uint32
|
||||
flags uint32
|
||||
time uint32
|
||||
dwExtraInfo uintptr
|
||||
}
|
||||
|
||||
// MouseEvent 为归一化的鼠标事件(已从 Win32 消息转换)。
|
||||
type MouseEvent struct {
|
||||
Message uint32 // WM_* 消息号
|
||||
X, Y int32 // 屏幕坐标
|
||||
MouseData int32 // 滚轮 delta 等附加数据
|
||||
}
|
||||
|
||||
// MouseHook 为 WH_MOUSE_LL 低级鼠标钩子。
|
||||
// 回调运行在专用消息循环线程上,只做入队,绝不阻塞。
|
||||
type MouseHook struct {
|
||||
ch chan MouseEvent
|
||||
mu sync.Mutex
|
||||
started bool
|
||||
stopped bool
|
||||
threadID uint32
|
||||
done chan struct{}
|
||||
installed chan struct{} // 安装结果就绪后关闭(Start 同步等待)
|
||||
dropped uint64 // 溢出丢弃计数(限速日志用)
|
||||
calls uint64 // 回调被系统调用次数(健康度观测)
|
||||
installErrVal error
|
||||
}
|
||||
|
||||
// NewMouseHook 创建钩子,buf 为事件通道容量。
|
||||
func NewMouseHook(buf int) *MouseHook {
|
||||
return &MouseHook{ch: make(chan MouseEvent, buf)}
|
||||
}
|
||||
|
||||
// Events 返回事件流。
|
||||
func (h *MouseHook) Events() <-chan MouseEvent { return h.ch }
|
||||
|
||||
// Dropped 返回因通道满而丢弃的事件数(高频限流的观测指标)。
|
||||
func (h *MouseHook) Dropped() uint64 { return h.dropped }
|
||||
|
||||
// CallbackCalls 返回钩子回调被系统调用的总次数(健康度观测)。
|
||||
func (h *MouseHook) CallbackCalls() uint64 { return h.calls }
|
||||
|
||||
// InstallErr 返回钩子安装错误(若有)。Start 后稍等片刻再查询。
|
||||
func (h *MouseHook) InstallErr() error {
|
||||
h.mu.Lock()
|
||||
defer h.mu.Unlock()
|
||||
return h.installErrVal
|
||||
}
|
||||
|
||||
// Start 在专用 goroutine 上安装钩子并进入消息循环,同步等待安装结果。
|
||||
// 不阻塞调用方超过安装等待时间。
|
||||
func (h *MouseHook) Start() error {
|
||||
h.mu.Lock()
|
||||
if h.started {
|
||||
h.mu.Unlock()
|
||||
return nil
|
||||
}
|
||||
h.started = true
|
||||
h.done = make(chan struct{})
|
||||
h.installed = make(chan struct{})
|
||||
go h.run()
|
||||
h.mu.Unlock() // 先释放锁:等待期间 run() 可能写 installErrVal
|
||||
|
||||
// 同步等待安装结果:失败立刻返回错误,避免静默失效。
|
||||
select {
|
||||
case <-h.installed:
|
||||
if err := h.InstallErr(); err != nil {
|
||||
return err
|
||||
}
|
||||
case <-time.After(time.Second):
|
||||
return fmt.Errorf("mouse hook install timeout")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// Stop 结束消息循环并卸载钩子。幂等,等待循环退出。
|
||||
func (h *MouseHook) Stop() error {
|
||||
h.mu.Lock()
|
||||
if !h.started || h.stopped {
|
||||
h.mu.Unlock()
|
||||
return nil
|
||||
}
|
||||
h.stopped = true
|
||||
tid := h.threadID
|
||||
h.mu.Unlock()
|
||||
|
||||
if tid != 0 {
|
||||
_ = postThreadMessage(tid, wmQuit, 0, 0)
|
||||
}
|
||||
<-h.done
|
||||
return nil
|
||||
}
|
||||
|
||||
func (h *MouseHook) run() {
|
||||
// 钩子生命周期必须固定在单一 OS 线程:GetCurrentThreadId、
|
||||
// SetWindowsHookExW、GetMessage 循环必须在同一线程,否则
|
||||
// Stop 的 WM_QUIT 会投递到错误的线程导致消息循环无法退出。
|
||||
runtime.LockOSThread()
|
||||
defer runtime.UnlockOSThread()
|
||||
defer close(h.done)
|
||||
h.threadID = windows.GetCurrentThreadId()
|
||||
|
||||
// NewCallback 生成的指针必须保持存活;cb 存于字段(GC 安全)。
|
||||
var hhk uintptr
|
||||
cb := syscall.NewCallback(func(code int32, wParam, lParam uintptr) uintptr {
|
||||
// 钩子回调运行在 syscall 边界线程上:一旦 panic 将直接拖垮整个
|
||||
// 进程(无法被其他 goroutine 的 recover 捕获)。recover 兜底,
|
||||
// 记录崩溃后丢弃事件,避免静默消失。
|
||||
defer func() {
|
||||
if r := recover(); r != nil {
|
||||
LogGoPanic("mouse-hook-callback", r, debugStack())
|
||||
}
|
||||
}()
|
||||
h.calls++
|
||||
if code >= 0 && hhk != 0 {
|
||||
ms := *(**MSLLHOOKSTRUCT)(unsafe.Pointer(&lParam))
|
||||
ev := MouseEvent{Message: uint32(wParam), X: ms.pt.X, Y: ms.pt.Y, MouseData: int32(ms.mouseData)}
|
||||
select {
|
||||
case h.ch <- ev:
|
||||
default:
|
||||
h.dropped++
|
||||
}
|
||||
}
|
||||
r, _, _ := procCallNextHookEx.Call(hhk, uintptr(code), wParam, lParam)
|
||||
return r
|
||||
})
|
||||
|
||||
r, _, err := procSetWindowsHookExW.Call(whMouseLL, cb, 0, 0)
|
||||
if r == 0 {
|
||||
// 安装失败:记录并通知 Start。
|
||||
h.mu.Lock()
|
||||
h.installErrVal = err
|
||||
h.mu.Unlock()
|
||||
close(h.installed)
|
||||
return
|
||||
}
|
||||
hhk = r
|
||||
close(h.installed) // 安装结果就绪,Start 继续
|
||||
|
||||
// 消息循环:低级钩子需要消息泵;WM_QUIT 时 GetMessage 返回 0。
|
||||
for {
|
||||
var m msg
|
||||
n, err := getMessage(&m, 0, 0, 0)
|
||||
if n == 0 || n == -1 || err != nil {
|
||||
break
|
||||
}
|
||||
}
|
||||
procUnhookWindowsHookEx.Call(hhk)
|
||||
hhk = 0
|
||||
}
|
||||
@@ -0,0 +1,53 @@
|
||||
package windows
|
||||
|
||||
import (
|
||||
"syscall"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
// TestHookReceivesMouseMoveIntegration 真实移动鼠标验证钩子事件流。
|
||||
// 仅在显式启用时运行(默认跳过,避免干扰用户会话)。
|
||||
func TestHookReceivesMouseMoveIntegration(t *testing.T) {
|
||||
if testing.Short() {
|
||||
t.Skip("short mode")
|
||||
}
|
||||
h := NewMouseHook(64)
|
||||
if err := h.Start(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer h.Stop()
|
||||
time.Sleep(300 * time.Millisecond)
|
||||
if err := h.InstallErr(); err != nil {
|
||||
t.Fatalf("install: %v", err)
|
||||
}
|
||||
|
||||
// 移动到两个不同位置,确保产生真实移动事件。
|
||||
procSetCursorPos := syscall.NewLazyDLL("user32.dll").NewProc("SetCursorPos")
|
||||
moved := false
|
||||
for _, pos := range [][2]int32{{100, 100}, {400, 300}} {
|
||||
r, _, _ := procSetCursorPos.Call(uintptr(pos[0]), uintptr(pos[1]))
|
||||
if r != 0 {
|
||||
moved = true
|
||||
}
|
||||
time.Sleep(100 * time.Millisecond)
|
||||
}
|
||||
if !moved {
|
||||
t.Skip("session has no active input desktop (e.g. disconnected RDP); physical input unavailable")
|
||||
}
|
||||
|
||||
select {
|
||||
case ev := <-h.Events():
|
||||
t.Logf("received mouse event: msg=%#x pos=(%d,%d)", ev.Message, ev.X, ev.Y)
|
||||
case <-time.After(2 * time.Second):
|
||||
// 区分环境问题(回调从未被调用)与代码问题(回调被调用但事件丢失)。
|
||||
if h.CallbackCalls() == 0 {
|
||||
// SetCursorPos 成功但系统从未回调钩子:无活动输入桌面。
|
||||
procForeground := syscall.NewLazyDLL("user32.dll").NewProc("GetForegroundWindow")
|
||||
fg, _, _ := procForeground.Call()
|
||||
t.Logf("callback calls = 0, foreground=%x", fg)
|
||||
t.Skip("session lacks active input delivery (RDP/headless)")
|
||||
}
|
||||
t.Fatalf("callback called %d times but no event received", h.CallbackCalls())
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
package windows
|
||||
|
||||
import (
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
// TestMouseHookInstallSmoke 在真实 Windows 会话中验证低级鼠标钩子
|
||||
// 安装/停止路径(SetWindowsHookExW + 消息循环 + UnhookWindowsHookEx)。
|
||||
func TestMouseHookInstallSmoke(t *testing.T) {
|
||||
h := NewMouseHook(64)
|
||||
if err := h.Start(); err != nil {
|
||||
t.Fatalf("start: %v", err)
|
||||
}
|
||||
time.Sleep(200 * time.Millisecond) // 等待 goroutine 安装钩子
|
||||
if err := h.InstallErr(); err != nil {
|
||||
t.Fatalf("hook install failed: %v", err)
|
||||
}
|
||||
if err := h.Stop(); err != nil {
|
||||
t.Fatalf("stop: %v", err)
|
||||
}
|
||||
// Stop 幂等
|
||||
if err := h.Stop(); err != nil {
|
||||
t.Fatalf("stop again: %v", err)
|
||||
}
|
||||
// 重新启动(Stop 后不可再用,此处仅验证不 panic)
|
||||
}
|
||||
|
||||
// TestMouseHookStartTwice 验证重复 Start 不重复安装。
|
||||
func TestMouseHookStartTwice(t *testing.T) {
|
||||
h := NewMouseHook(64)
|
||||
if err := h.Start(); err != nil {
|
||||
t.Fatalf("start: %v", err)
|
||||
}
|
||||
if err := h.Start(); err != nil {
|
||||
t.Fatalf("start again: %v", err)
|
||||
}
|
||||
time.Sleep(100 * time.Millisecond)
|
||||
if err := h.InstallErr(); err != nil {
|
||||
t.Fatalf("hook install failed: %v", err)
|
||||
}
|
||||
if err := h.Stop(); err != nil {
|
||||
t.Fatalf("stop: %v", err)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
// Package windows 中 notify 层已大幅简化:移除独立的 NIM 图标注册与
|
||||
// 隐藏窗口/worker 线程,全部气泡通知通过 fork 的 systray 库复用主进程
|
||||
// 托盘图标位置(systray.SetBalloon),消除"两个 ZerOriginTool 托盘图标"
|
||||
// 中第二个为空白占位的问题。
|
||||
package windows
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"log/slog"
|
||||
|
||||
"zerorigin/internal/platform/systray"
|
||||
)
|
||||
|
||||
// notifyLog 通知层诊断日志(由 app 层注入;未注入时使用默认 logger)。
|
||||
var notifyLog = slog.Default()
|
||||
|
||||
// SetNotifyLogger 注入通知层诊断日志。
|
||||
func SetNotifyLogger(l *slog.Logger) {
|
||||
if l != nil {
|
||||
notifyLog = l
|
||||
}
|
||||
}
|
||||
|
||||
// ShowBalloon 通过 systray 的托盘图标显示气泡通知。
|
||||
// systray 必须已 Run(图标已注册);若未启动则返回 ErrSystrayNotReady。
|
||||
func ShowBalloon(title, text string) error {
|
||||
if err := systray.SetBalloon(title, text); err != nil {
|
||||
// systray 未启动时 NID 为 nil,错误信息固定且无外部上下文价值。
|
||||
notifyLog.Warn("balloon failed", "title", title, "err", err)
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// ShowBalloonWithIcon 为向后兼容保留:systray 图标由 systray 自己管理,
|
||||
// 不再支持外部指定图标资源 ID。等同于 ShowBalloon。
|
||||
func ShowBalloonWithIcon(title, text string, iconResourceID uintptr) error {
|
||||
return ShowBalloon(title, text)
|
||||
}
|
||||
|
||||
// ErrSystrayNotReady 表示 systray 图标尚未注册(应在主进程早期检查)。
|
||||
var ErrSystrayNotReady = errors.New("systray icon not initialized")
|
||||
@@ -0,0 +1,54 @@
|
||||
package windows
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"syscall"
|
||||
"unsafe"
|
||||
)
|
||||
|
||||
var (
|
||||
user32 = syscall.NewLazyDLL("user32.dll")
|
||||
shell32 = syscall.NewLazyDLL("shell32.dll")
|
||||
kernel32 = syscall.NewLazyDLL("kernel32.dll")
|
||||
procMessageBoxW = user32.NewProc("MessageBoxW")
|
||||
procShellExecuteW = shell32.NewProc("ShellExecuteW")
|
||||
)
|
||||
|
||||
// ShowMessageBox 显示模态消息框(单实例冲突等提示用)。
|
||||
func ShowMessageBox(title, text string) {
|
||||
titlePtr, _ := syscall.UTF16PtrFromString(title)
|
||||
textPtr, _ := syscall.UTF16PtrFromString(text)
|
||||
procMessageBoxW.Call(0, uintptr(unsafe.Pointer(textPtr)), uintptr(unsafe.Pointer(titlePtr)), 0x00000040 /* MB_ICONINFORMATION */)
|
||||
}
|
||||
|
||||
// OpenPath 用系统默认程序打开路径(目录或文件),例如 ShellExecute 打开配置目录。
|
||||
func OpenPath(path string) error {
|
||||
return OpenPathWithArgs(path, "")
|
||||
}
|
||||
|
||||
// OpenPathWithArgs 用系统默认程序打开路径,并附加命令行参数。
|
||||
// 参数为结构化字符串,不经过 cmd /c(架构文档 §9.2 约束)。
|
||||
func OpenPathWithArgs(path, args string) error {
|
||||
p, err := syscall.UTF16PtrFromString(path)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
var argsPtr *uint16
|
||||
if args != "" {
|
||||
argsPtr, err = syscall.UTF16PtrFromString(args)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
// ShellExecuteW(hwnd, "open", path, args, NULL, SW_SHOWNORMAL)
|
||||
r, _, _ := procShellExecuteW.Call(0, uintptr(unsafe.Pointer(openVerb())), uintptr(unsafe.Pointer(p)), uintptr(unsafe.Pointer(argsPtr)), 0, 1)
|
||||
if r <= 32 {
|
||||
return fmt.Errorf("shell execute %q failed: code %d", path, r)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func openVerb() *uint16 {
|
||||
s, _ := syscall.UTF16PtrFromString("open")
|
||||
return s
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
// Package windows 集中封装 Windows API 调用。
|
||||
// 工程内其他包不得直接加载 user32.dll / kernel32.dll 等 DLL。
|
||||
package windows
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"os/user"
|
||||
|
||||
"golang.org/x/sys/windows"
|
||||
)
|
||||
|
||||
// ErrAlreadyRunning 表示已有另一个主进程实例在运行。
|
||||
var ErrAlreadyRunning = errors.New("another instance is already running")
|
||||
|
||||
// SingleInstance 为单实例互斥锁持有者。
|
||||
type SingleInstance struct {
|
||||
h windows.Handle
|
||||
}
|
||||
|
||||
// AcquireSingleInstance 创建以当前用户 SID 命名的命名互斥锁。
|
||||
// 已存在时返回 ErrAlreadyRunning;成功时调用方必须调用 Release。
|
||||
func AcquireSingleInstance() (*SingleInstance, error) {
|
||||
u, err := user.Current()
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("get current user: %w", err)
|
||||
}
|
||||
name, err := windows.UTF16PtrFromString(`Local\ZerOriginTool-` + u.Uid)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
h, err := windows.CreateMutex(nil, false, name)
|
||||
if err != nil {
|
||||
if err == windows.ERROR_ALREADY_EXISTS {
|
||||
return nil, ErrAlreadyRunning
|
||||
}
|
||||
return nil, fmt.Errorf("create mutex: %w", err)
|
||||
}
|
||||
return &SingleInstance{h: h}, nil
|
||||
}
|
||||
|
||||
// Release 释放互斥锁句柄。幂等。
|
||||
func (s *SingleInstance) Release() {
|
||||
if s.h != 0 {
|
||||
windows.CloseHandle(s.h)
|
||||
s.h = 0
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,271 @@
|
||||
package windows
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"runtime"
|
||||
"syscall"
|
||||
"unsafe"
|
||||
)
|
||||
|
||||
// 虚拟桌面 COM 直调实现(无快捷键依赖,兼容输入法占用 Win+Ctrl 的系统)。
|
||||
//
|
||||
// 获取路径(社区标准,PowerToys/sswitch 等均采用):
|
||||
//
|
||||
// CoCreateInstance(CLSID_ImmersiveShell, IID_IServiceProvider)
|
||||
// → QueryService(CLSID_VirtualDesktopAPI_Unknown, IID_IVirtualDesktopManagerInternal)
|
||||
// → GetCurrentDesktop / GetDesktops / SwitchDesktop
|
||||
//
|
||||
// 版本差异:Win10 2004 ~ Win11 23H2 使用经典 IID {EF9F1A6C-...};
|
||||
// Win11 24H2+(build 26100+)使用新 IID {53F5CA0B-...}。
|
||||
// 两者 vtable 前段布局一致(GetCurrentDesktop=6 / GetDesktops=7 / SwitchDesktop=9),
|
||||
// 因此共用同一套调用代码,仅 IID 不同。运行时不匹配则回退另一套。
|
||||
//
|
||||
// 接口方法(槽位含 IUnknown 前 3 个):
|
||||
//
|
||||
// IVirtualDesktopManagerInternal: GetCurrentDesktop(6) GetDesktops(7) SwitchDesktop(9)
|
||||
// IObjectArray: GetCount(3) GetAt(4)
|
||||
// IVirtualDesktop: GetId(4)
|
||||
|
||||
var (
|
||||
ole32Com = syscall.NewLazyDLL("ole32.dll")
|
||||
procCoInitializeEx = ole32Com.NewProc("CoInitializeEx")
|
||||
procCoUninitialize = ole32Com.NewProc("CoUninitialize")
|
||||
procCoCreateInstance = ole32Com.NewProc("CoCreateInstance")
|
||||
)
|
||||
|
||||
type comGUID struct {
|
||||
Data1 uint32
|
||||
Data2 uint16
|
||||
Data3 uint16
|
||||
Data4 [8]byte
|
||||
}
|
||||
|
||||
func comGUIDFromString(s string) comGUID {
|
||||
var g comGUID
|
||||
var d1, d2, d3, d4, d5, d6, d7, d8 uint32
|
||||
n, _ := fmt.Sscanf(s, "%08x-%04x-%04x-%02x%02x-%02x%02x%02x%02x%02x%02x",
|
||||
&g.Data1, &g.Data2, &g.Data3, &d1, &d2, &d3, &d4, &d5, &d6, &d7, &d8)
|
||||
if n != 11 {
|
||||
panic("invalid GUID string: " + s)
|
||||
}
|
||||
g.Data4 = [8]byte{byte(d1), byte(d2), byte(d3), byte(d4), byte(d5), byte(d6), byte(d7), byte(d8)}
|
||||
return g
|
||||
}
|
||||
|
||||
var (
|
||||
guidImmersiveShell = comGUIDFromString("C2F03A33-21F5-47FA-B4BB-156362A2F239")
|
||||
guidVirtualDesktopAPI = comGUIDFromString("C5E0CDCA-7B6E-41B2-9FC4-D93975CC467B")
|
||||
guidServiceProvider = comGUIDFromString("6D5140C1-7436-11CE-8034-00AA006009FA")
|
||||
guidObjectArray = comGUIDFromString("92CA9DCD-5622-4BBA-A805-5E9F541BD8C9")
|
||||
guidVDClassic = comGUIDFromString("FF72FFDD-BE7E-43FC-9C03-AD81681E88E4")
|
||||
guidVD24H2 = comGUIDFromString("3F07F4BE-B107-441A-AF0F-39D82529072C")
|
||||
guidVDMgrClassic = comGUIDFromString("EF9F1A6C-D3CC-4358-B712-F84B635BEBE7")
|
||||
guidVDMgr24H2 = comGUIDFromString("53F5CA0B-158F-4124-900C-057158060B27")
|
||||
)
|
||||
|
||||
const (
|
||||
clsctxInprocServer = 0x1
|
||||
clsctxLocalServer = 0x4
|
||||
// COINIT_MULTITHREADED:MTA 下 COM 调用不绑定线程,goroutine 调度安全。
|
||||
coinitMultithreaded = 0x0
|
||||
)
|
||||
|
||||
// comCall 调用 COM 接口 vtable 方法。返回 HRESULT。
|
||||
func comCall(iface uintptr, slot uint32, args ...uintptr) uintptr {
|
||||
// iface 是 COM 接口指针:指向 vtable 指针。
|
||||
// 逐层读取(保持 unsafe.Pointer 类型,通过 vet 检查):
|
||||
// 接口指针 → vtable 数组首地址 → 槽位函数指针
|
||||
p := *(*unsafe.Pointer)(unsafe.Pointer(&iface))
|
||||
vtable := *(*unsafe.Pointer)(p)
|
||||
fn := *(*uintptr)(unsafe.Pointer(uintptr(vtable) + uintptr(slot)*8))
|
||||
r, _, _ := syscall.SyscallN(fn, append([]uintptr{iface}, args...)...)
|
||||
return r
|
||||
}
|
||||
|
||||
// comRelease 释放 COM 接口(槽位 2 = IUnknown.Release)。
|
||||
func comRelease(iface uintptr) {
|
||||
if iface != 0 {
|
||||
comCall(iface, 2)
|
||||
}
|
||||
}
|
||||
|
||||
// desktopManager 持有虚拟桌面管理器与相关接口。
|
||||
// 注意:不跨调用缓存。实测缓存的 RPC 代理在 CoUninitialize 后失效,
|
||||
// 第二次使用会访问违例(0xc0000005);每次调用完整重建最可靠。
|
||||
type desktopManager struct {
|
||||
mgr uintptr // IVirtualDesktopManagerInternal
|
||||
vdIID comGUID // IVirtualDesktop 接口 IID(按版本)
|
||||
}
|
||||
|
||||
// openDesktopManager 获取虚拟桌面管理器。按版本回退:
|
||||
// 先尝试 24H2+ 新 IID,失败后尝试经典 IID。
|
||||
// 调用方必须已 CoInitializeEx(见 SwitchDesktopCOM)。
|
||||
func openDesktopManager() (*desktopManager, error) {
|
||||
var shell uintptr
|
||||
hr, _, _ := procCoCreateInstance.Call(
|
||||
uintptr(unsafe.Pointer(&guidImmersiveShell)), 0,
|
||||
clsctxInprocServer|clsctxLocalServer,
|
||||
uintptr(unsafe.Pointer(&guidServiceProvider)),
|
||||
uintptr(unsafe.Pointer(&shell)))
|
||||
if shell == 0 {
|
||||
return nil, fmt.Errorf("create ImmersiveShell: hr=0x%08x", hr)
|
||||
}
|
||||
defer comRelease(shell)
|
||||
|
||||
var mgr uintptr
|
||||
// QueryService 为 IServiceProvider 槽位 3:(rguid, riid, ppv)
|
||||
hr = comCall(shell, 3,
|
||||
uintptr(unsafe.Pointer(&guidVirtualDesktopAPI)),
|
||||
uintptr(unsafe.Pointer(&guidVDMgr24H2)),
|
||||
uintptr(unsafe.Pointer(&mgr)))
|
||||
if mgr == 0 {
|
||||
hr = comCall(shell, 3,
|
||||
uintptr(unsafe.Pointer(&guidVirtualDesktopAPI)),
|
||||
uintptr(unsafe.Pointer(&guidVDMgrClassic)),
|
||||
uintptr(unsafe.Pointer(&mgr)))
|
||||
if mgr == 0 {
|
||||
return nil, fmt.Errorf("query virtual desktop manager: hr=0x%08x", hr)
|
||||
}
|
||||
return &desktopManager{mgr: mgr, vdIID: guidVDClassic}, nil
|
||||
}
|
||||
return &desktopManager{mgr: mgr, vdIID: guidVD24H2}, nil
|
||||
}
|
||||
|
||||
func (m *desktopManager) close() {
|
||||
comRelease(m.mgr)
|
||||
}
|
||||
|
||||
// desktopIDs 枚举所有桌面 GUID(按系统顺序)。
|
||||
func (m *desktopManager) desktopIDs() ([]comGUID, error) {
|
||||
var cur uintptr
|
||||
if hr := comCall(m.mgr, 6, uintptr(unsafe.Pointer(&cur))); hr != 0 || cur == 0 {
|
||||
return nil, fmt.Errorf("GetCurrentDesktop: hr=0x%08x", hr)
|
||||
}
|
||||
defer comRelease(cur)
|
||||
|
||||
var arr uintptr
|
||||
if hr := comCall(m.mgr, 7, uintptr(unsafe.Pointer(&arr))); hr != 0 || arr == 0 {
|
||||
return nil, fmt.Errorf("GetDesktops: hr=0x%08x", hr)
|
||||
}
|
||||
defer comRelease(arr)
|
||||
|
||||
var count uintptr
|
||||
if hr := comCall(arr, 3, uintptr(unsafe.Pointer(&count))); hr != 0 {
|
||||
return nil, fmt.Errorf("IObjectArray.GetCount: hr=0x%08x", hr)
|
||||
}
|
||||
|
||||
ids := make([]comGUID, 0, count)
|
||||
for i := uintptr(0); i < count; i++ {
|
||||
var vd uintptr
|
||||
if hr := comCall(arr, 4, i, uintptr(unsafe.Pointer(&m.vdIID)), uintptr(unsafe.Pointer(&vd))); hr != 0 || vd == 0 {
|
||||
// 单个桌面获取失败:跳过(保持其余可用)
|
||||
continue
|
||||
}
|
||||
var id comGUID
|
||||
comCall(vd, 4, uintptr(unsafe.Pointer(&id))) // IVirtualDesktop.GetId(槽位 4,两版一致)
|
||||
comRelease(vd)
|
||||
ids = append(ids, id)
|
||||
}
|
||||
if len(ids) == 0 {
|
||||
return nil, fmt.Errorf("no virtual desktops enumerated")
|
||||
}
|
||||
return ids, nil
|
||||
}
|
||||
|
||||
// currentDesktopIndex 返回当前桌面在列表中的索引。
|
||||
func (m *desktopManager) currentDesktopIndex(ids []comGUID) (int, error) {
|
||||
var cur uintptr
|
||||
if hr := comCall(m.mgr, 6, uintptr(unsafe.Pointer(&cur))); hr != 0 || cur == 0 {
|
||||
return -1, fmt.Errorf("GetCurrentDesktop: hr=0x%08x", hr)
|
||||
}
|
||||
defer comRelease(cur)
|
||||
var id comGUID
|
||||
comCall(cur, 4, uintptr(unsafe.Pointer(&id)))
|
||||
for i := range ids {
|
||||
if ids[i] == id {
|
||||
return i, nil
|
||||
}
|
||||
}
|
||||
return -1, fmt.Errorf("current desktop not found in list")
|
||||
}
|
||||
|
||||
// switchToIndex 切换到指定索引的桌面。
|
||||
func (m *desktopManager) switchToIndex(idx int) error {
|
||||
var arr uintptr
|
||||
if hr := comCall(m.mgr, 7, uintptr(unsafe.Pointer(&arr))); hr != 0 || arr == 0 {
|
||||
return fmt.Errorf("GetDesktops: hr=0x%08x", hr)
|
||||
}
|
||||
defer comRelease(arr)
|
||||
var vd uintptr
|
||||
if hr := comCall(arr, 4, uintptr(idx), uintptr(unsafe.Pointer(&m.vdIID)), uintptr(unsafe.Pointer(&vd))); hr != 0 || vd == 0 {
|
||||
return fmt.Errorf("GetAt(%d): hr=0x%08x", idx, hr)
|
||||
}
|
||||
defer comRelease(vd)
|
||||
if hr := comCall(m.mgr, 9, vd); hr != 0 {
|
||||
return fmt.Errorf("SwitchDesktop: hr=0x%08x", hr)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// switchAdjacent 直接切换到物理相邻桌面(GetAdjacentDesktop + SwitchDesktop,
|
||||
// 3 次 COM 调用,避免完整枚举)。dir > 0 向右,dir < 0 向左。
|
||||
func (m *desktopManager) switchAdjacent(dir int32) error {
|
||||
direction := uintptr(4) // RightDirection
|
||||
if dir < 0 {
|
||||
direction = 3 // LeftDirection
|
||||
}
|
||||
var cur uintptr
|
||||
if hr := comCall(m.mgr, 6, uintptr(unsafe.Pointer(&cur))); hr != 0 || cur == 0 {
|
||||
return fmt.Errorf("GetCurrentDesktop: hr=0x%08x", hr)
|
||||
}
|
||||
defer comRelease(cur)
|
||||
var adj uintptr
|
||||
if hr := comCall(m.mgr, 8, cur, direction, uintptr(unsafe.Pointer(&adj))); hr != 0 || adj == 0 {
|
||||
return fmt.Errorf("GetAdjacentDesktop: hr=0x%08x", hr)
|
||||
}
|
||||
defer comRelease(adj)
|
||||
if hr := comCall(m.mgr, 9, adj); hr != 0 {
|
||||
return fmt.Errorf("SwitchDesktop: hr=0x%08x", hr)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// SwitchDesktopCOM 通过 COM 直调切换虚拟桌面(不依赖任何快捷键)。
|
||||
// dir > 0 向右(下一个桌面),dir < 0 向左。
|
||||
// 主路径:GetAdjacentDesktop 直切;边界或接口失效时回退枚举取模。
|
||||
func SwitchDesktopCOM(dir int32) error {
|
||||
if dir == 0 {
|
||||
return fmt.Errorf("switch desktop: dir must be non-zero")
|
||||
}
|
||||
// COM 调用线程约束:goroutine 在 syscall 之间可能被迁移到其他 OS 线程,
|
||||
// 而未初始化的线程调用 COM 代理会访问违例(0xc0000005)。
|
||||
// 锁定 OS 线程,保证 CoInitializeEx/所有 comCall/CoUninitialize 同线程。
|
||||
runtime.LockOSThread()
|
||||
defer runtime.UnlockOSThread()
|
||||
procCoInitializeEx.Call(0, coinitMultithreaded)
|
||||
defer procCoUninitialize.Call()
|
||||
|
||||
m, err := openDesktopManager()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer m.close()
|
||||
if err := m.switchAdjacent(dir); err == nil {
|
||||
return nil
|
||||
}
|
||||
// 边界(如最后一个桌面向右):枚举取模循环切换。
|
||||
ids, err := m.desktopIDs()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if len(ids) < 2 {
|
||||
return fmt.Errorf("switch desktop: only %d desktop(s), cannot switch", len(ids))
|
||||
}
|
||||
cur, err := m.currentDesktopIndex(ids)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
target := cur + int(dir)
|
||||
target = ((target % len(ids)) + len(ids)) % len(ids)
|
||||
return m.switchToIndex(target)
|
||||
}
|
||||
@@ -0,0 +1,119 @@
|
||||
package windows
|
||||
|
||||
import (
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"golang.org/x/sys/windows/registry"
|
||||
)
|
||||
|
||||
// TestVirtualDesktopQueryMatchesRegistry 验证 COM 查询的桌面列表与当前桌面
|
||||
// 和注册表(Explorer\VirtualDesktops)一致 —— 接口 IID 与 vtable 槽位正确性的
|
||||
// 端到端证据。headless/无 explorer 环境自动跳过。
|
||||
func TestVirtualDesktopQueryMatchesRegistry(t *testing.T) {
|
||||
procCoInitializeEx.Call(0, coinitMultithreaded)
|
||||
defer procCoUninitialize.Call()
|
||||
|
||||
m, err := openDesktopManager()
|
||||
if err != nil {
|
||||
t.Skipf("virtual desktop COM unavailable (explorer not running?): %v", err)
|
||||
}
|
||||
defer m.close()
|
||||
|
||||
ids, err := m.desktopIDs()
|
||||
if err != nil {
|
||||
t.Fatalf("desktopIDs: %v", err)
|
||||
}
|
||||
if len(ids) < 1 {
|
||||
t.Fatal("no desktops enumerated")
|
||||
}
|
||||
cur, err := m.currentDesktopIndex(ids)
|
||||
if err != nil {
|
||||
t.Fatalf("currentDesktopIndex: %v", err)
|
||||
}
|
||||
t.Logf("COM: %d desktops, current index %d", len(ids), cur)
|
||||
|
||||
// 注册表对照:CurrentVirtualDesktop(16 字节 GUID)
|
||||
k, err := registry.OpenKey(registry.CURRENT_USER,
|
||||
`SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\VirtualDesktops`, registry.READ)
|
||||
if err != nil {
|
||||
t.Skipf("registry key unavailable: %v", err)
|
||||
}
|
||||
defer k.Close()
|
||||
raw, _, err := k.GetBinaryValue("CurrentVirtualDesktop")
|
||||
if err != nil || len(raw) != 16 {
|
||||
t.Skipf("no CurrentVirtualDesktop registry value: %v", err)
|
||||
}
|
||||
var regGUID comGUID
|
||||
copy(regGUID.Data4[:], raw[8:16])
|
||||
regGUID.Data1 = uint32(raw[0]) | uint32(raw[1])<<8 | uint32(raw[2])<<16 | uint32(raw[3])<<24
|
||||
regGUID.Data2 = uint16(raw[4]) | uint16(raw[5])<<8
|
||||
regGUID.Data3 = uint16(raw[6]) | uint16(raw[7])<<8
|
||||
|
||||
if ids[cur] != regGUID {
|
||||
t.Fatalf("current desktop mismatch: COM=%v registry=%v", ids[cur], regGUID)
|
||||
}
|
||||
t.Logf("registry cross-check OK: current desktop GUID matches")
|
||||
}
|
||||
|
||||
// TestSwitchDesktopCOM 验证完整切换链路(向右切 + 向左切回)。
|
||||
// headless 会话无用户影响;结束前恢复原桌面。
|
||||
func TestSwitchDesktopCOM(t *testing.T) {
|
||||
procCoInitializeEx.Call(0, coinitMultithreaded)
|
||||
defer procCoUninitialize.Call()
|
||||
|
||||
// 切换前基线
|
||||
ids0, idx0, err := queryDesktopState()
|
||||
if err != nil {
|
||||
t.Skipf("query before: %v", err)
|
||||
}
|
||||
if len(ids0) < 2 {
|
||||
t.Skipf("only %d desktop(s), nothing to switch", len(ids0))
|
||||
}
|
||||
|
||||
// 向右切
|
||||
if err := SwitchDesktopCOM(1); err != nil {
|
||||
t.Fatalf("SwitchDesktopCOM(1): %v", err)
|
||||
}
|
||||
time.Sleep(200 * time.Millisecond) // 等待 explorer 生效
|
||||
_, idx1, err := queryDesktopState()
|
||||
if err != nil {
|
||||
t.Fatalf("query after switch: %v", err)
|
||||
}
|
||||
if idx1 == idx0 {
|
||||
t.Fatal("desktop did not change after SwitchDesktopCOM(1)")
|
||||
}
|
||||
t.Logf("switched to another desktop OK (idx %d -> %d)", idx0, idx1)
|
||||
|
||||
// 向左切回
|
||||
if err := SwitchDesktopCOM(-1); err != nil {
|
||||
t.Fatalf("SwitchDesktopCOM(-1): %v", err)
|
||||
}
|
||||
time.Sleep(200 * time.Millisecond)
|
||||
_, idx2, err := queryDesktopState()
|
||||
if err != nil {
|
||||
t.Fatalf("query after switch back: %v", err)
|
||||
}
|
||||
if idx2 != idx0 {
|
||||
t.Fatal("desktop did not return to original")
|
||||
}
|
||||
t.Logf("switched back to original desktop OK")
|
||||
}
|
||||
|
||||
// queryDesktopState 返回全部桌面 GUID 列表与当前索引。
|
||||
func queryDesktopState() ([]comGUID, int, error) {
|
||||
m, err := openDesktopManager()
|
||||
if err != nil {
|
||||
return nil, 0, err
|
||||
}
|
||||
defer m.close()
|
||||
ids, err := m.desktopIDs()
|
||||
if err != nil {
|
||||
return nil, 0, err
|
||||
}
|
||||
idx, err := m.currentDesktopIndex(ids)
|
||||
if err != nil {
|
||||
return nil, 0, err
|
||||
}
|
||||
return ids, idx, nil
|
||||
}
|
||||
@@ -0,0 +1,220 @@
|
||||
package windows
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"math"
|
||||
"runtime"
|
||||
"time"
|
||||
"unsafe"
|
||||
)
|
||||
|
||||
// 精确音量 COM 直调(Core Audio API,公开稳定接口,自 Windows Vista 起不变)。
|
||||
// 不注入媒体键,因此不受输入法/Quicker 等按键监听软件干扰。
|
||||
//
|
||||
// 获取链:IMMDeviceEnumerator.GetDefaultAudioEndpoint(eRender, eMultimedia)
|
||||
//
|
||||
// → IMMDevice.Activate(IID_IAudioEndpointVolume)
|
||||
//
|
||||
// IAudioEndpointVolume vtable(含 IUnknown 前 3 个):
|
||||
//
|
||||
// SetMasterVolumeLevelScalar = 7 (float32 0.0~1.0, GUID*)
|
||||
// GetMasterVolumeLevelScalar = 9 (*float32)
|
||||
// SetMute = 14 (BOOL, GUID*)
|
||||
// GetMute = 15 (*BOOL)
|
||||
var (
|
||||
guidMMDeviceEnumerator = comGUIDFromString("BCDE0395-E52F-467C-8E3D-C4579291692E")
|
||||
iidIMMDeviceEnumerator = comGUIDFromString("A95664D2-9614-4F35-A746-DE8DB63617E6")
|
||||
iidIMMDevice = comGUIDFromString("D666063F-1587-4E43-81F1-B948E807363F")
|
||||
iidAudioEndpointVolume = comGUIDFromString("5CDF2C82-841E-4546-9722-0CF74078229A")
|
||||
)
|
||||
|
||||
const (
|
||||
eRender = 0
|
||||
// 音频设备角色(ERole)。角色不同可解析到不同默认设备:
|
||||
// eConsole=0(控制台应用)、eMultimedia=1(多媒体应用)、eCommunications=2(通信)。
|
||||
// 任务栏音量图标 / Win11 快速设置面板控制的是 eMultimedia 默认端点,
|
||||
// 即用户实际"听到"的系统输出设备。使用 eConsole 在多设备环境(如
|
||||
// 音箱 + USB 耳机 + HDMI)下可能解析到非聆听设备,导致 Set 成功但音量无变化。
|
||||
eConsole = 0
|
||||
eMultimedia = 1
|
||||
eCommunications = 2
|
||||
clsctxAll = 0x17 // CLSCTX_ALL
|
||||
comTrue = 1
|
||||
comFalse = 0
|
||||
volumeSetEpsilon = 0.01 // 音量读回验证容差(scalar 0.0~1.0)
|
||||
)
|
||||
|
||||
// openEndpointVolume 打开默认渲染端点的 IAudioEndpointVolume。
|
||||
// 每次调用完整重建 IMMDeviceEnumerator → IMMDevice → Activate 链
|
||||
// (不跨调用缓存:与虚拟桌面同理,缓存的 COM 代理在 CoUninitialize 后失效)。
|
||||
// 角色使用 eMultimedia:与任务栏/快速设置音量条一致,指向用户实际聆听设备。
|
||||
// 调用方必须已 CoInitializeEx 并 LockOSThread(见 VolumeAdjustPercent)。
|
||||
func openEndpointVolume() (uintptr, error) {
|
||||
var enumerator uintptr
|
||||
hr, _, _ := procCoCreateInstance.Call(
|
||||
uintptr(unsafe.Pointer(&guidMMDeviceEnumerator)), 0, clsctxAll,
|
||||
uintptr(unsafe.Pointer(&iidIMMDeviceEnumerator)),
|
||||
uintptr(unsafe.Pointer(&enumerator)))
|
||||
if enumerator == 0 {
|
||||
return 0, fmt.Errorf("create device enumerator: hr=0x%08x", hr)
|
||||
}
|
||||
defer comRelease(enumerator)
|
||||
|
||||
var device uintptr
|
||||
// IMMDeviceEnumerator.GetDefaultAudioEndpoint(槽位 4)
|
||||
if hr := comCall(enumerator, 4, eRender, eMultimedia, uintptr(unsafe.Pointer(&device))); hr != 0 || device == 0 {
|
||||
return 0, fmt.Errorf("get default audio endpoint: hr=0x%08x", hr)
|
||||
}
|
||||
defer comRelease(device)
|
||||
|
||||
var vol uintptr
|
||||
// IMMDevice.Activate(槽位 3)
|
||||
if hr := comCall(device, 3, uintptr(unsafe.Pointer(&iidAudioEndpointVolume)), clsctxAll, 0, uintptr(unsafe.Pointer(&vol))); hr != 0 || vol == 0 {
|
||||
return 0, fmt.Errorf("activate endpoint volume: hr=0x%08x", hr)
|
||||
}
|
||||
return vol, nil
|
||||
}
|
||||
|
||||
// getMasterVolumeScalar 读取当前音量(0.0~1.0 线性)。槽位 9。
|
||||
func getMasterVolumeScalar(vol uintptr) (float32, error) {
|
||||
var s float32
|
||||
if hr := comCall(vol, 9, uintptr(unsafe.Pointer(&s))); hr != 0 {
|
||||
return 0, fmt.Errorf("get volume scalar: hr=0x%08x", hr)
|
||||
}
|
||||
return s, nil
|
||||
}
|
||||
|
||||
// setMasterVolumeScalar 设置音量(0.0~1.0 线性)。槽位 7。
|
||||
func setMasterVolumeScalar(vol uintptr, scalar float32) error {
|
||||
if hr := comCall(vol, 7, uintptr(math.Float32bits(scalar)), 0); hr != 0 {
|
||||
return fmt.Errorf("set volume scalar: hr=0x%08x", hr)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// getMuteCOM 读取静音状态。槽位 15。
|
||||
func getMuteCOM(vol uintptr) (bool, error) {
|
||||
var muted int32
|
||||
if hr := comCall(vol, 15, uintptr(unsafe.Pointer(&muted))); hr != 0 {
|
||||
return false, fmt.Errorf("get mute: hr=0x%08x", hr)
|
||||
}
|
||||
return muted != 0, nil
|
||||
}
|
||||
|
||||
// setMuteCOM 设置静音。槽位 14。
|
||||
func setMuteCOM(vol uintptr, mute bool) error {
|
||||
m := uintptr(comFalse)
|
||||
if mute {
|
||||
m = comTrue
|
||||
}
|
||||
if hr := comCall(vol, 14, m, 0); hr != 0 {
|
||||
return fmt.Errorf("set mute: hr=0x%08x", hr)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// setMasterVolumeScalarVerified 设置音量并读回验证。
|
||||
// 部分驱动/端点状态会返回 S_OK 但实际不生效(表现为"音量没动"),
|
||||
// 读回可区分"程序没改到"与"改的不是聆听设备"。容忍短暂异步应用。
|
||||
func setMasterVolumeScalarVerified(vol uintptr, scalar float32) error {
|
||||
if err := setMasterVolumeScalar(vol, scalar); err != nil {
|
||||
return err
|
||||
}
|
||||
for i := 0; i < 3; i++ {
|
||||
after, err := getMasterVolumeScalar(vol)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if math.Abs(float64(after-scalar)) <= volumeSetEpsilon {
|
||||
return nil
|
||||
}
|
||||
if i < 2 {
|
||||
time.Sleep(10 * time.Millisecond)
|
||||
}
|
||||
}
|
||||
after, _ := getMasterVolumeScalar(vol)
|
||||
return fmt.Errorf("volume set not applied: want %.2f got %.2f", scalar, after)
|
||||
}
|
||||
|
||||
// setMuteVerified 设置静音并读回验证(同 setMasterVolumeScalarVerified)。
|
||||
func setMuteVerified(vol uintptr, mute bool) error {
|
||||
if err := setMuteCOM(vol, mute); err != nil {
|
||||
return err
|
||||
}
|
||||
for i := 0; i < 3; i++ {
|
||||
got, err := getMuteCOM(vol)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if got == mute {
|
||||
return nil
|
||||
}
|
||||
if i < 2 {
|
||||
time.Sleep(10 * time.Millisecond)
|
||||
}
|
||||
}
|
||||
got, _ := getMuteCOM(vol)
|
||||
return fmt.Errorf("mute set not applied: want %v got %v", mute, got)
|
||||
}
|
||||
|
||||
// withVolumeCOM 在完整 COM 生命周期内执行 fn(线程锁定,MTA)。
|
||||
func withVolumeCOM(fn func(vol uintptr) error) error {
|
||||
runtime.LockOSThread()
|
||||
defer runtime.UnlockOSThread()
|
||||
procCoInitializeEx.Call(0, coinitMultithreaded)
|
||||
defer procCoUninitialize.Call()
|
||||
|
||||
vol, err := openEndpointVolume()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer comRelease(vol)
|
||||
return fn(vol)
|
||||
}
|
||||
|
||||
// GetMasterVolumePercent 读取当前音量百分比(0~100)。诊断/读回用。
|
||||
func GetMasterVolumePercent() (int, error) {
|
||||
var pct int
|
||||
err := withVolumeCOM(func(vol uintptr) error {
|
||||
scalar, err := getMasterVolumeScalar(vol)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
pct = int(math.Round(float64(scalar) * 100))
|
||||
return nil
|
||||
})
|
||||
return pct, err
|
||||
}
|
||||
|
||||
// VolumeAdjustPercent 以百分比步进调整音量(1 = ±1%)。dir > 0 增大。
|
||||
func VolumeAdjustPercent(dir int32) error {
|
||||
if dir == 0 {
|
||||
return fmt.Errorf("volume adjust: delta must be non-zero")
|
||||
}
|
||||
return withVolumeCOM(func(vol uintptr) error {
|
||||
scalar, err := getMasterVolumeScalar(vol)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
cur := int32(math.Round(float64(scalar) * 100))
|
||||
target := cur + dir
|
||||
if target < 0 {
|
||||
target = 0
|
||||
}
|
||||
if target > 100 {
|
||||
target = 100
|
||||
}
|
||||
return setMasterVolumeScalarVerified(vol, float32(target)/100)
|
||||
})
|
||||
}
|
||||
|
||||
// ToggleMuteCOM 切换静音。
|
||||
func ToggleMuteCOM() error {
|
||||
return withVolumeCOM(func(vol uintptr) error {
|
||||
muted, err := getMuteCOM(vol)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return setMuteVerified(vol, !muted)
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,214 @@
|
||||
package windows
|
||||
|
||||
import (
|
||||
"math"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
// TestVolumeEndpointCOM 验证 COM 音量接口可用性(仅诊断,无设备时跳过)。
|
||||
// 成功时验证读取/写入音量往返(恢复原值)。
|
||||
func TestVolumeEndpointCOM(t *testing.T) {
|
||||
if testing.Short() {
|
||||
t.Skip("short mode")
|
||||
}
|
||||
err := withVolumeCOM(func(vol uintptr) error {
|
||||
scalar, err := getMasterVolumeScalar(vol)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if scalar < 0 || scalar > 1 {
|
||||
t.Fatalf("scalar out of range: %v", scalar)
|
||||
}
|
||||
muted, err := getMuteCOM(vol)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
t.Logf("当前音量: %.1f%%, 静音: %v", scalar*100, muted)
|
||||
// 往返测试:读取 → 写回(同值)→ 恢复
|
||||
original := scalar
|
||||
if err := setMasterVolumeScalar(vol, original); err != nil {
|
||||
return err
|
||||
}
|
||||
after, err := getMasterVolumeScalar(vol)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if math.Abs(float64(after-original)) > 0.01 {
|
||||
t.Fatalf("round trip mismatch: %v -> %v", original, after)
|
||||
}
|
||||
t.Logf("COM 音量读写往返 OK")
|
||||
return nil
|
||||
})
|
||||
if err != nil {
|
||||
t.Skipf("audio endpoint unavailable (headless/no device?): %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
// TestVolumeAdjustPercent 验证百分比计算正确性(纯逻辑,不依赖设备)。
|
||||
func TestVolumeAdjustPercent(t *testing.T) {
|
||||
cases := []struct {
|
||||
cur, delta, want int32
|
||||
}{
|
||||
{50, 1, 51},
|
||||
{50, -1, 49},
|
||||
{99, 5, 100}, // 上限
|
||||
{1, -5, 0}, // 下限
|
||||
{0, -1, 0},
|
||||
{100, 1, 100},
|
||||
}
|
||||
for _, c := range cases {
|
||||
target := c.cur + c.delta
|
||||
if target < 0 {
|
||||
target = 0
|
||||
}
|
||||
if target > 100 {
|
||||
target = 100
|
||||
}
|
||||
if target != c.want {
|
||||
t.Errorf("clamp(%d%+d) = %d, want %d", c.cur, c.delta, target, c.want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// TestVolumeAdjustPercentApplies 差分回归测试:调节后读回必须真的变化。
|
||||
// 现有往返测试写回同值,无法发现"Set 返回 S_OK 但实际没生效"的静默 no-op
|
||||
// (本次 bug 的根因形态)。本测试写一个不同的值并读回断言,失败即回归。
|
||||
func TestVolumeAdjustPercentApplies(t *testing.T) {
|
||||
if testing.Short() {
|
||||
t.Skip("short mode")
|
||||
}
|
||||
before, err := GetMasterVolumePercent()
|
||||
if err != nil {
|
||||
t.Skipf("audio endpoint unavailable (headless/no device?): %v", err)
|
||||
}
|
||||
if before < 99 {
|
||||
// 增大 1% → 读回 must == before+1 → 恢复
|
||||
if err := VolumeAdjustPercent(1); err != nil {
|
||||
t.Fatalf("VolumeAdjustPercent(+1): %v", err)
|
||||
}
|
||||
after, err := GetMasterVolumePercent()
|
||||
if err != nil {
|
||||
t.Fatalf("readback after up: %v", err)
|
||||
}
|
||||
if after != before+1 {
|
||||
t.Fatalf("volume_up not applied: %d -> %d (want %d)", before, after, before+1)
|
||||
}
|
||||
if err := VolumeAdjustPercent(-1); err != nil {
|
||||
t.Fatalf("VolumeAdjustPercent(-1) restore: %v", err)
|
||||
}
|
||||
restored, err := GetMasterVolumePercent()
|
||||
if err != nil {
|
||||
t.Fatalf("readback after restore: %v", err)
|
||||
}
|
||||
if restored != before {
|
||||
t.Fatalf("volume restore failed: %d -> %d (want %d)", before, restored, before)
|
||||
}
|
||||
} else {
|
||||
// 已在上限附近:先降 1% → 读回 must == before-1 → 恢复
|
||||
if err := VolumeAdjustPercent(-1); err != nil {
|
||||
t.Fatalf("VolumeAdjustPercent(-1): %v", err)
|
||||
}
|
||||
after, err := GetMasterVolumePercent()
|
||||
if err != nil {
|
||||
t.Fatalf("readback after down: %v", err)
|
||||
}
|
||||
if after != before-1 {
|
||||
t.Fatalf("volume_down not applied: %d -> %d (want %d)", before, after, before-1)
|
||||
}
|
||||
if err := VolumeAdjustPercent(1); err != nil {
|
||||
t.Fatalf("VolumeAdjustPercent(+1) restore: %v", err)
|
||||
}
|
||||
restored, err := GetMasterVolumePercent()
|
||||
if err != nil {
|
||||
t.Fatalf("readback after restore: %v", err)
|
||||
}
|
||||
if restored != before {
|
||||
t.Fatalf("volume restore failed: %d -> %d (want %d)", before, restored, before)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// readMuteState 读取当前静音状态(诊断/断言用)。
|
||||
func readMuteState(t *testing.T) (bool, error) {
|
||||
t.Helper()
|
||||
var muted bool
|
||||
err := withVolumeCOM(func(vol uintptr) error {
|
||||
got, err := getMuteCOM(vol)
|
||||
muted = got
|
||||
return err
|
||||
})
|
||||
return muted, err
|
||||
}
|
||||
|
||||
// TestToggleMuteApplies 差分回归测试:静音切换后读回必须真的变化。
|
||||
func TestToggleMuteApplies(t *testing.T) {
|
||||
if testing.Short() {
|
||||
t.Skip("short mode")
|
||||
}
|
||||
before, err := readMuteState(t)
|
||||
if err != nil {
|
||||
t.Skipf("audio endpoint unavailable (headless/no device?): %v", err)
|
||||
}
|
||||
if err := ToggleMuteCOM(); err != nil {
|
||||
t.Fatalf("ToggleMuteCOM: %v", err)
|
||||
}
|
||||
after, err := readMuteState(t)
|
||||
if err != nil {
|
||||
t.Fatalf("readback after toggle: %v", err)
|
||||
}
|
||||
if after == before {
|
||||
t.Fatalf("mute toggle not applied: %v -> %v", before, after)
|
||||
}
|
||||
if err := ToggleMuteCOM(); err != nil {
|
||||
t.Fatalf("ToggleMuteCOM restore: %v", err)
|
||||
}
|
||||
restored, err := readMuteState(t)
|
||||
if err != nil {
|
||||
t.Fatalf("readback after restore: %v", err)
|
||||
}
|
||||
if restored != before {
|
||||
t.Fatalf("mute restore failed: %v -> %v (want %v)", before, restored, before)
|
||||
}
|
||||
}
|
||||
|
||||
// TestVolumeAdjustRepeatedGoroutines 模拟真实触发模式:每次调节由独立
|
||||
// goroutine(可能不同 OS 线程)发起,验证反复 COM 会话不退化
|
||||
// (与 TestSwitchDesktopCOMCrossGoroutine 同思路的回归测试)。
|
||||
func TestVolumeAdjustRepeatedGoroutines(t *testing.T) {
|
||||
if testing.Short() {
|
||||
t.Skip("short mode")
|
||||
}
|
||||
base, err := GetMasterVolumePercent()
|
||||
if err != nil {
|
||||
t.Skipf("audio endpoint unavailable (headless/no device?): %v", err)
|
||||
}
|
||||
// 避免在 0/100 边界处因 clamp 导致净变化:靠近上限时先降后升。
|
||||
upFirst := base < 99
|
||||
for i := 0; i < 4; i++ {
|
||||
done := make(chan error, 1)
|
||||
go func(up bool) {
|
||||
var err error
|
||||
if up {
|
||||
err = VolumeAdjustPercent(1)
|
||||
if err == nil {
|
||||
err = VolumeAdjustPercent(-1)
|
||||
}
|
||||
} else {
|
||||
err = VolumeAdjustPercent(-1)
|
||||
if err == nil {
|
||||
err = VolumeAdjustPercent(1)
|
||||
}
|
||||
}
|
||||
done <- err
|
||||
}(upFirst)
|
||||
select {
|
||||
case err := <-done:
|
||||
if err != nil {
|
||||
t.Fatalf("第%d次调节返回错误: %v", i+1, err)
|
||||
}
|
||||
case <-time.After(5 * time.Second):
|
||||
t.Fatalf("第%d次调节超时", i+1)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
package windows
|
||||
|
||||
// GetMuteState 读取当前默认渲染端点的静音状态。
|
||||
// 供动作层在静音切换后读回状态用于 Toast 显示;复用 volume_com.go 的
|
||||
// COM 生命周期封装与 getMuteCOM,不改动既有实现。
|
||||
func GetMuteState() (bool, error) {
|
||||
var muted bool
|
||||
err := withVolumeCOM(func(vol uintptr) error {
|
||||
m, err := getMuteCOM(vol)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
muted = m
|
||||
return nil
|
||||
})
|
||||
return muted, err
|
||||
}
|
||||
@@ -0,0 +1,91 @@
|
||||
package windows
|
||||
|
||||
import (
|
||||
"syscall"
|
||||
"unsafe"
|
||||
)
|
||||
|
||||
// 本文件集中封装 platform/windows 需要的 user32 基础 API 胶水,
|
||||
// 保持"所有 DLL 访问集中于本包"的约束。
|
||||
|
||||
// msg 对应 Win32 MSG 结构。
|
||||
type msg struct {
|
||||
hwnd uintptr
|
||||
message uint32
|
||||
wParam uintptr
|
||||
lParam uintptr
|
||||
time uint32
|
||||
pt struct{ x, y int32 }
|
||||
}
|
||||
|
||||
// rect 对应 Win32 RECT 结构。
|
||||
type rect struct {
|
||||
Left, Top, Right, Bottom int32
|
||||
}
|
||||
|
||||
var (
|
||||
procEnumDisplayMonitors = user32Hook.NewProc("EnumDisplayMonitors")
|
||||
procGetSystemMetrics = user32Hook.NewProc("GetSystemMetrics")
|
||||
procGetMessageW = user32Hook.NewProc("GetMessageW")
|
||||
procPostThreadMessageW = user32Hook.NewProc("PostThreadMessageW")
|
||||
)
|
||||
|
||||
// getMessage 进入消息等待;返回 0 表示 WM_QUIT,-1 表示错误。
|
||||
func getMessage(m *msg, hwnd uintptr, min, max uint32) (int32, error) {
|
||||
r, _, err := procGetMessageW.Call(
|
||||
uintptr(unsafe.Pointer(m)), hwnd, uintptr(min), uintptr(max))
|
||||
return int32(int64(r)), err
|
||||
}
|
||||
|
||||
// postThreadMessage 向线程消息队列投递消息。
|
||||
func postThreadMessage(threadID uint32, m uint32, wParam, lParam uintptr) error {
|
||||
r, _, err := procPostThreadMessageW.Call(uintptr(threadID), uintptr(m), wParam, lParam)
|
||||
if r == 0 {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// getSystemMetrics 查询系统指标(SM_CXSCREEN 等)。
|
||||
func getSystemMetrics(index int32) int32 {
|
||||
r, _, _ := procGetSystemMetrics.Call(uintptr(index))
|
||||
return int32(r)
|
||||
}
|
||||
|
||||
// enumDisplayMonitorsCB 为 EnumDisplayMonitors 的 Win32 回调(包级单例)。
|
||||
//
|
||||
// ⚠️ 必须复用:syscall.NewCallback 每次调用都会在 Go runtime 的 Windows
|
||||
// 回调表(cb_max=2000 槽,见 runtime/zcallback_windows.go)登记新条目且
|
||||
// 永不释放。高频路径(全屏轮询 300ms/次)每次新建回调会把表耗尽并触发
|
||||
// fatal error "too many callback functions"——进程在约 2000×300ms=600 秒
|
||||
// 整静默退出(windowsgui 下无任何日志)。2000 槽 ÷ 3.33 次/秒 ≈ 10 分钟,
|
||||
// 与本项目观察到的"启动后精确 10 分钟死亡"完全吻合。
|
||||
//
|
||||
// ⚠️ 回调的用户数据必须经 lParam 传递,绝不能在回调内访问全局共享状态:
|
||||
// EnumDisplayMonitors 是同步调用,回调会在同一 OS 线程回到 Go;若在回调
|
||||
// 内对"调用方持有的互斥锁"加锁,无论回调与调用方是否同 goroutine 都会
|
||||
// 死锁(同 goroutine:Mutex 不可重入;异 goroutine:循环等待),表现为
|
||||
// 进程存活但所有触发功能静默失效。
|
||||
var enumDisplayMonitorsCB = syscall.NewCallback(func(hMonitor, hdc, lprc, lparam uintptr) uintptr {
|
||||
if lprc != 0 {
|
||||
r := *(**rect)(unsafe.Pointer(&lprc))
|
||||
if r != nil {
|
||||
cb := *(*func(r rect) bool)(unsafe.Pointer(lparam))
|
||||
if cb != nil && !cb(*r) {
|
||||
return 0
|
||||
}
|
||||
}
|
||||
}
|
||||
return 1
|
||||
})
|
||||
|
||||
// enumDisplayMonitors 枚举显示器,cb 返回 false 停止。
|
||||
func enumDisplayMonitors(cb func(r rect) bool) error {
|
||||
// cb 通过 lParam 传给回调:EnumDisplayMonitors 同步返回,调用期间发起
|
||||
// 调用的 goroutine 处于 syscall 状态,其栈不会移动,&cb 保持有效。
|
||||
r, _, err := procEnumDisplayMonitors.Call(0, 0, enumDisplayMonitorsCB, uintptr(unsafe.Pointer(&cb)))
|
||||
if r == 0 {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,278 @@
|
||||
// Package rule 实现规则引擎:事件 → 匹配 → 冷却 → 动作链执行。
|
||||
// 引擎不依赖 Win32 具体实现;运行时使用内存快照,不读磁盘。
|
||||
package rule
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"log/slog"
|
||||
"sort"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
"time"
|
||||
|
||||
"zerorigin/internal/action"
|
||||
"zerorigin/internal/config"
|
||||
"zerorigin/internal/trigger"
|
||||
)
|
||||
|
||||
// defaultActionTimeout 为单个动作的最大执行时间。
|
||||
const defaultActionTimeout = 10 * time.Second
|
||||
|
||||
// NewActionFunc 按 ID 构造动作实例(测试可注入 fake)。
|
||||
type NewActionFunc func(id string) (action.Action, error)
|
||||
|
||||
// Snapshot 为已校验规则的只读运行时快照。
|
||||
type Snapshot struct {
|
||||
Rules []*config.Rule // 按 priority 降序
|
||||
BadCount int // 被跳过的坏规则数量
|
||||
GlobalEnabled bool // 全局开关(config.global.enabled)
|
||||
}
|
||||
|
||||
// Engine 为规则引擎。
|
||||
type Engine struct {
|
||||
logger *slog.Logger
|
||||
newAction NewActionFunc
|
||||
|
||||
snap atomic.Pointer[Snapshot]
|
||||
|
||||
// fullscreen 为全屏状态提供者(由 app 注入,nil 表示不抑制)。
|
||||
fullscreen func() bool
|
||||
|
||||
mu sync.Mutex
|
||||
lastExec map[string]time.Time // 规则冷却:ID → 上次触发时间
|
||||
lastLog map[string]time.Time // 触发日志限速:ID → 上次 Info 时间
|
||||
running map[string]bool // 规则并发保护
|
||||
wg sync.WaitGroup
|
||||
}
|
||||
|
||||
// New 创建规则引擎。
|
||||
func New(logger *slog.Logger, newAction NewActionFunc) *Engine {
|
||||
if newAction == nil {
|
||||
newAction = action.New
|
||||
}
|
||||
return &Engine{
|
||||
logger: logger,
|
||||
newAction: newAction,
|
||||
lastExec: make(map[string]time.Time),
|
||||
lastLog: make(map[string]time.Time),
|
||||
running: make(map[string]bool),
|
||||
}
|
||||
}
|
||||
|
||||
// SetFullscreenProvider 注入全屏状态提供者(返回 true 表示前台窗口全屏)。
|
||||
// 引擎在规则匹配前查询;提供者为 nil 时不做全屏抑制。
|
||||
func (e *Engine) SetFullscreenProvider(f func() bool) {
|
||||
e.fullscreen = f
|
||||
}
|
||||
|
||||
// SetSnapshot 原子替换运行时快照。
|
||||
func (e *Engine) SetSnapshot(s *Snapshot) {
|
||||
e.snap.Store(s)
|
||||
}
|
||||
|
||||
// Snapshot 返回当前快照(可能为 nil)。
|
||||
func (e *Engine) Snapshot() *Snapshot {
|
||||
return e.snap.Load()
|
||||
}
|
||||
|
||||
// BuildSnapshot 从配置构造快照:逐条校验,坏规则跳过并计数。
|
||||
// 校验失败仅影响该规则,不阻止其他规则加载。
|
||||
func BuildSnapshot(cfg *config.Config, newAction NewActionFunc) *Snapshot {
|
||||
if newAction == nil {
|
||||
newAction = action.New
|
||||
}
|
||||
snap := &Snapshot{GlobalEnabled: cfg.Global.Enabled}
|
||||
for i := range cfg.Rules {
|
||||
r := &cfg.Rules[i]
|
||||
if err := validateRule(r, newAction); err != nil {
|
||||
snap.BadCount++
|
||||
continue
|
||||
}
|
||||
snap.Rules = append(snap.Rules, r)
|
||||
}
|
||||
// 优先级降序,稳定排序保证同优先级按配置顺序。
|
||||
sort.SliceStable(snap.Rules, func(i, j int) bool {
|
||||
return snap.Rules[i].Priority > snap.Rules[j].Priority
|
||||
})
|
||||
return snap
|
||||
}
|
||||
|
||||
// validateRule 校验单条规则。条件系统 MVP 不支持(非空即坏)。
|
||||
func validateRule(r *config.Rule, newAction NewActionFunc) error {
|
||||
if r.ID == "" {
|
||||
return errors.New("empty rule id")
|
||||
}
|
||||
if !trigger.Known(r.Trigger.Type) {
|
||||
return fmt.Errorf("unknown trigger %q", r.Trigger.Type)
|
||||
}
|
||||
if len(r.Actions) == 0 {
|
||||
return errors.New("rule has no actions")
|
||||
}
|
||||
if len(r.Conditions) > 0 {
|
||||
return errors.New("conditions not supported in MVP")
|
||||
}
|
||||
switch r.Fullscreen {
|
||||
case "", "ignore", "allow":
|
||||
default:
|
||||
return fmt.Errorf("invalid fullscreen value %q (want ignore|allow)", r.Fullscreen)
|
||||
}
|
||||
for _, a := range r.Actions {
|
||||
act, err := newAction(a.Type)
|
||||
if err != nil {
|
||||
return fmt.Errorf("action %q: %w", a.Type, err)
|
||||
}
|
||||
if err := act.Validate(a.Params); err != nil {
|
||||
return fmt.Errorf("action %q: %w", a.Type, err)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// TriggerKey 生成触发器去重键(type + 稳定序列化的参数)。
|
||||
func TriggerKey(tc config.TriggerConfig) string {
|
||||
b, _ := json.Marshal(tc.Params)
|
||||
return tc.Type + "|" + string(b)
|
||||
}
|
||||
|
||||
// matches 判断规则触发器是否匹配事件:类型一致且规则声明的
|
||||
// 参数与事件 payload 一致(事件多余的字段不参与匹配)。
|
||||
func matches(r *config.Rule, ev trigger.Event) bool {
|
||||
if r.Trigger.Type != ev.Type {
|
||||
return false
|
||||
}
|
||||
for k, want := range r.Trigger.Params {
|
||||
got, ok := ev.Payload[k]
|
||||
if !ok {
|
||||
continue
|
||||
}
|
||||
if fmt.Sprint(got) != fmt.Sprint(want) {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
// HandleEvent 处理触发事件:按优先级找到第一条匹配且可执行的规则,
|
||||
// 在独立 goroutine 中执行其动作链。必须在触发线程快速返回。
|
||||
func (e *Engine) HandleEvent(ev trigger.Event) {
|
||||
snap := e.snap.Load()
|
||||
if snap == nil || !snap.GlobalEnabled {
|
||||
return // 全局关闭时不匹配任何规则
|
||||
}
|
||||
fs := e.fullscreen != nil && e.fullscreen()
|
||||
for _, r := range snap.Rules {
|
||||
if !r.Enabled || !matches(r, ev) {
|
||||
continue
|
||||
}
|
||||
if fs && r.Fullscreen != "allow" {
|
||||
// 全屏前台窗口:默认忽略(allow 规则豁免)。
|
||||
continue
|
||||
}
|
||||
if !e.cooldownOK(r) {
|
||||
return // 冷却中:该事件已消耗,不再尝试其他规则
|
||||
}
|
||||
if !e.tryAcquire(r.ID) {
|
||||
return // 同规则执行中:丢弃新事件
|
||||
}
|
||||
e.wg.Add(1)
|
||||
go e.runRule(r, ev)
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
// cooldownOK 检查并预订规则冷却时间戳。
|
||||
func (e *Engine) cooldownOK(r *config.Rule) bool {
|
||||
e.mu.Lock()
|
||||
defer e.mu.Unlock()
|
||||
now := time.Now()
|
||||
if last, ok := e.lastExec[r.ID]; ok {
|
||||
if now.Sub(last) < time.Duration(r.CooldownMs)*time.Millisecond {
|
||||
return false
|
||||
}
|
||||
}
|
||||
e.lastExec[r.ID] = now
|
||||
return true
|
||||
}
|
||||
|
||||
func (e *Engine) tryAcquire(id string) bool {
|
||||
e.mu.Lock()
|
||||
defer e.mu.Unlock()
|
||||
if e.running[id] {
|
||||
return false
|
||||
}
|
||||
e.running[id] = true
|
||||
return true
|
||||
}
|
||||
|
||||
func (e *Engine) release(id string) {
|
||||
e.mu.Lock()
|
||||
defer e.mu.Unlock()
|
||||
delete(e.running, id)
|
||||
}
|
||||
|
||||
// firedLog 输出规则触发日志(高频规则限速采样:每规则每秒至多一条 Info)。
|
||||
func (e *Engine) firedLog(r *config.Rule, ev trigger.Event) {
|
||||
e.mu.Lock()
|
||||
now := time.Now()
|
||||
rateLimited := false
|
||||
if last, ok := e.lastLog[r.ID]; ok && now.Sub(last) < time.Second {
|
||||
rateLimited = true
|
||||
} else {
|
||||
e.lastLog[r.ID] = now
|
||||
}
|
||||
e.mu.Unlock()
|
||||
|
||||
if rateLimited {
|
||||
e.logger.Debug("rule fired", "rule", r.ID, "event", ev.Type, "actions", len(r.Actions))
|
||||
return
|
||||
}
|
||||
e.logger.Info("rule fired", "rule", r.ID, "event", ev.Type, "actions", len(r.Actions))
|
||||
}
|
||||
|
||||
// runRule 顺序执行规则的动作链,错误隔离:单动作失败记录并继续。
|
||||
func (e *Engine) runRule(r *config.Rule, ev trigger.Event) {
|
||||
defer e.wg.Done()
|
||||
defer e.release(r.ID)
|
||||
// 动作链 panic 兜底:任何动作实现异常不得拖垮主进程。
|
||||
defer func() {
|
||||
if rec := recover(); rec != nil {
|
||||
e.logger.Error("rule action panic", "rule", r.ID, "panic", rec)
|
||||
}
|
||||
}()
|
||||
|
||||
ctx, cancel := context.WithTimeout(context.Background(), defaultActionTimeout)
|
||||
defer cancel()
|
||||
|
||||
e.firedLog(r, ev)
|
||||
failed := 0
|
||||
for _, ac := range r.Actions {
|
||||
a, err := e.newAction(ac.Type)
|
||||
if err != nil {
|
||||
e.logger.Error("rule action skipped", "rule", r.ID, "action", ac.Type, "err", err)
|
||||
failed++
|
||||
continue
|
||||
}
|
||||
if err := a.Validate(ac.Params); err != nil {
|
||||
e.logger.Error("rule action invalid", "rule", r.ID, "action", ac.Type, "err", err)
|
||||
failed++
|
||||
continue
|
||||
}
|
||||
if err := a.Execute(ctx, ac.Params); err != nil {
|
||||
e.logger.Error("rule action failed", "rule", r.ID, "action", ac.Type, "err", err)
|
||||
failed++
|
||||
continue // 错误隔离:继续后续动作
|
||||
}
|
||||
e.logger.Debug("rule action ok", "rule", r.ID, "action", ac.Type)
|
||||
}
|
||||
if failed > 0 {
|
||||
e.logger.Warn("rule completed with errors", "rule", r.ID, "failed", failed)
|
||||
}
|
||||
}
|
||||
|
||||
// Wait 等待所有进行中的动作链结束(退出前调用)。
|
||||
func (e *Engine) Wait() {
|
||||
e.wg.Wait()
|
||||
}
|
||||
@@ -0,0 +1,314 @@
|
||||
package rule
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"log/slog"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"zerorigin/internal/action"
|
||||
"zerorigin/internal/config"
|
||||
"zerorigin/internal/trigger"
|
||||
)
|
||||
|
||||
// fakeAction 记录执行顺序与参数的可编程动作。
|
||||
type fakeAction struct {
|
||||
id string
|
||||
validate func(map[string]any) error
|
||||
execute func(ctx context.Context) error
|
||||
executed []string
|
||||
mu sync.Mutex
|
||||
block chan struct{} // 非 nil 时 Execute 阻塞等待
|
||||
}
|
||||
|
||||
func (f *fakeAction) ID() string { return f.id }
|
||||
func (f *fakeAction) Name() string { return f.id }
|
||||
func (f *fakeAction) Schema() action.ActionSchema {
|
||||
return action.ActionSchema{}
|
||||
}
|
||||
func (f *fakeAction) Validate(p map[string]any) error {
|
||||
if f.validate != nil {
|
||||
return f.validate(p)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
func (f *fakeAction) Execute(ctx context.Context, p map[string]any) error {
|
||||
f.mu.Lock()
|
||||
f.executed = append(f.executed, f.id)
|
||||
f.mu.Unlock()
|
||||
if f.block != nil {
|
||||
select {
|
||||
case <-f.block:
|
||||
case <-ctx.Done():
|
||||
return ctx.Err()
|
||||
}
|
||||
}
|
||||
if f.execute != nil {
|
||||
return f.execute(ctx)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
func (f *fakeAction) Executed() []string {
|
||||
f.mu.Lock()
|
||||
defer f.mu.Unlock()
|
||||
return append([]string(nil), f.executed...)
|
||||
}
|
||||
|
||||
// fakeRegistry 供测试注入的动作工厂。
|
||||
type fakeRegistry struct {
|
||||
acts map[string]*fakeAction
|
||||
}
|
||||
|
||||
func (r *fakeRegistry) newAction(id string) (action.Action, error) {
|
||||
a, ok := r.acts[id]
|
||||
if !ok {
|
||||
return nil, errors.New("no such action")
|
||||
}
|
||||
return a, nil
|
||||
}
|
||||
|
||||
func newTestEngine(t *testing.T, reg *fakeRegistry) *Engine {
|
||||
logger := slog.New(slog.NewTextHandler(discard{}, nil))
|
||||
e := New(logger, reg.newAction)
|
||||
t.Cleanup(e.Wait)
|
||||
return e
|
||||
}
|
||||
|
||||
type discard struct{}
|
||||
|
||||
func (discard) Write(p []byte) (int, error) { return len(p), nil }
|
||||
|
||||
func testRule(id string, priority int, trType string, trParams map[string]any, actions []config.ActionConfig, cooldown int) *config.Rule {
|
||||
return &config.Rule{
|
||||
ID: id,
|
||||
Name: id,
|
||||
Enabled: true,
|
||||
Priority: priority,
|
||||
Trigger: config.TriggerConfig{Type: trType, Params: trParams},
|
||||
Actions: actions,
|
||||
CooldownMs: cooldown,
|
||||
}
|
||||
}
|
||||
|
||||
func TestMatches(t *testing.T) {
|
||||
r := testRule("r1", 100, "mouse_corner", map[string]any{"corner": "bottom_left"}, nil, 0)
|
||||
ev := trigger.Event{Type: "mouse_corner", Payload: map[string]any{"corner": "bottom_left"}}
|
||||
if !matches(r, ev) {
|
||||
t.Fatal("should match")
|
||||
}
|
||||
ev2 := trigger.Event{Type: "mouse_corner", Payload: map[string]any{"corner": "top_left"}}
|
||||
if matches(r, ev2) {
|
||||
t.Fatal("different corner should not match")
|
||||
}
|
||||
ev3 := trigger.Event{Type: "mouse_edge_wheel", Payload: map[string]any{"corner": "bottom_left"}}
|
||||
if matches(r, ev3) {
|
||||
t.Fatal("different type should not match")
|
||||
}
|
||||
// 事件多余字段不参与匹配
|
||||
ev4 := trigger.Event{Type: "mouse_corner", Payload: map[string]any{"corner": "bottom_left", "direction": "up"}}
|
||||
if !matches(r, ev4) {
|
||||
t.Fatal("extra event field should not break match")
|
||||
}
|
||||
}
|
||||
|
||||
func TestBuildSnapshotSkipsBadRules(t *testing.T) {
|
||||
reg := &fakeRegistry{acts: map[string]*fakeAction{
|
||||
"a1": {id: "a1"},
|
||||
}}
|
||||
cfg := &config.Config{Global: config.GlobalConfig{Enabled: true}, Rules: []config.Rule{
|
||||
*testRule("good", 100, "mouse_corner", map[string]any{"corner": "bottom_left"}, []config.ActionConfig{{Type: "a1"}}, 0),
|
||||
*testRule("bad-action", 100, "mouse_corner", map[string]any{"corner": "top_left"}, []config.ActionConfig{{Type: "nope"}}, 0),
|
||||
*testRule("bad-trigger", 100, "no_such", nil, []config.ActionConfig{{Type: "a1"}}, 0),
|
||||
*testRule("bad-conditions", 100, "mouse_corner", map[string]any{"corner": "top_right"},
|
||||
[]config.ActionConfig{{Type: "a1"}},
|
||||
0, // 注意:Conditions 手动设置
|
||||
),
|
||||
}}
|
||||
cfg.Rules[3].Conditions = []config.ConditionConfig{{Type: "x"}}
|
||||
snap := BuildSnapshot(cfg, reg.newAction)
|
||||
if len(snap.Rules) != 1 {
|
||||
t.Fatalf("active rules = %d, want 1", len(snap.Rules))
|
||||
}
|
||||
if snap.BadCount != 3 {
|
||||
t.Fatalf("bad count = %d, want 3", snap.BadCount)
|
||||
}
|
||||
}
|
||||
|
||||
func TestPriorityOrder(t *testing.T) {
|
||||
reg := &fakeRegistry{acts: map[string]*fakeAction{
|
||||
"a": {id: "a"},
|
||||
}}
|
||||
e := newTestEngine(t, reg)
|
||||
// 两条规则同触发器:低优先级在前(模拟配置顺序),高优先级应优先执行
|
||||
cfg := &config.Config{Global: config.GlobalConfig{Enabled: true}, Rules: []config.Rule{
|
||||
*testRule("low", 10, "hotkey", map[string]any{"hotkey": "ctrl+alt+d"}, []config.ActionConfig{{Type: "a"}}, 0),
|
||||
*testRule("high", 100, "hotkey", map[string]any{"hotkey": "ctrl+alt+d"}, []config.ActionConfig{{Type: "a"}}, 0),
|
||||
}}
|
||||
e.SetSnapshot(BuildSnapshot(cfg, reg.newAction))
|
||||
// 快照应按优先级降序
|
||||
snap := e.Snapshot()
|
||||
if snap.Rules[0].ID != "high" || snap.Rules[1].ID != "low" {
|
||||
t.Fatalf("sort order wrong: %s, %s", snap.Rules[0].ID, snap.Rules[1].ID)
|
||||
}
|
||||
e.HandleEvent(trigger.Event{Type: "hotkey", Payload: map[string]any{"hotkey": "ctrl+alt+d"}})
|
||||
time.Sleep(50 * time.Millisecond)
|
||||
// 高优先级执行了一次,低优先级未执行(HandleEvent 只执行第一条匹配)
|
||||
if got := reg.acts["a"].Executed(); len(got) != 1 {
|
||||
t.Fatalf("executed = %v, want exactly 1", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCooldown(t *testing.T) {
|
||||
reg := &fakeRegistry{acts: map[string]*fakeAction{
|
||||
"a": {id: "a"},
|
||||
}}
|
||||
e := newTestEngine(t, reg)
|
||||
cfg := &config.Config{Global: config.GlobalConfig{Enabled: true}, Rules: []config.Rule{
|
||||
*testRule("r", 100, "hotkey", map[string]any{"hotkey": "ctrl+alt+d"}, []config.ActionConfig{{Type: "a"}}, 200),
|
||||
}}
|
||||
e.SetSnapshot(BuildSnapshot(cfg, reg.newAction))
|
||||
ev := trigger.Event{Type: "hotkey", Payload: map[string]any{"hotkey": "ctrl+alt+d"}}
|
||||
e.HandleEvent(ev)
|
||||
e.HandleEvent(ev) // 冷却期内:应丢弃
|
||||
time.Sleep(50 * time.Millisecond)
|
||||
if got := reg.acts["a"].Executed(); len(got) != 1 {
|
||||
t.Fatalf("executed = %v, want 1 (cooldown should drop second)", got)
|
||||
}
|
||||
time.Sleep(250 * time.Millisecond)
|
||||
e.HandleEvent(ev)
|
||||
time.Sleep(50 * time.Millisecond)
|
||||
if got := reg.acts["a"].Executed(); len(got) != 2 {
|
||||
t.Fatalf("executed = %v, want 2 after cooldown", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestErrorIsolation(t *testing.T) {
|
||||
reg := &fakeRegistry{acts: map[string]*fakeAction{
|
||||
"fail": {id: "fail", execute: func(context.Context) error { return errors.New("boom") }},
|
||||
"ok": {id: "ok"},
|
||||
}}
|
||||
e := newTestEngine(t, reg)
|
||||
cfg := &config.Config{Global: config.GlobalConfig{Enabled: true}, Rules: []config.Rule{
|
||||
*testRule("r", 100, "hotkey", map[string]any{"hotkey": "ctrl+alt+d"},
|
||||
[]config.ActionConfig{{Type: "fail"}, {Type: "ok"}}, 0),
|
||||
}}
|
||||
e.SetSnapshot(BuildSnapshot(cfg, reg.newAction))
|
||||
e.HandleEvent(trigger.Event{Type: "hotkey", Payload: map[string]any{"hotkey": "ctrl+alt+d"}})
|
||||
time.Sleep(50 * time.Millisecond)
|
||||
got := reg.acts["ok"].Executed()
|
||||
if len(got) != 1 {
|
||||
t.Fatalf("ok action executed = %v, want 1 (isolation should continue)", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestConcurrencyGuard(t *testing.T) {
|
||||
reg := &fakeRegistry{acts: map[string]*fakeAction{
|
||||
"slow": {id: "slow", block: make(chan struct{})},
|
||||
}}
|
||||
e := newTestEngine(t, reg)
|
||||
cfg := &config.Config{Global: config.GlobalConfig{Enabled: true}, Rules: []config.Rule{
|
||||
*testRule("r", 100, "hotkey", map[string]any{"hotkey": "ctrl+alt+d"}, []config.ActionConfig{{Type: "slow"}}, 0),
|
||||
}}
|
||||
e.SetSnapshot(BuildSnapshot(cfg, reg.newAction))
|
||||
ev := trigger.Event{Type: "hotkey", Payload: map[string]any{"hotkey": "ctrl+alt+d"}}
|
||||
e.HandleEvent(ev) // 启动第一个(阻塞)
|
||||
e.HandleEvent(ev) // 同规则执行中:丢弃
|
||||
time.Sleep(50 * time.Millisecond)
|
||||
close(reg.acts["slow"].block) // 放行
|
||||
time.Sleep(50 * time.Millisecond)
|
||||
if got := reg.acts["slow"].Executed(); len(got) != 1 {
|
||||
t.Fatalf("executed = %v, want 1 (concurrent drop)", got)
|
||||
}
|
||||
}
|
||||
|
||||
// TestGlobalEnabled 验证全局开关:关闭时事件不触发任何规则。
|
||||
func TestGlobalEnabled(t *testing.T) {
|
||||
reg := &fakeRegistry{acts: map[string]*fakeAction{
|
||||
"a": {id: "a"},
|
||||
}}
|
||||
e := newTestEngine(t, reg)
|
||||
cfg := &config.Config{
|
||||
Global: config.GlobalConfig{Enabled: false},
|
||||
Rules: []config.Rule{
|
||||
*testRule("r", 100, "hotkey", map[string]any{"hotkey": "ctrl+alt+d"}, []config.ActionConfig{{Type: "a"}}, 0),
|
||||
},
|
||||
}
|
||||
snap := BuildSnapshot(cfg, reg.newAction)
|
||||
if snap.GlobalEnabled {
|
||||
t.Fatal("GlobalEnabled should be false")
|
||||
}
|
||||
e.SetSnapshot(snap)
|
||||
e.HandleEvent(trigger.Event{Type: "hotkey", Payload: map[string]any{"hotkey": "ctrl+alt+d"}})
|
||||
time.Sleep(50 * time.Millisecond)
|
||||
if got := reg.acts["a"].Executed(); len(got) != 0 {
|
||||
t.Fatalf("executed = %v, want 0 when globally disabled", got)
|
||||
}
|
||||
// 开启后应触发
|
||||
cfg.Global.Enabled = true
|
||||
e.SetSnapshot(BuildSnapshot(cfg, reg.newAction))
|
||||
e.HandleEvent(trigger.Event{Type: "hotkey", Payload: map[string]any{"hotkey": "ctrl+alt+d"}})
|
||||
time.Sleep(50 * time.Millisecond)
|
||||
if got := reg.acts["a"].Executed(); len(got) != 1 {
|
||||
t.Fatalf("executed = %v, want 1 when enabled", got)
|
||||
}
|
||||
}
|
||||
|
||||
// TestFullscreenSuppression 验证全屏抑制:默认规则忽略、allow 规则豁免、退出全屏恢复。
|
||||
func TestFullscreenSuppression(t *testing.T) {
|
||||
reg := &fakeRegistry{acts: map[string]*fakeAction{
|
||||
"a": {id: "a"},
|
||||
"b": {id: "b"},
|
||||
}}
|
||||
e := newTestEngine(t, reg)
|
||||
|
||||
fs := true
|
||||
e.SetFullscreenProvider(func() bool { return fs })
|
||||
|
||||
// 两条同触发器规则:默认(ignore) + allow
|
||||
cfg := &config.Config{Global: config.GlobalConfig{Enabled: true}, Rules: []config.Rule{
|
||||
*testRule("default-rule", 200, "hotkey", map[string]any{"hotkey": "ctrl+alt+d"}, []config.ActionConfig{{Type: "a"}}, 0),
|
||||
*testRule("allow-rule", 100, "hotkey", map[string]any{"hotkey": "ctrl+alt+d"}, []config.ActionConfig{{Type: "b"}}, 0),
|
||||
}}
|
||||
cfg.Rules[1].Fullscreen = "allow"
|
||||
e.SetSnapshot(BuildSnapshot(cfg, reg.newAction))
|
||||
|
||||
ev := trigger.Event{Type: "hotkey", Payload: map[string]any{"hotkey": "ctrl+alt+d"}}
|
||||
|
||||
// 全屏:默认规则被忽略,allow 规则触发
|
||||
fs = true
|
||||
e.HandleEvent(ev)
|
||||
time.Sleep(50 * time.Millisecond)
|
||||
if got := reg.acts["a"].Executed(); len(got) != 0 {
|
||||
t.Fatalf("default rule executed in fullscreen: %v", got)
|
||||
}
|
||||
if got := reg.acts["b"].Executed(); len(got) != 1 {
|
||||
t.Fatalf("allow rule executed = %v, want 1", got)
|
||||
}
|
||||
|
||||
// 退出全屏:默认规则恢复
|
||||
fs = false
|
||||
e.HandleEvent(ev)
|
||||
time.Sleep(50 * time.Millisecond)
|
||||
if got := reg.acts["a"].Executed(); len(got) != 1 {
|
||||
t.Fatalf("default rule executed after fullscreen = %v, want 1", got)
|
||||
}
|
||||
}
|
||||
|
||||
// TestFullscreenProviderNil 验证未注入提供者时不抑制(默认行为兼容)。
|
||||
func TestFullscreenProviderNil(t *testing.T) {
|
||||
reg := &fakeRegistry{acts: map[string]*fakeAction{
|
||||
"a": {id: "a"},
|
||||
}}
|
||||
e := newTestEngine(t, reg) // 不注入 provider
|
||||
cfg := &config.Config{Global: config.GlobalConfig{Enabled: true}, Rules: []config.Rule{
|
||||
*testRule("r", 100, "hotkey", map[string]any{"hotkey": "ctrl+alt+d"}, []config.ActionConfig{{Type: "a"}}, 0),
|
||||
}}
|
||||
e.SetSnapshot(BuildSnapshot(cfg, reg.newAction))
|
||||
e.HandleEvent(trigger.Event{Type: "hotkey", Payload: map[string]any{"hotkey": "ctrl+alt+d"}})
|
||||
time.Sleep(50 * time.Millisecond)
|
||||
if got := reg.acts["a"].Executed(); len(got) != 1 {
|
||||
t.Fatalf("executed = %v, want 1 (no provider = no suppression)", got)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
package rule
|
||||
|
||||
import (
|
||||
"io"
|
||||
"log/slog"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"zerorigin/internal/config"
|
||||
"zerorigin/internal/trigger"
|
||||
)
|
||||
|
||||
// TestEndToEndWithRealActions 验证"事件 → 引擎匹配 → 真实动作链"完整链路
|
||||
// (真实 action.New 与真实 SendInput 调用,不 panic、不阻塞)。
|
||||
// 物理输入注入(鼠标移动/按键)依赖活动桌面会话,由手工验收覆盖。
|
||||
func TestEndToEndWithRealActions(t *testing.T) {
|
||||
logger := slog.New(slog.NewTextHandler(io.Discard, nil))
|
||||
cfg := config.Default()
|
||||
e := New(logger, nil) // nil → 真实 action.New
|
||||
e.SetSnapshot(BuildSnapshot(cfg, nil))
|
||||
|
||||
// 模拟左下角事件(与 mouse_corner 触发器真实 payload 一致)。
|
||||
e.HandleEvent(trigger.Event{
|
||||
Type: "mouse_corner",
|
||||
Timestamp: time.Now(),
|
||||
Payload: map[string]any{"corner": "bottom_left", "screen": "all"},
|
||||
})
|
||||
// 模拟顶部滚轮事件(与 mouse_edge_wheel 真实 payload 一致)。
|
||||
e.HandleEvent(trigger.Event{
|
||||
Type: "mouse_edge_wheel",
|
||||
Timestamp: time.Now(),
|
||||
Payload: map[string]any{"edge": "top", "direction": "up", "delta": 120},
|
||||
})
|
||||
e.Wait() // 等待动作链完成(含 SendInput 调用)
|
||||
|
||||
// 冷却保护下的重复事件不应产生问题。
|
||||
e.HandleEvent(trigger.Event{
|
||||
Type: "mouse_corner",
|
||||
Timestamp: time.Now(),
|
||||
Payload: map[string]any{"corner": "bottom_left", "screen": "all"},
|
||||
})
|
||||
e.Wait()
|
||||
}
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 28 KiB |
@@ -0,0 +1,109 @@
|
||||
// Package tray 封装系统托盘(fork of getlantern/systray v1.2.2,扩展了 SetBalloon API)。
|
||||
package tray
|
||||
|
||||
import (
|
||||
_ "embed"
|
||||
"log/slog"
|
||||
|
||||
"zerorigin/internal/platform/systray"
|
||||
|
||||
"zerorigin/internal/version"
|
||||
)
|
||||
|
||||
//go:embed icon.ico
|
||||
var iconBytes []byte
|
||||
|
||||
// Callbacks 为托盘菜单动作回调。
|
||||
type Callbacks struct {
|
||||
OnQuit func()
|
||||
OnOpenConfigFile func()
|
||||
OnOpenConfigDir func()
|
||||
OnOpenSettings func()
|
||||
// OnToggleEnabled 在"已启用"勾选被点击时回调,参数为新的期望状态。
|
||||
OnToggleEnabled func(enabled bool) bool
|
||||
// OnToggleAutoStart 在"开机自启"勾选被点击时回调,参数为新的期望状态,返回是否成功。
|
||||
OnToggleAutoStart func(enabled bool) bool
|
||||
// AutoStart 为开机自启初始状态(用于勾选显示)。
|
||||
AutoStart bool
|
||||
}
|
||||
|
||||
// Run 阻塞运行托盘直到退出;必须在主 goroutine 调用。
|
||||
// onExit 在托盘资源释放后回调,用于收尾清理。
|
||||
func Run(cb Callbacks, logger *slog.Logger, onExit func()) {
|
||||
systray.Run(
|
||||
func() {
|
||||
onReady(cb, logger)
|
||||
},
|
||||
func() {
|
||||
if onExit != nil {
|
||||
onExit()
|
||||
}
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
func onReady(cb Callbacks, logger *slog.Logger) {
|
||||
systray.SetIcon(iconBytes)
|
||||
systray.SetTitle("ZerOriginTool")
|
||||
systray.SetTooltip("ZerOriginTool - 零源工具箱")
|
||||
|
||||
mEnabled := systray.AddMenuItemCheckbox("已启用", "全局开关", true)
|
||||
mAutoStart := systray.AddMenuItemCheckbox("开机自启", "登录时自动启动", cb.AutoStart)
|
||||
systray.AddSeparator()
|
||||
mSettings := systray.AddMenuItem("设置…", "打开设置窗口")
|
||||
mConfigFile := systray.AddMenuItem("打开配置文件", "用默认编辑器打开 config.json")
|
||||
mConfigDir := systray.AddMenuItem("打开配置目录", "打开配置所在目录")
|
||||
systray.AddSeparator()
|
||||
mVersion := systray.AddMenuItem(version.String(), "版本信息")
|
||||
mVersion.Disable()
|
||||
systray.AddSeparator()
|
||||
mQuit := systray.AddMenuItem("退出", "退出 ZerOriginTool")
|
||||
|
||||
go func() {
|
||||
for {
|
||||
select {
|
||||
case <-mQuit.ClickedCh:
|
||||
logger.Info("tray quit clicked")
|
||||
if cb.OnQuit != nil {
|
||||
cb.OnQuit()
|
||||
}
|
||||
systray.Quit()
|
||||
return
|
||||
case <-mSettings.ClickedCh:
|
||||
if cb.OnOpenSettings != nil {
|
||||
cb.OnOpenSettings()
|
||||
}
|
||||
case <-mConfigFile.ClickedCh:
|
||||
if cb.OnOpenConfigFile != nil {
|
||||
cb.OnOpenConfigFile()
|
||||
}
|
||||
case <-mConfigDir.ClickedCh:
|
||||
if cb.OnOpenConfigDir != nil {
|
||||
cb.OnOpenConfigDir()
|
||||
}
|
||||
case <-mEnabled.ClickedCh:
|
||||
next := !mEnabled.Checked()
|
||||
if cb.OnToggleEnabled != nil && !cb.OnToggleEnabled(next) {
|
||||
continue // 回调失败:保持原状态
|
||||
}
|
||||
if next {
|
||||
mEnabled.Check()
|
||||
} else {
|
||||
mEnabled.Uncheck()
|
||||
}
|
||||
logger.Info("global enabled toggled", "enabled", next)
|
||||
case <-mAutoStart.ClickedCh:
|
||||
next := !mAutoStart.Checked()
|
||||
if cb.OnToggleAutoStart != nil && !cb.OnToggleAutoStart(next) {
|
||||
continue
|
||||
}
|
||||
if next {
|
||||
mAutoStart.Check()
|
||||
} else {
|
||||
mAutoStart.Uncheck()
|
||||
}
|
||||
logger.Info("auto start toggled", "enabled", next)
|
||||
}
|
||||
}
|
||||
}()
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
package trigger
|
||||
|
||||
import (
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
// TestWheelDebouncer 验证滑动去抖:同一方向窗口内合并,方向切换立即放行。
|
||||
func TestWheelDebouncer(t *testing.T) {
|
||||
d := wheelDebouncer{window: 100 * time.Millisecond}
|
||||
base := time.Now()
|
||||
|
||||
if !d.allow("up", base) {
|
||||
t.Fatal("first event should fire")
|
||||
}
|
||||
// 窗口内同方向:合并(并刷新窗口)
|
||||
if d.allow("up", base.Add(20*time.Millisecond)) {
|
||||
t.Fatal("same direction within window should be merged")
|
||||
}
|
||||
if d.allow("up", base.Add(90*time.Millisecond)) {
|
||||
t.Fatal("same direction within window should be merged")
|
||||
}
|
||||
// 自最后一次事件起窗口外:放行
|
||||
if !d.allow("up", base.Add(250*time.Millisecond)) {
|
||||
t.Fatal("same direction after window should fire")
|
||||
}
|
||||
// 方向切换:立即放行
|
||||
if !d.allow("down", base.Add(260*time.Millisecond)) {
|
||||
t.Fatal("direction switch should fire immediately")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,203 @@
|
||||
package trigger
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"runtime"
|
||||
"strings"
|
||||
"sync"
|
||||
"syscall"
|
||||
"time"
|
||||
"unsafe"
|
||||
)
|
||||
|
||||
const (
|
||||
wmHotkey = 0x0312
|
||||
wmQuit = 0x0012
|
||||
modAlt = 0x0001
|
||||
modControl = 0x0002
|
||||
modShift = 0x0004
|
||||
modWin = 0x0008
|
||||
hotkeyMsgBuf = 16
|
||||
)
|
||||
|
||||
func init() {
|
||||
Register("hotkey", func(params map[string]any) (Trigger, error) {
|
||||
hotkey, _ := params["hotkey"].(string)
|
||||
if hotkey == "" {
|
||||
return nil, fmt.Errorf("hotkey: missing param \"hotkey\" (e.g. \"ctrl+alt+d\")")
|
||||
}
|
||||
mods, vk, err := parseHotkey(hotkey)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &hotkeyTrigger{mods: mods, vk: vk, hotkey: hotkey}, nil
|
||||
})
|
||||
}
|
||||
|
||||
// parseHotkey 解析 "ctrl+alt+d" 形式的热键描述。
|
||||
func parseHotkey(s string) (mods uint32, vk uint16, err error) {
|
||||
for _, p := range strings.Split(strings.ToLower(s), "+") {
|
||||
switch p {
|
||||
case "ctrl":
|
||||
mods |= modControl
|
||||
case "alt":
|
||||
mods |= modAlt
|
||||
case "shift":
|
||||
mods |= modShift
|
||||
case "win":
|
||||
mods |= modWin
|
||||
case "":
|
||||
return 0, 0, fmt.Errorf("hotkey: empty modifier in %q", s)
|
||||
default:
|
||||
if vk != 0 {
|
||||
return 0, 0, fmt.Errorf("hotkey: multiple keys in %q", s)
|
||||
}
|
||||
vk = charVK(p)
|
||||
if vk == 0 {
|
||||
return 0, 0, fmt.Errorf("hotkey: unsupported key %q", p)
|
||||
}
|
||||
}
|
||||
}
|
||||
if vk == 0 {
|
||||
return 0, 0, fmt.Errorf("hotkey: missing key in %q", s)
|
||||
}
|
||||
return mods, vk, nil
|
||||
}
|
||||
|
||||
// charVK 将单个字符映射为虚拟键码(字母/数字)。
|
||||
func charVK(c string) uint16 {
|
||||
if len(c) != 1 {
|
||||
return 0
|
||||
}
|
||||
ch := c[0]
|
||||
switch {
|
||||
case ch >= 'a' && ch <= 'z':
|
||||
return uint16(ch - 'a' + 'A') // VK 不区分大小写
|
||||
case ch >= '0' && ch <= '9':
|
||||
return uint16(ch)
|
||||
}
|
||||
return 0
|
||||
}
|
||||
|
||||
// hotkeyTrigger 注册全局热键并监听 WM_HOTKEY。
|
||||
type hotkeyTrigger struct {
|
||||
mods uint32
|
||||
vk uint16
|
||||
hotkey string // 原始配置字符串(事件 payload 回传,供规则匹配)
|
||||
|
||||
mu sync.Mutex
|
||||
started bool
|
||||
emit func(Event)
|
||||
cancel context.CancelFunc
|
||||
done chan struct{}
|
||||
threadID uint32
|
||||
}
|
||||
|
||||
func (t *hotkeyTrigger) ID() string { return "hotkey" }
|
||||
func (t *hotkeyTrigger) Name() string { return "全局快捷键" }
|
||||
|
||||
func (t *hotkeyTrigger) Start(ctx context.Context, emit func(Event)) error {
|
||||
t.mu.Lock()
|
||||
defer t.mu.Unlock()
|
||||
if t.started {
|
||||
return nil
|
||||
}
|
||||
ctx, cancel := context.WithCancel(ctx)
|
||||
t.cancel = cancel
|
||||
t.emit = emit
|
||||
t.done = make(chan struct{})
|
||||
t.started = true
|
||||
go t.loop(ctx)
|
||||
return nil
|
||||
}
|
||||
|
||||
func (t *hotkeyTrigger) Stop() error {
|
||||
t.mu.Lock()
|
||||
defer t.mu.Unlock()
|
||||
if !t.started {
|
||||
return nil
|
||||
}
|
||||
t.started = false
|
||||
t.cancel()
|
||||
if t.threadID != 0 {
|
||||
// 唤醒消息循环,否则 GetMessage 可能永久阻塞。
|
||||
_ = postThreadMessage(t.threadID, wmQuit, 0, 0)
|
||||
}
|
||||
<-t.done
|
||||
return nil
|
||||
}
|
||||
|
||||
func (t *hotkeyTrigger) loop(ctx context.Context) {
|
||||
// 与鼠标钩子同理:RegisterHotKey / GetMessage / Stop 的 WM_QUIT
|
||||
// 必须固定在同一 OS 线程。
|
||||
runtime.LockOSThread()
|
||||
defer runtime.UnlockOSThread()
|
||||
defer close(t.done)
|
||||
t.threadID = getCurrentThreadId()
|
||||
const id = 1
|
||||
r, _, _ := procRegisterHotKey.Call(0, id, uintptr(t.mods), uintptr(t.vk))
|
||||
if r == 0 {
|
||||
// 注册失败(热键被占用等):静默返回,Stop 幂等。
|
||||
return
|
||||
}
|
||||
defer procUnregisterHotKey.Call(0, id)
|
||||
|
||||
for {
|
||||
var msg winMsg
|
||||
n, err := getMessage(&msg, 0, 0, 0)
|
||||
if n == 0 || n == -1 || err != nil {
|
||||
return
|
||||
}
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return
|
||||
default:
|
||||
}
|
||||
if msg.message == wmHotkey {
|
||||
t.emit(Event{
|
||||
Type: t.ID(),
|
||||
Timestamp: time.Now(),
|
||||
Payload: map[string]any{"hotkey": t.hotkey},
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// --- Win32 胶水(hotkey 专用,保持 DLL 访问集中于本包) ---
|
||||
|
||||
var (
|
||||
procRegisterHotKey = syscall.NewLazyDLL("user32.dll").NewProc("RegisterHotKey")
|
||||
procUnregisterHotKey = syscall.NewLazyDLL("user32.dll").NewProc("UnregisterHotKey")
|
||||
procGetMessageW = syscall.NewLazyDLL("user32.dll").NewProc("GetMessageW")
|
||||
procPostThreadMessageW = syscall.NewLazyDLL("user32.dll").NewProc("PostThreadMessageW")
|
||||
procGetCurrentThreadId = syscall.NewLazyDLL("kernel32.dll").NewProc("GetCurrentThreadId")
|
||||
)
|
||||
|
||||
func getCurrentThreadId() uint32 {
|
||||
r, _, _ := procGetCurrentThreadId.Call()
|
||||
return uint32(r)
|
||||
}
|
||||
|
||||
func postThreadMessage(threadID uint32, msg uint32, wParam, lParam uintptr) error {
|
||||
r, _, err := procPostThreadMessageW.Call(uintptr(threadID), uintptr(msg), wParam, lParam)
|
||||
if r == 0 {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
type winMsg struct {
|
||||
hwnd uintptr
|
||||
message uint32
|
||||
wParam uintptr
|
||||
lParam uintptr
|
||||
time uint32
|
||||
pt struct{ x, y int32 }
|
||||
}
|
||||
|
||||
func getMessage(msg *winMsg, hwnd uintptr, min, max uint32) (int32, error) {
|
||||
r, _, err := procGetMessageW.Call(
|
||||
uintptr(unsafe.Pointer(msg)), hwnd, uintptr(min), uintptr(max))
|
||||
return int32(int64(r)), err
|
||||
}
|
||||
@@ -0,0 +1,134 @@
|
||||
package trigger
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
pwin "zerorigin/internal/platform/windows"
|
||||
)
|
||||
|
||||
func init() {
|
||||
Register("mouse_corner", func(params map[string]any) (Trigger, error) {
|
||||
corner, _ := params["corner"].(string)
|
||||
if corner == "" {
|
||||
return nil, fmt.Errorf("mouse_corner: missing param \"corner\"")
|
||||
}
|
||||
switch corner {
|
||||
case "top_left", "top_right", "bottom_left", "bottom_right":
|
||||
default:
|
||||
return nil, fmt.Errorf("mouse_corner: invalid corner %q", corner)
|
||||
}
|
||||
screen, _ := params["screen"].(string)
|
||||
if screen == "" {
|
||||
screen = "all"
|
||||
}
|
||||
threshold := int32(32)
|
||||
if v, ok := params["threshold_px"]; ok {
|
||||
if f, ok := v.(float64); ok {
|
||||
threshold = int32(f)
|
||||
}
|
||||
}
|
||||
return &cornerTrigger{corner: corner, screen: screen, threshold: threshold}, nil
|
||||
})
|
||||
}
|
||||
|
||||
// cornerTrigger 检测鼠标进入指定屏幕角落。
|
||||
// 状态机:进入发一次事件,停留不重复,离开后重新进入才再发。
|
||||
type cornerTrigger struct {
|
||||
corner string
|
||||
screen string
|
||||
threshold int32
|
||||
|
||||
mu sync.Mutex
|
||||
started bool
|
||||
hook *pwin.MouseHook
|
||||
emit func(Event)
|
||||
cancel context.CancelFunc
|
||||
in bool // 当前是否停留在角落
|
||||
lastNear time.Time // 接近诊断日志限速
|
||||
}
|
||||
|
||||
func (t *cornerTrigger) ID() string { return "mouse_corner" }
|
||||
func (t *cornerTrigger) Name() string { return "鼠标进入屏幕角落" }
|
||||
|
||||
func (t *cornerTrigger) Start(ctx context.Context, emit func(Event)) error {
|
||||
t.mu.Lock()
|
||||
defer t.mu.Unlock()
|
||||
if t.started {
|
||||
return nil
|
||||
}
|
||||
ctx, cancel := context.WithCancel(ctx)
|
||||
t.cancel = cancel
|
||||
t.emit = emit
|
||||
t.hook = pwin.NewMouseHook(256)
|
||||
if err := t.hook.Start(); err != nil {
|
||||
cancel()
|
||||
return err
|
||||
}
|
||||
t.started = true
|
||||
go t.loop(ctx)
|
||||
return nil
|
||||
}
|
||||
|
||||
func (t *cornerTrigger) Stop() error {
|
||||
t.mu.Lock()
|
||||
defer t.mu.Unlock()
|
||||
if !t.started {
|
||||
return nil
|
||||
}
|
||||
t.started = false
|
||||
t.cancel()
|
||||
return t.hook.Stop()
|
||||
}
|
||||
|
||||
func (t *cornerTrigger) loop(ctx context.Context) {
|
||||
// 触发器 loop 为常驻 goroutine,panic 会拖垮整个进程:兜底记录不中断。
|
||||
defer func() {
|
||||
if r := recover(); r != nil {
|
||||
pwin.LogGoPanic("trigger.corner.loop", r, stackBuf())
|
||||
}
|
||||
}()
|
||||
rects := t.screenRects()
|
||||
for {
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return
|
||||
case ev := <-t.hook.Events():
|
||||
if ev.Message != pwin.WmMouseMove {
|
||||
continue
|
||||
}
|
||||
hit := pwin.CornerHit(rects, ev.X, ev.Y, t.threshold, t.corner)
|
||||
if hit && !t.in {
|
||||
t.in = true
|
||||
t.emit(Event{
|
||||
Type: t.ID(),
|
||||
Timestamp: time.Now(),
|
||||
Payload: map[string]any{"corner": t.corner, "screen": t.screen},
|
||||
})
|
||||
} else if !hit {
|
||||
t.in = false
|
||||
// 接近诊断:鼠标在阈值 4 倍范围内但未命中(限速采样),
|
||||
// 用于定位"滑到角落但没触发"的阈值问题。
|
||||
if pwin.CornerHit(rects, ev.X, ev.Y, t.threshold*4, t.corner) &&
|
||||
time.Since(t.lastNear) > 2*time.Second {
|
||||
t.lastNear = time.Now()
|
||||
logger.Debug("corner near but not hit", "corner", t.corner, "pos", fmt.Sprintf("(%d,%d)", ev.X, ev.Y), "threshold", t.threshold)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (t *cornerTrigger) screenRects() []pwin.MonitorRect {
|
||||
if t.screen == "primary" {
|
||||
return []pwin.MonitorRect{pwin.PrimaryMonitorRect()}
|
||||
}
|
||||
rects, err := pwin.MonitorRects()
|
||||
if err != nil {
|
||||
// 获取失败时退化为单主屏,保证功能不中断。
|
||||
return []pwin.MonitorRect{pwin.PrimaryMonitorRect()}
|
||||
}
|
||||
return rects
|
||||
}
|
||||
@@ -0,0 +1,152 @@
|
||||
package trigger
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
pwin "zerorigin/internal/platform/windows"
|
||||
)
|
||||
|
||||
func init() {
|
||||
Register("mouse_edge_wheel", func(params map[string]any) (Trigger, error) {
|
||||
edge, _ := params["edge"].(string)
|
||||
if edge == "" {
|
||||
edge = "top"
|
||||
}
|
||||
switch edge {
|
||||
case "top", "bottom", "left", "right":
|
||||
default:
|
||||
return nil, fmt.Errorf("mouse_edge_wheel: invalid edge %q", edge)
|
||||
}
|
||||
threshold := int32(32)
|
||||
if v, ok := params["threshold_px"]; ok {
|
||||
if f, ok := v.(float64); ok {
|
||||
threshold = int32(f)
|
||||
}
|
||||
}
|
||||
return &edgeWheelTrigger{edge: edge, threshold: threshold}, nil
|
||||
})
|
||||
}
|
||||
|
||||
// edgeWheelTrigger 检测光标位于屏幕边缘时的滚轮事件。
|
||||
// 一次滚轮滑动(快速滚动)会产生一串 WM_MOUSEWHEEL 事件,
|
||||
// 由 wheelDebouncer 合并为一次触发;方向切换立即放行。
|
||||
type edgeWheelTrigger struct {
|
||||
edge string
|
||||
threshold int32
|
||||
|
||||
mu sync.Mutex
|
||||
started bool
|
||||
hook *pwin.MouseHook
|
||||
emit func(Event)
|
||||
cancel context.CancelFunc
|
||||
deb wheelDebouncer
|
||||
}
|
||||
|
||||
func (t *edgeWheelTrigger) ID() string { return "mouse_edge_wheel" }
|
||||
func (t *edgeWheelTrigger) Name() string { return "屏幕边缘滚轮" }
|
||||
|
||||
func (t *edgeWheelTrigger) Start(ctx context.Context, emit func(Event)) error {
|
||||
t.mu.Lock()
|
||||
defer t.mu.Unlock()
|
||||
if t.started {
|
||||
return nil
|
||||
}
|
||||
ctx, cancel := context.WithCancel(ctx)
|
||||
t.cancel = cancel
|
||||
t.emit = emit
|
||||
t.hook = pwin.NewMouseHook(256)
|
||||
if err := t.hook.Start(); err != nil {
|
||||
cancel()
|
||||
return err
|
||||
}
|
||||
t.started = true
|
||||
go t.loop(ctx)
|
||||
return nil
|
||||
}
|
||||
|
||||
func (t *edgeWheelTrigger) Stop() error {
|
||||
t.mu.Lock()
|
||||
defer t.mu.Unlock()
|
||||
if !t.started {
|
||||
return nil
|
||||
}
|
||||
t.started = false
|
||||
t.cancel()
|
||||
return t.hook.Stop()
|
||||
}
|
||||
|
||||
func (t *edgeWheelTrigger) loop(ctx context.Context) {
|
||||
// 触发器 loop 为常驻 goroutine,panic 会拖垮整个进程:兜底记录不中断。
|
||||
defer func() {
|
||||
if r := recover(); r != nil {
|
||||
pwin.LogGoPanic("trigger.edgeWheel.loop", r, stackBuf())
|
||||
}
|
||||
}()
|
||||
rects, err := pwin.MonitorRects()
|
||||
if err != nil {
|
||||
rects = []pwin.MonitorRect{pwin.PrimaryMonitorRect()}
|
||||
}
|
||||
for {
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return
|
||||
case ev := <-t.hook.Events():
|
||||
if ev.Message != pwin.WmMouseWheel {
|
||||
continue
|
||||
}
|
||||
if !pwin.EdgeHit(rects, ev.X, ev.Y, t.threshold, t.edge) {
|
||||
continue
|
||||
}
|
||||
delta := wheelDelta(ev.MouseData)
|
||||
if delta == 0 {
|
||||
continue
|
||||
}
|
||||
dir := "up"
|
||||
if delta < 0 {
|
||||
dir = "down"
|
||||
}
|
||||
now := time.Now()
|
||||
if !t.deb.allow(dir, now) {
|
||||
continue // 同一方向的连续滑动:合并为一次触发
|
||||
}
|
||||
t.emit(Event{
|
||||
Type: t.ID(),
|
||||
Timestamp: now,
|
||||
Payload: map[string]any{"edge": t.edge, "direction": dir, "delta": delta},
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// debounceWindow 为滚轮滑动去抖窗口:同一方向在此窗口内的
|
||||
// 连续事件视为同一次滑动。方向切换立即放行。
|
||||
const debounceWindow = 120 * time.Millisecond
|
||||
|
||||
// wheelDebouncer 合并同一方向的连续滚轮事件。
|
||||
type wheelDebouncer struct {
|
||||
window time.Duration
|
||||
last time.Time
|
||||
dir string
|
||||
}
|
||||
|
||||
// allow 报告方向 dir 在时刻 now 是否允许触发(未在去抖窗口内)。
|
||||
func (d *wheelDebouncer) allow(dir string, now time.Time) bool {
|
||||
if d.window == 0 {
|
||||
d.window = debounceWindow
|
||||
}
|
||||
if now.Sub(d.last) < d.window && d.dir == dir {
|
||||
d.last = now
|
||||
return false
|
||||
}
|
||||
d.last = now
|
||||
d.dir = dir
|
||||
return true
|
||||
}
|
||||
|
||||
// wheelDelta 从 MSLLHOOKSTRUCT.mouseData 高位字提取带符号滚轮增量。
|
||||
func wheelDelta(mouseData int32) int32 {
|
||||
return int32(int16(uint32(mouseData) >> 16))
|
||||
}
|
||||
@@ -0,0 +1,88 @@
|
||||
// Package trigger 定义触发器接口、事件模型与注册表。
|
||||
// 触发器只负责采集外部输入并产生标准事件,不得包含业务动作判断。
|
||||
package trigger
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"log/slog"
|
||||
"runtime"
|
||||
"sync"
|
||||
"time"
|
||||
)
|
||||
|
||||
// logger 为触发器诊断日志(由 app 注入)。高频路径只打采样日志。
|
||||
var logger = slog.Default()
|
||||
|
||||
// SetLogger 注入触发器诊断日志器。
|
||||
func SetLogger(l *slog.Logger) {
|
||||
if l != nil {
|
||||
logger = l
|
||||
}
|
||||
}
|
||||
|
||||
// Event 为触发器产生的标准事件。
|
||||
type Event struct {
|
||||
Type string
|
||||
Timestamp time.Time
|
||||
Payload map[string]any
|
||||
}
|
||||
|
||||
// Trigger 为触发器接口。
|
||||
//
|
||||
// 约束:
|
||||
// - Start 不得阻塞调用方;
|
||||
// - Stop 必须幂等;
|
||||
// - 停止后不得继续发送事件;
|
||||
// - 回调(emit)不得执行耗时动作;
|
||||
// - 高频事件必须限流或合并。
|
||||
type Trigger interface {
|
||||
ID() string
|
||||
Name() string
|
||||
Start(ctx context.Context, emit func(Event)) error
|
||||
Stop() error
|
||||
}
|
||||
|
||||
// Factory 根据配置参数构造触发器实例。
|
||||
type Factory func(params map[string]any) (Trigger, error)
|
||||
|
||||
var (
|
||||
registryMu sync.RWMutex
|
||||
registry = map[string]Factory{}
|
||||
)
|
||||
|
||||
// Register 注册触发器工厂。重复注册同一 ID 会 panic(编程错误)。
|
||||
func Register(id string, f Factory) {
|
||||
registryMu.Lock()
|
||||
defer registryMu.Unlock()
|
||||
if _, ok := registry[id]; ok {
|
||||
panic(fmt.Sprintf("trigger %q already registered", id))
|
||||
}
|
||||
registry[id] = f
|
||||
}
|
||||
|
||||
// New 按 ID 构造触发器实例。
|
||||
func New(id string, params map[string]any) (Trigger, error) {
|
||||
registryMu.RLock()
|
||||
f, ok := registry[id]
|
||||
registryMu.RUnlock()
|
||||
if !ok {
|
||||
return nil, fmt.Errorf("unknown trigger type %q", id)
|
||||
}
|
||||
return f(params)
|
||||
}
|
||||
|
||||
// Known 报告触发器 ID 是否已注册。
|
||||
func Known(id string) bool {
|
||||
registryMu.RLock()
|
||||
defer registryMu.RUnlock()
|
||||
_, ok := registry[id]
|
||||
return ok
|
||||
}
|
||||
|
||||
// stackBuf 返回当前 goroutine 堆栈(崩溃取证用,各 loop 的 recover 调用)。
|
||||
func stackBuf() []byte {
|
||||
buf := make([]byte, 32<<10)
|
||||
n := runtime.Stack(buf, false)
|
||||
return buf[:n]
|
||||
}
|
||||
@@ -0,0 +1,94 @@
|
||||
package trigger
|
||||
|
||||
import (
|
||||
"context"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func TestParseHotkey(t *testing.T) {
|
||||
cases := []struct {
|
||||
in string
|
||||
wantMod uint32
|
||||
wantVK uint16
|
||||
wantErr bool
|
||||
}{
|
||||
{"ctrl+alt+d", modControl | modAlt, 0x44, false},
|
||||
{"ctrl+shift+9", modControl | modShift, '9', false},
|
||||
{"win+a", modWin, 'A', false},
|
||||
{"d", 0, 0x44, false},
|
||||
{"", 0, 0, true},
|
||||
{"ctrl++alt", 0, 0, true},
|
||||
{"ctrl+alt+d+f", 0, 0, true},
|
||||
{"ctrl+alt+?", 0, 0, true},
|
||||
}
|
||||
for _, c := range cases {
|
||||
mods, vk, err := parseHotkey(c.in)
|
||||
if (err != nil) != c.wantErr {
|
||||
t.Errorf("parseHotkey(%q) err = %v, wantErr %v", c.in, err, c.wantErr)
|
||||
continue
|
||||
}
|
||||
if err == nil && (mods != c.wantMod || vk != c.wantVK) {
|
||||
t.Errorf("parseHotkey(%q) = mods %#x vk %#x, want %#x/%#x", c.in, mods, vk, c.wantMod, c.wantVK)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestTriggerRegistry(t *testing.T) {
|
||||
if !Known("mouse_corner") || !Known("mouse_edge_wheel") || !Known("hotkey") {
|
||||
t.Fatal("builtin triggers not registered")
|
||||
}
|
||||
if Known("no_such_trigger") {
|
||||
t.Fatal("unknown trigger reported as known")
|
||||
}
|
||||
if _, err := New("no_such_trigger", nil); err == nil {
|
||||
t.Fatal("New(unknown) should fail")
|
||||
}
|
||||
}
|
||||
|
||||
func TestNewMouseCornerValidation(t *testing.T) {
|
||||
if _, err := New("mouse_corner", map[string]any{}); err == nil {
|
||||
t.Fatal("missing corner should fail")
|
||||
}
|
||||
if _, err := New("mouse_corner", map[string]any{"corner": "middle"}); err == nil {
|
||||
t.Fatal("invalid corner should fail")
|
||||
}
|
||||
tr, err := New("mouse_corner", map[string]any{"corner": "bottom_left", "screen": "all"})
|
||||
if err != nil {
|
||||
t.Fatalf("valid corner failed: %v", err)
|
||||
}
|
||||
if tr.ID() != "mouse_corner" {
|
||||
t.Fatalf("ID = %q", tr.ID())
|
||||
}
|
||||
}
|
||||
|
||||
func TestWheelDelta(t *testing.T) {
|
||||
if d := wheelDelta(0x00780000); d != 120 {
|
||||
t.Errorf("wheelDelta(0x00780000) = %d, want 120", d)
|
||||
}
|
||||
v := uint32(0xFF880000)
|
||||
if d := wheelDelta(int32(v)); d != -120 {
|
||||
t.Errorf("wheelDelta(0xFF880000) = %d, want -120", d)
|
||||
}
|
||||
}
|
||||
|
||||
// TestHotkeyTriggerStopIdempotent 验证 Stop 可重复调用且不阻塞。
|
||||
func TestHotkeyTriggerStopIdempotent(t *testing.T) {
|
||||
tr, err := New("hotkey", map[string]any{"hotkey": "ctrl+alt+d"})
|
||||
if err != nil {
|
||||
t.Fatalf("new hotkey: %v", err)
|
||||
}
|
||||
if err := tr.Stop(); err != nil {
|
||||
t.Fatalf("stop before start: %v", err)
|
||||
}
|
||||
if err := tr.Start(context.Background(), nil); err != nil {
|
||||
t.Fatalf("start: %v", err)
|
||||
}
|
||||
time.Sleep(50 * time.Millisecond)
|
||||
if err := tr.Stop(); err != nil {
|
||||
t.Fatalf("stop: %v", err)
|
||||
}
|
||||
if err := tr.Stop(); err != nil {
|
||||
t.Fatalf("stop again: %v", err)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
// Package version 提供构建时注入的版本信息。
|
||||
package version
|
||||
|
||||
import "fmt"
|
||||
|
||||
// 以下变量由构建时 -ldflags 注入,例如:
|
||||
//
|
||||
// go build -ldflags "-X zerorigin/internal/version.Version=0.1.0 \
|
||||
// -X zerorigin/internal/version.Commit=$(git rev-parse --short HEAD) \
|
||||
// -X zerorigin/internal/version.Date=$(date -u +%Y-%m-%dT%H:%M:%SZ)"
|
||||
var (
|
||||
Version = "0.1.0-dev"
|
||||
Commit = "unknown"
|
||||
Date = "unknown"
|
||||
)
|
||||
|
||||
// String 返回单行版本描述。
|
||||
func String() string {
|
||||
return fmt.Sprintf("ZerOriginTool %s (commit %s, built %s)", Version, Commit, Date)
|
||||
}
|
||||
Reference in new issue
Block a user