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)
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user