fix(windows): start a responsive tray immediately after installation

This commit is contained in:
cabbage committed 2026-10-27 07:43:37 +00:00
1 parent 14cb3570c1
commit d59b2d5463
13 files changed
+850 -106

No files matched your search

+141 -22
View File
@@ -15,9 +15,11 @@ import (
"os"
"os/exec"
"path/filepath"
"runtime"
"strings"
"sync"
"syscall"
"time"
"unicode/utf8"
"unsafe"
@@ -32,6 +34,7 @@ const (
wmLButtonDblClick = 0x0203
wmApp = 0x8000
trayMessage = wmApp + 1
trayResponse = wmApp + 2
trayIconID = 1
trayNIMAdd = 0
trayNIMModify = 1
@@ -50,6 +53,7 @@ const (
var (
ErrTrayAlreadyRunning = errors.New("RVBox tray is already running in this session")
user32Tray = syscall.NewLazyDLL("user32.dll")
kernel32Tray = syscall.NewLazyDLL("kernel32.dll")
shell32Tray = syscall.NewLazyDLL("shell32.dll")
procRegisterClassEx = user32Tray.NewProc("RegisterClassExW")
procCreateWindowEx = user32Tray.NewProc("CreateWindowExW")
@@ -69,9 +73,11 @@ var (
procDestroyMenu = user32Tray.NewProc("DestroyMenu")
procGetCursorPos = user32Tray.NewProc("GetCursorPos")
procSetForeground = user32Tray.NewProc("SetForegroundWindow")
procGetModuleHandle = user32Tray.NewProc("GetModuleHandleW")
procGetModuleHandle = kernel32Tray.NewProc("GetModuleHandleW")
procRegisterMessage = user32Tray.NewProc("RegisterWindowMessageW")
procShellNotify = shell32Tray.NewProc("Shell_NotifyIconW")
procShellIconRect = shell32Tray.NewProc("Shell_NotifyIconGetRect")
procFindWindow = user32Tray.NewProc("FindWindowW")
trayCallback = syscall.NewCallback(trayWindowProc)
trayWindows sync.Map // hwnd -> *trayWindow
taskbarCreatedMessage uint32
@@ -113,9 +119,10 @@ type trayIconData struct {
Tip [128]uint16
State uint32
StateMask uint32
InfoFlags uint32
InfoTitle [64]uint16
InfoData [256]uint16
TimeoutOrVersion uint32
InfoTitle [64]uint16
InfoFlags uint32
Guid [16]byte
BalloonIcon uintptr
}
@@ -127,6 +134,15 @@ type trayWindow struct {
tooltip string
output io.Writer
closeOnce sync.Once
ctx context.Context
responses chan trayActionResult
pending bool // UI-thread owned; at most one bounded request at a time.
}
type trayActionResult struct {
action Action
response Frame
err error
}
// Run starts one notification icon for the current logged-in session. It
@@ -138,24 +154,27 @@ func Run(ctx context.Context, output io.Writer) error {
return err
}
defer winapi.CloseHandle(mutex)
response, err := Request(ctx, Frame{Action: ActionStatus})
tooltip := "RVBox service unavailable"
if err == nil {
tooltip = string(response.Payload)
}
if tooltip == "" {
tooltip = "RVBox service"
}
ctx, cancel := context.WithCancel(ctx)
defer cancel()
ready := make(chan *trayWindow, 1)
done := make(chan error, 1)
go runTrayMessageLoop(output, tooltip, ready, done)
// Icon creation never waits for the daemon or the network. Status refresh
// is asynchronous after the icon exists, including when the service is down.
go runTrayMessageLoop(ctx, output, "RVBox service", ready, done)
var window *trayWindow
select {
case window = <-ready:
case err := <-done:
return err
case <-ctx.Done():
return nil
// Do not abandon an in-progress startup and leave an orphan icon.
select {
case window = <-ready:
_, _, _ = procPostMessage.Call(window.hwnd, wmClose, 0, 0)
return <-done
case err := <-done:
return err
}
}
select {
case <-ctx.Done():
@@ -177,7 +196,7 @@ func acquireTrayMutex() (winapi.Handle, error) {
if err != nil {
return 0, err
}
mutex, err := winapi.CreateMutex(nil, true, name)
mutex, err := winapi.CreateMutex(nil, false, name)
if errors.Is(err, winapi.ERROR_ALREADY_EXISTS) {
if mutex != 0 {
_ = winapi.CloseHandle(mutex)
@@ -190,14 +209,25 @@ func acquireTrayMutex() (winapi.Handle, error) {
return mutex, nil
}
func runTrayMessageLoop(output io.Writer, tooltip string, ready chan<- *trayWindow, done chan<- error) {
func runTrayMessageLoop(ctx context.Context, output io.Writer, tooltip string, ready chan<- *trayWindow, done chan<- error) {
runtime.LockOSThread()
defer runtime.UnlockOSThread()
if ctx.Err() != nil {
done <- nil
return
}
className, err := winapi.UTF16PtrFromString("RVBoxTrayWindowV1")
if err != nil {
done <- err
return
}
instance, _, _ := procGetModuleHandle.Call(0)
icon, _, _ := procLoadIcon.Call(0, uintptr(trayIDIApplication))
// Release builds embed the application's icon as resource 1. Unit-test
// binaries have no resource, so retain the standard icon as a fallback.
icon, _, _ := procLoadIcon.Call(instance, 1)
if icon == 0 {
icon, _, _ = procLoadIcon.Call(0, uintptr(trayIDIApplication))
}
cursor, _, _ := procLoadCursor.Call(0, uintptr(trayIDCArrow))
class := trayClass{CbSize: uint32(unsafe.Sizeof(trayClass{})), WndProc: trayCallback, HInstance: instance, HIcon: icon, HCursor: cursor, ClassName: className, HIconSm: icon}
if result, _, callErr := procRegisterClassEx.Call(uintptr(unsafe.Pointer(&class))); result == 0 && !errors.Is(callErr, winapi.ERROR_CLASS_ALREADY_EXISTS) {
@@ -210,9 +240,9 @@ func runTrayMessageLoop(output io.Writer, tooltip string, ready chan<- *trayWind
done <- callErr
return
}
window := &trayWindow{hwnd: hwnd, class: className, tooltip: tooltip, output: output}
window := &trayWindow{hwnd: hwnd, class: className, tooltip: tooltip, output: output, ctx: ctx, responses: make(chan trayActionResult, 1)}
window.icon = trayIconData{CbSize: uint32(unsafe.Sizeof(trayIconData{})), HWnd: hwnd, UID: trayIconID, UFlags: trayNIFMessage | trayNIFIcon | trayNIFTip, UCallbackMessage: trayMessage, HIcon: icon}
copy(window.icon.Tip[:], winapi.StringToUTF16(tooltip))
copy(window.icon.Tip[:len(window.icon.Tip)-1], winapi.StringToUTF16(tooltip))
trayWindows.Store(hwnd, window)
messageName, _ := winapi.UTF16PtrFromString("TaskbarCreated")
registeredMessage, _, _ := procRegisterMessage.Call(uintptr(unsafe.Pointer(messageName)))
@@ -225,6 +255,7 @@ func runTrayMessageLoop(output io.Writer, tooltip string, ready chan<- *trayWind
}
_, _, _ = procShowWindow.Call(hwnd, traySWHide)
ready <- window
window.action(ActionStatus)
for {
var message trayMessageRecord
result, _, getErr := procGetMessage.Call(uintptr(unsafe.Pointer(&message)), 0, 0, 0)
@@ -262,6 +293,11 @@ func trayWindowProc(hwnd uintptr, message uint32, wParam, lParam uintptr) uintpt
window.action(Action(uint16(wParam)))
}
return 0
case trayResponse:
if window != nil {
window.applyResponse()
}
return 0
case trayMessage:
if window != nil && (uint32(lParam) == wmRButtonUp || uint32(lParam) == wmLButtonDblClick) {
window.showMenu()
@@ -283,7 +319,7 @@ func (window *trayWindow) addIcon() error {
window.icon.UFlags = trayNIFMessage | trayNIFIcon | trayNIFTip
if result, _, err := procShellNotify.Call(uintptr(trayNIMAdd), uintptr(unsafe.Pointer(&window.icon))); result == 0 {
if err == syscall.Errno(0) {
err = syscall.GetLastError()
err = errors.New("Shell_NotifyIconW did not accept the notification icon")
}
return err
}
@@ -329,8 +365,38 @@ func (window *trayWindow) action(action Action) {
_, _, _ = procDestroyWindow.Call(window.hwnd)
return
}
response, err := Request(context.Background(), Frame{Action: action})
if err != nil {
if window.pending {
return
}
window.pending = true
go func() {
response, err := Request(window.ctx, Frame{Action: action})
select {
case window.responses <- trayActionResult{action: action, response: response, err: err}:
_, _, _ = procPostMessage.Call(window.hwnd, trayResponse, 0, 0)
case <-window.ctx.Done():
}
}()
}
func (window *trayWindow) applyResponse() {
var result trayActionResult
select {
case result = <-window.responses:
default:
return
}
window.pending = false
action, response := result.action, result.response
if result.err != nil {
if isServiceMutation(action) {
// A stopped service has no pipe to answer Start. The same narrow
// UAC helper is valid both for absent IPC and denied authorization.
if err := runElevatedServiceAction(action); err == nil {
window.setTooltip("RVBox elevation requested")
return
}
}
window.setTooltip("RVBox service unavailable")
return
}
@@ -351,6 +417,59 @@ func (window *trayWindow) action(action Action) {
}
}
// WaitReady is used only by the interactive installer in the same desktop
// session. It confirms Shell has accepted an actual icon, not merely that a
// child process was spawned. It never opens daemon config or state.
func WaitReady(ctx context.Context) error {
class, _ := winapi.UTF16PtrFromString("RVBoxTrayWindowV1")
type identifier struct {
Size uint32
HWnd uintptr
UID uint32
GUID [16]byte
}
type rectangle struct{ Left, Top, Right, Bottom int32 }
timer := time.NewTicker(50 * time.Millisecond)
defer timer.Stop()
for {
hwnd, _, _ := procFindWindow.Call(uintptr(unsafe.Pointer(class)), 0)
if hwnd != 0 {
id := identifier{Size: uint32(unsafe.Sizeof(identifier{})), HWnd: hwnd, UID: trayIconID}
var rect rectangle
result, _, _ := procShellIconRect.Call(uintptr(unsafe.Pointer(&id)), uintptr(unsafe.Pointer(&rect)))
if int32(result) == 0 {
return nil
}
}
select {
case <-ctx.Done():
return ctx.Err()
case <-timer.C:
}
}
}
// CloseCurrent lets an elevated installer update the canonical executable
// without leaving this desktop's old frontend holding the image open. It is
// deliberately a same-session window message, not service session injection.
func CloseCurrent(ctx context.Context) error {
class, _ := winapi.UTF16PtrFromString("RVBoxTrayWindowV1")
timer := time.NewTicker(50 * time.Millisecond)
defer timer.Stop()
for {
hwnd, _, _ := procFindWindow.Call(uintptr(unsafe.Pointer(class)), 0)
if hwnd == 0 {
return nil
}
_, _, _ = procPostMessage.Call(hwnd, wmClose, 0, 0)
select {
case <-ctx.Done():
return ctx.Err()
case <-timer.C:
}
}
}
func isServiceMutation(action Action) bool {
return action == ActionStartService || action == ActionStopService || action == ActionRestartService || action == ActionSetAutomatic || action == ActionSetManual
}
@@ -418,7 +537,7 @@ func (window *trayWindow) setTooltip(value string) {
for index := range window.icon.Tip {
window.icon.Tip[index] = 0
}
copy(window.icon.Tip[:], winapi.StringToUTF16(value))
copy(window.icon.Tip[:len(window.icon.Tip)-1], winapi.StringToUTF16(value))
_, _, _ = procShellNotify.Call(uintptr(trayNIMModify), uintptr(unsafe.Pointer(&window.icon)))
}