迁移到 mygo 单进程架构并接入签名自更新
- 单进程:托盘常驻 + 原生设置窗口(internal/settings),移除 Wails 前端与 IPC - 触发器(鼠标角落 / 边缘滚轮 / 热键)+ 规则引擎 + 动作注册表 - 调节提示条:截屏 + glass.Blur 三层毛玻璃、背景跟随屏幕变化、悬停光感与拖动 - 音量 Core Audio COM、亮度 DDC/CI(gamma 兜底)、多显示器求平均 - 配置热重载 + 版本迁移 v1→v5、便携模式、崩溃取证三件套 - updater/native 插件 + 托盘「检查更新…」,watchdog 识别更新重启 - 自建 Gitea 发布:scripts/publish-gitea.ps1(updates.url 指向 latest Release)
This commit is contained in:
1 parent
814012ec52
commit
0b8b9b0775
202 files changed
+7254
-13572
No files matched your search
@@ -20,15 +20,19 @@ func SetLogger(l *slog.Logger) {
|
||||
}
|
||||
}
|
||||
|
||||
// ParamSpec 描述一个动作参数。
|
||||
// ParamSpec 描述一个动作参数(同时供设置界面渲染表单)。
|
||||
type ParamSpec struct {
|
||||
Name string
|
||||
Type string // "string" | "int" | "bool"
|
||||
Label string // 中文标签(设置界面显示)
|
||||
Type string // "string" | "int" | "bool" | "select"
|
||||
Required bool
|
||||
Default any
|
||||
Options []string // Type=="select" 时的可选值
|
||||
Labels []string // 与 Options 一一对应的中文显示名(nil 表示直接显示值)
|
||||
Help string // 帮助文本(设置界面显示为提示)
|
||||
}
|
||||
|
||||
// ActionSchema 描述动作的参数契约(供校验与未来 UI 使用)。
|
||||
// ActionSchema 描述动作的参数契约(供校验与设置界面渲染使用)。
|
||||
type ActionSchema struct {
|
||||
Params []ParamSpec
|
||||
}
|
||||
@@ -46,8 +50,9 @@ type Action interface {
|
||||
type Factory func() Action
|
||||
|
||||
var (
|
||||
registryMu sync.RWMutex
|
||||
registry = map[string]Factory{}
|
||||
registryMu sync.RWMutex
|
||||
registry = map[string]Factory{}
|
||||
registryOrder []string
|
||||
)
|
||||
|
||||
// Register 注册动作工厂。重复注册同一 ID 会 panic(编程错误)。
|
||||
@@ -58,6 +63,7 @@ func Register(id string, f Factory) {
|
||||
panic(fmt.Sprintf("action %q already registered", id))
|
||||
}
|
||||
registry[id] = f
|
||||
registryOrder = append(registryOrder, id)
|
||||
}
|
||||
|
||||
// New 按 ID 构造动作实例。
|
||||
@@ -79,6 +85,29 @@ func Known(id string) bool {
|
||||
return ok
|
||||
}
|
||||
|
||||
// IDs 返回全部已注册动作 ID(按注册先后顺序稳定排序)。
|
||||
func IDs() []string {
|
||||
registryMu.RLock()
|
||||
defer registryMu.RUnlock()
|
||||
ids := make([]string, 0, len(registryOrder))
|
||||
ids = append(ids, registryOrder...)
|
||||
return ids
|
||||
}
|
||||
|
||||
// DisplayName 返回动作的中文显示名;未知 ID 原样返回。
|
||||
func DisplayName(id string) string {
|
||||
registryMu.RLock()
|
||||
f, ok := registry[id]
|
||||
registryMu.RUnlock()
|
||||
if !ok {
|
||||
return id
|
||||
}
|
||||
if a := f(); a != nil {
|
||||
return a.Name()
|
||||
}
|
||||
return id
|
||||
}
|
||||
|
||||
// GetString 从参数 map 读取字符串参数。
|
||||
func GetString(params map[string]any, name string) string {
|
||||
s, _ := params[name].(string)
|
||||
|
||||
@@ -0,0 +1,156 @@
|
||||
package action
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"zerorigin/internal/osd"
|
||||
pwin "zerorigin/internal/platform/windows"
|
||||
)
|
||||
|
||||
func init() {
|
||||
Register("brightness_up", func() Action { return &brightnessAction{dir: 1} })
|
||||
Register("brightness_down", func() Action { return &brightnessAction{dir: -1} })
|
||||
}
|
||||
|
||||
const (
|
||||
// brightnessToastTitle 亮度调节 Toast 标题。
|
||||
brightnessToastTitle = "屏幕亮度"
|
||||
// brightnessWarnInterval 亮度失败日志的最小间隔(避免滚轮连滚刷日志)。
|
||||
brightnessWarnInterval = 5 * time.Second
|
||||
)
|
||||
|
||||
// brightnessAction 屏幕亮度调节(DDC/CI 优先,gamma 软件调光兜底)。
|
||||
//
|
||||
// 手感为滚轮设计:滚轮触发器每"一格"产生一次事件(见 trigger.wheelNotcher),
|
||||
// 本动作只把增量放进合并队列立即返回,由后台 worker 按实际耗时批量下发,
|
||||
// 因此用户快速连滚多格时既不会丢事件,也不会因为 DDC 慢而堆积动作链。
|
||||
type brightnessAction struct {
|
||||
dir int32
|
||||
}
|
||||
|
||||
func (a *brightnessAction) ID() string {
|
||||
if a.dir > 0 {
|
||||
return "brightness_up"
|
||||
}
|
||||
return "brightness_down"
|
||||
}
|
||||
|
||||
func (a *brightnessAction) Name() string {
|
||||
if a.dir > 0 {
|
||||
return "屏幕调亮"
|
||||
}
|
||||
return "屏幕调暗"
|
||||
}
|
||||
|
||||
func (a *brightnessAction) Schema() ActionSchema {
|
||||
return ActionSchema{Params: []ParamSpec{
|
||||
{Name: "steps", Label: "步进(百分比)", Type: "int", Required: false, Default: 5,
|
||||
Help: "每格滚轮改变的亮度百分比(1-100)"},
|
||||
}}
|
||||
}
|
||||
|
||||
func (a *brightnessAction) Validate(params map[string]any) error {
|
||||
if steps := GetInt(params, "steps"); steps < 0 {
|
||||
return fmt.Errorf("brightness: steps must be >= 0")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (a *brightnessAction) Execute(ctx context.Context, params map[string]any) error {
|
||||
steps := GetInt(params, "steps")
|
||||
if steps <= 0 {
|
||||
steps = 1
|
||||
}
|
||||
if steps > 100 {
|
||||
steps = 100
|
||||
}
|
||||
queueBrightness(a.dir*int32(steps), NotificationsAllowed(ctx))
|
||||
return nil
|
||||
}
|
||||
|
||||
// brightnessQueue 合并待下发的亮度增量。
|
||||
//
|
||||
// DDC/CI 的单次调用是慢速 I2C 事务(多显示器时可达几十毫秒),若每个滚轮
|
||||
// 事件都同步调用,引擎的"同规则执行中丢弃新事件"会让快速连滚丢失大半。
|
||||
// 这里把增量累加后由一个 worker 串行下发:动作立即返回,队列在后台按批
|
||||
// 应用,滚 4 格等价于一次 +20%(或分几批),既不丢也不会过冲。
|
||||
var brightnessQueue struct {
|
||||
mu sync.Mutex
|
||||
pending int32
|
||||
pendingToast bool // 本批增量是否允许弹系统通知(规则级开关在入队前捕获)
|
||||
running bool
|
||||
lastWarn time.Time
|
||||
}
|
||||
|
||||
// queueBrightness 累加亮度增量并唤醒 worker(非阻塞)。
|
||||
func queueBrightness(delta int32, toast bool) {
|
||||
if delta == 0 {
|
||||
return
|
||||
}
|
||||
q := &brightnessQueue
|
||||
q.mu.Lock()
|
||||
q.pending += delta
|
||||
q.pendingToast = q.pendingToast || toast
|
||||
if q.running {
|
||||
q.mu.Unlock()
|
||||
return
|
||||
}
|
||||
q.running = true
|
||||
q.mu.Unlock()
|
||||
go drainBrightnessQueue()
|
||||
}
|
||||
|
||||
// drainBrightnessQueue 串行下发累计的亮度增量,直到队列为空。
|
||||
// ⚠️ 运行在独立 goroutine:panic 必须自兜底,否则拖垮进程。
|
||||
func drainBrightnessQueue() {
|
||||
q := &brightnessQueue
|
||||
defer func() {
|
||||
if r := recover(); r != nil {
|
||||
pwin.LogGoPanic("action.brightness.queue", r, debugStackBuf())
|
||||
q.mu.Lock()
|
||||
q.running = false
|
||||
q.mu.Unlock()
|
||||
}
|
||||
}()
|
||||
for {
|
||||
q.mu.Lock()
|
||||
pending := q.pending
|
||||
toast := q.pendingToast
|
||||
q.pending = 0
|
||||
q.pendingToast = false
|
||||
if pending == 0 {
|
||||
q.running = false
|
||||
q.mu.Unlock()
|
||||
return
|
||||
}
|
||||
q.mu.Unlock()
|
||||
|
||||
info, err := pwin.AdjustBrightness(pending)
|
||||
if err != nil {
|
||||
// 失败按时间限速记录:滚轮连滚时同一原因只记一条。
|
||||
now := time.Now()
|
||||
q.mu.Lock()
|
||||
if now.Sub(q.lastWarn) >= brightnessWarnInterval {
|
||||
q.lastWarn = now
|
||||
q.mu.Unlock()
|
||||
logger.Warn("brightness adjust failed", "delta", pending, "err", err)
|
||||
continue
|
||||
}
|
||||
q.mu.Unlock()
|
||||
continue
|
||||
}
|
||||
text := fmt.Sprintf("亮度: %d%%", info.Percent)
|
||||
if info.Gamma {
|
||||
// 软件调光:显示器不支持 DDC/CI,走 gamma ramp(不是真实背光)。
|
||||
text += "(软件调光)"
|
||||
logger.Debug("brightness adjusted (gamma)", "delta", pending, "percent", info.Percent)
|
||||
} else {
|
||||
logger.Debug("brightness adjusted", "delta", pending, "percent", info.Percent, "monitors", info.Monitors)
|
||||
}
|
||||
osd.ShowBrightness(info.Percent, info.Gamma)
|
||||
scheduleToast(brightnessToastTitle, text, toast)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
package action
|
||||
|
||||
import "context"
|
||||
|
||||
// ruleNotifyKey 是规则级"是否显示通知"开关在 context 中的键。
|
||||
//
|
||||
// 规则引擎在派发动作前把当前规则的 notify 写入 context:动作实现不
|
||||
// 直接依赖 config.Rule,异步路径(音量媒体键读回、亮度合并队列)也能
|
||||
// 在启动 goroutine 前捕获该值,避免 context 取消后读不到。
|
||||
type ruleNotifyKey struct{}
|
||||
|
||||
// WithRuleNotify 把规则级通知开关写入 context。
|
||||
func WithRuleNotify(ctx context.Context, notify bool) context.Context {
|
||||
return context.WithValue(ctx, ruleNotifyKey{}, notify)
|
||||
}
|
||||
|
||||
// RuleNotify 读取规则级通知开关;未设置时默认允许通知。
|
||||
func RuleNotify(ctx context.Context) bool {
|
||||
if ctx == nil {
|
||||
return true
|
||||
}
|
||||
if v, ok := ctx.Value(ruleNotifyKey{}).(bool); ok {
|
||||
return v
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
// NotificationsAllowed 返回当前动作是否允许弹桌面通知:
|
||||
// 全局总开关(global.notify)与规则级开关同时开启才允许。
|
||||
//
|
||||
// 调节提示条(internal/osd)不经过这里,始终显示;这里只控制右下角
|
||||
// 系统 Toast,包括自动调节通知和显式的 show_notification 动作。
|
||||
func NotificationsAllowed(ctx context.Context) bool {
|
||||
return toastEnabled.Load() && RuleNotify(ctx)
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
package action
|
||||
|
||||
import (
|
||||
"context"
|
||||
"testing"
|
||||
)
|
||||
|
||||
// TestRuleNotifyContext 验证规则级通知标记可传递且缺省为允许。
|
||||
func TestRuleNotifyContext(t *testing.T) {
|
||||
if got := RuleNotify(nil); !got {
|
||||
t.Fatal("nil ctx should allow notify")
|
||||
}
|
||||
if got := RuleNotify(context.Background()); !got {
|
||||
t.Fatal("ctx without rule notify should allow notify")
|
||||
}
|
||||
ctx := WithRuleNotify(context.Background(), false)
|
||||
if got := RuleNotify(ctx); got {
|
||||
t.Fatal("rule notify=false should be propagated")
|
||||
}
|
||||
if got := RuleNotify(WithRuleNotify(ctx, true)); !got {
|
||||
t.Fatal("inner rule notify=true should override")
|
||||
}
|
||||
}
|
||||
|
||||
// TestNotificationsAllowed 验证全局开关与规则级开关是"与"关系。
|
||||
func TestNotificationsAllowed(t *testing.T) {
|
||||
defer SetToastEnabled(true)
|
||||
SetToastEnabled(true)
|
||||
if !NotificationsAllowed(WithRuleNotify(context.Background(), true)) {
|
||||
t.Fatal("global on + rule on should allow")
|
||||
}
|
||||
if NotificationsAllowed(WithRuleNotify(context.Background(), false)) {
|
||||
t.Fatal("rule off should suppress toast")
|
||||
}
|
||||
SetToastEnabled(false)
|
||||
if NotificationsAllowed(context.Background()) {
|
||||
t.Fatal("global off should suppress toast")
|
||||
}
|
||||
}
|
||||
@@ -18,7 +18,8 @@ func (a *delayAction) Name() string { return "延迟" }
|
||||
|
||||
func (a *delayAction) Schema() ActionSchema {
|
||||
return ActionSchema{Params: []ParamSpec{
|
||||
{Name: "ms", Type: "int", Required: true},
|
||||
{Name: "ms", Label: "延迟(毫秒)", Type: "int", Required: true,
|
||||
Help: "动作链中等待的毫秒数(>=0)"},
|
||||
}}
|
||||
}
|
||||
|
||||
|
||||
@@ -2,6 +2,7 @@ package action
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"sync"
|
||||
"time"
|
||||
@@ -18,10 +19,18 @@ func init() {
|
||||
// switchDesktopShared 为共享的切换桌面动作实例。
|
||||
var switchDesktopShared = &switchDesktopAction{}
|
||||
|
||||
// 切换实现变量化,便于单测注入 fake(生产路径仍为平台层函数)。
|
||||
var (
|
||||
switchDesktopCOM = pwin.SwitchDesktopCOM
|
||||
switchDesktopViaTaskView = pwin.SwitchDesktopViaTaskView
|
||||
virtualDesktopCount = pwin.VirtualDesktopCount
|
||||
)
|
||||
|
||||
// switchDesktopAction 切换虚拟桌面。
|
||||
// mode: alternate(往返)/ left / right。
|
||||
// method: com(默认,COM 直调,无快捷键依赖)/ taskview(Win+Tab 导航)/ hotkey(Win+Ctrl+方向键,
|
||||
// 仅当系统快捷键未被占用时可用)。com 失败时自动回退 taskview。
|
||||
// 仅当系统快捷键未被占用时可用)。com 普通失败时回退 taskview;单桌面时直接报错,
|
||||
// 避免任务视图停留前台后被全屏检测误判。
|
||||
type switchDesktopAction struct {
|
||||
mu sync.Mutex
|
||||
next int32 // alternate 模式下上次切换方向,用于往返
|
||||
@@ -32,9 +41,16 @@ 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},
|
||||
{Name: "mode", Label: "切换方向", Type: "select", Required: true, Default: "alternate",
|
||||
Options: []string{"alternate", "left", "right"},
|
||||
Labels: []string{"交替往返", "上一个桌面", "下一个桌面"},
|
||||
Help: "alternate:左右交替往返;left/right:固定方向"},
|
||||
{Name: "method", Label: "切换方式", Type: "select", Required: false, Default: "com",
|
||||
Options: []string{"com", "taskview", "hotkey"},
|
||||
Labels: []string{"COM 直调(推荐)", "任务视图导航", "Win+Ctrl+方向键"},
|
||||
Help: "com:COM 直调(推荐);taskview:Win+Tab 导航;hotkey:Win+Ctrl+方向键"},
|
||||
{Name: "taskview_delay_ms", Label: "Task View 等待(ms)", Type: "int", Required: false, Default: 400,
|
||||
Help: "taskview 方式下等待切换动画的毫秒数;<=0 按 400ms"},
|
||||
}}
|
||||
}
|
||||
|
||||
@@ -74,15 +90,26 @@ func (a *switchDesktopAction) Execute(ctx context.Context, params map[string]any
|
||||
a.next = -dir
|
||||
a.mu.Unlock()
|
||||
}
|
||||
switch GetString(params, "method") {
|
||||
method := GetString(params, "method")
|
||||
delay := time.Duration(GetInt(params, "taskview_delay_ms")) * time.Millisecond
|
||||
// 单桌面时 taskview / hotkey 都无法切换;任务视图还会停留在前台,
|
||||
// 被全屏检测误判后抑制全部规则,因此提前返回明确错误。
|
||||
if method == "taskview" || method == "hotkey" {
|
||||
if n, err := virtualDesktopCount(); err == nil && n < 2 {
|
||||
return fmt.Errorf("%w (found %d)", pwin.ErrNotEnoughDesktops, n)
|
||||
}
|
||||
}
|
||||
switch 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 switchDesktopViaTaskView(dir, delay)
|
||||
default: // com:COM 直调;仅非单桌面错误才回退 taskview
|
||||
if err := switchDesktopCOM(dir); err == nil {
|
||||
return nil
|
||||
} else if errors.Is(err, pwin.ErrNotEnoughDesktops) {
|
||||
return err
|
||||
}
|
||||
return pwin.SwitchDesktopViaTaskView(dir, time.Duration(GetInt(params, "taskview_delay_ms"))*time.Millisecond)
|
||||
return switchDesktopViaTaskView(dir, delay)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,113 @@
|
||||
package action
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
pwin "zerorigin/internal/platform/windows"
|
||||
)
|
||||
|
||||
// restoreDesktopFakes 在测试结束时恢复平台函数,避免影响其他用例。
|
||||
func restoreDesktopFakes(t *testing.T, com func(int32) error, taskView func(int32, time.Duration) error, count func() (int, error)) {
|
||||
t.Helper()
|
||||
oldCOM, oldTaskView, oldCount := switchDesktopCOM, switchDesktopViaTaskView, virtualDesktopCount
|
||||
t.Cleanup(func() {
|
||||
switchDesktopCOM = oldCOM
|
||||
switchDesktopViaTaskView = oldTaskView
|
||||
virtualDesktopCount = oldCount
|
||||
})
|
||||
switchDesktopCOM = com
|
||||
switchDesktopViaTaskView = taskView
|
||||
virtualDesktopCount = count
|
||||
}
|
||||
|
||||
// TestSwitchDesktopNoTaskViewFallbackOnSingleDesktop 验证单桌面时 COM 返回
|
||||
// ErrNotEnoughDesktops,不得回退任务视图(否则任务视图会留在前台)。
|
||||
func TestSwitchDesktopNoTaskViewFallbackOnSingleDesktop(t *testing.T) {
|
||||
taskViewCalls := 0
|
||||
restoreDesktopFakes(t,
|
||||
func(int32) error { return fmt.Errorf("%w (found 1)", pwin.ErrNotEnoughDesktops) },
|
||||
func(int32, time.Duration) error { taskViewCalls++; return nil },
|
||||
nil,
|
||||
)
|
||||
|
||||
err := (&switchDesktopAction{}).Execute(context.Background(), map[string]any{
|
||||
"mode": "right", "method": "com", "taskview_delay_ms": 0,
|
||||
})
|
||||
if !errors.Is(err, pwin.ErrNotEnoughDesktops) {
|
||||
t.Fatalf("Execute error = %v, want ErrNotEnoughDesktops", err)
|
||||
}
|
||||
if taskViewCalls != 0 {
|
||||
t.Fatalf("task view fallback called %d times, want 0 on single desktop", taskViewCalls)
|
||||
}
|
||||
}
|
||||
|
||||
// TestSwitchDesktopCOMErrorFallsBackToTaskView 验证普通 COM 错误仍回退
|
||||
// 任务视图,并透传方向与等待时长。
|
||||
func TestSwitchDesktopCOMErrorFallsBackToTaskView(t *testing.T) {
|
||||
gotDir := int32(0)
|
||||
gotDelay := time.Duration(0)
|
||||
restoreDesktopFakes(t,
|
||||
func(int32) error { return errors.New("com unavailable") },
|
||||
func(dir int32, delay time.Duration) error {
|
||||
gotDir, gotDelay = dir, delay
|
||||
return nil
|
||||
},
|
||||
nil,
|
||||
)
|
||||
|
||||
err := (&switchDesktopAction{}).Execute(context.Background(), map[string]any{
|
||||
"mode": "left", "method": "com", "taskview_delay_ms": 500,
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("Execute error = %v, want nil (fallback succeeds)", err)
|
||||
}
|
||||
if gotDir != -1 || gotDelay != 500*time.Millisecond {
|
||||
t.Fatalf("fallback got dir=%d delay=%v, want -1/500ms", gotDir, gotDelay)
|
||||
}
|
||||
}
|
||||
|
||||
// TestSwitchDesktopTaskViewGuardSingleDesktop 验证显式 taskview 方式在
|
||||
// 单桌面时提前失败,不打开任务视图。
|
||||
func TestSwitchDesktopTaskViewGuardSingleDesktop(t *testing.T) {
|
||||
comCalls, taskViewCalls := 0, 0
|
||||
restoreDesktopFakes(t,
|
||||
func(int32) error { comCalls++; return nil },
|
||||
func(int32, time.Duration) error { taskViewCalls++; return nil },
|
||||
func() (int, error) { return 1, nil },
|
||||
)
|
||||
|
||||
err := (&switchDesktopAction{}).Execute(context.Background(), map[string]any{
|
||||
"mode": "right", "method": "taskview",
|
||||
})
|
||||
if !errors.Is(err, pwin.ErrNotEnoughDesktops) {
|
||||
t.Fatalf("Execute error = %v, want ErrNotEnoughDesktops", err)
|
||||
}
|
||||
if comCalls != 0 || taskViewCalls != 0 {
|
||||
t.Fatalf("switches called (com=%d taskview=%d), want none", comCalls, taskViewCalls)
|
||||
}
|
||||
}
|
||||
|
||||
// TestSwitchDesktopTaskViewCountFailureProceeds 验证数量查询失败不阻断
|
||||
// taskview 方式(保持旧行为,失败由动作本身报错)。
|
||||
func TestSwitchDesktopTaskViewCountFailureProceeds(t *testing.T) {
|
||||
gotDelay := time.Duration(0)
|
||||
restoreDesktopFakes(t,
|
||||
func(int32) error { return nil },
|
||||
func(_ int32, delay time.Duration) error { gotDelay = delay; return nil },
|
||||
func() (int, error) { return 0, errors.New("query failed") },
|
||||
)
|
||||
|
||||
err := (&switchDesktopAction{}).Execute(context.Background(), map[string]any{
|
||||
"mode": "right", "method": "taskview", "taskview_delay_ms": 900,
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("Execute error = %v, want nil", err)
|
||||
}
|
||||
if gotDelay != 900*time.Millisecond {
|
||||
t.Fatalf("delay = %v, want 900ms", gotDelay)
|
||||
}
|
||||
}
|
||||
@@ -22,8 +22,10 @@ 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: ""},
|
||||
{Name: "path", Label: "程序路径", Type: "string", Required: true,
|
||||
Help: `Windows 绝对路径,例如 C:\Windows\notepad.exe`},
|
||||
{Name: "args", Label: "启动参数", Type: "string", Required: false, Default: "",
|
||||
Help: "传给程序的命令行参数(可选)"},
|
||||
}}
|
||||
}
|
||||
|
||||
|
||||
@@ -4,14 +4,14 @@ import (
|
||||
"context"
|
||||
"fmt"
|
||||
|
||||
pwin "zerorigin/internal/platform/windows"
|
||||
"github.com/egoist/mygo"
|
||||
)
|
||||
|
||||
func init() {
|
||||
Register("show_notification", func() Action { return ¬ificationAction{} })
|
||||
}
|
||||
|
||||
// notificationAction 显示系统托盘气泡通知。
|
||||
// notificationAction 显示系统桌面通知。
|
||||
type notificationAction struct{}
|
||||
|
||||
func (a *notificationAction) ID() string { return "show_notification" }
|
||||
@@ -19,8 +19,8 @@ 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},
|
||||
{Name: "title", Label: "标题", Type: "string", Required: true},
|
||||
{Name: "text", Label: "内容", Type: "string", Required: true},
|
||||
}}
|
||||
}
|
||||
|
||||
@@ -35,5 +35,26 @@ func (a *notificationAction) Validate(params map[string]any) error {
|
||||
}
|
||||
|
||||
func (a *notificationAction) Execute(ctx context.Context, params map[string]any) error {
|
||||
return pwin.ShowBalloon(GetString(params, "title"), GetString(params, "text"))
|
||||
if !NotificationsAllowed(ctx) {
|
||||
logger.Debug("show_notification suppressed by notify switch", "action", a.ID())
|
||||
return nil
|
||||
}
|
||||
if err := notifyDesktop(GetString(params, "title"), GetString(params, "text")); err != nil {
|
||||
return fmt.Errorf("show_notification: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// notifyDesktop 通过 mygo 通知后端显示一条桌面通知。
|
||||
// mygo 通知后端要求应用已启动:测试环境或启动早期调用时返回错误而不是 panic。
|
||||
func notifyDesktop(title, body string) (err error) {
|
||||
defer func() {
|
||||
if r := recover(); r != nil {
|
||||
err = fmt.Errorf("notification backend unavailable: %v", r)
|
||||
}
|
||||
}()
|
||||
if !mygo.NotificationsSupported() {
|
||||
return fmt.Errorf("当前环境不支持桌面通知")
|
||||
}
|
||||
return mygo.NewNotification(mygo.NotificationOptions{Title: title, Body: body}).Show()
|
||||
}
|
||||
+11
-4
@@ -6,7 +6,7 @@ import (
|
||||
"net/url"
|
||||
"strings"
|
||||
|
||||
pwin "zerorigin/internal/platform/windows"
|
||||
"github.com/egoist/mygo"
|
||||
)
|
||||
|
||||
func init() {
|
||||
@@ -21,7 +21,8 @@ func (a *openURLAction) Name() string { return "打开链接" }
|
||||
|
||||
func (a *openURLAction) Schema() ActionSchema {
|
||||
return ActionSchema{Params: []ParamSpec{
|
||||
{Name: "url", Type: "string", Required: true},
|
||||
{Name: "url", Label: "链接(URL)", Type: "string", Required: true,
|
||||
Help: "仅支持 http/https 链接"},
|
||||
}}
|
||||
}
|
||||
|
||||
@@ -43,6 +44,12 @@ func (a *openURLAction) Validate(params map[string]any) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
func (a *openURLAction) Execute(ctx context.Context, params map[string]any) error {
|
||||
return pwin.OpenPath(GetString(params, "url"))
|
||||
func (a *openURLAction) Execute(ctx context.Context, params map[string]any) (err error) {
|
||||
// mygo 的 Shell 模块要求应用已启动;测试环境调用时给出错误而不是 panic。
|
||||
defer func() {
|
||||
if r := recover(); r != nil {
|
||||
err = fmt.Errorf("open_url: shell backend unavailable: %v", r)
|
||||
}
|
||||
}()
|
||||
return mygo.Shell.OpenExternal(GetString(params, "url"))
|
||||
}
|
||||
+118
-39
@@ -5,6 +5,7 @@ import (
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"zerorigin/internal/osd"
|
||||
pwin "zerorigin/internal/platform/windows"
|
||||
)
|
||||
|
||||
@@ -15,13 +16,13 @@ func init() {
|
||||
}
|
||||
|
||||
// volumeStepAction 音量步进。
|
||||
// steps: 百分比步进(默认 1 = ±1%)。
|
||||
// steps: 每次触发的目标百分比变化(默认 4,约等于两格系统媒体键)。
|
||||
// 滚轮触发器按"格"上报事件,因此滚一格就是一次 ±steps% 的调节。
|
||||
// method: media(默认,SendInput 媒体键 VK_VOLUME_UP/DOWN,由系统 Shell 处理:
|
||||
//
|
||||
// Win11 显示完整 OSD(设备名+滑块+数字+应用入口)且立即生效)/
|
||||
//
|
||||
// com(IAudioEndpointVolume 直调,精确百分比,但 OSD 简化、个别设备无效)/
|
||||
// hotkey(media 的别名,兼容旧配置)。
|
||||
// Win11 显示完整 OSD(设备名+滑块+数字+应用入口)且立即生效;媒体键每次约 2%,
|
||||
// 奇数步进无法精确表达,会自动改用 COM)/ com(IAudioEndpointVolume 直调,
|
||||
// 精确百分比,但 OSD 简化、个别设备无效)/ hotkey(media 的别名,兼容旧配置)。
|
||||
//
|
||||
// 背景:COM 直调返回 S_OK 且读回验证通过,但 Win11 音频服务未将其视为
|
||||
// "系统级音量调节"→ OSD 简化为最小版,且若默认端点与应用实际聆听设备
|
||||
@@ -45,8 +46,14 @@ func (a *volumeStepAction) Name() string {
|
||||
|
||||
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"},
|
||||
{Name: "steps", Label: "步进(百分比)", Type: "int", Required: false, Default: 4,
|
||||
Help: "每格滚轮改变的音量百分比;媒体键每次约 2%,奇数步进会自动改用 COM 精确调节"},
|
||||
{Name: "method", Label: "调节方式", Type: "select", Required: false, Default: "media",
|
||||
Options: []string{"media", "com"},
|
||||
Labels: []string{"媒体键", "COM 接口"},
|
||||
Help: "media:SendInput 媒体键(Win11 完整 OSD;奇数步进自动切 COM);com:IAudioEndpointVolume 直调"},
|
||||
{Name: "toast", Label: "弹出通知", Type: "bool", Required: false, Default: false,
|
||||
Help: "调节后额外弹出桌面通知;系统本身已有音量 OSD,默认关闭"},
|
||||
}}
|
||||
}
|
||||
|
||||
@@ -69,13 +76,27 @@ func (a *volumeStepAction) Execute(ctx context.Context, params map[string]any) e
|
||||
steps = 1
|
||||
}
|
||||
delta := a.dir * int32(steps)
|
||||
if volumeMethod(GetString(params, "method")) == "com" {
|
||||
// COM 直调(精确百分比,用户显式选择);失败时记录原因并回退媒体键。
|
||||
toast := GetBool(params, "toast")
|
||||
method := volumeMethod(GetString(params, "method"))
|
||||
if volumeUseCOM(method, steps) {
|
||||
// COM 直调(精确百分比):用户显式选择 com,或 media 遇到奇数步进
|
||||
// (媒体键固定约 2%/次,1% 会被放大成 2%)。失败时回退媒体键。
|
||||
if method == "media" {
|
||||
logger.Debug("volume odd step uses COM for exact percent", "action", a.ID(), "steps", steps)
|
||||
}
|
||||
if err := pwin.VolumeAdjustPercent(delta); err == nil {
|
||||
// 诊断读回:确认程序视角下音量确实变化(区分"程序没改到"与"改的不是聆听设备")。
|
||||
// COM 路径没有 Shell 音量条:读回后始终显示自绘提示条;
|
||||
// 同时只有"动作 toast + 规则开关 + 全局开关"都允许时才弹系统通知。
|
||||
allowed := NotificationsAllowed(ctx)
|
||||
if after, err2 := pwin.GetMasterVolumePercent(); err2 == nil {
|
||||
osd.ShowVolume(after)
|
||||
logger.Debug("volume adjusted", "action", a.ID(), "after_percent", after)
|
||||
notifyVolume(after, volumeStepKind(a.dir))
|
||||
if toast && allowed {
|
||||
notifyVolumeAllowed(after, volumeStepKind(a.dir), allowed)
|
||||
}
|
||||
} else {
|
||||
logger.Debug("volume adjusted", "action", a.ID(), "delta_percent", delta,
|
||||
"read_after_err", err2)
|
||||
}
|
||||
return nil
|
||||
} else {
|
||||
@@ -83,7 +104,10 @@ func (a *volumeStepAction) Execute(ctx context.Context, params map[string]any) e
|
||||
}
|
||||
}
|
||||
// 媒体键路径(默认):由系统 Shell 处理 → 完整 OSD + 立即生效。
|
||||
n := volumeStepCount(delta)
|
||||
// 系统媒体键每次约 2%,按 steps/2 换算按次数(至少 1 次);间隔只留
|
||||
// 5ms,让一次滚轮事件在 ~10ms 内返回,避免引擎"执行中丢弃新事件"
|
||||
// 在快速连滚时吃掉后续几格。
|
||||
n := mediaPressCount(delta)
|
||||
for i := 0; i < n; i++ {
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
@@ -93,22 +117,65 @@ func (a *volumeStepAction) Execute(ctx context.Context, params map[string]any) e
|
||||
if err := pwin.VolumeStep(delta); err != nil {
|
||||
return err
|
||||
}
|
||||
// 连续按键留出间隔,避免系统吞掉相邻的相同按键事件。
|
||||
if i < n-1 {
|
||||
time.Sleep(30 * time.Millisecond)
|
||||
time.Sleep(mediaKeyGap)
|
||||
}
|
||||
}
|
||||
// 调节成功后弹出系统 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)
|
||||
// 读回与 Toast 放到后台:媒体键由 Shell 异步应用,需要稍等再读,
|
||||
// 不能让动作链在这里阻塞(否则滚轮连滚会被引擎丢弃)。
|
||||
// 通知默认关闭:Win11 的媒体键 OSD 已经显示音量,再弹 Toast 会很吵。
|
||||
if toast && NotificationsAllowed(ctx) {
|
||||
// 媒体键自带系统 OSD,这里不再显示自绘提示条,避免双层提示。
|
||||
notifyVolumeAfterMediaKeys(a.dir, true)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// volumeUseCOM 判断本次音量调节是否需要 COM 精确路径。
|
||||
// 用户显式选择 com 时始终走 COM;media 路径的媒体键每次约 2%,
|
||||
// 奇数步进(如 1%)无法精确表达,自动改用 COM,避免把 1% 调成 2%。
|
||||
func volumeUseCOM(method string, steps int) bool {
|
||||
if method == "com" {
|
||||
return true
|
||||
}
|
||||
return steps%2 != 0
|
||||
}
|
||||
|
||||
// mediaKeyGap 为连续媒体键之间的最小间隔(过短会被系统合并/吞掉)。
|
||||
const mediaKeyGap = 5 * time.Millisecond
|
||||
|
||||
// mediaPressCount 把目标百分比换算成媒体键次数(系统媒体键每步约 2%)。
|
||||
func mediaPressCount(delta int32) int {
|
||||
steps := float64(delta)
|
||||
if steps < 0 {
|
||||
steps = -steps
|
||||
}
|
||||
n := int(steps/2 + 0.5)
|
||||
if n < 1 {
|
||||
n = 1
|
||||
}
|
||||
return n
|
||||
}
|
||||
|
||||
// notifyVolumeAfterMediaKeys 后台读回音量并弹出去抖 Toast。
|
||||
// allowed 已包含规则级开关,必须在启动 goroutine 前捕获。
|
||||
// ⚠️ 独立 goroutine:panic 必须自兜底,否则拖垮进程。
|
||||
func notifyVolumeAfterMediaKeys(dir int32, allowed bool) {
|
||||
go func() {
|
||||
defer func() {
|
||||
if r := recover(); r != nil {
|
||||
pwin.LogGoPanic("action.volume.notify", r, debugStackBuf())
|
||||
}
|
||||
}()
|
||||
time.Sleep(60 * time.Millisecond)
|
||||
if after, err := pwin.GetMasterVolumePercent(); err == nil {
|
||||
notifyVolumeAllowed(after, volumeStepKind(dir), allowed)
|
||||
} else {
|
||||
logger.Debug("volume toast: read volume failed", "err", err)
|
||||
}
|
||||
}()
|
||||
}
|
||||
|
||||
// volumeStepKind 返回音量调节方向标签(供 Toast 内容使用)。
|
||||
func volumeStepKind(dir int32) string {
|
||||
if dir > 0 {
|
||||
@@ -125,7 +192,12 @@ func (a *muteAction) Name() string { return "静音切换" }
|
||||
|
||||
func (a *muteAction) Schema() ActionSchema {
|
||||
return ActionSchema{Params: []ParamSpec{
|
||||
{Name: "method", Type: "string", Required: false, Default: "media"},
|
||||
{Name: "method", Label: "切换方式", Type: "select", Required: false, Default: "media",
|
||||
Options: []string{"media", "com"},
|
||||
Labels: []string{"媒体键", "COM 接口"},
|
||||
Help: "media:SendInput 媒体键;com:IAudioEndpointVolume 直调"},
|
||||
{Name: "toast", Label: "弹出通知", Type: "bool", Required: false, Default: false,
|
||||
Help: "切换后额外弹出桌面通知;系统本身已有静音 OSD,默认关闭"},
|
||||
}}
|
||||
}
|
||||
|
||||
@@ -138,40 +210,55 @@ func (a *muteAction) Validate(params map[string]any) error {
|
||||
}
|
||||
|
||||
func (a *muteAction) Execute(ctx context.Context, params map[string]any) error {
|
||||
toast := GetBool(params, "toast")
|
||||
allowed := NotificationsAllowed(ctx)
|
||||
if volumeMethod(GetString(params, "method")) == "com" {
|
||||
// COM 直调(精确,用户显式选择);失败时记录原因并回退媒体键。
|
||||
if err := pwin.ToggleMuteCOM(); err == nil {
|
||||
notifyMuteResult()
|
||||
err := pwin.ToggleMuteCOM()
|
||||
if err == nil {
|
||||
// COM 没有系统静音 OSD:读回状态与音量,显示自绘提示条。
|
||||
if muted, err2 := pwin.GetMuteState(); err2 == nil {
|
||||
percent := -1
|
||||
if p, err3 := pwin.GetMasterVolumePercent(); err3 == nil {
|
||||
percent = p
|
||||
}
|
||||
osd.ShowMute(muted, percent)
|
||||
}
|
||||
if toast && allowed {
|
||||
notifyMuteResult(allowed)
|
||||
}
|
||||
return nil
|
||||
} else {
|
||||
logger.Warn("mute COM failed, falling back to media key", "err", err)
|
||||
}
|
||||
logger.Warn("mute COM failed, falling back to media key", "err", err)
|
||||
}
|
||||
// 媒体键路径由 Shell 处理并自带静音 OSD,不再叠一层自绘提示。
|
||||
if err := pwin.VolumeMute(); err != nil {
|
||||
return err
|
||||
}
|
||||
notifyMuteResult()
|
||||
if toast && allowed {
|
||||
notifyMuteResult(allowed)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// notifyMuteResult 读回当前静音状态并弹出系统 Toast(去抖由 notifyVolume 处理)。
|
||||
// 媒体键由 Shell 异步处理,先短暂等待再读回,避免读到切换前状态。
|
||||
func notifyMuteResult() {
|
||||
func notifyMuteResult(allowed bool) {
|
||||
time.Sleep(80 * time.Millisecond)
|
||||
for i := 0; i < 3; i++ {
|
||||
muted, err := pwin.GetMuteState()
|
||||
if err == nil {
|
||||
if muted {
|
||||
notifyVolume(0, "mute")
|
||||
notifyVolumeAllowed(0, "mute", allowed)
|
||||
} else {
|
||||
notifyVolume(0, "unmute")
|
||||
notifyVolumeAllowed(0, "unmute", allowed)
|
||||
}
|
||||
return
|
||||
}
|
||||
time.Sleep(40 * time.Millisecond)
|
||||
}
|
||||
logger.Debug("volume toast: read mute state failed")
|
||||
notifyVolume(0, "mute_unknown")
|
||||
notifyVolumeAllowed(0, "mute_unknown", allowed)
|
||||
}
|
||||
|
||||
// volumeMethod 归一化 method 参数:""(默认)→ media;hotkey 是 media 的别名。
|
||||
@@ -185,11 +272,3 @@ func volumeMethod(raw string) string {
|
||||
}
|
||||
return "media"
|
||||
}
|
||||
|
||||
// volumeStepCount 返回媒体键路径需要发送的按键次数(delta 的绝对值)。
|
||||
func volumeStepCount(delta int32) int {
|
||||
if delta < 0 {
|
||||
return int(-delta)
|
||||
}
|
||||
return int(delta)
|
||||
}
|
||||
@@ -4,11 +4,35 @@ import (
|
||||
"fmt"
|
||||
"runtime"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
"time"
|
||||
|
||||
pwin "zerorigin/internal/platform/windows"
|
||||
)
|
||||
|
||||
// toastEnabled 为全局通知总开关(配置 global.notify,默认开启)。
|
||||
// 所有右下角系统 Toast(自动调节提示与显式的 show_notification)都受它
|
||||
// 控制;屏幕底部的调节提示条(internal/osd)不受影响。
|
||||
var toastEnabled atomic.Bool
|
||||
|
||||
func init() { toastEnabled.Store(true) }
|
||||
|
||||
// SetToastEnabled 设置是否允许自动调节类 Toast。
|
||||
// 关闭时立即取消尚未显示的待发通知,避免"关掉后还弹最后一个"。
|
||||
func SetToastEnabled(on bool) {
|
||||
toastEnabled.Store(on)
|
||||
if on {
|
||||
return
|
||||
}
|
||||
toastMu.Lock()
|
||||
if toastTimer != nil {
|
||||
toastTimer.Stop()
|
||||
toastTimer = nil
|
||||
}
|
||||
toastNext = nil
|
||||
toastMu.Unlock()
|
||||
}
|
||||
|
||||
// 音量 Toast 去抖实现:快速连按时合并为最后一次显示,
|
||||
// 避免 Win11 系统 OSD 数字太小/消失太快时 Toast 弹窗闪烁。
|
||||
//
|
||||
@@ -30,8 +54,8 @@ const (
|
||||
volumeToastMuteTitle = "静音"
|
||||
)
|
||||
|
||||
// showBalloonFunc 底层系统通知函数(变量便于测试注入替换)。
|
||||
var showBalloonFunc = pwin.ShowBalloon
|
||||
// notifyFunc 底层系统通知函数(变量便于测试注入替换)。
|
||||
var notifyFunc = notifyDesktop
|
||||
|
||||
// toastContent 待显示的 Toast 内容。
|
||||
type toastContent struct {
|
||||
@@ -48,7 +72,15 @@ var (
|
||||
// notifyVolume 在音量/静音动作成功后显示系统 Toast(默认 500ms 去抖合并)。
|
||||
// level: 调节后的音量百分比(仅 up/down 使用;静音动作传 0,文本不依赖 level)。
|
||||
// kind: up | down | mute | unmute | mute_unknown。
|
||||
//
|
||||
// 保留 allowed=true 的便捷入口给测试与内部默认路径;动作实现应调用
|
||||
// notifyVolumeAllowed,把规则级开关明确带进来。
|
||||
func notifyVolume(level int, kind string) {
|
||||
notifyVolumeAllowed(level, kind, true)
|
||||
}
|
||||
|
||||
// notifyVolumeAllowed 按规则级通知开关显示音量/静音 Toast。
|
||||
func notifyVolumeAllowed(level int, kind string, allowed bool) {
|
||||
var title, text string
|
||||
switch kind {
|
||||
case "up", "down":
|
||||
@@ -60,11 +92,16 @@ func notifyVolume(level int, kind string) {
|
||||
default:
|
||||
title, text = volumeToastMuteTitle, "静音已切换"
|
||||
}
|
||||
scheduleToast(title, text)
|
||||
scheduleToast(title, text, allowed)
|
||||
}
|
||||
|
||||
// scheduleToast 去抖调度:窗口内多次调用只显示最后一次内容。
|
||||
func scheduleToast(title, text string) {
|
||||
// allowed 是调用方在异步路径启动前捕获的规则级开关;全局开关关闭时
|
||||
// 同样直接忽略,不创建计时器。
|
||||
func scheduleToast(title, text string, allowed bool) {
|
||||
if !allowed || !toastEnabled.Load() {
|
||||
return
|
||||
}
|
||||
toastMu.Lock()
|
||||
defer toastMu.Unlock()
|
||||
|
||||
@@ -90,10 +127,10 @@ func flushToast() {
|
||||
toastNext = nil
|
||||
toastMu.Unlock()
|
||||
|
||||
if next == nil {
|
||||
if next == nil || !toastEnabled.Load() {
|
||||
return
|
||||
}
|
||||
if err := showBalloonFunc(next.title, next.text); err != nil {
|
||||
if err := notifyFunc(next.title, next.text); err != nil {
|
||||
logger.Warn("volume toast failed", "err", err)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -20,12 +20,12 @@ func resetToastForTest() {
|
||||
// swapToastForTest 替换去抖窗口与底层通知函数,返回还原函数。
|
||||
func swapToastForTest(window time.Duration, fn func(title, text string) error) func() {
|
||||
oldWindow := volumeToastDebounceWindow
|
||||
oldFunc := showBalloonFunc
|
||||
oldFunc := notifyFunc
|
||||
volumeToastDebounceWindow = window
|
||||
showBalloonFunc = fn
|
||||
notifyFunc = fn
|
||||
return func() {
|
||||
volumeToastDebounceWindow = oldWindow
|
||||
showBalloonFunc = oldFunc
|
||||
notifyFunc = oldFunc
|
||||
}
|
||||
}
|
||||
|
||||
@@ -137,3 +137,68 @@ func TestVolumeToastMuteText(t *testing.T) {
|
||||
}
|
||||
mu.Unlock()
|
||||
}
|
||||
|
||||
// TestToastDisabledGate 验证全局开关关闭时既不显示新通知,
|
||||
// 也会清掉已经排队但尚未显示的通知。
|
||||
func TestToastDisabledGate(t *testing.T) {
|
||||
var (
|
||||
mu sync.Mutex
|
||||
calls int
|
||||
)
|
||||
restore := swapToastForTest(10*time.Millisecond, func(string, string) error {
|
||||
mu.Lock()
|
||||
calls++
|
||||
mu.Unlock()
|
||||
return nil
|
||||
})
|
||||
defer restore()
|
||||
resetToastForTest()
|
||||
defer resetToastForTest()
|
||||
SetToastEnabled(true)
|
||||
defer SetToastEnabled(true)
|
||||
|
||||
SetToastEnabled(false)
|
||||
notifyVolume(30, "up")
|
||||
time.Sleep(50 * time.Millisecond)
|
||||
mu.Lock()
|
||||
if calls != 0 {
|
||||
mu.Unlock()
|
||||
t.Fatalf("disabled toast produced %d notifications, want 0", calls)
|
||||
}
|
||||
mu.Unlock()
|
||||
|
||||
// 先排队再关闭:关闭时必须取消待发通知。
|
||||
SetToastEnabled(true)
|
||||
notifyVolume(30, "up")
|
||||
SetToastEnabled(false)
|
||||
time.Sleep(50 * time.Millisecond)
|
||||
mu.Lock()
|
||||
if calls != 0 {
|
||||
mu.Unlock()
|
||||
t.Fatalf("pending toast should be cancelled after disable, got %d", calls)
|
||||
}
|
||||
mu.Unlock()
|
||||
}
|
||||
|
||||
// TestVolumeSchemaToastDefaultOff 验证音量/静音动作默认不弹额外通知
|
||||
// (系统自身已有 OSD),用户仍可在规则里显式打开。
|
||||
func TestVolumeSchemaToastDefaultOff(t *testing.T) {
|
||||
for _, id := range []string{"volume_up", "volume_down", "toggle_mute"} {
|
||||
act, err := New(id)
|
||||
if err != nil {
|
||||
t.Fatalf("%s: %v", id, err)
|
||||
}
|
||||
var found bool
|
||||
for _, p := range act.Schema().Params {
|
||||
if p.Name == "toast" {
|
||||
found = true
|
||||
if p.Type != "bool" || p.Default != false {
|
||||
t.Errorf("%s toast = type %q default %v, want bool false", id, p.Type, p.Default)
|
||||
}
|
||||
}
|
||||
}
|
||||
if !found {
|
||||
t.Errorf("%s missing toast param", id)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -37,21 +37,46 @@ func TestVolumeMethodSelection(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// TestVolumeStepCount 验证媒体键路径按键次数 = |delta|。
|
||||
func TestVolumeStepCount(t *testing.T) {
|
||||
// TestVolumeUseCOM 验证奇数步进自动改用 COM,偶数步进仍走媒体键。
|
||||
func TestVolumeUseCOM(t *testing.T) {
|
||||
cases := []struct {
|
||||
method string
|
||||
steps int
|
||||
want bool
|
||||
}{
|
||||
{"media", 1, true},
|
||||
{"media", 3, true},
|
||||
{"media", 5, true},
|
||||
{"media", 2, false},
|
||||
{"media", 4, false},
|
||||
{"com", 1, true},
|
||||
{"com", 2, true},
|
||||
}
|
||||
for _, c := range cases {
|
||||
if got := volumeUseCOM(c.method, c.steps); got != c.want {
|
||||
t.Errorf("volumeUseCOM(%q, %d) = %v, want %v", c.method, c.steps, got, c.want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// TestMediaPressCount 验证百分比到媒体键次数的换算(每步约 2%,至少 1 次)。
|
||||
func TestMediaPressCount(t *testing.T) {
|
||||
cases := []struct {
|
||||
delta int32
|
||||
want int
|
||||
}{
|
||||
{4, 2},
|
||||
{1, 1},
|
||||
{3, 3},
|
||||
{-1, 1},
|
||||
{-5, 5},
|
||||
{0, 0},
|
||||
{2, 1},
|
||||
{3, 2},
|
||||
{10, 5},
|
||||
{-4, 2},
|
||||
{-7, 4},
|
||||
{0, 1}, // 最小一次按键(Execute 里 steps<=0 会先归一化为 1)
|
||||
}
|
||||
for _, c := range cases {
|
||||
if got := volumeStepCount(c.delta); got != c.want {
|
||||
t.Errorf("volumeStepCount(%d) = %d, want %d", c.delta, got, c.want)
|
||||
if got := mediaPressCount(c.delta); got != c.want {
|
||||
t.Errorf("mediaPressCount(%d) = %d, want %d", c.delta, got, c.want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user