Files
magpie/internal/gui/zoom_windows_arm64.go
T
yetone d159314e35 gui: a hidden window's WebView2 goes on its low memory target on Windows
molamaker11 on X: "magpie后台占用快接近600MB了。win端 这个能优化一下吗。比如剔除一些动画".

Cause. On Windows the tray panel and the main window are both made at
start and only hidden when closed, so two WebView2 renderers, the GPU
process and the browser process stay up in the tray. They were kept at
WebView2's normal memory target, so a hidden window held what it last
drew: after the window had been open, the GPU process kept ~85 MB and the
main renderer ~70 MB. Animations are not the cost: hidden pages run no
layout or style (LayoutCount/RecalcStyleCount 0 over CDP), the JS heaps
are 5 to 8 MB each, and the Go process is ~40 MB private (liveHeap 25 MB).

Fix. lowWhileHidden (memtarget_windows.go) sets
ICoreWebView2_19::put_MemoryUsageTargetLevel to LOW on each hide and on a
page that comes while the window is hidden (both windows are made hidden,
and get no hide), and back to NORMAL on each show. The page stays loaded
and running, unlike lightweight mode, whose default the owner turned off
on 10-21 because reopening reloaded the page. The vtable slot is 120:
ICoreWebView2_19's vtable holds every inherited method, counted in
WebView2.h of SDK 1.0.2210.55 (a first build that used slot 4 called
get_Source and crashed at start). zoom_windows_arm64.go's reflection walk
to the controller is now chromiumPart, shared with it. macOS and Linux:
WKWebView and WebKitGTK have no memory target magpie can set, so
memtarget_other.go is a no-op.

