diff --git a/internal/gui/app.go b/internal/gui/app.go index 1c19884bc..d4227360a 100644 --- a/internal/gui/app.go +++ b/internal/gui/app.go @@ -318,16 +318,18 @@ func (h *host) zoomWindows() { // blanks before WebView2 can read them, are merged into Wails' own (#2753), // after magpie's own (sharedFrameProcess). // Display changes are read with a callback made once (screens_windows.go). +// Chromium's occlusion tracking is off (occlusionOff). func windowsOptions() application.WindowsOptions { disabled, enabled, other := webView2Args(webview2env.Args) disabled = sharedFrameProcess(disabled, enabled) + disabled = occlusionOff(disabled, enabled) return application.WindowsOptions{ DisableQuitOnLastWindowClosed: true, WebviewUserDataPath: appdir.WebView(), DisabledFeatures: disabled, EnabledFeatures: enabled, AdditionalBrowserArgs: other, - WndProcInterceptor: screensWndProc, + WndProcInterceptor: appWndProc, } } diff --git a/internal/gui/quiet_restart_windows_test.go b/internal/gui/quiet_restart_windows_test.go new file mode 100644 index 000000000..c11de9894 --- /dev/null +++ b/internal/gui/quiet_restart_windows_test.go @@ -0,0 +1,490 @@ +//go:build windows && !nogui + +package gui + +import ( + "context" + "fmt" + "log" + "net/http" + "os" + "os/exec" + "path/filepath" + "strconv" + "strings" + "sync" + "syscall" + "testing" + "time" + "unsafe" + + "github.com/wailsapp/wails/v3/pkg/application" + "github.com/wailsapp/wails/v3/pkg/events" + "golang.org/x/sys/windows" + + "github.com/yetone/magpie/internal/proc" + "github.com/yetone/magpie/internal/settings" + "github.com/yetone/magpie/internal/update" +) + +// aquaarboraurum on X: the window a restart to update brings back is +// white, every time, its title bar there and its page alive; a restart by +// hand, or a reload, draws it. The restart is played here as magpie makes +// it on Windows: an old process with its window up starts the new one +// detached (update's launch), marks the restart as one by itself +// (markQuietRestart) and quits; the new one waits for it to go +// (AwaitPredecessor), for its WebView2 profile (webView2Ready), reads the +// mark and opens its window as the app does (openMain). The new window's +// page must be drawn: its own pixels (PrintWindow) not white, and the +// page told it is visible. +// +// The windows are real, so this runs on the Windows box's signed-in +// session, not over ssh (session 0). +const testRestartDrawEnv = "MAGPIE_TEST_RESTART_DRAW" + +func TestRestartedWindowIsDrawn(t *testing.T) { + var session uint32 + if err := windows.ProcessIdToSessionId(windows.GetCurrentProcessId(), &session); err != nil || session == 0 { + t.Skip("no interactive desktop (session 0): run it in the signed-in session") + } + self, err := os.Executable() + if err != nil { + t.Fatal(err) + } + for _, mode := range []string{"quiet", "asked", "quiet-behind", "asked-behind", "quiet-behind-max", "asked-behind-max", "quiet-cover", "asked-cover", "quiet-cover-max", "quiet-cloak", "asked-cloak", "quiet-min", "quiet-min-max"} { + t.Run(mode, func(t *testing.T) { + ctx, cancel := context.WithTimeout(context.Background(), 120*time.Second) + defer cancel() + // not t.TempDir: WebView2's processes still hold files in it + home, err := os.MkdirTemp("", "magpie-restart-draw-") + if err != nil { + t.Fatal(err) + } + defer os.RemoveAll(home) + result := filepath.Join(home, "result.txt") + cmd := exec.CommandContext(ctx, self, "-test.run=^$") + cmd.Env = append(os.Environ(), testRestartDrawEnv+"=old,"+mode+","+result, + "XDG_CONFIG_HOME="+filepath.Join(home, "config"), "LOCALAPPDATA="+filepath.Join(home, "local"), "APPDATA="+filepath.Join(home, "roaming")) + out, err := cmd.CombinedOutput() + if err != nil || !strings.Contains(string(out), "restart draw: old done") { + t.Fatalf("old: %v\n%s", err, out) + } + var got []byte + for deadline := time.Now().Add(90 * time.Second); ; time.Sleep(250 * time.Millisecond) { + if got, err = os.ReadFile(result); err == nil && strings.Contains(string(got), "restart draw: end") { + break + } + if time.Now().After(deadline) { + t.Fatalf("the new one wrote nothing in time: %s", got) + } + } + for _, l := range strings.Split(strings.TrimSpace(string(got)), "\n") { + t.Log(strings.TrimSpace(l)) + } + if !strings.Contains(string(got), "restart draw: ok") { + t.Fatalf("%s: the window the restart brought back wasn't drawn", mode) + } + }) + } +} + +var ( + procPrintWindow = user32.NewProc("PrintWindow") + procWindowFromPoint = user32.NewProc("WindowFromPoint") + procGetAncestor = user32.NewProc("GetAncestor") + procCreateCompatibleDC = windows.NewLazySystemDLL("gdi32.dll").NewProc("CreateCompatibleDC") + procCreateCompatibleBitmap = windows.NewLazySystemDLL("gdi32.dll").NewProc("CreateCompatibleBitmap") + procSelectObject = windows.NewLazySystemDLL("gdi32.dll").NewProc("SelectObject") + procDeleteObject = windows.NewLazySystemDLL("gdi32.dll").NewProc("DeleteObject") + procDeleteDC = windows.NewLazySystemDLL("gdi32.dll").NewProc("DeleteDC") + procDwmSetWindowAttribute = windows.NewLazySystemDLL("dwmapi.dll").NewProc("DwmSetWindowAttribute") +) + +// ownWhiteShare is whiteShare over the window's own pixels, as DWM +// composes them (PrintWindow, PW_RENDERFULLCONTENT): what the window +// shows whether another covers it or not. On the main thread. +func ownWhiteShare(w *application.WebviewWindow) float64 { + hwnd := uintptr(w.NativeWindow()) + var r struct{ L, T, R, B int32 } + procGetClientRect.Call(hwnd, uintptr(unsafe.Pointer(&r))) + if r.R-r.L <= 0 || r.B-r.T <= 0 { + return 1 + } + screen, _, _ := procGetDC.Call(0) + defer procReleaseDC.Call(0, screen) + dc, _, _ := procCreateCompatibleDC.Call(screen) + defer procDeleteDC.Call(dc) + bmp, _, _ := procCreateCompatibleBitmap.Call(screen, uintptr(r.R-r.L), uintptr(r.B-r.T)) + defer procDeleteObject.Call(bmp) + old, _, _ := procSelectObject.Call(dc, bmp) + defer procSelectObject.Call(dc, old) + const pwClientOnly, pwRenderFullContent = 1, 2 + if ok, _, _ := procPrintWindow.Call(hwnd, dc, pwClientOnly|pwRenderFullContent); ok == 0 { + return 1 + } + white, all := 0, 0 + for i := 1; i < 10; i++ { + for j := 1; j < 10; j++ { + c, _, _ := procGetPixel.Call(dc, uintptr((r.R-r.L)*int32(i)/10), uintptr((r.B-r.T)*int32(j)/10)) + if c == 0xFFFFFFFF { + continue + } + all++ + if c&0xff > 240 && c>>8&0xff > 240 && c>>16&0xff > 240 { + white++ + } + } + } + if all == 0 { + return 1 + } + return float64(white) / float64(all) +} + +// screenWhiteShare is whiteShare over the points of w's client area where +// the screen shows w (not another window over it), and how many there were. +func screenWhiteShare(w *application.WebviewWindow) (share float64, seen int) { + hwnd := uintptr(w.NativeWindow()) + var r struct{ L, T, R, B int32 } + procGetClientRect.Call(hwnd, uintptr(unsafe.Pointer(&r))) + var o struct{ X, Y int32 } + procClientToScreen.Call(hwnd, uintptr(unsafe.Pointer(&o))) + dc, _, _ := procGetDC.Call(0) + defer procReleaseDC.Call(0, dc) + white := 0 + for i := 1; i < 10; i++ { + for j := 1; j < 10; j++ { + x := o.X + r.L + (r.R-r.L)*int32(i)/10 + y := o.Y + r.T + (r.B-r.T)*int32(j)/10 + at, _, _ := procWindowFromPoint.Call(uintptr(uint32(x)) | uintptr(uint32(y))<<32) + const gaRoot = 2 + if root, _, _ := procGetAncestor.Call(at, gaRoot); root != hwnd { + continue + } + c, _, _ := procGetPixel.Call(dc, uintptr(x), uintptr(y)) + if c == 0xFFFFFFFF { + continue + } + seen++ + if c&0xff > 240 && c>>8&0xff > 240 && c>>16&0xff > 240 { + white++ + } + } + } + if seen == 0 { + return 0, 0 + } + return float64(white) / float64(seen), seen +} + +func init() { + v := os.Getenv(testRestartDrawEnv) + if v == "" { + return + } + parts := strings.SplitN(v, ",", 3) + if len(parts) != 3 { + panic("restart draw: " + v) + } + role, mode, result := parts[0], parts[1], parts[2] + var report func(format string, a ...any) + if role == "old" { + report = func(format string, a ...any) { fmt.Printf("restart draw: "+format+"\n", a...) } + } else { + f, err := os.OpenFile(result+".part", os.O_CREATE|os.O_WRONLY|os.O_TRUNC, 0o644) + if err != nil { + panic(err) + } + report = func(format string, a ...any) { fmt.Fprintf(f, "restart draw: "+format+"\n", a...); f.Sync() } + end := func(ok bool) { + if ok { + report("ok") + } + report("end") + f.Close() + os.Rename(result+".part", result) + } + defer func() { + if r := recover(); r != nil { + report("panic: %v", r) + end(false) + os.Exit(1) + } + }() + restartDrawNew(mode, report, end) + os.Exit(0) + } + restartDrawOld(mode, report) + os.Exit(0) +} + +// restartDrawPage is blue, says once it has loaded, and every 50ms +// whether it is visible. +func restartDrawPage(loaded chan<- struct{}, seen chan<- string) http.Handler { + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + switch r.URL.Path { + case "/vis": + select { + case seen <- r.URL.Query().Get("s"): + default: + } + return + case "/loaded": + select { + case loaded <- struct{}{}: + default: + } + return + } + w.Header().Set("Content-Type", "text/html") + fmt.Fprint(w, `
magpie`) + }) +} + +// restartDrawOld is the magpie before: its window up and drawn, it starts +// the new one as update's launch does and quits. +func restartDrawOld(mode string, report func(string, ...any)) { + fail := func(format string, a ...any) { report(format, a...); os.Exit(1) } + loaded := make(chan struct{}, 16) + seen := make(chan string, 4096) + app := application.New(application.Options{ + Name: "magpie restart draw regression", + Windows: windowsOptions(), + Assets: application.AssetOptions{Handler: restartDrawPage(loaded, seen)}, + }) + h := &host{app: app} + app.Event.OnApplicationEvent(events.Common.ApplicationStarted, func(*application.ApplicationEvent) { + go func() { + application.InvokeSync(func() { h.openMain("") }) + select { + case <-loaded: + case <-time.After(30 * time.Second): + fail("old: the page didn't load") + } + time.Sleep(time.Second) + if strings.Contains(mode, "-max") { + s := settings.Load() + s.WindowMaximised = true + settings.Save(s) + } + if strings.Contains(mode, "behind") || strings.Contains(mode, "cover") { + // another app in front, as the user is in one when a + // restart by itself comes: a small window at the corner, + // or (cover) one over the whole screen, the window shown + // under it + form := `$f.StartPosition = 'Manual'; $f.Left = 0; $f.Top = 0; $f.Width = 240; $f.Height = 160` + if strings.Contains(mode, "cover") { + form = `$f.FormBorderStyle = 'None'; $f.TopMost = $true; $f.WindowState = 'Maximized'; $f.BackColor = 'Black'` + } + ps := exec.Command("powershell", "-NoProfile", "-Command", + `Add-Type -AssemblyName System.Windows.Forms; $f = New-Object System.Windows.Forms.Form; `+form+`; $f.Text = 'other app'; $f.ShowDialog()`) + if err := ps.Start(); err != nil { + fail("old: the other app: %v", err) + } + other := uint32(ps.Process.Pid) + os.Setenv("MAGPIE_TEST_OTHER_PID", strconv.Itoa(int(other))) + for deadline := time.Now().Add(20 * time.Second); ; time.Sleep(100 * time.Millisecond) { + var pid uint32 + windows.GetWindowThreadProcessId(windows.GetForegroundWindow(), &pid) + if pid == other { + break + } + if time.Now().After(deadline) { + fail("old: the other app never came to the front") + } + } + } + if strings.Contains(mode, "-min") { + // minimised on the taskbar as the restart comes (#3495) + application.InvokeSync(func() { h.main.Minimise() }) + time.Sleep(time.Second) + } + if strings.HasPrefix(mode, "quiet") { + markQuietRestart(strings.Contains(mode, "-min")) + } else { + unmarkQuietRestart() + } + self, _ := os.Executable() + // as update's launch starts the new version: detached, no + // console, its window on the desktop this one is on + cmd := proc.Command(self, "-test.run=^$") + cmd.Env = append(os.Environ(), "MAGPIE_REPLACES="+strconv.Itoa(os.Getpid()), + testRestartDrawEnv+"=new,"+mode+","+strings.SplitN(os.Getenv(testRestartDrawEnv), ",", 3)[2]) + if cmd.SysProcAttr == nil { + cmd.SysProcAttr = &syscall.SysProcAttr{} + } + cmd.SysProcAttr.CreationFlags |= 0x00000008 | 0x00000200 // DETACHED_PROCESS, CREATE_NEW_PROCESS_GROUP + if err := cmd.Start(); err != nil { + fail("old: starting the new one: %v", err) + } + cmd.Process.Release() + time.Sleep(time.Second) + report("old done") + app.Quit() + }() + }) + if err := app.Run(); err != nil { + panic(err) + } +} + +// restartDrawNew is the version restarted into: it starts as the app does +// and says what its window shows. +func restartDrawNew(mode string, report func(string, ...any), end func(bool)) { + update.AwaitPredecessor() + webView2Ready(webView2Dir(), "restart-draw", 30*time.Second) + quiet, minimised := takeQuietRestart() + if quiet != strings.HasPrefix(mode, "quiet") || minimised != strings.Contains(mode, "-min") { + report("the mark read back quiet=%v minimised=%v", quiet, minimised) + end(false) + os.Exit(1) + } + quietShow.Store(quiet) + quietMinimised.Store(quiet && minimised) + loaded := make(chan struct{}, 16) + seen := make(chan string, 4096) + app := application.New(application.Options{ + Name: "magpie restart draw regression", + Windows: windowsOptions(), + Assets: application.AssetOptions{Handler: restartDrawPage(loaded, seen)}, + }) + h := &host{app: app} + ok := true + logged := &lockedLog{} + log.SetOutput(logged) + h.mendOnWake() + app.Event.OnApplicationEvent(events.Common.ApplicationStarted, func(*application.ApplicationEvent) { + go func() { + defer func() { + if pid, err := strconv.Atoi(os.Getenv("MAGPIE_TEST_OTHER_PID")); err == nil { + endProcess(uint32(pid)) + } + end(ok) + app.Quit() + }() + cloak := func(on bool) { + v := uint32(0) + if on { + v = 1 + } + r, _, _ := procDwmSetWindowAttribute.Call(uintptr(h.main.NativeWindow()), 13, uintptr(unsafe.Pointer(&v)), 4) // DWMWA_CLOAK + report("cloak %v: %#x", on, r) + } + application.InvokeSync(func() { + h.openMain("") + // shown while nothing of it can be seen, as on a locked + // screen: the window cloaked from before it is shown + if strings.Contains(mode, "cloak") { + cloak(true) + } + }) + select { + case <-loaded: + case <-time.After(30 * time.Second): + report("the page didn't load") + ok = false + return + } + if strings.Contains(mode, "-min") { + // on the taskbar, then restored as a click on its button does + var up bool + for deadline := time.Now().Add(15 * time.Second); !up && time.Now().Before(deadline); time.Sleep(50 * time.Millisecond) { + application.InvokeSync(func() { up = h.main != nil && h.main.IsVisible() }) + } + time.Sleep(2 * time.Second) + procPostMessageW.Call(uintptr(h.main.NativeWindow()), 0x0112, 0xF120, 0) // WM_SYSCOMMAND, SC_RESTORE + } + var open bool + for deadline := time.Now().Add(15 * time.Second); !open && time.Now().Before(deadline); time.Sleep(50 * time.Millisecond) { + application.InvokeSync(func() { open = h.main != nil && windowOpen(h.main) }) + } + if !open { + report("the window never opened") + ok = false + return + } + if strings.Contains(mode, "cloak") { + time.Sleep(3 * time.Second) + application.InvokeSync(func() { cloak(false) }) + time.Sleep(500 * time.Millisecond) + } + if strings.Contains(mode, "cover") { + // the cover goes after the window has been up under it + time.Sleep(2 * time.Second) + if pid, err := strconv.Atoi(os.Getenv("MAGPIE_TEST_OTHER_PID")); err == nil { + endProcess(uint32(pid)) + } + time.Sleep(500 * time.Millisecond) + } + // what the window shows over the next seconds, nothing touching it + last := "" + var own, scr float64 + var seenPts int + var maxed bool + for i := 0; i < 16; i++ { + time.Sleep(500 * time.Millisecond) + for drained := false; !drained; { + select { + case s := <-seen: + last = s + default: + drained = true + } + } + application.InvokeSync(func() { + own = ownWhiteShare(h.main) + scr, seenPts = screenWhiteShare(h.main) + maxed = h.main.IsMaximised() + }) + fg := windows.GetForegroundWindow() == windows.HWND(uintptr(h.main.NativeWindow())) + report("%4.1fs page %s, own white %.2f, screen white %.2f over %d points, foreground %v, maximised %v", float64(i+1)/2, last, own, scr, seenPts, fg, maxed) + } + if last != "visible" || own > 0.5 || seenPts > 0 && scr > 0.5 { + ok = false + } + // the screen back: an unlock reaches the app's own main-thread + // window and draws the open window again, which stays drawn + if w := ownMainThreadWindow(); w == 0 { + report("no main-thread window of our own") + ok = false + } else { + procPostMessageW.Call(w, wmWTSSessionChange, wtsSessionUnlock, 0) + } + time.Sleep(1500 * time.Millisecond) + application.InvokeSync(func() { own = ownWhiteShare(h.main) }) + got := logged.String() + report("after an unlock: own white %.2f; log:\n%s", own, got) + if !strings.Contains(got, "the session was unlocked; drawing it again") || strings.Contains(got, "doesn't draw the windows again") || own > 0.5 { + ok = false + } + // the WebView2 browser started without occlusion tracking + cmd, _ := proc.Command("powershell", "-NoProfile", "-Command", + fmt.Sprintf("(Get-CimInstance Win32_Process -Filter \"Name='msedgewebview2.exe' AND ParentProcessId=%d\").CommandLine", os.Getpid())).Output() + report("browser: %s", strings.TrimSpace(string(cmd))) + if !strings.Contains(string(cmd), "CalculateNativeWinOcclusion") { + ok = false + } + }() + }) + if err := app.Run(); err != nil { + panic(err) + } +} + +// lockedLog keeps what the app logs, for the checks to read. +type lockedLog struct { + mu sync.Mutex + b strings.Builder +} + +func (l *lockedLog) Write(p []byte) (int, error) { + l.mu.Lock() + defer l.mu.Unlock() + return l.b.Write(p) +} + +func (l *lockedLog) String() string { + l.mu.Lock() + defer l.mu.Unlock() + return l.b.String() +} diff --git a/internal/gui/screenback_windows.go b/internal/gui/screenback_windows.go new file mode 100644 index 000000000..d6d1b9d41 --- /dev/null +++ b/internal/gui/screenback_windows.go @@ -0,0 +1,131 @@ +//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): the screen +// coming back draws the windows again, and the screens are read +// (screensWndProc). Neither keeps a message from Wails but the screens'. +var appWndProc = func(hwnd uintptr, msg uint32, wParam, lParam uintptr) (uintptr, bool) { + if why := screenBackFrom(msg, wParam, lParam); why != "" { + if f := screenBack.Load(); f != nil { + (*f)(why) + } + } + return screensWndProc(hwnd, msg, wParam, lParam) +} diff --git a/internal/gui/screenback_windows_test.go b/internal/gui/screenback_windows_test.go new file mode 100644 index 000000000..a2210f1d2 --- /dev/null +++ b/internal/gui/screenback_windows_test.go @@ -0,0 +1,56 @@ +//go:build windows && !nogui + +package gui + +import ( + "testing" + "unsafe" + + "golang.org/x/sys/windows" +) + +// The screen coming back, and only that, draws magpie's windows again: an +// unlock, or the display on after it was off. Windows says the display is +// on when the watch is registered; that is no change. +func TestScreenBackFrom(t *testing.T) { + displayOff.Store(false) + t.Cleanup(func() { displayOff.Store(false) }) + display := func(state uint32, guid windows.GUID) string { + s := powerBroadcastSetting{PowerSetting: guid, DataLength: 4, Data: state} + return screenBackFrom(wmPowerBroadcast, pbtPowerSettingChange, uintptr(unsafe.Pointer(&s))) + } + other := windows.GUID{Data1: 1} + for _, c := range []struct { + name, want string + got func() string + }{ + {"unlocked", "the session was unlocked", func() string { return screenBackFrom(wmWTSSessionChange, wtsSessionUnlock, 0) }}, + {"locked", "", func() string { return screenBackFrom(wmWTSSessionChange, 0x7, 0) }}, + {"on when registered", "", func() string { return display(1, guidConsoleDisplayState) }}, + {"off", "", func() string { return display(0, guidConsoleDisplayState) }}, + {"another setting's on", "", func() string { return display(1, other) }}, + {"dimmed", "", func() string { return display(2, guidConsoleDisplayState) }}, + {"on after off", "the display came on", func() string { return display(1, guidConsoleDisplayState) }}, + {"on again", "", func() string { return display(1, guidConsoleDisplayState) }}, + {"another power event", "", func() string { return screenBackFrom(wmPowerBroadcast, 0x7, 0) }}, + } { + if got := c.got(); got != c.want { + t.Errorf("%s: %q, want %q", c.name, got, c.want) + } + } +} + +// The app's interceptor hands an unlock on and still lets the screens' +// own handling see every message. +func TestAppWndProcSaysTheScreenIsBack(t *testing.T) { + var said []string + back := func(why string) { said = append(said, why) } + was := screenBack.Load() + screenBack.Store(&back) + t.Cleanup(func() { screenBack.Store(was) }) + appWndProc(0, wmWTSSessionChange, wtsSessionUnlock, 0) + appWndProc(0, wmWTSSessionChange, 0x7, 0) + if len(said) != 1 || said[0] != "the session was unlocked" { + t.Fatalf("said %q, want one unlock", said) + } +} diff --git a/internal/gui/webview2.go b/internal/gui/webview2.go index 148671149..568a6724e 100644 --- a/internal/gui/webview2.go +++ b/internal/gui/webview2.go @@ -68,6 +68,13 @@ var webView2Words = map[string][2]string{ "Die Download-Seite jetzt öffnen?"}, } +// webViewOcclusion is Chromium's tracking of whether a window is covered, +// turned off for magpie's windows (windowsOptions): when it is wrong, as +// for a window shown while the screen is locked or the display off, the +// page stays white (screenback_windows.go). A hidden or minimised window is +// told so by Wails (put_IsVisible) without it. +const webViewOcclusion = "CalculateNativeWinOcclusion" + // webView2Args sorts what the user put in WEBVIEW2_ADDITIONAL_BROWSER_ARGUMENTS // (webview2env.Args) into Wails' three options, which it passes as the // app's own arguments: the features to disable, the ones to enable, and @@ -120,6 +127,16 @@ func sharedFrameProcess(disabled, enabled []string) []string { return addFeatures([]string{isolateSandboxedFrames}, strings.Join(disabled, ",")) } +// occlusionOff adds webViewOcclusion to the disabled features, after the +// user's own; a user who enables it in WEBVIEW2_ADDITIONAL_BROWSER_ARGUMENTS +// keeps it on. +func occlusionOff(disabled, enabled []string) []string { + if slices.Contains(enabled, webViewOcclusion) { + return disabled + } + return addFeatures(disabled, webViewOcclusion) +} + // addFeatures adds a comma list's features to have, each once. func addFeatures(have []string, list string) []string { for _, f := range strings.Split(strings.Trim(list, `"`), ",") { diff --git a/internal/gui/webview2_args_test.go b/internal/gui/webview2_args_test.go index d9a935c07..3e5949761 100644 --- a/internal/gui/webview2_args_test.go +++ b/internal/gui/webview2_args_test.go @@ -43,14 +43,14 @@ func TestWebView2ArgsMergeTheUsers(t *testing.T) { name, env string want []string }{ - {"none set", "", []string{"--disable-features=msSmartScreenProtection,IsolateSandboxedIframes"}}, + {"none set", "", []string{"--disable-features=msSmartScreenProtection,IsolateSandboxedIframes,CalculateNativeWinOcclusion"}}, {"the reporter's", "--disable-features=RendererCodeIntegrity", - []string{"--disable-features=msSmartScreenProtection,IsolateSandboxedIframes,RendererCodeIntegrity"}}, + []string{"--disable-features=msSmartScreenProtection,IsolateSandboxedIframes,RendererCodeIntegrity,CalculateNativeWinOcclusion"}}, {"twice, with magpie's own and a repeat", `--disable-features=A,msSmartScreenProtection --disable-features="B, A"`, - []string{"--disable-features=msSmartScreenProtection,IsolateSandboxedIframes,A,B"}}, + []string{"--disable-features=msSmartScreenProtection,IsolateSandboxedIframes,A,B,CalculateNativeWinOcclusion"}}, {"enable and others kept", " --enable-features=X,Y\t--remote-debugging-port=9333 --proxy-server=\"http://h:1 x\" --enable-features=Y,Z --lang=de ", - []string{"--disable-features=msSmartScreenProtection,IsolateSandboxedIframes", "--enable-features=X,Y,Z", "--remote-debugging-port=9333", `--proxy-server="http://h:1 x"`, "--lang=de"}}, - {"a bare switch", "--disable-features", []string{"--disable-features=msSmartScreenProtection,IsolateSandboxedIframes"}}, + []string{"--disable-features=msSmartScreenProtection,IsolateSandboxedIframes,CalculateNativeWinOcclusion", "--enable-features=X,Y,Z", "--remote-debugging-port=9333", `--proxy-server="http://h:1 x"`, "--lang=de"}}, + {"a bare switch", "--disable-features", []string{"--disable-features=msSmartScreenProtection,IsolateSandboxedIframes,CalculateNativeWinOcclusion"}}, } { t.Run(c.name, func(t *testing.T) { was := webview2env.Args @@ -126,6 +126,41 @@ func TestWebView2KeepsPluginFramesInTheWindowProcess(t *testing.T) { } } +// aquaarboraurum on X: a window shown while the screen is locked can stay +// white once Chromium's occlusion tracking has taken it as covered. +// magpie's WebView2 starts with the tracking off, once only; a user who +// turns it on keeps it. +func TestWebView2OcclusionTrackingOff(t *testing.T) { + was := webview2env.Args + t.Cleanup(func() { webview2env.Args = was }) + for _, c := range []struct { + env string + off, on int + }{ + {"", 1, 0}, + {"--disable-features=CalculateNativeWinOcclusion,A", 1, 0}, + {"--enable-features=CalculateNativeWinOcclusion", 0, 1}, + } { + webview2env.Args = c.env + args := wailsBrowserArgs(windowsOptions()) + var off, on int + for _, a := range args { + k, v, _ := strings.Cut(a, "=") + for _, f := range strings.Split(v, ",") { + if f == "CalculateNativeWinOcclusion" && k == "--disable-features" { + off++ + } + if f == "CalculateNativeWinOcclusion" && k == "--enable-features" { + on++ + } + } + } + if off != c.off || on != c.on { + t.Errorf("%q: WebView2 starts with %q: occlusion tracking disabled %d times, enabled %d, want %d and %d", c.env, args, off, on, c.off, c.on) + } + } +} + // Nothing in the defaults turns renderer code integrity off: only a user // who asks for it gets it (#2753). func TestWebView2KeepsCodeIntegrityByDefault(t *testing.T) { @@ -157,7 +192,7 @@ func TestWebView2ArgsSurviveWailsInit(t *testing.T) { if err != nil { t.Fatalf("child: %v\n%s", err, out) } - if !strings.Contains(string(out), `disabled=["IsolateSandboxedIframes" "RendererCodeIntegrity"]`) { + if !strings.Contains(string(out), `disabled=["IsolateSandboxedIframes" "RendererCodeIntegrity" "CalculateNativeWinOcclusion"]`) { t.Fatalf("the started value didn't reach the options:\n%s", out) } t.Logf("%s", strings.SplitN(string(out), "\n", 2)[0]) diff --git a/internal/gui/webviewmend_app.go b/internal/gui/webviewmend_app.go index 6b0eb5246..88652bca8 100644 --- a/internal/gui/webviewmend_app.go +++ b/internal/gui/webviewmend_app.go @@ -5,6 +5,7 @@ package gui import ( "log" "sync" + "sync/atomic" "time" "github.com/wailsapp/wails/v3/pkg/application" @@ -123,16 +124,33 @@ func (h *host) remakeWindow(w *application.WebviewWindow) { } // mendOnWake draws the open windows again after the computer wakes: a GPU -// that lost its device while asleep can leave WebView2's surface white. +// that lost its device while asleep can leave WebView2's surface white. And +// when the screen comes back without a sleep, unlocked or the display on +// again (screenBackFrom, Windows only): a window first shown while nobody +// could see it may keep a white surface (aquaarboraurum on X, after each +// restart to update, which AutoRestart makes while the user is away). func (h *host) mendOnWake() { h.app.Event.OnApplicationEvent(events.Common.SystemDidWake, func(*application.ApplicationEvent) { - application.InvokeAsync(func() { - for _, w := range []*application.WebviewWindow{h.main, h.panel} { - if w != nil && windowOpen(w) { - log.Printf("webview (%s window): the computer woke; drawing it again", w.Name()) - redrawShown(w) - } - } - }) + application.InvokeAsync(func() { h.redrawOpen("the computer woke") }) + }) + back := func(why string) { application.InvokeAsync(func() { h.redrawOpen(why) }) } + screenBack.Store(&back) + h.app.Event.OnApplicationEvent(events.Common.ApplicationStarted, func(*application.ApplicationEvent) { + application.InvokeAsync(watchScreenBack) }) } + +// screenBack is what the screen coming back does (mendOnWake), nil until +// the app is up. +var screenBack atomic.Pointer[func(why string)] + +// redrawOpen draws each open window again (redrawShown), saying why in the +// log; on the main thread. +func (h *host) redrawOpen(why string) { + for _, w := range []*application.WebviewWindow{h.main, h.panel} { + if w != nil && windowOpen(w) { + log.Printf("webview (%s window): %s; drawing it again", w.Name(), why) + redrawShown(w) + } + } +} diff --git a/internal/gui/webviewmend_other.go b/internal/gui/webviewmend_other.go index 2e7e3f3d1..cf62f3902 100644 --- a/internal/gui/webviewmend_other.go +++ b/internal/gui/webviewmend_other.go @@ -13,3 +13,8 @@ func webViewVisible(*application.WebviewWindow, bool) error { return nil } func reloadWebView(*application.WebviewWindow) error { return nil } func awaitBrowserGone() {} + +// The screen coming back is watched on Windows only (screenback_windows.go). +func watchScreenBack() {} + +var appWndProc func(hwnd uintptr, msg uint32, wParam, lParam uintptr) (uintptr, bool)