迁移到 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:
zerorigin committed 2026-11-16 10:31:44 +08:00
1 parent 814012ec52
commit 0b8b9b0775
202 files changed
+7254 -13572

No files matched your search

-236
View File
@@ -1,236 +0,0 @@
/*
Package systray is a cross-platform Go library to place an icon and menu in the notification area.
*/
package systray
import (
"fmt"
"runtime"
"sync"
"sync/atomic"
"github.com/getlantern/golog"
)
var (
log = golog.LoggerFor("systray")
systrayReady func()
systrayExit func()
menuItems = make(map[uint32]*MenuItem)
menuItemsLock sync.RWMutex
currentID = uint32(0)
quitOnce sync.Once
)
func init() {
runtime.LockOSThread()
}
// MenuItem is used to keep track each menu item of systray.
// Don't create it directly, use the one systray.AddMenuItem() returned
type MenuItem struct {
// ClickedCh is the channel which will be notified when the menu item is clicked
ClickedCh chan struct{}
// id uniquely identify a menu item, not supposed to be modified
id uint32
// title is the text shown on menu item
title string
// tooltip is the text shown when pointing to menu item
tooltip string
// disabled menu item is grayed out and has no effect when clicked
disabled bool
// checked menu item has a tick before the title
checked bool
// has the menu item a checkbox (Linux)
isCheckable bool
// parent item, for sub menus
parent *MenuItem
}
func (item *MenuItem) String() string {
if item.parent == nil {
return fmt.Sprintf("MenuItem[%d, %q]", item.id, item.title)
}
return fmt.Sprintf("MenuItem[%d, parent %d, %q]", item.id, item.parent.id, item.title)
}
// newMenuItem returns a populated MenuItem object
func newMenuItem(title string, tooltip string, parent *MenuItem) *MenuItem {
return &MenuItem{
ClickedCh: make(chan struct{}),
id: atomic.AddUint32(&currentID, 1),
title: title,
tooltip: tooltip,
disabled: false,
checked: false,
isCheckable: false,
parent: parent,
}
}
// Run initializes GUI and starts the event loop, then invokes the onReady
// callback. It blocks until systray.Quit() is called.
func Run(onReady func(), onExit func()) {
Register(onReady, onExit)
nativeLoop()
}
// Register initializes GUI and registers the callbacks but relies on the
// caller to run the event loop somewhere else. It's useful if the program
// needs to show other UI elements, for example, webview.
// To overcome some OS weirdness, On macOS versions before Catalina, calling
// this does exactly the same as Run().
func Register(onReady func(), onExit func()) {
if onReady == nil {
systrayReady = func() {}
} else {
// Run onReady on separate goroutine to avoid blocking event loop
readyCh := make(chan interface{})
go func() {
<-readyCh
onReady()
}()
systrayReady = func() {
close(readyCh)
}
}
// unlike onReady, onExit runs in the event loop to make sure it has time to
// finish before the process terminates
if onExit == nil {
onExit = func() {}
}
systrayExit = onExit
registerSystray()
}
// Quit the systray
func Quit() {
quitOnce.Do(quit)
}
// AddMenuItem adds a menu item with the designated title and tooltip.
// It can be safely invoked from different goroutines.
// Created menu items are checkable on Windows and OSX by default. For Linux you have to use AddMenuItemCheckbox
func AddMenuItem(title string, tooltip string) *MenuItem {
item := newMenuItem(title, tooltip, nil)
item.update()
return item
}
// AddMenuItemCheckbox adds a menu item with the designated title and tooltip and a checkbox for Linux.
// It can be safely invoked from different goroutines.
// On Windows and OSX this is the same as calling AddMenuItem
func AddMenuItemCheckbox(title string, tooltip string, checked bool) *MenuItem {
item := newMenuItem(title, tooltip, nil)
item.isCheckable = true
item.checked = checked
item.update()
return item
}
// AddSeparator adds a separator bar to the menu
func AddSeparator() {
addSeparator(atomic.AddUint32(&currentID, 1))
}
// AddSubMenuItem adds a nested sub-menu item with the designated title and tooltip.
// It can be safely invoked from different goroutines.
// Created menu items are checkable on Windows and OSX by default. For Linux you have to use AddSubMenuItemCheckbox
func (item *MenuItem) AddSubMenuItem(title string, tooltip string) *MenuItem {
child := newMenuItem(title, tooltip, item)
child.update()
return child
}
// AddSubMenuItemCheckbox adds a nested sub-menu item with the designated title and tooltip and a checkbox for Linux.
// It can be safely invoked from different goroutines.
// On Windows and OSX this is the same as calling AddSubMenuItem
func (item *MenuItem) AddSubMenuItemCheckbox(title string, tooltip string, checked bool) *MenuItem {
child := newMenuItem(title, tooltip, item)
child.isCheckable = true
child.checked = checked
child.update()
return child
}
// SetTitle set the text to display on a menu item
func (item *MenuItem) SetTitle(title string) {
item.title = title
item.update()
}
// SetTooltip set the tooltip to show when mouse hover
func (item *MenuItem) SetTooltip(tooltip string) {
item.tooltip = tooltip
item.update()
}
// Disabled checks if the menu item is disabled
func (item *MenuItem) Disabled() bool {
return item.disabled
}
// Enable a menu item regardless if it's previously enabled or not
func (item *MenuItem) Enable() {
item.disabled = false
item.update()
}
// Disable a menu item regardless if it's previously disabled or not
func (item *MenuItem) Disable() {
item.disabled = true
item.update()
}
// Hide hides a menu item
func (item *MenuItem) Hide() {
hideMenuItem(item)
}
// Show shows a previously hidden menu item
func (item *MenuItem) Show() {
showMenuItem(item)
}
// Checked returns if the menu item has a check mark
func (item *MenuItem) Checked() bool {
return item.checked
}
// Check a menu item regardless if it's previously checked or not
func (item *MenuItem) Check() {
item.checked = true
item.update()
}
// Uncheck a menu item regardless if it's previously unchecked or not
func (item *MenuItem) Uncheck() {
item.checked = false
item.update()
}
// update propagates changes on a menu item to systray
func (item *MenuItem) update() {
menuItemsLock.Lock()
menuItems[item.id] = item
menuItemsLock.Unlock()
addOrUpdateMenuItem(item)
}
func systrayMenuItemSelected(id uint32) {
menuItemsLock.RLock()
item, ok := menuItems[id]
menuItemsLock.RUnlock()
if !ok {
log.Errorf("No menu item with ID %v", id)
return
}
select {
case item.ClickedCh <- struct{}{}:
// in case no one waiting for the channel
default:
}
}
@@ -1,107 +0,0 @@
// +build !windows
// go:build !windows
package systray
// #include "systray.h"
import "C"
import (
"errors"
"unsafe"
)
func registerSystray() {
C.registerSystray()
}
func nativeLoop() {
C.nativeLoop()
}
func quit() {
C.quit()
}
// SetIcon sets the systray icon.
// iconBytes should be the content of .ico for windows and .ico/.jpg/.png
// for other platforms.
func SetIcon(iconBytes []byte) {
cstr := (*C.char)(unsafe.Pointer(&iconBytes[0]))
C.setIcon(cstr, (C.int)(len(iconBytes)), false)
}
// SetTitle sets the systray title, only available on Mac and Linux.
func SetTitle(title string) {
C.setTitle(C.CString(title))
}
// SetTooltip sets the systray tooltip to display on mouse hover of the tray icon,
// only available on Mac and Windows.
func SetTooltip(tooltip string) {
C.setTooltip(C.CString(tooltip))
}
// SetBalloon 仅 Windows 支持,其他平台返回错误。
func SetBalloon(title, text string) error {
return errors.New("SetBalloon: only supported on Windows")
}
func addOrUpdateMenuItem(item *MenuItem) {
var disabled C.short
if item.disabled {
disabled = 1
}
var checked C.short
if item.checked {
checked = 1
}
var isCheckable C.short
if item.isCheckable {
isCheckable = 1
}
var parentID uint32 = 0
if item.parent != nil {
parentID = item.parent.id
}
C.add_or_update_menu_item(
C.int(item.id),
C.int(parentID),
C.CString(item.title),
C.CString(item.tooltip),
disabled,
checked,
isCheckable,
)
}
func addSeparator(id uint32) {
C.add_separator(C.int(id))
}
func hideMenuItem(item *MenuItem) {
C.hide_menu_item(
C.int(item.id),
)
}
func showMenuItem(item *MenuItem) {
C.show_menu_item(
C.int(item.id),
)
}
//export systray_ready
func systray_ready() {
systrayReady()
}
//export systray_on_exit
func systray_on_exit() {
systrayExit()
}
//export systray_menu_item_selected
func systray_menu_item_selected(cID C.int) {
systrayMenuItemSelected(uint32(cID))
}
File diff suppressed because it is too large. Load diff
-51
View File
@@ -1,51 +0,0 @@
package windows
import (
"os"
"golang.org/x/sys/windows/registry"
)
// 开机自启:写入当前用户的 Run 注册表项(不修改 HKLM,架构文档 §9.1 约束)。
const (
autoStartKey = `Software\Microsoft\Windows\CurrentVersion\Run`
autoStartValue = "ZerOriginTool"
)
// IsAutoStartEnabled 报告开机自启是否已启用。
func IsAutoStartEnabled() bool {
k, err := registry.OpenKey(registry.CURRENT_USER, autoStartKey, registry.QUERY_VALUE)
if err != nil {
return false
}
defer k.Close()
_, _, err = k.GetStringValue(autoStartValue)
return err == nil
}
// SetAutoStart 启用/禁用开机自启。使用 exe 的绝对路径。
func SetAutoStart(enabled bool) error {
if !enabled {
return disableAutoStart()
}
exe, err := os.Executable()
if err != nil {
return err
}
k, err := registry.OpenKey(registry.CURRENT_USER, autoStartKey, registry.SET_VALUE)
if err != nil {
return err
}
defer k.Close()
return k.SetStringValue(autoStartValue, exe)
}
func disableAutoStart() error {
k, err := registry.OpenKey(registry.CURRENT_USER, autoStartKey, registry.SET_VALUE)
if err != nil {
return err
}
defer k.Close()
return k.DeleteValue(autoStartValue)
}
@@ -0,0 +1,74 @@
package windows
import (
"fmt"
"strings"
"syscall"
"unsafe"
)
// 旧版(mygo 之前)的自启实现直接写 HKCU Run:值名 ZerOriginTool,数据为
// 未加引号的可执行文件绝对路径。新版交由 mygo 管理(值形如
// "<exe>" --mygo-opened-at-login)。两者同名时新值会覆盖旧值,但旧条目若
// 仍在(用户升级后尚未在新版设置里重新开启自启),开机会同时启动两个
// 实例;因此启动时清理旧格式条目。
const (
legacyRunKey = `Software\Microsoft\Windows\CurrentVersion\Run`
legacyRunValue = "ZerOriginTool"
loginArgMarker = "--mygo-opened-at-login"
hkeyCurrentUser = 0x80000001
keyQueryValue = 0x0001
keySetValue = 0x0002
runKeyAccess = keyQueryValue | keySetValue
errorFileNotFound = 2
)
var (
migrateAdvapi32 = syscall.NewLazyDLL("advapi32.dll")
procRegOpenKeyExW = migrateAdvapi32.NewProc("RegOpenKeyExW")
procRegQueryValueExW = migrateAdvapi32.NewProc("RegQueryValueExW")
procRegDeleteValueW = migrateAdvapi32.NewProc("RegDeleteValueW")
procRegCloseKey = migrateAdvapi32.NewProc("RegCloseKey")
)
// MigrateLegacyAutoStart 删除旧版写入的自启条目,报告是否确实删除了。
// removed 为 true 表示用户原先通过旧版启用过开机自启,调用方可据此在
// 新版中沿用该选择。已由 mygo 管理的条目(值中含登录标记)保持不动。
func MigrateLegacyAutoStart() (removed bool, err error) {
key, err := syscall.UTF16PtrFromString(legacyRunKey)
if err != nil {
return false, err
}
var hkey uintptr
if rc, _, _ := procRegOpenKeyExW.Call(hkeyCurrentUser, uintptr(unsafe.Pointer(key)), 0, runKeyAccess, uintptr(unsafe.Pointer(&hkey))); rc != 0 {
return false, nil // 没有 Run 键:不存在旧条目
}
defer procRegCloseKey.Call(hkey)
name, err := syscall.UTF16PtrFromString(legacyRunValue)
if err != nil {
return false, err
}
var typ, size uint32
if rc, _, _ := procRegQueryValueExW.Call(hkey, uintptr(unsafe.Pointer(name)), 0, uintptr(unsafe.Pointer(&typ)), 0, uintptr(unsafe.Pointer(&size))); rc != 0 || size == 0 {
return false, nil
}
buf := make([]uint16, (int(size)+1)/2)
if rc, _, _ := procRegQueryValueExW.Call(hkey, uintptr(unsafe.Pointer(name)), 0, uintptr(unsafe.Pointer(&typ)), uintptr(unsafe.Pointer(&buf[0])), uintptr(unsafe.Pointer(&size))); rc != 0 {
return false, fmt.Errorf("query legacy autostart value: error %d", rc)
}
data := syscall.UTF16ToString(buf)
if strings.Contains(data, loginArgMarker) {
return false, nil // 新版写入的值,保留
}
if rc, _, _ := procRegDeleteValueW.Call(hkey, uintptr(unsafe.Pointer(name))); rc != 0 {
if rc == errorFileNotFound {
return false, nil
}
return false, fmt.Errorf("delete legacy autostart value: error %d", rc)
}
return true, nil
}
+411
View File
@@ -0,0 +1,411 @@
package windows
import (
"fmt"
"sync"
"syscall"
"unsafe"
)
// 屏幕亮度调节:优先 DDC/CI(dxva2,真实背光),不支持时退化为
// gamma ramp 软件调光(covers 内置屏/虚拟屏等没有 DDC 输出的场景)。
var (
dxva2Hook = syscall.NewLazyDLL("dxva2.dll")
gdi32Hook = syscall.NewLazyDLL("gdi32.dll")
procGetNumberOfPhysicalMonitorsFromHMONITOR = dxva2Hook.NewProc("GetNumberOfPhysicalMonitorsFromHMONITOR")
procGetPhysicalMonitorsFromHMONITOR = dxva2Hook.NewProc("GetPhysicalMonitorsFromHMONITOR")
procDestroyPhysicalMonitors = dxva2Hook.NewProc("DestroyPhysicalMonitors")
procGetMonitorBrightness = dxva2Hook.NewProc("GetMonitorBrightness")
procSetMonitorBrightness = dxva2Hook.NewProc("SetMonitorBrightness")
procGetDC = user32Hook.NewProc("GetDC")
procReleaseDC = user32Hook.NewProc("ReleaseDC")
procGetDeviceGammaRamp = gdi32Hook.NewProc("GetDeviceGammaRamp")
procSetDeviceGammaRamp = gdi32Hook.NewProc("SetDeviceGammaRamp")
)
// physicalMonitor 对应 Win32 PHYSICAL_MONITOR(x64 下 264 字节)。
type physicalMonitor struct {
hPhysicalMonitor uintptr
description [128]uint16
}
// BrightnessInfo 描述一次亮度查询/调节的结果。
type BrightnessInfo struct {
Percent int // 当前亮度百分比(多显示器为平均值)
Monitors int // 成功读到/调节的显示器数量
Total int // 枚举到的物理显示器数量
Gamma bool // true 表示走的是 gamma 软件调光(不是真实背光)
}
// brightnessMu 串行化亮度操作:DDC/CI 调用与 gamma ramp 修改都不可并发。
var brightnessMu sync.Mutex
// monitorHandlesIn 为 EnumDisplayMonitors 回调的收集缓冲。
// 回调必须用包级单例(syscall.NewCallback 回调表仅 2000 槽,见 AGENTS.md),
// 回调在 EnumDisplayMonitors 内同步执行,用包级缓冲即可避免 unsafe 指针
// 往返;brightnessMu 已把调用串行化,另加锁只为防跨包并发误用。
var (
monitorHandlesMu sync.Mutex
monitorHandlesIn []uintptr
)
// enumMonitorHandlesCB 收集 HMONITOR 的 EnumDisplayMonitors 回调。
var enumMonitorHandlesCB = syscall.NewCallback(func(hMonitor, hdc, lprc, lparam uintptr) uintptr {
if hMonitor != 0 {
monitorHandlesMu.Lock()
monitorHandlesIn = append(monitorHandlesIn, hMonitor)
monitorHandlesMu.Unlock()
}
return 1
})
// monitorHandles 枚举当前所有显示器句柄(HMONITOR)。
func monitorHandles() ([]uintptr, error) {
monitorHandlesMu.Lock()
monitorHandlesIn = monitorHandlesIn[:0]
monitorHandlesMu.Unlock()
if r, _, err := procEnumDisplayMonitors.Call(0, 0, enumMonitorHandlesCB, 0); r == 0 {
return nil, err
}
monitorHandlesMu.Lock()
defer monitorHandlesMu.Unlock()
return append([]uintptr(nil), monitorHandlesIn...), nil
}
// GetBrightness 查询当前屏幕亮度(仅 DDC/CI;gamma 回退时返回记录值)。
func GetBrightness() (BrightnessInfo, error) {
brightnessMu.Lock()
defer brightnessMu.Unlock()
return queryBrightness()
}
// AdjustBrightness 按 deltaPercent 调节亮度(正数调亮,负数调暗)。
// 优先逐台 DDC/CI 显示器;全部不支持时退化为 gamma 软件调光。
func AdjustBrightness(deltaPercent int32) (BrightnessInfo, error) {
brightnessMu.Lock()
defer brightnessMu.Unlock()
info, err := adjustDDC(deltaPercent)
if err == nil && info.Monitors > 0 {
return info, nil
}
gammaInfo, gammaErr := adjustGamma(deltaPercent)
if gammaErr == nil {
if err != nil {
// DDC 枚举/读取失败,记在返回值外的调用方日志里即可。
gammaInfo.Total = info.Total
}
return gammaInfo, nil
}
if err != nil {
return info, fmt.Errorf("brightness: no DDC/CI monitor: %w; gamma fallback: %v", err, gammaErr)
}
return info, fmt.Errorf("brightness: no DDC/CI-capable monitor; gamma fallback: %w", gammaErr)
}
// SetBrightness 把亮度设为指定百分比(拖动提示条进度条用)。
// 与 AdjustBrightness 一样 DDC/CI 优先、gamma 兜底。
func SetBrightness(percent int32) (BrightnessInfo, error) {
if percent < 0 {
percent = 0
}
if percent > 100 {
percent = 100
}
brightnessMu.Lock()
defer brightnessMu.Unlock()
info, err := setDDCAbsolute(percent)
if err == nil && info.Monitors > 0 {
return info, nil
}
gammaInfo, gammaErr := setGammaAbsolute(percent)
if gammaErr == nil {
if err != nil {
gammaInfo.Total = info.Total
}
return gammaInfo, nil
}
if err != nil {
return info, fmt.Errorf("brightness: no DDC/CI monitor: %w; gamma fallback: %v", err, gammaErr)
}
return info, fmt.Errorf("brightness: no DDC/CI-capable monitor; gamma fallback: %w", gammaErr)
}
// queryBrightness 只读查询,不改变亮度。
func queryBrightness() (BrightnessInfo, error) {
info, err := adjustDDC(0)
if err == nil && info.Monitors > 0 {
return info, nil
}
return gammaInfo(), nil
}
// adjustDDC 枚举物理显示器并按 delta 调节(delta=0 仅读取)。
func adjustDDC(delta int32) (BrightnessInfo, error) {
return applyDDC(delta, false)
}
// setDDCAbsolute 把每台物理显示器设为绝对百分比。
func setDDCAbsolute(percent int32) (BrightnessInfo, error) {
return applyDDC(percent, true)
}
// applyDDC 枚举物理显示器并按 delta 调节或按 value 设绝对值(delta=0 仅读取)。
func applyDDC(value int32, absolute bool) (BrightnessInfo, error) {
handles, err := monitorHandles()
if err != nil {
return BrightnessInfo{}, fmt.Errorf("enumerate monitors: %w", err)
}
info := BrightnessInfo{}
sumPercent := 0
var firstErr error
for _, hmon := range handles {
var count uint32
r, _, callErr := procGetNumberOfPhysicalMonitorsFromHMONITOR.Call(hmon, uintptr(unsafe.Pointer(&count)))
if r == 0 || count == 0 {
if firstErr == nil && callErr != nil {
firstErr = callErr
}
continue
}
monitors := make([]physicalMonitor, count)
if r2, _, _ := procGetPhysicalMonitorsFromHMONITOR.Call(
hmon, uintptr(count), uintptr(unsafe.Pointer(&monitors[0]))); r2 == 0 {
continue
}
for i := range monitors {
pm := &monitors[i]
info.Total++
percent, ok := monitorBrightnessPercent(pm.hPhysicalMonitor)
if !ok {
continue
}
if absolute {
if !setMonitorBrightnessAbsolute(pm.hPhysicalMonitor, value) {
continue
}
percent, _ = monitorBrightnessPercent(pm.hPhysicalMonitor)
} else if value != 0 {
if !setMonitorBrightnessRelative(pm.hPhysicalMonitor, value) {
continue
}
percent, _ = monitorBrightnessPercent(pm.hPhysicalMonitor)
}
info.Monitors++
sumPercent += percent
}
procDestroyPhysicalMonitors.Call(uintptr(count), uintptr(unsafe.Pointer(&monitors[0])))
}
if info.Monitors > 0 {
info.Percent = sumPercent / info.Monitors
}
return info, firstErr
}
// monitorBrightnessPercent 读取单台物理显示器的亮度百分比。
func monitorBrightnessPercent(h uintptr) (int, bool) {
var minV, curV, maxV uint32
r, _, _ := procGetMonitorBrightness.Call(h,
uintptr(unsafe.Pointer(&minV)), uintptr(unsafe.Pointer(&curV)), uintptr(unsafe.Pointer(&maxV)))
if r == 0 || maxV <= minV {
return 0, false
}
pct := int((curV - minV) * 100 / (maxV - minV))
if pct < 0 {
pct = 0
}
if pct > 100 {
pct = 100
}
return pct, true
}
// setMonitorBrightnessRelative 按百分比增量调节单台显示器亮度。
func setMonitorBrightnessRelative(h uintptr, delta int32) bool {
var minV, curV, maxV uint32
r, _, _ := procGetMonitorBrightness.Call(h,
uintptr(unsafe.Pointer(&minV)), uintptr(unsafe.Pointer(&curV)), uintptr(unsafe.Pointer(&maxV)))
if r == 0 || maxV <= minV {
return false
}
span := int64(maxV) - int64(minV)
step := int64(delta) * span / 100
if step == 0 && delta != 0 {
step = 1
if delta < 0 {
step = -1
}
}
next := int64(curV) + step
if next < int64(minV) {
next = int64(minV)
}
if next > int64(maxV) {
next = int64(maxV)
}
r2, _, _ := procSetMonitorBrightness.Call(h, uintptr(next))
return r2 != 0
}
// setMonitorBrightnessAbsolute 把单台显示器亮度设为指定百分比。
func setMonitorBrightnessAbsolute(h uintptr, percent int32) bool {
var minV, curV, maxV uint32
r, _, _ := procGetMonitorBrightness.Call(h,
uintptr(unsafe.Pointer(&minV)), uintptr(unsafe.Pointer(&curV)), uintptr(unsafe.Pointer(&maxV)))
if r == 0 || maxV <= minV {
return false
}
span := int64(maxV) - int64(minV)
next := int64(minV) + int64(percent)*span/100
if next < int64(minV) {
next = int64(minV)
}
if next > int64(maxV) {
next = int64(maxV)
}
r2, _, _ := procSetMonitorBrightness.Call(h, uintptr(next))
return r2 != 0
}
// gammaRamp 对应 Win32 的 3×256 WORD gamma ramp。
type gammaRamp struct {
Red [256]uint16
Green [256]uint16
Blue [256]uint16
}
// gammaState 记录 gamma 软件调光的当前级别与基线(首次调光时读取)。
var gammaState struct {
mu sync.Mutex
loaded bool
level int32 // 0-100,100 表示未调暗
base gammaRamp
usable bool
}
// adjustGamma 通过 gamma ramp 实现软件调光(无 DDC 时兜底)。
func adjustGamma(delta int32) (BrightnessInfo, error) {
gammaState.mu.Lock()
defer gammaState.mu.Unlock()
if !gammaState.loaded {
if err := loadGammaBaseLocked(); err != nil {
return BrightnessInfo{}, err
}
gammaState.level = 100
gammaState.loaded = true
}
if !gammaState.usable {
return BrightnessInfo{}, fmt.Errorf("gamma ramp unavailable")
}
return setGammaLevelLocked(gammaState.level + delta)
}
// setGammaAbsolute 把 gamma 软件调光级别设为绝对值(百分比)。
func setGammaAbsolute(percent int32) (BrightnessInfo, error) {
gammaState.mu.Lock()
defer gammaState.mu.Unlock()
if !gammaState.loaded {
if err := loadGammaBaseLocked(); err != nil {
return BrightnessInfo{}, err
}
gammaState.level = 100
gammaState.loaded = true
}
if !gammaState.usable {
return BrightnessInfo{}, fmt.Errorf("gamma ramp unavailable")
}
return setGammaLevelLocked(percent)
}
// setGammaLevelLocked 把 gamma 级别设为 level 并写入 ramp。
// 调用方必须已持有 gammaState.mu 且完成基线加载。
func setGammaLevelLocked(level int32) (BrightnessInfo, error) {
if level > 100 {
level = 100
}
if level < 5 {
level = 5
}
if level == gammaState.level {
// 已到边界或目标相同:仍返回成功(不报错),避免滚轮在端点反复弹错误。
return BrightnessInfo{Percent: int(level), Gamma: true}, nil
}
gammaState.level = level
ramp := scaleGammaRamp(gammaState.base, level)
hdc, _, _ := procGetDC.Call(0)
if hdc == 0 {
return BrightnessInfo{}, fmt.Errorf("get desktop dc failed")
}
defer procReleaseDC.Call(0, hdc)
r, _, err := procSetDeviceGammaRamp.Call(hdc, uintptr(unsafe.Pointer(&ramp)))
if r == 0 {
return BrightnessInfo{}, fmt.Errorf("set device gamma ramp: %w", err)
}
return BrightnessInfo{Percent: int(level), Monitors: 1, Gamma: true}, nil
}
// gammaInfo 返回 gamma 调光当前状态(未启用时按 100 处理)。
func gammaInfo() BrightnessInfo {
gammaState.mu.Lock()
defer gammaState.mu.Unlock()
level := int32(100)
if gammaState.loaded {
level = gammaState.level
}
return BrightnessInfo{Percent: int(level), Monitors: 1, Gamma: true}
}
// loadGammaBaseLocked 读取当前 gamma ramp 作为调光基线。
func loadGammaBaseLocked() error {
hdc, _, _ := procGetDC.Call(0)
if hdc == 0 {
return fmt.Errorf("get desktop dc failed")
}
defer procReleaseDC.Call(0, hdc)
var ramp gammaRamp
r, _, err := procGetDeviceGammaRamp.Call(hdc, uintptr(unsafe.Pointer(&ramp)))
if r == 0 {
return fmt.Errorf("get device gamma ramp: %w", err)
}
gammaState.base = ramp
gammaState.usable = true
return nil
}
// scaleGammaRamp 按 level(0-100)缩放基线 ramp(纯函数,便于单测)。
func scaleGammaRamp(base gammaRamp, level int32) gammaRamp {
if level > 100 {
level = 100
}
if level < 0 {
level = 0
}
factor := float64(level) / 100
var out gammaRamp
for i := 0; i < 256; i++ {
out.Red[i] = scaleGammaValue(base.Red[i], factor)
out.Green[i] = scaleGammaValue(base.Green[i], factor)
out.Blue[i] = scaleGammaValue(base.Blue[i], factor)
}
return out
}
// scaleGammaValue 缩放单个 ramp 值并夹取到 uint16 范围。
func scaleGammaValue(v uint16, factor float64) uint16 {
scaled := float64(v) * factor
if scaled < 0 {
return 0
}
if scaled > 65535 {
return 65535
}
return uint16(scaled)
}
+172
View File
@@ -0,0 +1,172 @@
package windows
// 屏幕区域截屏:提示条需要把背后的桌面内容模糊后作为自绘背景。
//
// 仅依赖 user32/gdi32 的基础 API;返回 *image.RGBA(alpha 恒为 255),
// 由调用方决定模糊与缩放。窗口坐标是虚拟屏幕物理像素,可跨负数显示器。
import (
"fmt"
"image"
"unsafe"
)
const (
srccopy = 0x00CC0020
biRGB = 0
)
var (
procGetCursorPos = user32Hook.NewProc("GetCursorPos")
procCreateCompatibleDC = gdi32Hook.NewProc("CreateCompatibleDC")
procCreateCompatibleBitmap = gdi32Hook.NewProc("CreateCompatibleBitmap")
procSelectObject = gdi32Hook.NewProc("SelectObject")
procBitBlt = gdi32Hook.NewProc("BitBlt")
procGetDIBits = gdi32Hook.NewProc("GetDIBits")
procDeleteDC = gdi32Hook.NewProc("DeleteDC")
procDeleteObject = gdi32Hook.NewProc("DeleteObject")
procGetPixel = gdi32Hook.NewProc("GetPixel")
)
// bitmapInfoHeader 对应 Win32 BITMAPINFOHEADER(40 字节)。
type bitmapInfoHeader struct {
size uint32
width int32
height int32
planes uint16
bitCount uint16
compression uint32
sizeImage uint32
xPelsPerMeter int32
yPelsPerMeter int32
clrUsed uint32
clrImportant uint32
}
// bitmapInfo 对应 Win32 BITMAPINFO;32bpp BI_RGB 不需要调色板。
type bitmapInfo struct {
header bitmapInfoHeader
colors [1]uint32
}
// CursorPos 返回当前光标在虚拟屏幕上的物理像素坐标。
//
// 提示条是鼠标穿透窗口,收不到鼠标消息,悬停判断只能靠读光标位置。
func CursorPos() (x, y int, ok bool) {
var p struct{ x, y int32 }
r, _, _ := procGetCursorPos.Call(uintptr(unsafe.Pointer(&p)))
if r == 0 {
return 0, 0, false
}
return int(p.x), int(p.y), true
}
// WindowRect 读取窗口在虚拟屏幕上的物理像素矩形。
func WindowRect(hwnd uintptr) (x, y, width, height int, ok bool) {
if hwnd == 0 {
return 0, 0, 0, 0, false
}
var r rect
hr, _, _ := procGetWindowRect.Call(hwnd, uintptr(unsafe.Pointer(&r)))
if hr == 0 || r.Right <= r.Left || r.Bottom <= r.Top {
return 0, 0, 0, 0, false
}
return int(r.Left), int(r.Top), int(r.Right - r.Left), int(r.Bottom - r.Top), true
}
// CaptureRect 截取虚拟屏幕上的一个物理像素矩形。坐标可为负数(副屏在
// 主屏左侧/上方时)。失败时返回错误,调用方应退化为纯色面板。
func CaptureRect(x, y, width, height int) (*image.RGBA, error) {
if width <= 0 || height <= 0 {
return nil, fmt.Errorf("capture: invalid size %dx%d", width, height)
}
screenDC, _, err := procGetDC.Call(0)
if screenDC == 0 {
return nil, fmt.Errorf("capture: get screen dc: %v", err)
}
defer procReleaseDC.Call(0, screenDC)
memDC, _, err := procCreateCompatibleDC.Call(screenDC)
if memDC == 0 {
return nil, fmt.Errorf("capture: create memory dc: %v", err)
}
defer procDeleteDC.Call(memDC)
bmp, _, err := procCreateCompatibleBitmap.Call(screenDC, uintptr(width), uintptr(height))
if bmp == 0 {
return nil, fmt.Errorf("capture: create bitmap: %v", err)
}
defer procDeleteObject.Call(bmp)
old, _, err := procSelectObject.Call(memDC, bmp)
if old == 0 {
return nil, fmt.Errorf("capture: select bitmap: %v", err)
}
// GetDIBits 要求位图不再被选入 DC,因此在读取像素前先恢复旧对象。
defer procSelectObject.Call(memDC, old)
r, _, err := procBitBlt.Call(
memDC, 0, 0, uintptr(width), uintptr(height),
screenDC, uintptr(int32(x)), uintptr(int32(y)), srccopy)
if r == 0 {
return nil, fmt.Errorf("capture: bitblt %d,%d %dx%d: %v", x, y, width, height, err)
}
// 先把位图从 DC 里换出来;defer 里再恢复一次是幂等的。
if r, _, _ := procSelectObject.Call(memDC, old); r == 0 {
return nil, fmt.Errorf("capture: deselect bitmap failed")
}
bi := bitmapInfo{header: bitmapInfoHeader{
size: uint32(unsafe.Sizeof(bitmapInfoHeader{})),
width: int32(width),
height: -int32(height), // 负高度表示 top-down DIB
planes: 1,
bitCount: 32,
compression: biRGB,
}}
buf := make([]byte, width*height*4)
r, _, err = procGetDIBits.Call(
memDC, bmp, 0, uintptr(height),
uintptr(unsafe.Pointer(&buf[0])),
uintptr(unsafe.Pointer(&bi)), 0)
if r == 0 {
return nil, fmt.Errorf("capture: getdibits: %v", err)
}
img := image.NewRGBA(image.Rect(0, 0, width, height))
for row := 0; row < height; row++ {
src := buf[row*width*4:]
dst := img.Pix[row*img.Stride:]
for col := 0; col < width; col++ {
s := col * 4
d := col * 4
// DIB 32bpp BI_RGB 是 B,G,R,X;输出 RGBA 并强制不透明。
dst[d+0] = src[s+2]
dst[d+1] = src[s+1]
dst[d+2] = src[s+0]
dst[d+3] = 255
}
}
return img, nil
}
// ScreenPixel 读取虚拟屏幕上单个物理像素的颜色,返回的是 DWM 合成后的最终
// 画面。提示条窗口内胶囊以外的四角是透明的,读这些点就能拿到"胶囊下面正
// 在显示什么",用来判断背景是否已经变了(变了才值得重新截屏)。
func ScreenPixel(x, y int) (r, g, b uint8, ok bool) {
dc, _, _ := procGetDC.Call(0)
if dc == 0 {
return 0, 0, 0, false
}
defer procReleaseDC.Call(0, dc)
v, _, _ := procGetPixel.Call(dc, uintptr(int32(x)), uintptr(int32(y)))
// CLR_INVALID:坐标不在屏幕内或读取失败(COLORREF 全 1)。
if uint32(v) == 0xFFFFFFFF {
return 0, 0, 0, false
}
// COLORREF 的字节序是 0x00BBGGRR。
return uint8(v), uint8(v >> 8), uint8(v >> 16), true
}
+1 -1
View File
@@ -26,7 +26,7 @@ import (
)
var (
crashKernel32 = syscall.NewLazyDLL("kernel32.dll")
crashKernel32 = syscall.NewLazyDLL("kernel32.dll")
procSetUnhandledExceptionFilter2 = crashKernel32.NewProc("SetUnhandledExceptionFilter")
procAddVectoredExceptionHandler = crashKernel32.NewProc("AddVectoredExceptionHandler")
procCreateFileW2 = crashKernel32.NewProc("CreateFileW")
+14
View File
@@ -0,0 +1,14 @@
package windows
import "testing"
// TestCursorPosSmoke 验证能读到光标位置;无活动输入桌面时跳过。
func TestCursorPosSmoke(t *testing.T) {
x, y, ok := CursorPos()
if !ok {
t.Skip("cursor position unavailable (no active input desktop)")
}
if x < -100000 || y < -100000 || x > 100000 || y > 100000 {
t.Fatalf("CursorPos = (%d,%d), outside virtual screen range", x, y)
}
}
+13 -4
View File
@@ -98,14 +98,23 @@ func SwitchVirtualDesktop(dir int32) error {
// DefaultTaskViewDelay 为 Win+Tab 打开任务视图后等待动画就绪的默认时长。
const DefaultTaskViewDelay = 400 * time.Millisecond
// normalizeTaskViewDelay 将 <=0 的等待时长归一化为默认值。
// 兼容旧配置中的 taskview_delay_ms=0:0 会让方向键/Enter 在任务视图
// 动画完成前发出,任务视图随后可能停留在前台。
func normalizeTaskViewDelay(delay time.Duration) time.Duration {
if delay <= 0 {
return DefaultTaskViewDelay
}
return delay
}
// SwitchDesktopViaTaskView 通过任务视图导航切换虚拟桌面:
// Win+Tab 打开任务视图 → 方向键选择相邻桌面 → Enter 确认。
// 不依赖 Win+Ctrl 组合,避免与输入法全局热键冲突。
// delay 为任务视图打开后的等待时长(<0 时使用默认值)。
// delay 为任务视图打开后的等待时长;<=0(含配置默认的 0)使用默认值,
// 避免在动画完成前发送方向键/Enter,导致任务视图停留在前台。
func SwitchDesktopViaTaskView(dir int32, delay time.Duration) error {
if delay < 0 {
delay = DefaultTaskViewDelay
}
delay = normalizeTaskViewDelay(delay)
var key uint16 = vkRight
if dir < 0 {
key = vkLeft
+31 -10
View File
@@ -42,18 +42,39 @@ func isDesktopClass(cls string) bool {
return false
}
// taskViewClass 为 Win11 任务视图的 XAML Shell 覆盖层窗口类。
//
// 任务视图窗口覆盖全屏且没有 WS_MAXIMIZE 样式;若打开时被当作普通全屏
// 前台窗口,会抑制全部角落/边缘规则(任务视图留在前台时音量/亮度滚轮
// 全部失效)。它是 Shell UI,不算需要抑制规则的全屏应用。
const taskViewClass = "XamlExplorerHostIslandWindow"
// isShellOverlayClass 报告窗口类名是否为需要排除的全屏 Shell 覆盖层。
func isShellOverlayClass(cls string) bool {
switch cls {
case taskViewClass:
return true
}
return false
}
// windowClassName 读取窗口类名(失败返回空串)。
func windowClassName(hwnd uintptr) string {
var buf [64]uint16
n, _, _ := procGetClassNameW.Call(hwnd, uintptr(unsafe.Pointer(&buf[0])), uintptr(len(buf)))
if n == 0 {
return ""
}
return syscall.UTF16ToString(buf[:n])
}
// isDesktopWindow 判断窗口是否为桌面窗口(Progman 桌面或其壁纸层 WorkerW)。
//
// 空桌面(任务栏无任何程序)时前台窗口就是桌面窗口:其矩形覆盖整个屏幕且
// 没有 WS_MAXIMIZE 样式,仅靠覆盖率阈值会被误判为全屏,从而错误抑制角落/
// 边缘规则(症状:空虚拟桌面上切桌面/调音量全部失效)。桌面不算全屏。
func isDesktopWindow(hwnd uintptr) bool {
var buf [64]uint16
n, _, _ := procGetClassNameW.Call(hwnd, uintptr(unsafe.Pointer(&buf[0])), uintptr(len(buf)))
if n == 0 {
return false
}
return isDesktopClass(syscall.UTF16ToString(buf[:n]))
return isDesktopClass(windowClassName(hwnd))
}
// IsFullscreenRect 判定窗口矩形是否覆盖屏幕矩形达到阈值(纯函数,可测)。
@@ -108,10 +129,10 @@ func foregroundFullscreen() bool {
if hwnd == 0 {
return false
}
// 空桌面(任务栏无程序)时前台窗口是桌面 Progman/WorkerW:矩形覆盖
// 全屏且无 WS_MAXIMIZE,仅靠覆盖率会被误判为全屏,导致角落/边缘规则
// 被错误抑制。桌面窗口不算全屏。
if isDesktopWindow(hwnd) {
// 空桌面(任务栏无程序)时前台窗口是桌面 Progman/WorkerW,或任务视图
// 打开时的 XAML 覆盖层:矩形覆盖全屏且无 WS_MAXIMIZE,仅靠覆盖率会被
// 误判为全屏,导致角落/边缘规则被错误抑制。它们不算全屏应用。
if cls := windowClassName(hwnd); isDesktopClass(cls) || isShellOverlayClass(cls) {
return false
}
// 最大化窗口不是全屏:任务栏可见时最大化窗口覆盖工作区 ≈96%,
@@ -60,6 +60,25 @@ func TestIsDesktopClass(t *testing.T) {
}
}
// TestIsShellOverlayClass 验证任务视图覆盖层类名识别(打开任务视图时
// 不应抑制全部规则,回归:音量滚轮无反应)。
func TestIsShellOverlayClass(t *testing.T) {
cases := []struct {
cls string
want bool
}{
{"XamlExplorerHostIslandWindow", true}, // Win11 任务视图
{"Progman", false},
{"Chrome_WidgetWin_1", false},
{"", false},
}
for _, c := range cases {
if got := isShellOverlayClass(c.cls); got != c.want {
t.Errorf("isShellOverlayClass(%q) = %v, want %v", c.cls, got, c.want)
}
}
}
// TestIsDesktopWindowReal 集成验证:GetDesktopWindow 返回的系统桌面窗口
// (类名 #32769)必须判定为桌面(防止空桌面被误判全屏导致规则抑制)。
func TestIsDesktopWindowReal(t *testing.T) {
+5 -5
View File
@@ -28,7 +28,7 @@ var (
heartbeatPsapi = syscall.NewLazyDLL("psapi.dll")
procGetProcessMemoryInfo = heartbeatPsapi.NewProc("GetProcessMemoryInfo")
heartbeatKernel32 = syscall.NewLazyDLL("kernel32.dll")
heartbeatKernel32 = syscall.NewLazyDLL("kernel32.dll")
procGetCurrentProcess = heartbeatKernel32.NewProc("GetCurrentProcess")
)
@@ -63,10 +63,10 @@ func SelfWorkingSetMB() int64 {
// heartbeatEntry 为心跳文件内容(JSON,便于后续脚本分析)。
type heartbeatEntry struct {
PID int `json:"pid"`
TS string `json:"ts"`
UptimeS int64 `json:"uptime_s"`
MemMB int64 `json:"mem_mb"`
PID int `json:"pid"`
TS string `json:"ts"`
UptimeS int64 `json:"uptime_s"`
MemMB int64 `json:"mem_mb"`
}
// StartHeartbeat 启动心跳 goroutine:interval 周期写心跳文件,超过
+31 -4
View File
@@ -4,6 +4,7 @@ import (
"fmt"
"runtime"
"sync"
"sync/atomic"
"syscall"
"time"
"unsafe"
@@ -14,10 +15,13 @@ import (
// 低级鼠标钩子常量。
const (
whMouseLL = 14
// WmMouseMove / WmMouseWheel 为导出消息号,供触发器使用。
WmMouseMove = 0x0200
WmMouseWheel = 0x020A
wmQuit = 0x0012
// WmMouseMove / WmMouseWheel / WmLButtonDown / WmLButtonUp 为导出消息号,
// 供触发器与提示条交互使用。
WmMouseMove = 0x0200
WmLButtonDown = 0x0201
WmLButtonUp = 0x0202
WmMouseWheel = 0x020A
wmQuit = 0x0012
)
var (
@@ -45,8 +49,14 @@ type MouseEvent struct {
Message uint32 // WM_* 消息号
X, Y int32 // 屏幕坐标
MouseData int32 // 滚轮 delta 等附加数据
// Blocked 表示事件已被过滤器吞掉:不再传给下面的窗口(背后的应用),
// 但本程序仍能从事件流里读到它。
Blocked bool
}
// filterFunc 为事件过滤器:返回 true 表示吞掉该事件。
type filterFunc func(MouseEvent) bool
// MouseHook 为 WH_MOUSE_LL 低级鼠标钩子。
// 回调运行在专用消息循环线程上,只做入队,绝不阻塞。
type MouseHook struct {
@@ -60,6 +70,9 @@ type MouseHook struct {
dropped uint64 // 溢出丢弃计数(限速日志用)
calls uint64 // 回调被系统调用次数(健康度观测)
installErrVal error
// filter 为可选的事件过滤器(atomic.Value 存 filterFunc)。
// 在钩子回调线程上同步执行,因此必须立即返回。
filter atomic.Value
}
// NewMouseHook 创建钩子,buf 为事件通道容量。
@@ -76,6 +89,13 @@ func (h *MouseHook) Dropped() uint64 { return h.dropped }
// CallbackCalls 返回钩子回调被系统调用的总次数(健康度观测)。
func (h *MouseHook) CallbackCalls() uint64 { return h.calls }
// SetFilter 设置事件过滤器:返回 true 的事件会被吞掉(不再传给下层窗口),
// 但仍带着 Blocked=true 进入事件流,供本程序处理。
// 过滤器在钩子回调线程上同步执行,必须立即返回,不得阻塞。
func (h *MouseHook) SetFilter(fn func(MouseEvent) bool) {
h.filter.Store(filterFunc(fn))
}
// InstallErr 返回钩子安装错误(若有)。Start 后稍等片刻再查询。
func (h *MouseHook) InstallErr() error {
h.mu.Lock()
@@ -151,11 +171,18 @@ func (h *MouseHook) run() {
if code >= 0 && hhk != 0 {
ms := *(**MSLLHOOKSTRUCT)(unsafe.Pointer(&lParam))
ev := MouseEvent{Message: uint32(wParam), X: ms.pt.X, Y: ms.pt.Y, MouseData: int32(ms.mouseData)}
if f, ok := h.filter.Load().(filterFunc); ok && f != nil && f(ev) {
ev.Blocked = true
}
select {
case h.ch <- ev:
default:
h.dropped++
}
if ev.Blocked {
// 返回非零表示已处理,系统不再把事件投递给其他程序。
return 1
}
}
r, _, _ := procCallNextHookEx.Call(hhk, uintptr(code), wParam, lParam)
return r
-42
View File
@@ -1,42 +0,0 @@
// Package windows 中 notify 层已大幅简化:移除独立的 NIM 图标注册与
// 隐藏窗口/worker 线程,全部气泡通知通过 fork 的 systray 库复用主进程
// 托盘图标位置(systray.SetBalloon),消除"两个 ZerOriginTool 托盘图标"
// 中第二个为空白占位的问题。
package windows
import (
"errors"
"log/slog"
"zerorigin/internal/platform/systray"
)
// notifyLog 通知层诊断日志(由 app 层注入;未注入时使用默认 logger)。
var notifyLog = slog.Default()
// SetNotifyLogger 注入通知层诊断日志。
func SetNotifyLogger(l *slog.Logger) {
if l != nil {
notifyLog = l
}
}
// ShowBalloon 通过 systray 的托盘图标显示气泡通知。
// systray 必须已 Run(图标已注册);若未启动则返回 ErrSystrayNotReady。
func ShowBalloon(title, text string) error {
if err := systray.SetBalloon(title, text); err != nil {
// systray 未启动时 NID 为 nil,错误信息固定且无外部上下文价值。
notifyLog.Warn("balloon failed", "title", title, "err", err)
return err
}
return nil
}
// ShowBalloonWithIcon 为向后兼容保留:systray 图标由 systray 自己管理,
// 不再支持外部指定图标资源 ID。等同于 ShowBalloon。
func ShowBalloonWithIcon(title, text string, iconResourceID uintptr) error {
return ShowBalloon(title, text)
}
// ErrSystrayNotReady 表示 systray 图标尚未注册(应在主进程早期检查)。
var ErrSystrayNotReady = errors.New("systray icon not initialized")
+42 -27
View File
@@ -1,3 +1,4 @@
// 系统交互封装:打开路径/URL、带参启动进程、启动期消息框。
package windows
import (
@@ -6,49 +7,63 @@ import (
"unsafe"
)
var (
user32 = syscall.NewLazyDLL("user32.dll")
shell32 = syscall.NewLazyDLL("shell32.dll")
kernel32 = syscall.NewLazyDLL("kernel32.dll")
procMessageBoxW = user32.NewProc("MessageBoxW")
procShellExecuteW = shell32.NewProc("ShellExecuteW")
const (
swShowNormal = 1
mbIconInformation = 0x00000040
)
// ShowMessageBox 显示模态消息框(单实例冲突等提示用)。
func ShowMessageBox(title, text string) {
titlePtr, _ := syscall.UTF16PtrFromString(title)
textPtr, _ := syscall.UTF16PtrFromString(text)
procMessageBoxW.Call(0, uintptr(unsafe.Pointer(textPtr)), uintptr(unsafe.Pointer(titlePtr)), 0x00000040 /* MB_ICONINFORMATION */)
}
var (
procShellExecuteW = syscall.NewLazyDLL("shell32.dll").NewProc("ShellExecuteW")
procMessageBoxW = syscall.NewLazyDLL("user32.dll").NewProc("MessageBoxW")
)
// OpenPath 用系统默认程序打开路径(目录或文件),例如 ShellExecute 打开配置目录。
// OpenPath 用系统默认关联打开路径或 URL(无参数)。
func OpenPath(path string) error {
return OpenPathWithArgs(path, "")
}
// OpenPathWithArgs 用系统默认程序打开路径,并附加命令行参数。
// 参数为结构化字符串,不经过 cmd /c(架构文档 §9.2 约束)。
// OpenPathWithArgs 通过 ShellExecuteW 打开路径并传入命令行参数。
// 安全约束:path 与 args 作为独立参数传递,不做 shell 拼接。
func OpenPathWithArgs(path, args string) error {
p, err := syscall.UTF16PtrFromString(path)
if err != nil {
return fmt.Errorf("shell execute %q: %w", path, err)
}
var argPtr *uint16
if args != "" {
a, err := syscall.UTF16PtrFromString(args)
if err != nil {
return fmt.Errorf("shell execute %q: %w", path, err)
}
argPtr = a
}
verb, err := syscall.UTF16PtrFromString("open")
if err != nil {
return err
}
var argsPtr *uint16
if args != "" {
argsPtr, err = syscall.UTF16PtrFromString(args)
if err != nil {
return err
}
}
// ShellExecuteW(hwnd, "open", path, args, NULL, SW_SHOWNORMAL)
r, _, _ := procShellExecuteW.Call(0, uintptr(unsafe.Pointer(openVerb())), uintptr(unsafe.Pointer(p)), uintptr(unsafe.Pointer(argsPtr)), 0, 1)
r, _, _ := procShellExecuteW.Call(
0,
uintptr(unsafe.Pointer(verb)),
uintptr(unsafe.Pointer(p)),
uintptr(unsafe.Pointer(argPtr)),
0,
swShowNormal,
)
if r <= 32 {
return fmt.Errorf("shell execute %q failed: code %d", path, r)
}
return nil
}
func openVerb() *uint16 {
s, _ := syscall.UTF16PtrFromString("open")
return s
// ShowMessageBox 显示阻塞式信息框(仅用于启动期致命提示:单实例冲突等)。
func ShowMessageBox(title, text string) {
t, err := syscall.UTF16PtrFromString(title)
if err != nil {
return
}
m, err := syscall.UTF16PtrFromString(text)
if err != nil {
return
}
procMessageBoxW.Call(0, uintptr(unsafe.Pointer(m)), uintptr(unsafe.Pointer(t)), mbIconInformation)
}
-48
View File
@@ -1,48 +0,0 @@
// Package windows 集中封装 Windows API 调用。
// 工程内其他包不得直接加载 user32.dll / kernel32.dll 等 DLL。
package windows
import (
"errors"
"fmt"
"os/user"
"golang.org/x/sys/windows"
)
// ErrAlreadyRunning 表示已有另一个主进程实例在运行。
var ErrAlreadyRunning = errors.New("another instance is already running")
// SingleInstance 为单实例互斥锁持有者。
type SingleInstance struct {
h windows.Handle
}
// AcquireSingleInstance 创建以当前用户 SID 命名的命名互斥锁。
// 已存在时返回 ErrAlreadyRunning;成功时调用方必须调用 Release。
func AcquireSingleInstance() (*SingleInstance, error) {
u, err := user.Current()
if err != nil {
return nil, fmt.Errorf("get current user: %w", err)
}
name, err := windows.UTF16PtrFromString(`Local\ZerOriginTool-` + u.Uid)
if err != nil {
return nil, err
}
h, err := windows.CreateMutex(nil, false, name)
if err != nil {
if err == windows.ERROR_ALREADY_EXISTS {
return nil, ErrAlreadyRunning
}
return nil, fmt.Errorf("create mutex: %w", err)
}
return &SingleInstance{h: h}, nil
}
// Release 释放互斥锁句柄。幂等。
func (s *SingleInstance) Release() {
if s.h != 0 {
windows.CloseHandle(s.h)
s.h = 0
}
}
+30 -1
View File
@@ -1,12 +1,18 @@
package windows
import (
"errors"
"fmt"
"runtime"
"syscall"
"unsafe"
)
// ErrNotEnoughDesktops 表示系统只有一个虚拟桌面,无法切换。
// 动作层据此避免回退到任务视图:单桌面下任务视图会停留在前台,
// 随后被全屏检测误判,抑制所有角落/边缘规则。
var ErrNotEnoughDesktops = errors.New("switch desktop: at least two virtual desktops required")
// 虚拟桌面 COM 直调实现(无快捷键依赖,兼容输入法占用 Win+Ctrl 的系统)。
//
// 获取路径(社区标准,PowerToys/sswitch 等均采用):
@@ -259,7 +265,7 @@ func SwitchDesktopCOM(dir int32) error {
return err
}
if len(ids) < 2 {
return fmt.Errorf("switch desktop: only %d desktop(s), cannot switch", len(ids))
return fmt.Errorf("%w (found %d)", ErrNotEnoughDesktops, len(ids))
}
cur, err := m.currentDesktopIndex(ids)
if err != nil {
@@ -269,3 +275,26 @@ func SwitchDesktopCOM(dir int32) error {
target = ((target % len(ids)) + len(ids)) % len(ids)
return m.switchToIndex(target)
}
// VirtualDesktopCount 查询系统虚拟桌面数量。
//
// 动作层在 taskview / hotkey 方式前调用它,避免在只有一个桌面时打开
// 任务视图(任务视图会留在前台,随后被全屏检测误判为全屏,抑制全部规则)。
// 查询失败不阻断调用方,由调用方保持原有行为。
func VirtualDesktopCount() (int, error) {
runtime.LockOSThread()
defer runtime.UnlockOSThread()
procCoInitializeEx.Call(0, coinitMultithreaded)
defer procCoUninitialize.Call()
m, err := openDesktopManager()
if err != nil {
return 0, err
}
defer m.close()
ids, err := m.desktopIDs()
if err != nil {
return 0, err
}
return len(ids), nil
}
@@ -1,6 +1,7 @@
package windows
import (
"errors"
"testing"
"time"
@@ -100,6 +101,52 @@ func TestSwitchDesktopCOM(t *testing.T) {
t.Logf("switched back to original desktop OK")
}
// TestNormalizeTaskViewDelay 验证配置 0/负值归一化为默认等待,
// 正值为显式配置保持原样(旧配置 taskview_delay_ms=0 曾导致任务视图停留)。
func TestNormalizeTaskViewDelay(t *testing.T) {
cases := []struct {
in time.Duration
want time.Duration
}{
{0, DefaultTaskViewDelay},
{-time.Second, DefaultTaskViewDelay},
{time.Millisecond, time.Millisecond},
{500 * time.Millisecond, 500 * time.Millisecond},
}
for _, c := range cases {
if got := normalizeTaskViewDelay(c.in); got != c.want {
t.Errorf("normalizeTaskViewDelay(%v) = %v, want %v", c.in, got, c.want)
}
}
}
// TestVirtualDesktopCount 验证数量查询可用且至少返回一个桌面。
func TestVirtualDesktopCount(t *testing.T) {
n, err := VirtualDesktopCount()
if err != nil {
t.Skipf("virtual desktop query unavailable: %v", err)
}
if n < 1 {
t.Fatalf("VirtualDesktopCount = %d, want >= 1", n)
}
}
// TestSwitchDesktopCOMSingleDesktop 验证单桌面时 SwitchDesktopCOM 返回
// ErrNotEnoughDesktops 哨兵(多桌面环境自动跳过)。
func TestSwitchDesktopCOMSingleDesktop(t *testing.T) {
n, err := VirtualDesktopCount()
if err != nil {
t.Skipf("virtual desktop query unavailable: %v", err)
}
if n >= 2 {
t.Skipf("environment has %d desktops, single-desktop case not applicable", n)
}
err = SwitchDesktopCOM(1)
if !errors.Is(err, ErrNotEnoughDesktops) {
t.Fatalf("SwitchDesktopCOM error = %v, want ErrNotEnoughDesktops", err)
}
}
// queryDesktopState 返回全部桌面 GUID 列表与当前索引。
func queryDesktopState() ([]comGUID, int, error) {
m, err := openDesktopManager()
+20
View File
@@ -208,6 +208,26 @@ func VolumeAdjustPercent(dir int32) error {
})
}
// SetMasterVolumePercent 把音量直接设为指定百分比(拖动提示条进度条用)。
func SetMasterVolumePercent(percent int) error {
if percent < 0 {
percent = 0
}
if percent > 100 {
percent = 100
}
return withVolumeCOM(func(vol uintptr) error {
return setMasterVolumeScalarVerified(vol, float32(percent)/100)
})
}
// SetMute 设置静音(false 取消静音)。
func SetMute(mute bool) error {
return withVolumeCOM(func(vol uintptr) error {
return setMuteVerified(vol, mute)
})
}
// ToggleMuteCOM 切换静音。
func ToggleMuteCOM() error {
return withVolumeCOM(func(vol uintptr) error {
+58
View File
@@ -0,0 +1,58 @@
package windows
import (
"syscall"
"unsafe"
)
// 本文件封装覆盖层窗口(提示条)的 DWM 外形修正。原生 UI 的透明窗口保留
// WS_CAPTION,mygo 还会给 Panel / Frameless+CornerRadius 的窗口设置
// DWMWCP_ROUND。Windows 11 于是在窗口外围画一圈约 8px 圆角的系统边框,
// 并在窗口外投下阴影:26px 胶囊的操作提示条四角会露出一层额外的圆角矩形。
// 关掉窗口圆角并让 DWM 不画边框后,窗口恢复为直角矩形、四角完全透明,
// 由视图自绘的胶囊成为唯一可见形状。
const (
dwmwaWindowCornerPreference = 33
dwmwaBorderColor = 34
// DWMWCP_DONOTROUND:不要让 DWM 给窗口加圆角。
dwmWindowCornerDoNotRound = 1
// DWMWA_COLOR_NONE:让 DWM 不画窗口边框。
dwmColorNone = 0xFFFFFFFE
)
var (
dwmapiHook = syscall.NewLazyDLL("dwmapi.dll")
procDwmSetWindowAttribute = dwmapiHook.NewProc("DwmSetWindowAttribute")
procDwmFlush = dwmapiHook.NewProc("DwmFlush")
)
// PrepareOverlayWindow 把提示条窗口修正成无系统外框的直角透明窗口:
// 关闭 DWM 圆角(否则窗口外沿 8px 圆角出现边框与阴影)并去掉边框颜色。
// 属性在旧系统上可能不支持,失败时静默忽略,不影响窗口内容。
func PrepareOverlayWindow(hwnd uintptr) {
if hwnd == 0 {
return
}
corner := int32(dwmWindowCornerDoNotRound)
procDwmSetWindowAttribute.Call(
hwnd,
dwmwaWindowCornerPreference,
uintptr(unsafe.Pointer(&corner)),
4,
)
border := uint32(dwmColorNone)
procDwmSetWindowAttribute.Call(
hwnd,
dwmwaBorderColor,
uintptr(unsafe.Pointer(&border)),
4,
)
}
// FlushDwm 阻塞到 DWM 完成一次合成。提示条要"藏一帧再截屏"时必须先等这一
// 帧落地,否则 BitBlt 读到的还是含胶囊的旧画面。
func FlushDwm() {
procDwmFlush.Call()
}