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

@@ -68,6 +68,13 @@ const (
StatePaused
)
// Status is read-only SCM state. Query never requests service mutation rights.
type Status struct {
Installed bool
State State
Startup StartupMode
}
type Command uint8
const (
@@ -118,6 +125,7 @@ func Transition(state State, command Command) (State, error) {
// Install, Uninstall, Start, and Stop are intentionally narrow. Their
// platform implementations return ErrUnsupported on non-Windows builds.
func Install(spec InstallSpec) error { return installNative(spec) }
func Query() (Status, error) { return queryNative() }
func Uninstall() error { return uninstallNative() }
func Configure(startup StartupMode) error { return configureNative(startup) }
func Start() error { return startNative() }
@@ -4,6 +4,7 @@ package windowsservice
import "context"
func queryNative() (Status, error) { return Status{}, ErrUnsupported }
func installNative(InstallSpec) error { return ErrUnsupported }
func uninstallNative() error { return ErrUnsupported }
func configureNative(StartupMode) error { return ErrUnsupported }
@@ -19,6 +19,52 @@ func connect() (*mgr.Mgr, error) {
return mgr.Connect()
}
func queryNative() (Status, error) {
manager, err := windows.OpenSCManager(nil, nil, windows.SC_MANAGER_CONNECT)
if err != nil {
return Status{}, err
}
defer windows.CloseServiceHandle(manager)
name, _ := windows.UTF16PtrFromString(Name)
handle, err := windows.OpenService(manager, name, windows.SERVICE_QUERY_STATUS|windows.SERVICE_QUERY_CONFIG)
if errors.Is(err, windows.ERROR_SERVICE_DOES_NOT_EXIST) {
return Status{State: StateStopped}, nil
}
if err != nil {
return Status{}, err
}
defer windows.CloseServiceHandle(handle)
service := mgr.Service{Name: Name, Handle: handle}
status, err := service.Query()
if err != nil {
return Status{}, err
}
configuration, err := service.Config()
if err != nil {
return Status{}, err
}
state := StateUnknown
switch status.State {
case svc.Running:
state = StateRunning
case svc.Stopped:
state = StateStopped
case svc.StartPending, svc.ContinuePending:
state = StateStartPending
case svc.StopPending:
state = StateStopPending
case svc.Paused, svc.PausePending:
state = StatePaused
}
startup := StartupMode("")
if configuration.StartType == mgr.StartAutomatic {
startup = StartupAutomatic
} else if configuration.StartType == mgr.StartManual {
startup = StartupManual
}
return Status{Installed: true, State: state, Startup: startup}, nil
}
func installNative(spec InstallSpec) error {
if err := spec.Validate(); err != nil {
return err
@@ -13,9 +13,54 @@ import (
"time"
"unsafe"
"github.com/rvbox/rvbox/internal/client/windowsservice"
winapi "golang.org/x/sys/windows"
)
func TestNativeTrayReadOnlyServiceQuery_HP_WINTRAY_07(t *testing.T) {
status, err := windowsservice.Query()
if err != nil {
t.Fatalf("unprivileged read-only SCM query: %v", err)
}
if !status.Installed && status.State != windowsservice.StateStopped {
t.Fatalf("missing service state=%#v", status)
}
if status.Installed && status.State == windowsservice.StateUnknown {
t.Fatalf("installed service state=%#v", status)
}
}
func TestNativeTrayMenuFlagsAndRefresh_HP_WINTRAY_08(t *testing.T) {
runtime.LockOSThread()
defer runtime.UnlockOSThread()
menu, _, err := procCreatePopup.Call()
if menu == 0 {
t.Fatal(err)
}
defer procDestroyMenu.Call(menu)
w := &trayWindow{menu: menu, status: MenuStatus{Label: "Status: running", AutoStart: true, StartupKnown: true, CanStop: true}}
for _, item := range trayMenu(w.status) {
flags, text := menuItemFlags(item)
if ok, _, err := procAppendMenu.Call(menu, flags, uintptr(item.Action), uintptr(unsafe.Pointer(text))); ok == 0 {
t.Fatal(err)
}
}
getState := user32Tray.NewProc("GetMenuState")
banner, _, _ := getState.Call(menu, 0, trayMFByPosition)
auto, _, _ := getState.Call(menu, 7, trayMFByPosition)
if banner == ^uintptr(0) || banner&trayMFDisabled == 0 || auto&trayMFChecked == 0 {
t.Fatalf("initial menu flags banner=%#x auto=%#x", banner, auto)
}
w.status = MenuStatus{Label: "Status: stopped", StartupKnown: true, CanStart: true}
w.refreshMenu()
auto, _, _ = getState.Call(menu, 7, trayMFByPosition)
start, _, _ := getState.Call(menu, 5, trayMFByPosition)
stop, _, _ := getState.Call(menu, 6, trayMFByPosition)
if auto&trayMFChecked != 0 || start&trayMFDisabled != 0 || stop&trayMFDisabled == 0 {
t.Fatalf("updated menu flags start=%#x stop=%#x auto=%#x", start, stop, auto)
}
}
func trayTestName() string {
return fmt.Sprintf(`\\.\pipe\rvbox-tray-test-%d-%d`, winapi.GetCurrentProcessId(), time.Now().UnixNano())
}
@@ -206,7 +251,7 @@ func TestNativeTrayWindowLifecycle_HP_WINTRAY_04(t *testing.T) {
defer cancel()
ready := make(chan *trayWindow, 1)
done := make(chan error, 1)
go runTrayMessageLoop(ctx, io.Discard, "RVBox native tray test", ready, done)
go runTrayMessageLoop(ctx, io.Discard, "RVBox native tray test", ready, done, "")
var window *trayWindow
select {
case window = <-ready:
+1 -1
View File
@@ -17,7 +17,7 @@ func Serve(context.Context, Handler) error { return ErrUnsupported }
func Request(context.Context, Frame) (Frame, error) { return Frame{}, ErrUnsupported }
func Run(context.Context, io.Writer) error { return ErrUnsupported }
func Run(context.Context, string, io.Writer) error { return ErrUnsupported }
func WaitReady(context.Context) error { return ErrUnsupported }
+68
View File
@@ -0,0 +1,68 @@
package windowstray
import "github.com/rvbox/rvbox/internal/client/windowsservice"
// MenuStatus contains only presentation facts, never configuration or spool data.
type MenuStatus struct {
Label string
AutoStart bool
StartupKnown bool
CanStart bool
CanStop bool
}
func menuStatus(service windowsservice.Status, queryErr error, connection string) MenuStatus {
result := MenuStatus{Label: "Status: unavailable"}
if queryErr != nil {
return result
}
result.StartupKnown = service.Installed && (service.Startup == windowsservice.StartupAutomatic || service.Startup == windowsservice.StartupManual)
result.AutoStart = service.Startup == windowsservice.StartupAutomatic
switch service.State {
case windowsservice.StateStopped:
result.Label = "Status: stopped"
result.CanStart = service.Installed
case windowsservice.StateStartPending:
result.Label = "Status: starting"
case windowsservice.StateStopPending:
result.Label = "Status: stopping"
case windowsservice.StatePaused:
result.Label, result.CanStop = "Status: paused", true
case windowsservice.StateRunning:
result.Label, result.CanStop = "Status: disconnected", true
if connection == "running" {
result.Label = "Status: running"
}
}
return result
}
func automaticAction(automatic bool) Action {
if automatic {
return ActionSetManual
}
return ActionSetAutomatic
}
type menuItem struct {
Action Action
Label string
Disabled bool
Checked bool
Separator bool
}
func trayMenu(status MenuStatus) []menuItem {
return []menuItem{
{Label: status.Label, Disabled: true},
{Separator: true},
{Action: ActionOpenConfig, Label: "Open config"},
{Action: ActionOpenLog, Label: "Open log"},
{Separator: true},
{Action: ActionStartService, Label: "Start service", Disabled: !status.CanStart},
{Action: ActionStopService, Label: "Stop service", Disabled: !status.CanStop},
{Action: ActionSetAutomatic, Label: "Auto start", Disabled: !status.StartupKnown, Checked: status.AutoStart},
{Separator: true},
{Action: ActionExitTray, Label: "Exit"},
}
}
@@ -0,0 +1,65 @@
package windowstray
import (
"errors"
"strings"
"testing"
"github.com/rvbox/rvbox/internal/client/windowsservice"
)
func TestTrayStatusUsesSCMAndConnection_HP_WINTRAY_05(t *testing.T) {
for _, tc := range []struct {
name string
service windowsservice.Status
err error
connection string
label string
start, stop, auto, known bool
}{
{"connected", windowsservice.Status{Installed: true, State: windowsservice.StateRunning, Startup: windowsservice.StartupAutomatic}, nil, "running", "Status: running", false, true, true, true},
{"disconnected", windowsservice.Status{Installed: true, State: windowsservice.StateRunning, Startup: windowsservice.StartupManual}, nil, "disconnected", "Status: disconnected", false, true, false, true},
{"unresponsive pipe", windowsservice.Status{Installed: true, State: windowsservice.StateRunning, Startup: windowsservice.StartupAutomatic}, nil, "", "Status: disconnected", false, true, true, true},
{"stopped ignores stale connection", windowsservice.Status{Installed: true, State: windowsservice.StateStopped, Startup: windowsservice.StartupAutomatic}, nil, "running", "Status: stopped", true, false, true, true},
{"starting", windowsservice.Status{Installed: true, State: windowsservice.StateStartPending, Startup: windowsservice.StartupManual}, nil, "", "Status: starting", false, false, false, true},
{"stopping", windowsservice.Status{Installed: true, State: windowsservice.StateStopPending, Startup: windowsservice.StartupAutomatic}, nil, "running", "Status: stopping", false, false, true, true},
{"not installed", windowsservice.Status{State: windowsservice.StateStopped}, nil, "", "Status: stopped", false, false, false, false},
{"access denied", windowsservice.Status{}, errors.New("access denied"), "running", "Status: unavailable", false, false, false, false},
{"unknown startup", windowsservice.Status{Installed: true, State: windowsservice.StateRunning}, nil, "running", "Status: running", false, true, false, false},
} {
t.Run(tc.name, func(t *testing.T) {
got := menuStatus(tc.service, tc.err, tc.connection)
want := MenuStatus{Label: tc.label, CanStart: tc.start, CanStop: tc.stop, AutoStart: tc.auto, StartupKnown: tc.known}
if got != want {
t.Fatalf("status=%#v, want %#v", got, want)
}
})
}
}
func TestTrayMenuHasBannerAndSingleAutoToggle_HP_WINTRAY_06(t *testing.T) {
for _, automatic := range []bool{false, true} {
items := trayMenu(MenuStatus{Label: "Status: running", AutoStart: automatic, StartupKnown: true, CanStop: true})
if items[0].Action != 0 || !items[0].Disabled || items[0].Label != "Status: running" {
t.Fatalf("status is clickable: %#v", items[0])
}
count := 0
for _, item := range items {
if item.Action == ActionStatus || item.Action == ActionRestartService || item.Action == ActionSetManual || strings.Contains(item.Label, "automatically") || strings.Contains(item.Label, "manually") {
t.Fatalf("obsolete menu item: %#v", item)
}
if item.Label == "Auto start" {
count++
if item.Checked != automatic || item.Disabled {
t.Fatalf("bad toggle: %#v", item)
}
}
}
if count != 1 {
t.Fatalf("auto start count=%d", count)
}
if automaticAction(automatic) == ActionSetAutomatic && automatic || automaticAction(automatic) == ActionSetManual && !automatic {
t.Fatal("toggle does not invert confirmed SCM state")
}
}
}
+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")
}