Files
zerorigin 0b8b9b0775 迁移到 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)
2026-11-16 10:31:44 +08:00

1077 lines
36 KiB
Go
Raw Permalink 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 osd 在屏幕底部居中显示调节提示条(音量/亮度/静音)。
//
// 为什么需要自绘:音量走 COM 精确路径时不会经过 Shell 媒体键,因此系统
// 原生的音量条不会出现;媒体键路径虽然自带 OSD,但每格约 2% 无法精确到
// 1%。提示条独立于右下角系统通知,始终显示,保证"调了能看见"。
package osd
import (
"fmt"
"log/slog"
"math"
"sync"
"sync/atomic"
"time"
"github.com/egoist/mygo"
"github.com/egoist/mygo/plugins/glass"
"github.com/egoist/mygo/ui"
pwin "zerorigin/internal/platform/windows"
)
const (
// Width/Height 为横向胶囊尺寸(DIP),紧凑横向胶囊。左右两侧时胶囊
// 竖起来,宽高互换(见 sizeFor)。
Width = 260
Height = 52
// panelRadius 等于短边的一半,两端才是完整的半圆;竖排时短边是 Height,
// 圆角仍为 26,两端依旧是完整半圆。
panelRadius = Height / 2
// bottomMargin 为默认的胶囊与显示器工作区边缘距离(DIP)。
bottomMargin = 64
// maxPositionMargin 是提示条边距的兜底上限(DIP):配置校验已经限制
// 在 config.OSDMaxMargin,这里再按工作区尺寸钳制,保证胶囊不会跑出屏幕。
maxPositionMargin = 1000
// displayDuration 为提示条显示时长;连续调节会重置计时。
displayDuration = 2200 * time.Millisecond
// hoverCheckInterval 是鼠标停在提示条上时的复查间隔:悬停期间提示条
// 不消失,鼠标移开后才隐藏。
hoverCheckInterval = 150 * time.Millisecond
// reachMargin 是"光标正在靠近胶囊"的容差(DIP)。从屏幕顶部滚出提示条后
// 用户要把鼠标移到屏幕底部才能拖进度条,这段路程常超过 displayDuration;
// 因此光标进入胶囊外这个范围时先不消失,够得着才点得动。
reachMargin = 120
// maxNearKeeps 限制因靠近而延长显示的次数(每次 hoverCheckInterval),
// 约 3 秒;否则光标在提示条附近一停,提示条就永远不消失。
maxNearKeeps = 20
// hoverRedrawInterval 限制"光感跟随光标"的重绘频率(约 60fps):低级
// 鼠标钩子每秒会上报上千次移动,全部转成重绘会挤满主线程的消息队列,
// 而每次重绘都要重算一遍 backdrop 模糊。
hoverRedrawInterval = 16 * time.Millisecond
// backdropWatchInterval 是"背景变了没"的采样间隔;backdropColorDelta 是
// 判定变化的阈值(0-255 的三通道平均差);backdropReshotGap 限制重新截屏
// 的最小间隔——重截要让窗口藏一帧,不能太频繁。
backdropWatchInterval = 150 * time.Millisecond
backdropColorDelta = 24
backdropReshotGap = 600 * time.Millisecond
// hoverGlowRadius/hoverCoreRadius 是光标处柔光与亮核的半径(DIP)。
// 胶囊只有 52 DIP 高,半径再大就整块一起亮、看不出跟随;柔光取 70
// (水平约半个胶囊),亮核取 26,两层叠出"被照亮"的水光感。
hoverGlowRadius = 62
hoverCoreRadius = 18
// 进度条在窗口内的水平范围(DIP),必须与 view 的布局一致:
// 左 padding 14 + 图标 18 + 间距 10 之后开始,右侧留百分比文字 42 + 间距 10。
trackLeft = 42
trackWidth = 152
// 进度条在竖向窗口(52x260)内的垂直范围(DIP),必须与 verticalView 的
// 布局一致:上留 26 空白((260-208)/2)+ 图标 18 + 间距 10 之后开始,
// 下方留间距 10 + 百分比文字 18。
trackTop = 54
trackHeight = 152
// iconSize/valueHeight 是图标与百分比文字的边长,横竖布局共用。
iconSize = 18
valueHeight = 18
// verticalTrackWidth 是竖排时进度条的粗细。
trackThickness = 4
)
// kind 为提示条类型。
type kind int
const (
kindVolume kind = iota
kindMute
kindBrightness
)
// state 是提示条当前展示的内容。
type state struct {
kind kind
percent int
muted bool
// gamma 表示亮度由 gamma ramp 软件调光,仅用于无障碍说明。
gamma bool
}
var (
logger = slog.Default()
enabled atomic.Bool
mu sync.Mutex
cur state
generation uint64
hideTimer *time.Timer
// win 只在主线程访问(创建、定位、显示、隐藏)。
win *mygo.Window
// winX/winY 记录当前窗口创建时的目标位置;位置变化时必须重建窗口,
// 因为 mygo 的 SetPosition 对已显示的提示条窗口不生效。
winX, winY int
// winPos/winMargin 记录窗口创建时的位置设置;位置或边距变化时必须重建,
// 否则胶囊会停在旧位置(mygo 不支持对提示条窗口 SetPosition)。
winPos string
winMargin int
// geomVisible/geomX/geomY/geomW/geomH 是提示条显示几何的快照(左上角与
// 实际像素尺寸,高 DPI 下大于 DIP 尺寸)。用原子变量而不是互斥锁:
// 低级鼠标钩子的回调线程要在这里做命中判断与坐标换算,回调必须立即返回,
// 持锁等待会拖慢全系统的鼠标输入(Windows 对超时的低级钩子会直接忽略)。
geomVisible atomic.Bool
geomX atomic.Int32
geomY atomic.Int32
geomW atomic.Int32
geomH atomic.Int32
// nearKeeps 记录本次显示因"光标靠近"而延长的次数,有上限(见 maxNearKeeps)。
nearKeeps atomic.Int32
// dragging 标记进度条正在被拖动:拖动期间提示条不隐藏(即使指针
// 短暂移出胶囊),避免拖到一半提示条消失。
dragging atomic.Bool
// pos / posMargin 是提示条在屏幕上的位置(top/bottom/left/right)与
// 距该边距离(DIP),由配置热重载通过 SetPosition 写入。
pos atomic.Value // string
posMargin atomic.Int32
// hoverOn/hoverX/hoverY 是"光标光感"状态:钩子回调线程写、渲染线程读,
// 与几何快照一样只用原子量,绝不在这里持锁。
hoverOn atomic.Bool
hoverX atomic.Int32
hoverY atomic.Int32
// lastHoverPaint 记录上次请求光感重绘的时刻(UnixNano),用于节流。
lastHoverPaint atomic.Int64
// hoverCh 是"请重绘提示条"的有界通知(1 槽,满即丢弃)。钩子线程只做
// 非阻塞投递,重绘交给常驻协程:mygo.RunOnMain 会阻塞到主线程执行完,
// 放在低级鼠标钩子的回调里会拖慢全系统的鼠标输入。
hoverCh = make(chan struct{}, 1)
// backdropBase 是上次截屏时窗口四角采样到的背景色,三个分量都为 -1 表
// 示还没有基准(刚显示或刚隐藏);backdropReshotAt 记录上次重截时刻。
// 只在主线程读写。
backdropBase = [3]int32{-1, -1, -1}
backdropReshotAt time.Time
// shot 是窗口背后屏幕内容的原始截屏(未模糊),只在主线程访问。
// 模糊交给 glass.Blur 在渲染时做:插件的 backdrop 只采样同一窗口里先画
// 出来的内容,所以必须先把这张位图铺进视图,Material 才有东西可模糊。
shot *ui.Bitmap
)
// SetPosition 设置提示条显示位置与距屏幕边缘的距离(DIP)。
// position 为空或非法时按底部居中,margin 为负时取 0、超过 maxPositionMargin 时取上限。
// 可从任意 goroutine 调用(配置热重载);下一次显示时生效。
func SetPosition(position string, margin int) {
switch position {
case "top", "bottom", "left", "right":
default:
position = "bottom"
}
margin = clampMargin(margin)
pos.Store(position)
posMargin.Store(int32(margin))
}
// position 返回当前配置的显示位置与边距。
func position() (string, int) {
p, ok := pos.Load().(string)
if !ok || p == "" {
p = "bottom"
}
return p, clampMargin(int(posMargin.Load()))
}
// sizeFor 返回给定方位下的胶囊尺寸(DIP):贴在左右两侧时胶囊竖起来,
// 宽高互换,这样它沿屏幕侧边延伸,而不是横着扎进屏幕。
func sizeFor(position string) (int, int) {
if position == "left" || position == "right" {
return Height, Width
}
return Width, Height
}
// currentSize 返回按当前配置方位算出的胶囊 DIP 尺寸。
func currentSize() (int, int) {
p, _ := position()
return sizeFor(p)
}
// vertical 报告提示条是否竖排(贴在左右两侧时为 true)。
// 视图布局、进度条方向和拖动坐标映射都按它取分支。
func vertical() bool {
p, _ := position()
return p == "left" || p == "right"
}
// clampMargin 把边距限制在 0..maxPositionMargin。
func clampMargin(m int) int {
if m < 0 {
return 0
}
if m > maxPositionMargin {
return maxPositionMargin
}
return m
}
// Init 启用提示条并注入日志器;必须在应用就绪后调用。
// 窗口本身延迟到第一次 Show 时创建,避免常驻进程多一个隐藏窗口。
func Init(log *slog.Logger) {
if log != nil {
logger = log
}
enabled.Store(true)
}
// ShowVolume 显示音量百分比提示条。
func ShowVolume(percent int) {
show(state{kind: kindVolume, percent: percent})
}
// ShowBrightness 显示亮度百分比提示条;gamma 为 true 表示软件调光,
// 只在无障碍名称中说明,界面保持精简。
func ShowBrightness(percent int, gamma bool) {
show(state{kind: kindBrightness, percent: percent, gamma: gamma})
}
// ShowMute 显示静音状态;percent 为读回的音量百分比(读不到时传 -1)。
func ShowMute(muted bool, percent int) {
show(state{kind: kindMute, percent: percent, muted: muted})
}
// show 更新状态、重置隐藏计时并把窗口显示到鼠标所在显示器底部。
// 可从任意 goroutine 调用;窗口操作会切到主线程。
func show(st state) {
if !enabled.Load() {
return
}
mu.Lock()
cur = st
generation++
g := generation
if hideTimer != nil {
hideTimer.Stop()
}
hideTimer = time.AfterFunc(displayDuration, func() { hideWhenIdle(g) })
mu.Unlock()
mygo.RunOnMain(showOnMain)
logger.Debug("osd shown", "kind", st.kind, "percent", st.percent)
}
// hideWhenIdle 在显示计时到期时决定隐藏还是继续等待:鼠标停在提示条上
// 就一直保留(每 hoverCheckInterval 复查一次),鼠标移开立即隐藏。
func hideWhenIdle(g uint64) {
mu.Lock()
stale := g != generation
mu.Unlock()
if stale {
return
}
if dragging.Load() || PointerInside() {
rescheduleHover(g)
return
}
// 光标正在靠近胶囊时先不消失:提示条常出现在鼠标的对侧(顶部滚轮出门、
// 提示条在屏幕底部),固定显示时长往往不够走完这段路,用户会以为"拖不动"。
if PointerNear() && nearKeeps.Load() < maxNearKeeps {
nearKeeps.Add(1)
rescheduleHover(g)
return
}
hideIf(g)
}
// rescheduleHover 在当前代次上再等一个复查间隔。
func rescheduleHover(g uint64) {
mu.Lock()
if hideTimer != nil {
hideTimer.Stop()
}
hideTimer = time.AfterFunc(hoverCheckInterval, func() { hideWhenIdle(g) })
mu.Unlock()
}
// Visible 报告提示条当前是否正在显示。
func Visible() bool {
return geomVisible.Load()
}
// PointerInside 报告鼠标是否停在提示条胶囊内(用当前光标位置判断)。
func PointerInside() bool {
x, y, ok := pwin.CursorPos()
if !ok {
return false
}
return PointerInsideAt(x, y)
}
// PointerInsideAt 报告给定的屏幕像素坐标是否落在提示条胶囊内。
// 鼠标穿透时窗口收不到消息,悬停判断只能靠坐标;实现不加锁,因为低级鼠标
// 钩子的回调线程会频繁调用它。
func PointerInsideAt(x, y int) bool {
return insideRect(x, y, 0)
}
// PointerNear 报告鼠标是否已经靠近胶囊(容差 reachMargin):靠近期间提示条
// 暂不隐藏,好让用户来得及按下拖动。
func PointerNear() bool {
x, y, ok := pwin.CursorPos()
if !ok {
return false
}
return PointerNearAt(x, y)
}
// PointerNearAt 报告给定坐标是否落在胶囊外 reachMargin 的范围内。
func PointerNearAt(x, y int) bool {
if insideRect(x, y, 0) {
return true
}
return insideRect(x, y, reachMargin)
}
// insideRect 判断坐标是否落在胶囊(外扩 margin 像素)内。
func insideRect(x, y, margin int) bool {
if !geomVisible.Load() {
return false
}
m := int32(margin)
gx, gy := geomX.Load(), geomY.Load()
w, h := geomW.Load(), geomH.Load()
if w <= 0 || h <= 0 {
dw, dh := currentSize()
w, h = int32(dw), int32(dh)
}
return x >= int(gx-m) && x < int(gx+w+m) && y >= int(gy-m) && y < int(gy+h+m)
}
// PercentAtX 把屏幕横坐标换算成进度条百分比(0-100)。
// 坐标钳制在轨道两端,因此按在胶囊任意位置都能开始拖动并立即给出对应值;
// 高 DPI 下按窗口实际像素宽度换算。
func PercentAtX(x int) int {
dw, _ := currentSize()
sx, w := int(geomX.Load()), int(geomW.Load())
if w <= 0 {
w = dw
}
scale := float64(w) / float64(dw)
if scale <= 0 {
scale = 1
}
rel := (float64(x) - float64(sx)) / scale
t := (rel - trackLeft) / trackWidth
if t < 0 {
t = 0
}
if t > 1 {
t = 1
}
return int(math.Round(t * 100))
}
// PercentAtY 把屏幕纵坐标换算成进度条百分比(0-100),只在竖排时使用。
// 竖向进度条从下往上增长,因此越靠上值越大;坐标同样钳制在轨道两端,
// 因此按在胶囊任意位置都能开始拖动。高 DPI 下按窗口实际像素高度换算。
func PercentAtY(y int) int {
_, dh := currentSize()
sy, h := int(geomY.Load()), int(geomH.Load())
if h <= 0 {
h = dh
}
scale := float64(h) / float64(dh)
if scale <= 0 {
scale = 1
}
rel := (float64(y) - float64(sy)) / scale
t := (float64(trackTop+trackHeight) - rel) / trackHeight
if t < 0 {
t = 0
}
if t > 1 {
t = 1
}
return int(math.Round(t * 100))
}
// PercentAt 把屏幕坐标换算成进度条百分比:横排按横坐标,竖排按纵坐标。
// 钩子回调线程用它统一处理拖动,不必自己判断布局方向。
func PercentAt(x, y int) int {
if vertical() {
return PercentAtY(y)
}
return PercentAtX(x)
}
// PreviewPercent 只更新当前提示条的百分比并重置隐藏计时,类型与 gamma
// 标记保持不变(拖动进度条时用于实时反馈)。
func PreviewPercent(percent int) {
mu.Lock()
st := cur
mu.Unlock()
st.percent = percent
show(st)
}
// SetDragging 标记进度条拖动状态;拖动期间提示条不隐藏。
func SetDragging(on bool) {
dragging.Store(on)
}
// SetHover 记录光标在胶囊上的位置(屏幕像素),点亮跟随光标的光感。
// 由低级鼠标钩子的回调线程调用:只写原子量并按 hoverRedrawInterval 节流,
// 重绘交给消费协程,绝不在这里做窗口操作。
func SetHover(x, y int) {
if !geomVisible.Load() {
return
}
hoverX.Store(int32(x))
hoverY.Store(int32(y))
// 从未亮到亮时必须立刻重绘一次,否则第一次进入胶囊要等到下一次移动。
first := !hoverOn.Swap(true)
now := time.Now().UnixNano()
if !first && now-lastHoverPaint.Load() < int64(hoverRedrawInterval) {
return
}
lastHoverPaint.Store(now)
requestHoverRedraw()
}
// ClearHover 在光标离开胶囊时熄灭光感;只在真的从亮到灭时重绘一次。
func ClearHover() {
if !hoverOn.Swap(false) {
return
}
lastHoverPaint.Store(0)
requestHoverRedraw()
}
// Hovering 报告光感当前是否点亮。
func Hovering() bool { return hoverOn.Load() }
// requestHoverRedraw 投递一次重绘请求(非阻塞:1 槽满了说明已有待处理,
// 消费协程重绘时会读到最新的光标位置,不必排队)。
func requestHoverRedraw() {
select {
case hoverCh <- struct{}{}:
default:
}
}
// redrawLoop 是光感重绘的消费协程:把通知转成主线程的 Invalidate。
// 常驻整个进程(提示条是单例),不随显示/隐藏启停。
func redrawLoop() {
for range hoverCh {
mygo.RunOnMain(func() {
if win != nil && !win.IsDestroyed() && win.IsVisible() {
win.Invalidate()
}
})
}
}
// CurrentKind 返回当前提示条展示的类型("volume"/"mute"/"brightness"),
// 供滚轮调节决定调整音量还是亮度。
func CurrentKind() string {
st := snapshot()
switch st.kind {
case kindBrightness:
return "brightness"
case kindMute:
return "mute"
}
return "volume"
}
// hideIf 只隐藏仍然属于当前代次的提示条,避免旧计时器把新内容关掉。
func hideIf(g uint64) {
mu.Lock()
if g != generation {
mu.Unlock()
return
}
mu.Unlock()
geomVisible.Store(false)
nearKeeps.Store(0)
// 隐藏后光标坐标不再有意义,顺手熄灭光感,下次显示从"未悬停"开始。
hoverOn.Store(false)
// 重新显示时会重新截屏,这里的背景基准随之作废。
backdropBase = [3]int32{-1, -1, -1}
logger.Debug("osd hidden")
mygo.RunOnMain(func() {
if win != nil && !win.IsDestroyed() {
win.Hide()
}
})
}
// showOnMain 在主线程创建/定位/显示提示条窗口。
func showOnMain() {
if !enabled.Load() {
return
}
pos, margin := position()
sizeW, sizeH := sizeFor(pos)
x, y := positionForCursor()
// 显示器切换、配置改了方位或边距时目标位置会变化。mygo 的 SetPosition 对已存在的
// 提示条窗口不生效(实测窗口仍停在首次创建的位置),因此位置变化时重建窗口,
// 靠 NewWindow 的 X/Y 一次性放到正确位置。同时比较方位/边距本身:
// 换屏后新坐标可能恰好等于旧坐标,但设置已经变了。
moved := win != nil && (winX != x || winY != y || winPos != pos || winMargin != margin)
winPos, winMargin = pos, margin
if moved {
win.Destroy()
win = nil
}
if win == nil || win.IsDestroyed() {
win = mygo.NewWindow(mygo.WindowOptions{
Title: "零源工具箱 · 调节提示",
X: x,
Y: y,
Width: sizeW,
Height: sizeH,
UseContentSize: true,
Hidden: true,
Frameless: true,
Transparent: true,
AlwaysOnTop: true,
// Panel 让提示条浮于所有应用(含全屏)之上并跨虚拟桌面;
// 背景用自绘模糊,不依赖 DWM 材质。
Panel: true,
SkipTaskbar: true,
DisableResize: true,
DisableMove: true,
DisableMinimize: true,
DisableMaximize: true,
DisableClose: true,
DisableFullScreen: true,
DisableShadow: true,
CornerRadius: panelRadius,
// 不设置窗口 BackgroundColor:mygo 会把颜色转成 GDI 实心画刷并且
// 忽略 alpha,透明色也会变成不透明黑色,在胶囊外露出一层黑底。
// 不用窗口级 Acrylic:Windows 11 的 DWM 材质圆角固定约 8px,
// 与 26px 的胶囊不一致,胶囊四角会露出材质形成一圈边框。
// 背景改由 view 自绘:隐藏时截屏铺底 + glass.Blur 模糊 + 胶囊裁剪。
Content: ui.View(view),
})
// 用捕获的窗口变量比较,避免旧窗口延迟触发的 OnClosed 把新窗口置空。
created := win
win.OnClosed(func() {
if win == created {
win = nil
}
})
winX, winY = x, y
// 去掉 DWM 的窗口圆角与边框:否则会沿 8px 系统圆角在 26px 胶囊外
// 露出一圈额外的圆角矩形轮廓和阴影。
pwin.PrepareOverlayWindow(win.NativeHandle())
// 提示条不接收鼠标,避免挡住用户正在滚动的区域。
win.SetIgnoreMouseEvents(true)
// 新窗口还没有光感定位:等光标下一次移动再点亮。这里不能放在创建块
// 之外——滚轮/拖动每调一格都会走一遍 showOnMain,那样光效会被反复熄灭。
hoverOn.Store(false)
}
// 截取窗口背后的屏幕内容。必须在窗口隐藏时截屏,否则会把自己的
// 半透明面板一起截进去;位置变化后重建窗口也会走到这里。
if !win.IsVisible() {
refreshShot(win)
// 新底图意味着新的基准:显示后第一次采样只记录,不触发重截。
backdropBase = [3]int32{-1, -1, -1}
}
win.ShowInactive()
// 每次显示都重设鼠标穿透:首次 Show 前部分样式尚未落到原生窗口。
// 穿透后窗口收不到鼠标消息,悬停/滚轮由坐标判断(全局钩子)处理。
win.SetIgnoreMouseEvents(true)
win.Invalidate()
// 记录实际像素尺寸:高 DPI 下窗口大于 DIP 尺寸,悬停与拖动换算要用;
// 取不到时退回 DIP 尺寸(100% 缩放下两者一致)。
w, h := sizeW, sizeH
if _, _, rw, rh, ok := pwin.WindowRect(win.NativeHandle()); ok && rw > 0 && rh > 0 {
w, h = rw, rh
}
geomX.Store(int32(x))
geomY.Store(int32(y))
geomW.Store(int32(w))
geomH.Store(int32(h))
nearKeeps.Store(0)
geomVisible.Store(true)
}
// refreshShot 截取提示条窗口背后的屏幕区域,作为视图的底图层。
// 只在主线程、窗口隐藏时调用;失败时清空 shot,退化为纯深色半透明面板。
//
// 这里不做模糊:模糊由视图里的 glass.Blur 在渲染时完成(GPU 着色器、
// 半径按 DIP 自动乘缩放),旧实现的三次盒式模糊已删除。
func refreshShot(w *mygo.Window) {
if w == nil {
return
}
x, y, width, height, ok := pwin.WindowRect(w.NativeHandle())
if !ok {
logger.Warn("osd background: window rect unavailable")
shot = nil
return
}
img, err := pwin.CaptureRect(x, y, width, height)
if err != nil {
logger.Warn("osd background: capture failed", "err", err)
shot = nil
return
}
if shot == nil {
shot = ui.NewBitmap(img)
} else {
shot.Update(img)
}
}
// positionForCursor 按配置的位置计算提示条在鼠标所在显示器工作区的坐标。
func positionForCursor() (int, int) {
p := mygo.Screen.CursorScreenPoint()
d := mygo.Screen.DisplayNearestPoint(p)
wa := d.WorkArea
if wa.Width <= 0 || wa.Height <= 0 {
wa = mygo.Screen.PrimaryDisplay().WorkArea
}
pos, margin := position()
w, h := sizeFor(pos)
return positionIn(wa, w, h, pos, margin)
}
// clampSpan 把起点钳制进 [origin, origin+span-size];工作区比窗口还小时
// 退回起点,宁可盖住边缘也不把窗口放到屏幕外。
func clampSpan(pos, origin, span, size int) int {
if span < size {
return origin
}
if pos < origin {
return origin
}
if max := origin + span - size; pos > max {
return max
}
return pos
}
// positionIn 返回提示条在给定工作区内的左上角坐标。
//
// position 为 top/bottom/left/right:上下两个位置在水平方向居中、左右两个
// 位置在垂直方向居中,margin 是距该边的距离(DIP)。工作区太小或参数异常时
// 钳制到工作区内,绝不把窗口放到屏幕外。
func positionIn(wa mygo.Rectangle, width, height int, position string, margin int) (int, int) {
if wa.Width <= 0 || wa.Height <= 0 {
return wa.X, wa.Y
}
margin = clampMargin(margin)
x := wa.X + (wa.Width-width)/2
y := wa.Y + (wa.Height-height)/2
switch position {
case "top":
y = wa.Y + margin
case "left":
x = wa.X + margin
case "right":
x = wa.X + wa.Width - width - margin
default: // bottom,含空值与未知值
y = wa.Y + wa.Height - height - margin
}
x = clampSpan(x, wa.X, wa.Width, width)
y = clampSpan(y, wa.Y, wa.Height, height)
return x, y
}
// barWeights 返回进度条填充与剩余部分的 flex 权重,两者合计恒为 100。
// 进度条轨道是一个 Row;只有两个子节点同时存在时 Grow 才会按权重分配宽度。
func barWeights(percent int) (fill, rest float32) {
pct := clampPercent(percent)
return float32(pct), float32(100 - pct)
}
// clampPercent 把百分比钳制到 0-100;负值(读不到)按 0 显示。
func clampPercent(p int) int {
if p < 0 {
return 0
}
if p > 100 {
return 100
}
return p
}
// 提示条配色:低透明度面板让自绘的模糊桌面透出来,文字高对比并带轻微投影,
// 保证在亮背景上也读得清。
func panelColor() ui.Color { return ui.RGBA(14, 14, 18, 0.30) }
// panelColorFor 在光感点亮时把面板压淡一点:玻璃被照到,透出来的桌面更亮,
// 与指针处的柔光一起造成"亮起来"的错觉,而不是简单盖一层白。
func panelColorFor(lit bool) ui.Color {
if lit {
return ui.RGBA(14, 14, 18, 0.22)
}
return panelColor()
}
func borderColor() ui.Color { return ui.RGBA(255, 255, 255, 0.18) }
func innerBorderColor() ui.Color { return ui.RGBA(255, 255, 255, 0.10) }
func textColor() ui.Color { return ui.RGBA(255, 255, 255, 0.95) }
func trackColor() ui.Color { return ui.RGBA(255, 255, 255, 0.18) }
// valueColor 是百分比文字颜色:静音时压暗,明确表示"没有声音"。
func valueColor(st state) ui.Color {
if st.kind == kindMute && st.muted {
return ui.RGBA(255, 255, 255, 0.60)
}
return textColor()
}
// backdropBlurDIP 是胶囊背景的高斯模糊半径(DIP,标准差)。插件内部会乘
// 渲染缩放,高 DPI 下自动变粗,不需要像旧实现那样按截图宽度折算像素。
const backdropBlurDIP = 8
// backdropLayers 铺胶囊背景的三层:桌面截屏 → glass.Blur 模糊 → 深色面板。
// 必须画在内容之前:glass 的 backdrop 只采样同一窗口中此前绘制的内容,
// 顺序反了就只剩一片空白模糊。横排与竖排共用,圆角是短边的一半。
func backdropLayers(c *ui.Context) {
// 1. 截屏层:位图就是整个窗口的截屏,按整窗矩形铺才逐像素对齐,
// 并由 Clip 裁成两端完整的半圆。
ui.Box(c).Absolute().Top(0).Left(0).Right(0).Bottom(0).Draw(func(p *ui.Painter, r ui.Rect) {
if shot == nil {
return
}
p.Clip(r, panelRadius, func() {
p.Image(shot, r, ui.Cover)
})
})
// 2. 模糊层:插件把上一层画好的截屏当作 backdrop 做高斯模糊。不能用
// glass.Glass(Liquid Glass):它的色调映射会把桌面压成深色实体玻璃,
// 260×52 的窗格又低于 Clarity 的最小尺寸,细节全丢。
ui.Box(c).Absolute().Top(0).Left(0).Right(0).Bottom(0).Radius(panelRadius).
Material(glass.Blur{Radius: backdropBlurDIP})
// 3. 面板层:深色底 + 光影 + 描边,保证文字在任意背景上都读得清。
ui.Box(c).Absolute().Top(0).Left(0).Right(0).Bottom(0).Draw(drawPanel)
// 4. 光感层:光标停在胶囊上时在指针处点亮柔光,并在面板上多提一层亮。
ui.Box(c).Absolute().Top(0).Left(0).Right(0).Bottom(0).Draw(drawHover)
}
// drawPanel 在模糊层之上叠半透明底色、顶部高光、底部暗部与内外描边。
// 底色写 0.30 是为了让模糊后的桌面透出来,不能更厚。
func drawPanel(p *ui.Painter, r ui.Rect) {
// 光标停在胶囊上时整体再提一档:顶部高光更亮、内外描边更实,玻璃像被
// 指针照亮了一层。位置光斑由 drawHover 单独叠。
lit := hoverOn.Load()
topHighlight := float32(0.24)
inner, outer := innerBorderColor(), borderColor()
if lit {
topHighlight = 0.34
inner = ui.RGBA(255, 255, 255, 0.22)
outer = ui.RGBA(255, 255, 255, 0.38)
}
// Clip 保证两端是完整半圆:渐变与描边都跟着胶囊轮廓走。
p.Clip(r, panelRadius, func() {
p.Fill(r, panelColorFor(lit), panelRadius)
// 顶部高光渐隐 + 底部轻微暗部:光从上方打下来,玻璃才有厚度。
p.FillGradient(r, ui.LinearGradient{
Angle: 180,
Stops: []ui.GradientStop{
{Color: ui.RGBA(255, 255, 255, topHighlight), At: 0},
{Color: ui.RGBA(255, 255, 255, topHighlight*0.3), At: 0.45},
{Color: ui.RGBA(255, 255, 255, 0), At: 0.80},
},
}, panelRadius)
p.FillGradient(r, ui.LinearGradient{
Angle: 0,
Stops: []ui.GradientStop{
{Color: ui.RGBA(0, 0, 0, 0.22), At: 0},
{Color: ui.RGBA(0, 0, 0, 0), At: 0.60},
},
}, panelRadius)
// 内侧一圈更亮的反光边,强化玻璃边缘。
p.Stroke(insetRect(r, 1), inner, panelRadius-1, 1)
})
p.Stroke(r, outer, panelRadius, 1)
}
// drawHover 在面板之上画跟随光标的柔光:大范围柔光 + 小亮核两层,叠出
// "玻璃被指针照亮"的水光感。必须画在内容之前,否则会冲淡图标与百分比。
func drawHover(p *ui.Painter, r ui.Rect) {
if !hoverOn.Load() {
return
}
cx, cy := hoverCenter()
p.Clip(r, panelRadius, func() {
p.FillRadialGradient(r, ui.RadialGradient{
Center: ui.Point{X: cx, Y: cy},
Radius: hoverGlowRadius,
Stops: []ui.GradientStop{
{Color: ui.RGBA(255, 255, 255, 0.20), At: 0},
{Color: ui.RGBA(255, 255, 255, 0.07), At: 0.45},
{Color: ui.RGBA(255, 255, 255, 0), At: 1},
},
}, panelRadius)
p.FillRadialGradient(r, ui.RadialGradient{
Center: ui.Point{X: cx, Y: cy},
Radius: hoverCoreRadius,
Stops: []ui.GradientStop{
{Color: ui.RGBA(255, 255, 255, 0.26), At: 0},
{Color: ui.RGBA(255, 255, 255, 0), At: 1},
},
}, panelRadius)
})
}
// hoverCenter 把光标的屏幕像素坐标换算成相对窗口的 0-1 位置(径向渐变的
// Center 就用这个坐标系),越界钳在边缘:拖动时光标可能移出胶囊。
func hoverCenter() (float32, float32) {
w, h := int(geomW.Load()), int(geomH.Load())
if w <= 0 || h <= 0 {
w, h = currentSize()
}
cx := (float32(hoverX.Load()) - float32(geomX.Load())) / float32(w)
cy := (float32(hoverY.Load()) - float32(geomY.Load())) / float32(h)
return clamp01(cx), clamp01(cy)
}
// clamp01 把比例钳制到 0..1。
func clamp01(v float32) float32 {
if v < 0 {
return 0
}
if v > 1 {
return 1
}
return v
}
// backdropLoop 常驻协程:提示条显示期间每 backdropWatchInterval 采样一次
// 背景色。采样与重截都要碰窗口和屏幕,所以都投到主线程执行。
func backdropLoop() {
ticker := time.NewTicker(backdropWatchInterval)
defer ticker.Stop()
for range ticker.C {
if !geomVisible.Load() {
continue
}
mygo.RunOnMain(watchBackdrop)
}
}
// watchBackdrop 在主线程比较窗口四角的屏幕颜色,背景明显变化时重新截屏。
//
// 只在"背景真的变了"时才动手:重截必须先把窗口藏起来(否则 BitBlt 会把
// 胶囊自己截进底图),藏的那一帧用户能看见轻微闪烁,因此连续调节、悬停、
// 拖动这些背景没变的情况下只做几次 GetPixel,既不重绘也不闪。
func watchBackdrop() {
w := win
if w == nil || w.IsDestroyed() || !w.IsVisible() {
return
}
x, y, width, height, ok := pwin.WindowRect(w.NativeHandle())
if !ok {
return
}
r, g, b, ok := sampleBackdrop(x, y, width, height)
if !ok {
return
}
if backdropBase[0] < 0 {
backdropBase = [3]int32{int32(r), int32(g), int32(b)}
return
}
if backdropDelta(backdropBase, r, g, b) < backdropColorDelta {
return
}
if time.Since(backdropReshotAt) < backdropReshotGap {
return
}
backdropBase = [3]int32{int32(r), int32(g), int32(b)}
backdropReshotAt = time.Now()
// 藏一帧再截:DwmFlush 保证"没有胶囊"的那帧已经合成,BitBlt 才拿得到
// 干净背景。随后立刻显示回去,闪烁只有一帧。
w.Hide()
pwin.FlushDwm()
refreshShot(w)
w.ShowInactive()
w.SetIgnoreMouseEvents(true)
w.Invalidate()
}
// backdropDelta 返回采样色与基准色的三通道平均差(0-255)。
func backdropDelta(base [3]int32, r, g, b uint8) int {
return (absInt(int(r)-int(base[0])) +
absInt(int(g)-int(base[1])) +
absInt(int(b)-int(base[2]))) / 3
}
// sampleBackdrop 取窗口四角屏幕像素的平均色。
//
// 胶囊两端是半圆,四角是窗口内的透明区域,读那里的像素就是"胶囊背后正在
// 显示什么"——透明窗口不参与合成,读到的是底下真实画面。
func sampleBackdrop(x, y, width, height int) (uint8, uint8, uint8, bool) {
const inset = 4
points := [4][2]int{
{x + inset, y + inset},
{x + width - 1 - inset, y + inset},
{x + inset, y + height - 1 - inset},
{x + width - 1 - inset, y + height - 1 - inset},
}
var sr, sg, sb, n int
for _, pt := range points {
r, g, b, ok := pwin.ScreenPixel(pt[0], pt[1])
if !ok {
continue
}
sr += int(r)
sg += int(g)
sb += int(b)
n++
}
if n == 0 {
return 0, 0, 0, false
}
return uint8(sr / n), uint8(sg / n), uint8(sb / n), true
}
func absInt(v int) int {
if v < 0 {
return -v
}
return v
}
func init() {
go redrawLoop()
go backdropLoop()
}
// view 构建提示条:默认是横排的"图标 + 横向进度条 + 百分比";贴在左右两侧
// 时换成竖排的"图标 + 竖向进度条 + 百分比"。胶囊背景由左下三层叠加自绘
// (截屏 + glass.Blur + 深色面板),窗口本身完全透明。
func view(c *ui.Context) {
st := snapshot()
c.Root().Background(ui.Transparent)
if vertical() {
verticalView(c, st)
return
}
horizontalView(c, st)
}
// horizontalView 是横向胶囊:宽度 260、高度 52,内容是 Row。
func horizontalView(c *ui.Context, st state) {
ui.Box(c).Fill().Children(func() {
backdropLayers(c)
ui.Row(c).Absolute().Top(0).Left(0).Right(0).Bottom(0).Padding(10, 14).Gap(10).
AlignItems(ui.Center).Label(accessibleLabel(st)).
Children(func() {
ui.Icon(c, iconFor(st)).Size(iconSize, iconSize).TextColor(textColor())
ui.Row(c).Grow(1).Height(trackThickness).Radius(2).Background(trackColor()).Children(func() {
fill, rest := barWeights(st.percent)
if fill > 0 {
ui.Box(c).Grow(fill).Height(trackThickness).Radius(2).Background(accentFor(st))
}
if rest > 0 {
// 剩余宽度必须占一个透明兄弟节点,否则唯一的填充 Box 会吃掉整条轨道。
ui.Box(c).Grow(rest).Height(trackThickness).Background(ui.Transparent)
}
})
ui.Text(c, displayValue(st)).FontSize(14).FontWeight(600).TextColor(valueColor(st)).
Width(42).TextAlign(ui.End).FontFeatures("tnum").
TextShadow(0, 1, 4, ui.RGBA(0, 0, 0, 0.50))
})
})
}
// verticalView 是竖排胶囊:宽度 52、高度 260,内容是 Column。
// 自上而下 26 空白 + 图标 18 + 间距 10 + 进度条 152 + 间距 10 + 文字 18 + 26 空白
// 正好 260;这段布局必须与 trackTop/trackHeight 常量一致,拖动才准。
func verticalView(c *ui.Context, st state) {
padY := float32(Width-(iconSize+10+trackHeight+10+valueHeight)) / 2
ui.Box(c).Fill().Children(func() {
backdropLayers(c)
ui.Column(c).Absolute().Top(0).Left(0).Right(0).Bottom(0).Padding(padY, 10).Gap(10).
AlignItems(ui.Center).Label(accessibleLabel(st)).
Children(func() {
ui.Icon(c, iconFor(st)).Size(iconSize, iconSize).TextColor(textColor())
// 竖向进度条从下往上增长:上边是透明剩余段,下边是填充段,权重合计 100。
ui.Column(c).Width(trackThickness).Height(trackHeight).Radius(2).Background(trackColor()).Children(func() {
fill, rest := barWeights(st.percent)
if rest > 0 {
ui.Box(c).Grow(rest).Width(trackThickness).Background(ui.Transparent)
}
if fill > 0 {
ui.Box(c).Grow(fill).Width(trackThickness).Radius(2).Background(accentFor(st))
}
})
ui.Text(c, displayValue(st)).FontSize(14).FontWeight(600).TextColor(valueColor(st)).
Height(valueHeight).Width(Height).TextAlign(ui.Center).FontFeatures("tnum").
TextShadow(0, 1, 4, ui.RGBA(0, 0, 0, 0.50))
})
})
}
// insetRect 返回向内收缩 d 像素的矩形,用于内侧描边。
func insetRect(r ui.Rect, d float32) ui.Rect {
return ui.Rect{X: r.X + d, Y: r.Y + d, W: r.W - 2*d, H: r.H - 2*d}
}
// iconFor 返回提示条类型对应的矢量图标;静音时换成喇叭加叉。
func iconFor(st state) *ui.SVG {
switch st.kind {
case kindBrightness:
return brightnessIcon
case kindMute:
if st.muted {
return muteIcon
}
}
return volumeIcon
}
// accentFor 返回进度条颜色:音量蓝、亮度暖橙、静音灰。
func accentFor(st state) ui.Color {
switch st.kind {
case kindBrightness:
return ui.RGBA(255, 174, 64, 1)
case kindMute:
if st.muted {
return ui.RGBA(255, 255, 255, 0.38)
}
}
return ui.RGBA(64, 132, 255, 1)
}
// displayValue 返回右侧百分比;读不到音量时显示长横线。
func displayValue(st state) string {
if st.percent < 0 {
return "—"
}
return fmt.Sprintf("%d%%", clampPercent(st.percent))
}
// accessibleLabel 是不绘制、只供读屏使用的名称。
func accessibleLabel(st state) string {
value := displayValue(st)
switch st.kind {
case kindBrightness:
if st.gamma {
return "屏幕亮度 " + value + ",软件调光"
}
return "屏幕亮度 " + value
case kindMute:
if st.muted {
return "音量已静音"
}
return "音量 " + value
default:
return "音量 " + value
}
}
// snapshot 读取当前状态(主线程构建界面时可能与其他 goroutine 并发)。
func snapshot() state {
mu.Lock()
defer mu.Unlock()
return cur
}