Files
zerorigin-toolbox/internal/action/volumeToastDebounce.go
T
zerorigin2019 0a1c1e82ea 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
2026-08-05 00:42:45 +08:00

107 lines
3.1 KiB
Go
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
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]
}