feat(windows): simplify tray controls and allow installer-user config edits

This commit is contained in:
cabbage committed 2026-10-27 08:54:23 +00:00
1 parent d59b2d5463
commit ae5e979761
18 files changed
+611 -88

No files matched your search

+121 -56
View File
@@ -23,6 +23,7 @@ import (
"unicode/utf8"
"unsafe"
"github.com/rvbox/rvbox/internal/client/windowsservice"
winapi "golang.org/x/sys/windows"
)
@@ -30,6 +31,7 @@ const (
wmDestroy = 0x0002
wmClose = 0x0010
wmCommand = 0x0111
wmTimer = 0x0113
wmRButtonUp = 0x0205
wmLButtonDblClick = 0x0203
wmApp = 0x8000
@@ -45,6 +47,9 @@ const (
trayTPMRightBtn = 0x0002
trayMFString = 0x00000000
trayMFSeparator = 0x00000800
trayMFDisabled = 0x00000001
trayMFChecked = 0x00000008
trayMFByPosition = 0x00000400
traySWHide = 0
trayIDIApplication = 32512
trayIDCArrow = 32512
@@ -69,6 +74,7 @@ var (
procLoadCursor = user32Tray.NewProc("LoadCursorW")
procCreatePopup = user32Tray.NewProc("CreatePopupMenu")
procAppendMenu = user32Tray.NewProc("AppendMenuW")
procModifyMenu = user32Tray.NewProc("ModifyMenuW")
procTrackPopup = user32Tray.NewProc("TrackPopupMenu")
procDestroyMenu = user32Tray.NewProc("DestroyMenu")
procGetCursorPos = user32Tray.NewProc("GetCursorPos")
@@ -78,6 +84,8 @@ var (
procShellNotify = shell32Tray.NewProc("Shell_NotifyIconW")
procShellIconRect = shell32Tray.NewProc("Shell_NotifyIconGetRect")
procFindWindow = user32Tray.NewProc("FindWindowW")
procSetTimer = user32Tray.NewProc("SetTimer")
procKillTimer = user32Tray.NewProc("KillTimer")
trayCallback = syscall.NewCallback(trayWindowProc)
trayWindows sync.Map // hwnd -> *trayWindow
taskbarCreatedMessage uint32
@@ -128,27 +136,32 @@ type trayIconData struct {
}
type trayWindow struct {
hwnd uintptr
icon trayIconData
class *uint16
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.
hwnd uintptr
icon trayIconData
class *uint16
tooltip string
output io.Writer
closeOnce sync.Once
ctx context.Context
responses chan trayActionResult
pending bool // UI-thread owned; at most one background status request.
logPending bool
configPath string
status MenuStatus
menu uintptr
}
type trayActionResult struct {
action Action
response Frame
err error
status *MenuStatus
}
// Run starts one notification icon for the current logged-in session. It
// returns when the icon is closed, the service becomes unavailable, or ctx is
// cancelled; none of those outcomes affect the machine-wide service.
func Run(ctx context.Context, output io.Writer) error {
func Run(ctx context.Context, configPath string, output io.Writer) error {
mutex, err := acquireTrayMutex()
if err != nil {
return err
@@ -160,7 +173,7 @@ func Run(ctx context.Context, output io.Writer) error {
done := make(chan error, 1)
// 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)
go runTrayMessageLoop(ctx, output, "Status: checking", ready, done, configPath)
var window *trayWindow
select {
case window = <-ready:
@@ -209,7 +222,7 @@ func acquireTrayMutex() (winapi.Handle, error) {
return mutex, nil
}
func runTrayMessageLoop(ctx context.Context, 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, configPath string) {
runtime.LockOSThread()
defer runtime.UnlockOSThread()
if ctx.Err() != nil {
@@ -240,7 +253,7 @@ func runTrayMessageLoop(ctx context.Context, output io.Writer, tooltip string, r
done <- callErr
return
}
window := &trayWindow{hwnd: hwnd, class: className, tooltip: tooltip, output: output, ctx: ctx, responses: make(chan trayActionResult, 1)}
window := &trayWindow{hwnd: hwnd, class: className, tooltip: tooltip, output: output, ctx: ctx, responses: make(chan trayActionResult, 2), status: MenuStatus{Label: "Status: checking"}, configPath: configPath}
window.icon = trayIconData{CbSize: uint32(unsafe.Sizeof(trayIconData{})), HWnd: hwnd, UID: trayIconID, UFlags: trayNIFMessage | trayNIFIcon | trayNIFTip, UCallbackMessage: trayMessage, HIcon: icon}
copy(window.icon.Tip[:len(window.icon.Tip)-1], winapi.StringToUTF16(tooltip))
trayWindows.Store(hwnd, window)
@@ -256,6 +269,8 @@ func runTrayMessageLoop(ctx context.Context, output io.Writer, tooltip string, r
_, _, _ = procShowWindow.Call(hwnd, traySWHide)
ready <- window
window.action(ActionStatus)
_, _, _ = procSetTimer.Call(hwnd, 1, 2000, 0)
defer procKillTimer.Call(hwnd, 1)
for {
var message trayMessageRecord
result, _, getErr := procGetMessage.Call(uintptr(unsafe.Pointer(&message)), 0, 0, 0)
@@ -290,7 +305,16 @@ func trayWindowProc(hwnd uintptr, message uint32, wParam, lParam uintptr) uintpt
return 0
case wmCommand:
if window != nil {
window.action(Action(uint16(wParam)))
action := Action(uint16(wParam))
if action == ActionSetAutomatic {
action = automaticAction(window.status.AutoStart)
}
window.action(action)
}
return 0
case wmTimer:
if window != nil {
window.action(ActionStatus)
}
return 0
case trayResponse:
@@ -339,40 +363,95 @@ func (window *trayWindow) showMenu() {
return
}
defer procDestroyMenu.Call(menu)
add := func(action Action, label string) {
text, _ := winapi.UTF16PtrFromString(label)
procAppendMenu.Call(menu, trayMFString, uintptr(action), uintptr(unsafe.Pointer(text)))
window.menu = menu
defer func() { window.menu = 0 }()
for _, item := range trayMenu(window.status) {
flags, text := menuItemFlags(item)
procAppendMenu.Call(menu, flags, uintptr(item.Action), uintptr(unsafe.Pointer(text)))
}
add(ActionStatus, "Status")
add(ActionOpenConfig, "Open config")
add(ActionOpenLog, "Open log")
procAppendMenu.Call(menu, trayMFSeparator, 0, 0)
add(ActionStartService, "Start service")
add(ActionStopService, "Stop service")
add(ActionRestartService, "Restart service")
add(ActionSetAutomatic, "Start automatically")
add(ActionSetManual, "Start manually")
procAppendMenu.Call(menu, trayMFSeparator, 0, 0)
add(ActionExitTray, "Exit")
window.action(ActionStatus)
var point trayPoint
procGetCursorPos.Call(uintptr(unsafe.Pointer(&point)))
procSetForeground.Call(window.hwnd)
procTrackPopup.Call(menu, trayTPMRightBtn, uintptr(point.X), uintptr(point.Y), 0, window.hwnd, 0)
}
func menuItemFlags(item menuItem) (uintptr, *uint16) {
if item.Separator {
return trayMFSeparator, nil
}
flags := uintptr(trayMFString)
if item.Disabled {
flags |= trayMFDisabled
}
if item.Checked {
flags |= trayMFChecked
}
text, _ := winapi.UTF16PtrFromString(item.Label)
return flags, text
}
func (window *trayWindow) refreshMenu() {
if window.menu == 0 {
return
}
for index, item := range trayMenu(window.status) {
flags, text := menuItemFlags(item)
procModifyMenu.Call(window.menu, uintptr(index), flags|trayMFByPosition, uintptr(item.Action), uintptr(unsafe.Pointer(text)))
}
}
func (window *trayWindow) action(action Action) {
if action == ActionExitTray {
_, _, _ = procDestroyWindow.Call(window.hwnd)
return
}
if window.pending {
if action == ActionOpenConfig {
if err := openExactPath(window.configPath); err != nil {
window.setTooltip("RVBox: could not open config")
}
return
}
if isServiceMutation(action) {
// Service control remains a narrow UAC helper. It does not depend on
// a live pipe, and a background status poll cannot swallow this click.
if err := runElevatedServiceAction(action, window.configPath); err != nil && !errors.Is(err, winapi.ERROR_CANCELLED) {
window.setTooltip("RVBox: service action could not start")
}
window.action(ActionStatus)
return
}
if action == ActionStatus {
if window.pending {
return
}
window.pending = true
} else if action == ActionOpenLog {
if window.logPending {
return
}
window.logPending = true
} else {
return
}
window.pending = true
go func() {
response, err := Request(window.ctx, Frame{Action: action})
result := trayActionResult{action: action}
if action == ActionStatus {
service, err := windowsservice.Query()
connection := ""
if err == nil && service.State == windowsservice.StateRunning {
response, requestErr := Request(window.ctx, Frame{Action: ActionStatus})
if requestErr == nil {
connection = string(response.Payload)
}
}
status := menuStatus(service, err, connection)
result.status = &status
} else {
result.response, result.err = Request(window.ctx, Frame{Action: action})
}
select {
case window.responses <- trayActionResult{action: action, response: response, err: err}:
case window.responses <- result:
_, _, _ = procPostMessage.Call(window.hwnd, trayResponse, 0, 0)
case <-window.ctx.Done():
}
@@ -386,27 +465,20 @@ func (window *trayWindow) applyResponse() {
default:
return
}
window.pending = false
action, response := result.action, result.response
if action == ActionStatus && result.status != nil {
window.pending = false
window.status = *result.status
window.setTooltip("RVBox — " + window.status.Label)
window.refreshMenu()
return
}
window.logPending = false
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
}
if isServiceMutation(action) && strings.HasPrefix(string(response.Payload), "error:") {
if err := runElevatedServiceAction(action); err == nil {
window.setTooltip("RVBox elevation requested")
return
}
}
if action == ActionOpenConfig || action == ActionOpenLog {
if action == ActionOpenLog {
if err := openExactPath(string(response.Payload)); err != nil {
window.setTooltip("RVBox open failed")
}
@@ -478,7 +550,7 @@ func isServiceMutation(action Action) bool {
// remains the authorization boundary; this helper only replays the enum as a
// canonical rvbox mode under an administrator token when the tray's filtered
// token cannot mutate SCM state directly.
func runElevatedServiceAction(action Action) error {
func runElevatedServiceAction(action Action, configPath string) error {
mode := ""
switch action {
case ActionStartService:
@@ -498,13 +570,6 @@ func runElevatedServiceAction(action Action) error {
if err != nil {
return err
}
configPath := ""
for index := 0; index+1 < len(os.Args); index++ {
if os.Args[index] == "--config" {
configPath = os.Args[index+1]
break
}
}
if configPath == "" {
return errors.New("tray config path is unavailable")
}