Numbers. xiaomi-gpu, Windows 11, WebView2 156.0.4314.50, a release build
of each (-tags production,comlauncher -H windowsgui) in its own sandbox
profile with the same seeded sessions and usage (~248 MB of Claude
projects, 72 Codex rollouts, a 4.2 MB usage.jsonl), tray start. The whole
process tree (magpie plus msedgewebview2), private working set (Task
Manager's Memory column) / commit, MB:

                                       v0.1.2297     this change
  fresh tray, window never opened      205-209/316-332   81/323
  window open, every page clicked      304/482          236/467
  1 min after closing it               265/479           69/459
  5 min after closing it               ~203/~476         64/453
  idle 15-30 min later (sampled /5min) 200-214/474-481   -

  1 min after closing, by process: GPU 85 -> 2.6, main renderer 70 ->
  7.3, panel renderer ~50 -> 1.3, browser ~30 -> 6.2; magpie itself
  ~47 either way.

The commit charge barely moves: WebView2 trims the pages out of RAM to
the standby list and the page file rather than freeing them, so the
saving is RAM other apps get, not address space.

Reopening. Three trials, each window closed 3 to 5 minutes first, the
time for a view switch and two frames over CDP: the first trial took
901 ms on the first switch after reopening (v0.1.2297: 47 ms), then
12 to 31 ms; the other two trials were the same on both builds (first
frame 132 vs 131 ms, first switch 28 vs 30 ms, then 9 to 46 ms either
way).

Run: gofmt -l internal/gui (clean); on mote GOOS=windows go vet ./...,
GOOS=windows GOARCH=arm64 go vet ./internal/gui, GOOS=linux go vet -tags
nogui ./..., go vet ./..., go build; go test -timeout 45m ./... on this
tree (057c21b30, this commit with a draft message, on 91ffe5429): 80 packages ok, internal/gui and
internal/proc red. proc: TestNoCommandBypassesProc on
internal/claudetui/child_unix.go (c59c547c5, #4491). gui: ten AppKit
tests killed at their 30s bar on mote (#4125; TestDockJoinLeadsCommandTab,
TestPanelCloseHidesIt, TestCoveredWindowStaysUp and TestMainWindowCorners
red the same at 91ffe5429 alone) and TestSettingsSaveKeepsWhatItDoesNotSend
(#4514, red at 91ffe5429 too). This change adds no code to darwin; win-run go test ./internal/gui at this head: 6 red, the
same 6 at its parent 91ffe5429 run alone (TestGatewayHeldByAContainer,
#2107/#4115; TestLodyImportHandoff, TestImportStatusUnreadableIsUnknown,
TestAionUiImportRow, TestUpdateThatWontStart, #4115;
TestSettingsSaveKeepsWhatItDoesNotSend, #4514).

Not tried: a real user's profile with plugins (no bun/node host ran in
the sandbox) or signed-in accounts; an idle of many hours on the fix
build (#2515's 28h growth); Windows on arm64 (built and vetted, not run);
a WebView2 older than 1.0.2210, which answers E_NOINTERFACE and is
logged and left alone. No unit test: the call needs a live WebView2; it was checked on the box
by the numbers above. No GUI suite: app.js is unchanged.
2026-10-31 10:57:56 +08:00

109 lines
3.6 KiB
Go
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
//go:build windows && arm64 && !nogui
package gui
import (
"errors"
"fmt"
"log"
"math"
"sync"
"syscall"
"unsafe"
"github.com/wailsapp/wails/v3/pkg/application"
"golang.org/x/sys/windows"
)
// setPageZoom zooms w's page to z, the text size. On Windows on ARM,
// Wails' SetZoom (and the Zoom option a window is made with) never reaches
// the page: WebView2's put_ZoomFactor takes its double by value, which the
// ARM64 ABI passes in d0, and Go's syscall fills only x0–x7
// (golang.org/issue/62583), so Wails refuses the call and only logs it. The
// choice was saved and shown picked, and the page stayed at 100% (#2212).
// magpie makes the call itself, through a two-instruction thunk that moves
// the double's bits from x1 into d0.
func setPageZoom(w *application.WebviewWindow, z float64) {
if err := putZoomFactor(w, z); err != nil {
log.Println("text size:", err)
}
}
// zoomsAfterLoad: a window's Zoom option is lost here, so its text size is
// put on its page once WebView2 has made the page's controller.
const zoomsAfterLoad = true
// putZoomFactor calls ICoreWebView2Controller::put_ZoomFactor(z) on w's
// WebView2 controller.
func putZoomFactor(w *application.WebviewWindow, z float64) error {
ctrl := webviewController(w)
if ctrl == nil {
return errors.New("no WebView2 controller yet")
}
thunk, err := doubleThunk()
if err != nil {
return err
}
// ICoreWebView2ControllerVtbl: QueryInterface, AddRef, Release,
// get_IsVisible, put_IsVisible, get_Bounds, put_Bounds,
// get_ZoomFactor, put_ZoomFactor (WebView2.h; Wails'
// ICoreWebView2ControllerVtbl in the same order)
const putZoomFactorSlot = 8
vtbl := *(*unsafe.Pointer)(ctrl)
fn := *(*uintptr)(unsafe.Add(vtbl, putZoomFactorSlot*unsafe.Sizeof(uintptr(0))))
hr, _, _ := syscall.SyscallN(thunk, uintptr(ctrl), uintptr(math.Float64bits(z)), fn)
if int32(hr) < 0 {
return fmt.Errorf("put_ZoomFactor(%g): %w", z, windows.Errno(hr))
}
return nil
}
// webviewController is w's ICoreWebView2Controller, nil before WebView2
// has made it (chromiumPart). A Wails without it gives nil, and the text
// size stays as Wails left it.
func webviewController(w *application.WebviewWindow) unsafe.Pointer {
return chromiumPart(w, "controller")
}
var (
flushInstructionCache = windows.NewLazySystemDLL("kernel32.dll").NewProc("FlushInstructionCache")
thunkOnce sync.Once
thunkAddr uintptr
thunkErr error
)
// doubleThunk is code that calls x2 with x0 as it is and the bits in x1 as
// the double in d0, so a COM method taking (this, double) is called as
// SyscallN(thunk, this, bits, method):
//
// fmov d0, x1
// br x2
//
// br leaves the return address the caller's bl put in x30, so the method
// returns straight to Go's asmstdcall with its HRESULT in x0.
func doubleThunk() (uintptr, error) {
thunkOnce.Do(func() {
code := []uint32{0x9E670020, 0xD61F0040}
size := uintptr(len(code) * 4)
addr, err := windows.VirtualAlloc(0, size, windows.MEM_COMMIT|windows.MEM_RESERVE, windows.PAGE_READWRITE)
if err != nil {
thunkErr = fmt.Errorf("VirtualAlloc: %w", err)
return
}
// addr is memory VirtualAlloc gave, not Go's
copy(unsafe.Slice((*uint32)(*(*unsafe.Pointer)(unsafe.Pointer(&addr))), len(code)), code)
var old uint32
if err := windows.VirtualProtect(addr, size, windows.PAGE_EXECUTE_READ, &old); err != nil {
thunkErr = fmt.Errorf("VirtualProtect: %w", err)
return
}
if ok, _, err := flushInstructionCache.Call(uintptr(windows.CurrentProcess()), addr, size); ok == 0 {
thunkErr = fmt.Errorf("FlushInstructionCache: %w", err)
return
}
thunkAddr = addr
})
return thunkAddr, thunkErr
}