Files
magpie/internal/gui/screenback_windows.go
T
yetone ffb14c8260 gui: a restart by itself asks Windows for no attention (shangyuan0818 on X)
shangyuan0818 on X (Windows, AutoRestart and auto-update on, lightweight
mode off): magpie's window turned up on the taskbar by itself, its
button flashing orange, while they were in another app.

The cause: Wails (v3.0.0-beta.24) activates every window as it makes
it, hidden ones too. The panel's frame change (Frameless, run() in
webview_window_windows.go) and the main window's centring
(CenterWindow) are SetWindowPos calls without SWP_NOACTIVATE. The new
magpie a restart by itself starts runs in the background and may not
take the foreground, and Windows answers that ask by flashing the
window's taskbar button (HSHELL_FLASH) until it is clicked. Where it
may (nobody at the keyboard for a while), a hidden magpie window took
the keyboard from the app in front instead. The main window was then
shown with SW_SHOW, which activates it again, and a minimised one with
SetWindowPlacement(SW_SHOWMINNOACTIVE), which activates it all the
same.

Now a WH_CBT hook on Wails' main thread (noactivate_windows.go, put on
from appWndProc, which every WailsWebviewWindow message passes) turns
down HCBT_ACTIVATE for a magpie window that isn't shown, and for one
being shown quietly: showHere without focus (showQuietly) and
showMinimised. The tray's message-only window and Wails' disabled
main-thread window share the class and are left alone. A window the
user opens is shown and focused as before. Adding SWP_NOACTIVATE to the
moves' WINDOWPOS in WM_WINDOWPOSCHANGING doesn't stop the activation
(tried on the box).

TestRestartBySelfAsksNoAttention (new) plays the restart in a child
process, window and tray modes, another window in front: it records
the shell hook's notes for magpie's windows and the foreground, needs
none of either, the page drawn and visible, then that a user's
ShowMain brings the window to the front.
TestRestartMinimisedComesBackMinimised now makes its app with
windowsOptions(), as the real app does; without them its window kept
the foreground it took at creation and it was red on main and on this
change alike.

Run, on the Windows box (xiaomi-gpu, Windows 11, interactive session):
- TestRestartBySelfAsksNoAttention: red on the old code, green both
  modes with this change, green again at the pushed tree.
