Files
Reims-Go/internal/tray/tray_windows.go
T

672 lines
16 KiB
Go

//go:build windows
package tray
import (
"fmt"
"runtime"
"sync"
"syscall"
"unsafe"
"golang.org/x/sys/windows"
"golang.org/x/sys/windows/registry"
)
var (
user32 = syscall.NewLazyDLL("user32.dll")
procRegisterClassExW = user32.NewProc("RegisterClassExW")
procCreateWindowExW = user32.NewProc("CreateWindowExW")
procFindWindowExW = user32.NewProc("FindWindowExW")
procGetWindowThreadProcessID = user32.NewProc("GetWindowThreadProcessId")
procDestroyWindow = user32.NewProc("DestroyWindow")
procDefWindowProcW = user32.NewProc("DefWindowProcW")
procGetMessageW = user32.NewProc("GetMessageW")
procTranslateMessage = user32.NewProc("TranslateMessage")
procDispatchMessageW = user32.NewProc("DispatchMessageW")
procPostMessageW = user32.NewProc("PostMessageW")
procPostQuitMessage = user32.NewProc("PostQuitMessage")
procRegisterWindowMessageW = user32.NewProc("RegisterWindowMessageW")
procCreatePopupMenu = user32.NewProc("CreatePopupMenu")
procAppendMenuW = user32.NewProc("AppendMenuW")
procSetMenuDefaultItem = user32.NewProc("SetMenuDefaultItem")
procTrackPopupMenu = user32.NewProc("TrackPopupMenu")
procDestroyMenu = user32.NewProc("DestroyMenu")
procSetForegroundWindow = user32.NewProc("SetForegroundWindow")
procGetCursorPos = user32.NewProc("GetCursorPos")
procLoadIconW = user32.NewProc("LoadIconW")
procDestroyIcon = user32.NewProc("DestroyIcon")
procCreateIconFromResourceEx = user32.NewProc("CreateIconFromResourceEx")
procSetMenuItemInfoW = user32.NewProc("SetMenuItemInfoW")
procSetMenuInfo = user32.NewProc("SetMenuInfo")
procGetSystemMetrics = user32.NewProc("GetSystemMetrics")
gdi32 = syscall.NewLazyDLL("gdi32.dll")
procCreateDIBSection = gdi32.NewProc("CreateDIBSection")
procDeleteObject = gdi32.NewProc("DeleteObject")
kernel32 = syscall.NewLazyDLL("kernel32.dll")
procGetModuleHandle = kernel32.NewProc("GetModuleHandleW")
shell32 = syscall.NewLazyDLL("shell32.dll")
procShellNotifyIconW = shell32.NewProc("Shell_NotifyIconW")
)
const (
trayWindowClass = "ReimsGoTrayWindowClass"
trayWindowTitle = "Reims-Go Tray"
wmDestroy = 0x0002
wmClose = 0x0010
wmNull = 0x0000
wmContextMenu = 0x007B
wmCommand = 0x0111
wmLButtonUp = 0x0202
wmLButtonDbl = 0x0203
wmRButtonUp = 0x0205
wmUser = 0x0400
wmTrayIcon = wmUser + 1
nimAdd = 0x00000000
nimModify = 0x00000001
nimDelete = 0x00000002
nifMessage = 0x00000001
nifIcon = 0x00000002
nifTip = 0x00000004
nifInfo = 0x00000010
niifInfo = 0x00000001
niifError = 0x00000003
mfString = 0x00000000
mfGrayed = 0x00000001
mfPopup = 0x00000010
mfSeparator = 0x00000800
miimBitmap = 0x00000080
mimStyle = 0x00000010
mnsCheckOrBmp = 0x04000000
smCxMenuCheck = 71
dibRGBColors = 0
biRGB = 0
tpmRightButton = 0x0002
tpmBottomAlign = 0x0020
tpmReturnCmd = 0x0100
tpmNonotify = 0x0080
idiApplication = 32512
trayIconUID = 1
)
// RequestQuit invokes the tray's normal Exit command for the verified client
// process. The class, title and command ID also exist in older releases.
func RequestQuit(pid uint32) bool {
if pid == 0 {
return false
}
class := windows.StringToUTF16Ptr(trayWindowClass)
title := windows.StringToUTF16Ptr(trayWindowTitle)
var hwnd uintptr
for {
hwnd, _, _ = procFindWindowExW.Call(0, hwnd, uintptr(unsafe.Pointer(class)), uintptr(unsafe.Pointer(title)))
if hwnd == 0 {
return false
}
var owner uint32
procGetWindowThreadProcessID.Call(hwnd, uintptr(unsafe.Pointer(&owner)))
if owner == pid {
ok, _, _ := procPostMessageW.Call(hwnd, wmCommand, cmdQuit, 0)
return ok != 0
}
}
}
type wndClassExW struct {
CbSize uint32
Style uint32
LpfnWndProc uintptr
CbClsExtra int32
CbWndExtra int32
HInstance uintptr
HIcon uintptr
HCursor uintptr
HbrBackground uintptr
LpszMenuName *uint16
LpszClassName *uint16
HIconSm uintptr
}
type winPoint struct {
X, Y int32
}
type winMsg struct {
HWnd uintptr
Message uint32
WParam uintptr
LParam uintptr
Time uint32
Pt winPoint
}
type notifyIconDataW struct {
CbSize uint32
HWnd uintptr
UID uint32
UFlags uint32
UCallbackMessage uint32
HIcon uintptr
SzTip [128]uint16
DwState uint32
DwStateMask uint32
SzInfo [256]uint16
UVersionOrTimeout uint32
SzInfoTitle [64]uint16
DwInfoFlags uint32
GuidItem [16]byte
HBalloonIcon uintptr
}
type menuItemInfoW struct {
CbSize uint32
FMask uint32
FType uint32
FState uint32
WID uint32
HSubMenu uintptr
HbmpChecked uintptr
HbmpUnchecked uintptr
DwItemData uintptr
DwTypeData *uint16
Cch uint32
HbmpItem uintptr
}
type menuInfoW struct {
CbSize uint32
FMask uint32
DwStyle uint32
CyMax uint32
HbrBack uintptr
DwContextHelpID uint32
DwMenuData uintptr
}
type bitmapInfo struct {
BiSize uint32
BiWidth int32
BiHeight int32
BiPlanes uint16
BiBitCount uint16
BiCompression uint32
BiSizeImage uint32
BiXPelsPerMeter int32
BiYPelsPerMeter int32
BiClrUsed uint32
BiClrImportant uint32
BmiColors [1]uint32
}
var (
activeMu sync.RWMutex
activeMgr *Manager
)
// Manager owns the Windows notification area (system tray) icon and context menu.
type Manager struct {
mu sync.Mutex
cb Callbacks
iconPNG []byte
hwnd uintptr
hicon uintptr
customIcon bool
taskbarCreated uint32
tooltip string
closed bool
done chan struct{}
menuVMs []VMItem
}
// Start launches the Windows system tray icon on a dedicated locked OS thread.
func Start(iconPNG []byte, tooltip string, cb Callbacks) (*Manager, error) {
if tooltip == "" {
tooltip = "Reims-Go"
}
m := &Manager{
cb: cb,
iconPNG: iconPNG,
tooltip: tooltip,
done: make(chan struct{}),
}
ready := make(chan error, 1)
go m.runLoop(ready)
if err := <-ready; err != nil {
return nil, err
}
return m, nil
}
// UpdateTooltip refreshes the hover tooltip text of the tray icon.
func (m *Manager) UpdateTooltip(text string) {
if m == nil {
return
}
m.mu.Lock()
if m.closed || m.hwnd == 0 {
m.mu.Unlock()
return
}
m.tooltip = text
nid := m.buildNID(nifTip)
m.mu.Unlock()
_, _, _ = procShellNotifyIconW.Call(nimModify, uintptr(unsafe.Pointer(&nid)))
}
// Close removes the tray icon and stops the hidden window message loop.
func (m *Manager) Close() {
if m == nil {
return
}
m.mu.Lock()
if m.closed {
m.mu.Unlock()
return
}
m.closed = true
hwnd := m.hwnd
m.mu.Unlock()
if hwnd != 0 {
_, _, _ = procPostMessageW.Call(hwnd, wmClose, 0, 0)
<-m.done
}
}
func (m *Manager) buildNID(flags uint32) notifyIconDataW {
var nid notifyIconDataW
nid.CbSize = uint32(unsafe.Sizeof(nid))
nid.HWnd = m.hwnd
nid.UID = trayIconUID
nid.UFlags = flags
nid.UCallbackMessage = wmTrayIcon
nid.HIcon = m.hicon
tipU16, _ := syscall.UTF16FromString(m.tooltip)
for i := 0; i < len(tipU16) && i < len(nid.SzTip)-1; i++ {
nid.SzTip[i] = tipU16[i]
}
return nid
}
func (m *Manager) addTrayIcon() {
nid := m.buildNID(nifMessage | nifIcon | nifTip)
_, _, _ = procShellNotifyIconW.Call(nimAdd, uintptr(unsafe.Pointer(&nid)))
}
func (m *Manager) removeTrayIcon() {
nid := m.buildNID(0)
_, _, _ = procShellNotifyIconW.Call(nimDelete, uintptr(unsafe.Pointer(&nid)))
}
func (m *Manager) loadIcon() (uintptr, bool) {
if scaled, err := resizePNGIcon(m.iconPNG, 32); err == nil && len(scaled) > 0 {
h, _, _ := procCreateIconFromResourceEx.Call(
uintptr(unsafe.Pointer(&scaled[0])),
uintptr(len(scaled)),
1, // fIcon = TRUE
0x00030000,
32,
32,
0,
)
if h != 0 {
return h, true
}
}
h, _, _ := procLoadIconW.Call(0, uintptr(idiApplication))
return h, false
}
func (m *Manager) runLoop(ready chan<- error) {
runtime.LockOSThread()
defer runtime.UnlockOSThread()
defer close(m.done)
hInst, _, _ := procGetModuleHandle.Call(0)
className := windows.StringToUTF16Ptr(trayWindowClass)
tbMsgName, _ := syscall.UTF16PtrFromString("TaskbarCreated")
tbMsg, _, _ := procRegisterWindowMessageW.Call(uintptr(unsafe.Pointer(tbMsgName)))
m.taskbarCreated = uint32(tbMsg)
activeMu.Lock()
activeMgr = m
activeMu.Unlock()
defer func() {
activeMu.Lock()
if activeMgr == m {
activeMgr = nil
}
activeMu.Unlock()
}()
wc := wndClassExW{
CbSize: uint32(unsafe.Sizeof(wndClassExW{})),
LpfnWndProc: syscall.NewCallback(trayWndProc),
HInstance: hInst,
LpszClassName: className,
}
_, _, _ = procRegisterClassExW.Call(uintptr(unsafe.Pointer(&wc)))
winTitle := windows.StringToUTF16Ptr(trayWindowTitle)
hwnd, _, err := procCreateWindowExW.Call(
0,
uintptr(unsafe.Pointer(className)),
uintptr(unsafe.Pointer(winTitle)),
0,
0, 0, 0, 0,
0, 0, hInst, 0,
)
if hwnd == 0 {
ready <- fmt.Errorf("CreateWindowExW: %w", err)
return
}
hicon, custom := m.loadIcon()
m.mu.Lock()
m.hwnd = hwnd
m.hicon = hicon
m.customIcon = custom
m.mu.Unlock()
m.addTrayIcon()
ready <- nil
var msg winMsg
for {
ret, _, _ := procGetMessageW.Call(uintptr(unsafe.Pointer(&msg)), 0, 0, 0)
if int32(ret) <= 0 {
break
}
_, _, _ = procTranslateMessage.Call(uintptr(unsafe.Pointer(&msg)))
_, _, _ = procDispatchMessageW.Call(uintptr(unsafe.Pointer(&msg)))
}
m.removeTrayIcon()
if m.customIcon && m.hicon != 0 {
_, _, _ = procDestroyIcon.Call(m.hicon)
}
}
func appendMenuString(menu uintptr, flags uintptr, id uintptr, label string) {
u16, _ := syscall.UTF16PtrFromString(label)
_, _, _ = procAppendMenuW.Call(menu, flags, id, uintptr(unsafe.Pointer(u16)))
}
// Menu theme: tray menus sit next to the taskbar, so they follow the Windows
// *system* theme (SystemUsesLightTheme), as the shell's own tray menus do.
// uxtheme's SetPreferredAppMode (ordinal 135) forces dark or light for this
// process's popup menus and FlushMenuThemes (ordinal 136) applies a change
// made while running. Both are undocumented but stable since Windows 10 1903;
// where they are missing the menu keeps the default light look.
const (
appModeForceDark = 2
appModeForceLight = 3
)
var (
themeOnce sync.Once
setAppMode uintptr
flushMenuTheme uintptr
)
func systemUsesLightTheme() bool {
k, err := registry.OpenKey(registry.CURRENT_USER, `Software\Microsoft\Windows\CurrentVersion\Themes\Personalize`, registry.QUERY_VALUE)
if err != nil {
return true
}
defer k.Close()
v, _, err := k.GetIntegerValue("SystemUsesLightTheme")
return err != nil || v != 0
}
func applyMenuTheme() {
themeOnce.Do(func() {
h, err := windows.LoadLibrary("uxtheme.dll")
if err != nil {
return
}
setAppMode, _ = windows.GetProcAddressByOrdinal(h, 135)
flushMenuTheme, _ = windows.GetProcAddressByOrdinal(h, 136)
})
if setAppMode == 0 {
return
}
mode := uintptr(appModeForceDark)
if systemUsesLightTheme() {
mode = appModeForceLight
}
_, _, _ = syscall.SyscallN(setAppMode, mode)
if flushMenuTheme != 0 {
_, _, _ = syscall.SyscallN(flushMenuTheme)
}
}
// dotBitmap makes a 32-bit premultiplied-alpha DIB of a status dot, sized to
// the menu's check-mark cell. The caller deletes it once the menu is gone.
func dotBitmap(kind dotKind) uintptr {
size, _, _ := procGetSystemMetrics.Call(smCxMenuCheck)
if size < 12 {
size = 16
}
px := dotPixels(int(size), kind)
bi := bitmapInfo{BiWidth: int32(size), BiHeight: -int32(size), BiPlanes: 1, BiBitCount: 32, BiCompression: biRGB}
bi.BiSize = uint32(unsafe.Sizeof(bi) - unsafe.Sizeof(bi.BmiColors))
var bits unsafe.Pointer
hbm, _, _ := procCreateDIBSection.Call(0, uintptr(unsafe.Pointer(&bi)), dibRGBColors, uintptr(unsafe.Pointer(&bits)), 0, 0)
if hbm == 0 || bits == nil {
return 0
}
copy(unsafe.Slice((*byte)(bits), len(px)), px)
return hbm
}
// renderMenu turns menu entries into a Win32 popup menu. Bitmaps it creates
// are appended to *bitmaps for the caller to free after TrackPopupMenu.
func renderMenu(entries []menuEntry, bitmaps *[]uintptr, dots map[dotKind]uintptr) uintptr {
h, _, _ := procCreatePopupMenu.Call()
if h == 0 {
return 0
}
// One column for check marks and bitmaps, not two.
mi := menuInfoW{FMask: mimStyle, DwStyle: mnsCheckOrBmp}
mi.CbSize = uint32(unsafe.Sizeof(mi))
_, _, _ = procSetMenuInfo.Call(h, uintptr(unsafe.Pointer(&mi)))
for pos, e := range entries {
switch {
case e.Separator:
_, _, _ = procAppendMenuW.Call(h, mfSeparator, 0, 0)
continue
case len(e.Sub) > 0:
sub := renderMenu(e.Sub, bitmaps, dots)
if sub == 0 {
continue
}
appendMenuString(h, mfPopup, sub, e.Label)
default:
flags := uintptr(mfString)
if e.Disabled {
flags |= mfGrayed
}
appendMenuString(h, flags, uintptr(e.ID), e.Label)
if e.Default {
_, _, _ = procSetMenuDefaultItem.Call(h, uintptr(e.ID), 0)
}
}
if e.Dot != dotNone {
hbm, ok := dots[e.Dot]
if !ok {
hbm = dotBitmap(e.Dot)
dots[e.Dot] = hbm
if hbm != 0 {
*bitmaps = append(*bitmaps, hbm)
}
}
if hbm != 0 {
ii := menuItemInfoW{FMask: miimBitmap, HbmpItem: hbm}
ii.CbSize = uint32(unsafe.Sizeof(ii))
_, _, _ = procSetMenuItemInfoW.Call(h, uintptr(pos), 1, uintptr(unsafe.Pointer(&ii)))
}
}
}
return h
}
func (m *Manager) showContextMenu() {
var snap Snapshot
if m.cb.GetSnapshot != nil {
snap = m.cb.GetSnapshot()
}
if len(snap.VMs) > maxTrayVMs {
snap.VMs = snap.VMs[:maxTrayVMs]
}
m.mu.Lock()
m.menuVMs = append([]VMItem(nil), snap.VMs...)
m.mu.Unlock()
applyMenuTheme()
var bitmaps []uintptr
hMenu := renderMenu(buildMenu(snap), &bitmaps, map[dotKind]uintptr{})
if hMenu == 0 {
return
}
// DestroyMenu also destroys the submenus; bitmaps are freed separately.
defer func() {
_, _, _ = procDestroyMenu.Call(hMenu)
for _, hbm := range bitmaps {
_, _, _ = procDeleteObject.Call(hbm)
}
}()
var pt winPoint
_, _, _ = procGetCursorPos.Call(uintptr(unsafe.Pointer(&pt)))
_, _, _ = procSetForegroundWindow.Call(m.hwnd)
cmd, _, _ := procTrackPopupMenu.Call(
hMenu,
tpmRightButton|tpmBottomAlign|tpmReturnCmd|tpmNonotify,
uintptr(pt.X),
uintptr(pt.Y),
0,
m.hwnd,
0,
)
_, _, _ = procPostMessageW.Call(m.hwnd, wmNull, 0, 0)
if cmd != 0 {
m.dispatchCommand(int(cmd))
}
}
func (m *Manager) dispatchCommand(cmd int) {
switch cmd {
case cmdShow:
if m.cb.OnShow != nil {
go m.cb.OnShow()
}
case cmdNewVM:
if m.cb.OnNewVM != nil {
go m.cb.OnNewVM()
}
case cmdQuit:
if m.cb.OnQuit != nil {
go m.cb.OnQuit()
}
default:
idx, act, ok := decodeVMCmd(cmd)
if !ok {
return
}
m.mu.Lock()
var item VMItem
valid := idx < len(m.menuVMs)
if valid {
item = m.menuVMs[idx]
}
m.mu.Unlock()
if valid && m.cb.OnVMAction != nil {
go m.cb.OnVMAction(item.DriverID, item.Name, act)
}
}
}
// Notify shows a Windows notification from the tray icon, used for results
// of tray actions while the main window may be hidden.
func (m *Manager) Notify(title, text string, isError bool) {
if m == nil {
return
}
m.mu.Lock()
if m.closed || m.hwnd == 0 {
m.mu.Unlock()
return
}
nid := m.buildNID(nifInfo)
m.mu.Unlock()
copyUTF16(nid.SzInfoTitle[:], title)
copyUTF16(nid.SzInfo[:], text)
nid.DwInfoFlags = niifInfo
if isError {
nid.DwInfoFlags = niifError
}
_, _, _ = procShellNotifyIconW.Call(nimModify, uintptr(unsafe.Pointer(&nid)))
}
func copyUTF16(dst []uint16, s string) {
u, _ := syscall.UTF16FromString(s)
n := len(u)
if n > len(dst)-1 {
n = len(dst) - 1
}
copy(dst, u[:n])
dst[n] = 0
}
func trayWndProc(hwnd uintptr, msg uint32, wparam, lparam uintptr) uintptr {
activeMu.RLock()
m := activeMgr
activeMu.RUnlock()
if m != nil && m.taskbarCreated != 0 && msg == m.taskbarCreated {
m.addTrayIcon()
return 0
}
switch msg {
case wmTrayIcon:
ev := uint32(lparam & 0xFFFF)
switch ev {
case wmLButtonUp, wmLButtonDbl:
if m != nil && m.cb.OnShow != nil {
go m.cb.OnShow()
}
case wmRButtonUp, wmContextMenu:
if m != nil {
m.showContextMenu()
}
}
return 0
case wmCommand:
if m != nil {
m.dispatchCommand(int(wparam & 0xFFFF))
}
return 0
case wmClose:
_, _, _ = procDestroyWindow.Call(hwnd)
return 0
case wmDestroy:
_, _, _ = procPostQuitMessage.Call(0)
return 0
}
ret, _, _ := procDefWindowProcW.Call(hwnd, uintptr(msg), wparam, lparam)
return ret
}