package action import ( "context" "fmt" "time" "zerorigin/internal/osd" 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: 每次触发的目标百分比变化(默认 4,约等于两格系统媒体键)。 // 滚轮触发器按"格"上报事件,因此滚一格就是一次 ±steps% 的调节。 // method: media(默认,SendInput 媒体键 VK_VOLUME_UP/DOWN,由系统 Shell 处理: // // Win11 显示完整 OSD(设备名+滑块+数字+应用入口)且立即生效;媒体键每次约 2%, // 奇数步进无法精确表达,会自动改用 COM)/ 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", 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,默认关闭"}, }} } 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) 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) 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 { logger.Warn("volume COM failed, falling back to media key", "action", a.ID(), "err", err) } } // 媒体键路径(默认):由系统 Shell 处理 → 完整 OSD + 立即生效。 // 系统媒体键每次约 2%,按 steps/2 换算按次数(至少 1 次);间隔只留 // 5ms,让一次滚轮事件在 ~10ms 内返回,避免引擎"执行中丢弃新事件" // 在快速连滚时吃掉后续几格。 n := mediaPressCount(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(mediaKeyGap) } } // 读回与 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 { 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", 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,默认关闭"}, }} } 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 { toast := GetBool(params, "toast") allowed := NotificationsAllowed(ctx) if volumeMethod(GetString(params, "method")) == "com" { // COM 直调(精确,用户显式选择);失败时记录原因并回退媒体键。 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 } logger.Warn("mute COM failed, falling back to media key", "err", err) } // 媒体键路径由 Shell 处理并自带静音 OSD,不再叠一层自绘提示。 if err := pwin.VolumeMute(); err != nil { return err } if toast && allowed { notifyMuteResult(allowed) } return nil } // notifyMuteResult 读回当前静音状态并弹出系统 Toast(去抖由 notifyVolume 处理)。 // 媒体键由 Shell 异步处理,先短暂等待再读回,避免读到切换前状态。 func notifyMuteResult(allowed bool) { time.Sleep(80 * time.Millisecond) for i := 0; i < 3; i++ { muted, err := pwin.GetMuteState() if err == nil { if muted { notifyVolumeAllowed(0, "mute", allowed) } else { notifyVolumeAllowed(0, "unmute", allowed) } return } time.Sleep(40 * time.Millisecond) } logger.Debug("volume toast: read mute state failed") notifyVolumeAllowed(0, "mute_unknown", allowed) } // 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" }