- TestRestartMinimisedComesBackMinimised: red on the old code ("the
  window minimised took the foreground"), green with this change,
  restore and draw included.
- TestRestartedWindowIsDrawn (13 cases, the behind/cover cases shown
  quietly under another app): 13 of 13 at the pushed tree, with the
  setup fix in the commit after this one.
- The whole internal/gui package, old code and this change, compared:
  the same reds both sides apart from the two tests above (plugin-page,
  import-row, container and client-cert tests red on the box on main
  as well) and TestRestartedWindowIsDrawn's setup flake, fixed after.
- Broken by hand: the hook not put on, red (window 0x4 activation,
  tray took the foreground); showingQuietly never set, red (window:
  0x4).
Full suite on mica at 31a08ce8c (this change on 8334f1e6e), -timeout
45m: every package ok, internal/gui included, but internal/cli
(TestEveryRouteHasACommandOrIsNamed: 80a315a70's /api/page-away, since
named on main in 69946f43c; internal/cli green with that line) and internal/gateway, whose reds
are mica's disk filling up ("no space left on device", 2261 lines);
gateway doesn't import internal/gui, and it is ok at the pushed tree in
WSL (Ubuntu 24.04, 868s; mote was busy with another suite). go vet ./... (darwin) ok; Windows
vet and test compile on mote, Linux nogui vet on mote and gtk3 vet in
WSL ok at the pushed tree; gofmt clean.

Not tried: the grey, blank window they also saw was not reproduced; the
page was drawn on every activation tried. Linux (gtk_window_present
asks for focus the same way) is #6634. macOS needs no change:
makeKeyAndOrderFront doesn't activate a background app, and
requestUserAttention is called only by Flash, which magpie doesn't use;
not tried on a real Mac.
2026-11-14 18:02:33 +08:00

134 lines
4.8 KiB
Go

//go:build windows && !nogui
package gui
import (
"log"
"sync/atomic"
"unsafe"
"golang.org/x/sys/windows"
)
// A WebView2 window shown while the screen is locked or the display off
// can stay white once the user is back: Chromium's own occlusion tracking
// takes every window as covered then, and a surface first drawn in that
// state may not be drawn again. aquaarboraurum on X saw a white window
// after every restart to update. AutoRestart makes that restart once no
// request is going through magpie and its window has sat unused, as when
// the user is away and the screen locked; a restart by hand, with the
// user there, came up drawn. Not reproduced: the screen of the Windows box
// the tests run on can't be locked for them. magpie's windows are drawn
// again when the session is unlocked or the display comes on (mendOnWake),
// as closing the window to the tray and opening it again did by hand, and
// windowsOptions turns Chromium's occlusion tracking off
// (webViewOcclusion).
// The messages that say the screen is back (WinUser.h, WtsApi32.h).
const (
wmWTSSessionChange = 0x02B1
wtsSessionUnlock = 0x8
wmPowerBroadcast = 0x0218
pbtPowerSettingChange = 0x8013
notifyForThisSession = 0
deviceNotifyWindowHndl = 0
)
// guidConsoleDisplayState is GUID_CONSOLE_DISPLAY_STATE: the display off
// (0), on (1) or dimmed (2).
var guidConsoleDisplayState = windows.GUID{Data1: 0x6fe69556, Data2: 0x704a, Data3: 0x47a0,
Data4: [8]byte{0x8f, 0x24, 0xc2, 0x8d, 0x93, 0x6f, 0xda, 0x47}}
// powerBroadcastSetting is POWERBROADCAST_SETTING with the display state's
// DWORD as its data.
type powerBroadcastSetting struct {
PowerSetting windows.GUID
DataLength uint32
Data uint32
}
var (
procWTSRegisterSessionNotification = windows.NewLazySystemDLL("wtsapi32.dll").NewProc("WTSRegisterSessionNotification")
procRegisterPowerSettingNotification = windows.NewLazySystemDLL("user32.dll").NewProc("RegisterPowerSettingNotification")
procFindWindowExW = windows.NewLazySystemDLL("user32.dll").NewProc("FindWindowExW")
)
// displayOff: the display was last said to be off.
var displayOff atomic.Bool
// watchScreenBack has Wails' main-thread window told when the session is
// unlocked and when the display goes off or on; on the main thread, once.
func watchScreenBack() {
hwnd := ownMainThreadWindow()
if hwnd == 0 {
log.Println("webview: Wails' main-thread window not found; an unlock doesn't draw the windows again")
return
}
if r, _, err := procWTSRegisterSessionNotification.Call(hwnd, notifyForThisSession); r == 0 {
log.Printf("webview: an unlock doesn't draw the windows again: %v", err)
}
if r, _, err := procRegisterPowerSettingNotification.Call(hwnd, uintptr(unsafe.Pointer(&guidConsoleDisplayState)), deviceNotifyWindowHndl); r == 0 {
log.Printf("webview: the display coming on doesn't draw the windows again: %v", err)
}
}
// ownMainThreadWindow is this process's Wails main-thread window: another
// magpie's has the same title, during a restart's handover too.
func ownMainThreadWindow() uintptr {
title, err := windows.UTF16PtrFromString(wailsMainThread)
if err != nil {
return 0
}
pid := windows.GetCurrentProcessId()
for after := uintptr(0); ; {
w, _, _ := procFindWindowExW.Call(0, after, 0, uintptr(unsafe.Pointer(title)))
if w == 0 {
return 0
}
var p uint32
if _, err := windows.GetWindowThreadProcessId(windows.HWND(w), &p); err == nil && p == pid {
return w
}
after = w
}
}
// screenBackFrom says why msg brings the screen back ("" when it doesn't):
// the session unlocked, or the display on after it was off. Windows sends
// the display's state as it is on registering, which, on, is no change.
func screenBackFrom(msg uint32, wParam, lParam uintptr) string {
switch {
case msg == wmWTSSessionChange && wParam == wtsSessionUnlock:
return "the session was unlocked"
case msg == wmPowerBroadcast && wParam == pbtPowerSettingChange && lParam != 0:
// lParam is a pointer Windows owns for the message's length.
s := *(**powerBroadcastSetting)(unsafe.Pointer(&lParam))
if s.PowerSetting != guidConsoleDisplayState || s.DataLength < 4 {
return ""
}
switch s.Data {
case 0:
displayOff.Store(true)
case 1:
if displayOff.Swap(false) {
return "the display came on"
}
}
}
return ""
}
// appWndProc is the app's WndProcInterceptor (windowsOptions): a window
// not being shown for the user isn't activated (hookNoActivate), the screen
// coming back draws the windows again, and the screens are read
// (screensWndProc). None keeps a message from Wails but the screens'.
var appWndProc = func(hwnd uintptr, msg uint32, wParam, lParam uintptr) (uintptr, bool) {
hookNoActivate(hwnd)
if why := screenBackFrom(msg, wParam, lParam); why != "" {
if f := screenBack.Load(); f != nil {
(*f)(why)
}
}
return screensWndProc(hwnd, msg, wParam, lParam)
}