Files
core/gui/window/window_windows.go
T

705 lines
19 KiB
Go
Raw Normal View History

//go:build windows
package window
import (
"context"
"errors"
"fmt"
"net/http"
"runtime"
"sort"
"strings"
"sync"
"sync/atomic"
"syscall"
"time"
"unsafe"
"github.com/jchv/go-webview2/pkg/edge"
"golang.org/x/sys/windows"
"golang.org/x/sys/windows/registry"
)
// WebView2 needs every call on the thread that created it (STA, message
// loop). Lock the main goroutine to the main thread before main runs.
func init() { runtime.LockOSThread() }
// App origin on Windows. WebView2's WebResourceRequested intercepts this
// https URL before any network access; ".invalid" can never resolve, so a
// missed interception cannot reach a real host. Custom schemes would need
// ICoreWebView2EnvironmentOptions4, which pkg/edge does not pass.
const windowsOrigin = "https://yetano.invalid"
var (
user32 = windows.NewLazySystemDLL("user32.dll")
kernel32 = windows.NewLazySystemDLL("kernel32.dll")
pRegisterClassEx = user32.NewProc("RegisterClassExW")
pCreateWindowEx = user32.NewProc("CreateWindowExW")
pDefWindowProc = user32.NewProc("DefWindowProcW")
pShowWindow = user32.NewProc("ShowWindow")
pUpdateWindow = user32.NewProc("UpdateWindow")
pSetFocus = user32.NewProc("SetFocus")
pGetMessage = user32.NewProc("GetMessageW")
pPeekMessage = user32.NewProc("PeekMessageW")
pTranslate = user32.NewProc("TranslateMessage")
pDispatch = user32.NewProc("DispatchMessageW")
pPostMessage = user32.NewProc("PostMessageW")
pPostQuit = user32.NewProc("PostQuitMessage")
pDestroyWindow = user32.NewProc("DestroyWindow")
pIsWindow = user32.NewProc("IsWindow")
pLoadCursor = user32.NewProc("LoadCursorW")
pLoadIcon = user32.NewProc("LoadIconW")
pGetSysMetrics = user32.NewProc("GetSystemMetrics")
pGetModuleHandle = kernel32.NewProc("GetModuleHandleW")
dwmapi = windows.NewLazySystemDLL("dwmapi.dll")
pDwmSetAttribute = dwmapi.NewProc("DwmSetWindowAttribute")
pSetWindowPos = user32.NewProc("SetWindowPos")
pGetDpiForSystem = user32.NewProc("GetDpiForSystem")
)
func setAppIcon([]byte) {} // the icon comes from the .exe resources (RT_GROUP_ICON "APP")
const (
wmDestroy = 0x0002
wmMove = 0x0003
wmSize = 0x0005
wmClose = 0x0010
wmQuit = 0x0012
wmMoving = 0x0216
wmApp = 0x8000
pmRemove = 0x0001
swShow = 5
wsOverlapp = 0x00CF0000
)
type wndClassEx struct {
cbSize uint32
style uint32
lpfnWndProc uintptr
cbClsExtra int32
cbWndExtra int32
hInstance uintptr
hIcon uintptr
hCursor uintptr
hbrBackground uintptr
lpszMenuName *uint16
lpszClassName *uint16
hIconSm uintptr
}
type msgT struct {
hwnd uintptr
message uint32
wParam uintptr
lParam uintptr
time uint32
ptX int32
ptY int32
private uint32
}
var (
classOnce sync.Once
className *uint16
windowsMu sync.Mutex
byHWND = map[uintptr]*winBackend{}
)
func registerClass() {
classOnce.Do(func() {
className, _ = windows.UTF16PtrFromString("YetanoWebView")
hinst, _, _ := pGetModuleHandle.Call(0)
cursor, _, _ := pLoadCursor.Call(0, 32512) // IDC_ARROW
// The executable's own icon (gui/winres: RT_GROUP_ICON "APP"), else
// the stock application icon.
appName, _ := windows.UTF16PtrFromString("APP")
icon, _, _ := pLoadIcon.Call(hinst, uintptr(unsafe.Pointer(appName)))
if icon == 0 {
icon, _, _ = pLoadIcon.Call(0, 32512) // IDI_APPLICATION
}
wc := wndClassEx{
lpfnWndProc: windows.NewCallback(wndproc), hInstance: hinst, hCursor: cursor,
hIcon: icon, hIconSm: icon, lpszClassName: className, hbrBackground: 6, // COLOR_WINDOW+1
}
wc.cbSize = uint32(unsafe.Sizeof(wc))
pRegisterClassEx.Call(uintptr(unsafe.Pointer(&wc)))
})
}
type winBackend struct {
hwnd uintptr
chromium *edge.Chromium
opt Options
mu sync.Mutex
queue []func()
destroying bool
tasks taskTable
nextID atomic.Int64
}
func newBackend(opt Options) (backend, string, string, error) {
// A previous window in this process may still have teardown messages
// (including WM_QUIT) queued. pkg/edge's Embed waits for the controller
// with a GetMessage loop that gives up on WM_QUIT, so drain first.
if n := settle(200 * time.Millisecond); n > 0 && Debugf != nil {
Debugf("window: discarded %d WM_QUIT before creating a window", n)
}
registerClass()
b := &winBackend{opt: opt}
// The manifest declares per-monitor DPI awareness: sizes are physical
// pixels, so scale the requested (96-dpi) size.
if pGetDpiForSystem.Find() == nil {
if dpi, _, _ := pGetDpiForSystem.Call(); dpi > 96 {
opt.Width, opt.Height = opt.Width*int(dpi)/96, opt.Height*int(dpi)/96
}
}
title, _ := windows.UTF16PtrFromString(opt.Title)
sw, _, _ := pGetSysMetrics.Call(0) // SM_CXSCREEN
sh, _, _ := pGetSysMetrics.Call(1) // SM_CYSCREEN
x, y := (int(sw)-opt.Width)/2, (int(sh)-opt.Height)/2
hinst, _, _ := pGetModuleHandle.Call(0)
hwnd, _, err := pCreateWindowEx.Call(0, uintptr(unsafe.Pointer(className)), uintptr(unsafe.Pointer(title)),
wsOverlapp, uintptr(x), uintptr(y), uintptr(opt.Width), uintptr(opt.Height), 0, 0, hinst, 0)
if hwnd == 0 {
return nil, "", "", fmt.Errorf("window: CreateWindowEx: %v", err)
}
b.hwnd = hwnd
windowsMu.Lock()
byHWND[hwnd] = b
windowsMu.Unlock()
pShowWindow.Call(hwnd, swShow)
pUpdateWindow.Call(hwnd)
pSetFocus.Call(hwnd)
c := edge.NewChromium()
c.DataPath = opt.DataPath
c.MessageCallback = func(msg string) {
if opt.OnMessage != nil {
opt.OnMessage(msg)
}
}
if opt.Resource != nil {
c.WebResourceRequestedCallback = b.onResource
}
b.chromium = c
if !c.Embed(hwnd) {
b.Destroy()
return nil, "", "", errors.New("window: WebView2 could not be created (is the Microsoft Edge WebView2 Runtime installed?)")
}
c.Resize()
if s, err := c.GetSettings(); err == nil {
_ = s.PutAreDevToolsEnabled(opt.Debug)
_ = s.PutAreDefaultContextMenusEnabled(opt.Debug)
}
if opt.Resource != nil {
c.AddWebResourceRequestedFilter(windowsOrigin+"/*", edge.COREWEBVIEW2_WEB_RESOURCE_CONTEXT_ALL)
}
b.Init(postShimWindows)
return b, "win32/WebView2", windowsOrigin, nil
}
func wndproc(hwnd, msg, wp, lp uintptr) uintptr {
windowsMu.Lock()
b := byHWND[hwnd]
windowsMu.Unlock()
if b != nil {
switch msg {
case wmSize:
if b.chromium != nil {
b.chromium.Resize()
}
case wmMove, wmMoving:
if b.chromium != nil {
_ = b.chromium.NotifyParentWindowPositionChanged()
}
case wmApp:
b.runQueue()
return 0
case wmClose:
pDestroyWindow.Call(hwnd)
return 0
case wmDestroy:
b.mu.Lock()
programmatic := b.destroying
b.mu.Unlock()
if !programmatic {
pPostQuit.Call(0) // user closed the window: end Run
}
return 0
}
}
r, _, _ := pDefWindowProc.Call(hwnd, msg, wp, lp)
return r
}
func (b *winBackend) runQueue() {
b.mu.Lock()
q := b.queue
b.queue = nil
b.mu.Unlock()
for _, f := range q {
f()
}
}
func (b *winBackend) Init(js string) { b.chromium.Init(js) }
func (b *winBackend) Navigate(url string) { b.chromium.Navigate(url) }
func (b *winBackend) Eval(js string) { b.chromium.Eval(js) }
func (b *winBackend) Terminate() { pPostQuit.Call(0) }
// Dispatch posts to the window (not the thread), so closures also run while
// a modal loop (move/resize) is active.
func (b *winBackend) Dispatch(f func()) {
b.mu.Lock()
b.queue = append(b.queue, f)
b.mu.Unlock()
pPostMessage.Call(b.hwnd, wmApp, 0, 0)
}
func (b *winBackend) Run() {
var m msgT
for {
r, _, _ := pGetMessage.Call(uintptr(unsafe.Pointer(&m)), 0, 0, 0)
if int32(r) <= 0 {
return
}
pTranslate.Call(uintptr(unsafe.Pointer(&m)))
pDispatch.Call(uintptr(unsafe.Pointer(&m)))
}
}
// Destroy destroys the window synchronously (WebView2 is torn down with
// its parent) and pumps the remaining messages.
func (b *winBackend) Destroy() {
b.tasks.cancelAll()
b.mu.Lock()
b.destroying = true
b.mu.Unlock()
if ok, _, _ := pIsWindow.Call(b.hwnd); ok != 0 {
pDestroyWindow.Call(b.hwnd)
}
windowsMu.Lock()
delete(byHWND, b.hwnd)
windowsMu.Unlock()
if n := settle(200 * time.Millisecond); n > 0 && Debugf != nil {
Debugf("window: discarded %d WM_QUIT after destroy", n)
}
}
// settle pumps this thread's queue for d, dispatching normal messages and
// discarding WM_QUIT. It returns the number of WM_QUIT seen.
func settle(d time.Duration) int {
quits := 0
end := time.Now().Add(d)
var m msgT
for time.Now().Before(end) {
r, _, _ := pPeekMessage.Call(uintptr(unsafe.Pointer(&m)), 0, 0, 0, pmRemove)
if r == 0 {
time.Sleep(5 * time.Millisecond)
continue
}
if m.message == wmQuit {
quits++
continue
}
pTranslate.Call(uintptr(unsafe.Pointer(&m)))
pDispatch.Call(uintptr(unsafe.Pointer(&m)))
}
return quits
}
// ---- appearance ---------------------------------------------------------
// SetAppearance switches the title bar between light and dark
// (DWMWA_USE_IMMERSIVE_DARK_MODE). "system" follows the "app mode" setting.
func (b *winBackend) SetAppearance(mode string) {
dark := mode == "dark"
if mode != "light" && mode != "dark" {
dark = systemDark()
}
var v int32
if dark {
v = 1
}
const dwmwaUseImmersiveDarkMode = 20
pDwmSetAttribute.Call(b.hwnd, dwmwaUseImmersiveDarkMode, uintptr(unsafe.Pointer(&v)), 4)
// Redraw the non-client area so the change shows immediately.
const swpFlags = 0x0001 | 0x0002 | 0x0004 | 0x0010 | 0x0020 // NOSIZE|NOMOVE|NOZORDER|NOACTIVATE|FRAMECHANGED
pSetWindowPos.Call(b.hwnd, 0, 0, 0, 0, 0, swpFlags)
}
func systemDark() bool {
k, err := registry.OpenKey(registry.CURRENT_USER, `Software\Microsoft\Windows\CurrentVersion\Themes\Personalize`, registry.QUERY_VALUE)
if err != nil {
return false
}
defer k.Close()
v, _, err := k.GetIntegerValue("AppsUseLightTheme")
return err == nil && v == 0
}
// accentColor reads the accent color Windows uses for window chrome
// (HKCU\Software\Microsoft\Windows\DWM\AccentColor, 0xAABBGGRR).
func accentColor() string {
k, err := registry.OpenKey(registry.CURRENT_USER, `Software\Microsoft\Windows\DWM`, registry.QUERY_VALUE)
if err != nil {
return ""
}
defer k.Close()
v, _, err := k.GetIntegerValue("AccentColor")
if err != nil {
return ""
}
return fmt.Sprintf("#%02X%02X%02X", v&0xff, v>>8&0xff, v>>16&0xff)
}
// ---- raw COM helpers ----------------------------------------------------
func comCall(obj unsafe.Pointer, slot int, args ...uintptr) uintptr {
vtbl := *(*unsafe.Pointer)(obj)
fn := *(*uintptr)(unsafe.Add(vtbl, slot*int(unsafe.Sizeof(uintptr(0)))))
r, _, _ := syscall.SyscallN(fn, append([]uintptr{uintptr(obj)}, args...)...)
return r
}
func comRelease(obj unsafe.Pointer) {
if obj != nil {
comCall(obj, 2)
}
}
func coString(p *uint16) string {
if p == nil {
return ""
}
s := windows.UTF16PtrToString(p)
windows.CoTaskMemFree(unsafe.Pointer(p))
return s
}
// vtable slots, from WebView2.h
const (
argsPutResponse = 5
argsGetDeferral = 6
deferralComplete = 3
reqGetMethod = 5
reqGetContent = 7
reqGetHeaders = 9
hdrGetIterator = 8
iterGetCurrent = 3
iterHasCurrent = 4
iterMoveNext = 5
envCreateResponse = 4
streamRead = 3
)
// onResource runs on the UI thread for every request to windowsOrigin.
func (b *winBackend) onResource(req *edge.ICoreWebView2WebResourceRequest, args *edge.ICoreWebView2WebResourceRequestedEventArgs) {
rp, ap := unsafe.Pointer(req), unsafe.Pointer(args)
uri, _ := req.GetUri()
var method *uint16
comCall(rp, reqGetMethod, uintptr(unsafe.Pointer(&method)))
rr := &ResourceRequest{Method: coString(method), URL: uri, Header: http.Header{}}
var headers unsafe.Pointer
if comCall(rp, reqGetHeaders, uintptr(unsafe.Pointer(&headers))) == 0 && headers != nil {
var it unsafe.Pointer
if comCall(headers, hdrGetIterator, uintptr(unsafe.Pointer(&it))) == 0 && it != nil {
for {
var has int32
comCall(it, iterHasCurrent, uintptr(unsafe.Pointer(&has)))
if has == 0 {
break
}
var n, v *uint16
comCall(it, iterGetCurrent, uintptr(unsafe.Pointer(&n)), uintptr(unsafe.Pointer(&v)))
rr.Header.Add(coString(n), coString(v))
var more int32
comCall(it, iterMoveNext, uintptr(unsafe.Pointer(&more)))
}
comRelease(it)
}
comRelease(headers)
}
var content unsafe.Pointer
if comCall(rp, reqGetContent, uintptr(unsafe.Pointer(&content))) == 0 && content != nil {
buf := make([]byte, 64<<10)
for {
var n uint32
hr := comCall(content, streamRead, uintptr(unsafe.Pointer(&buf[0])), uintptr(len(buf)), uintptr(unsafe.Pointer(&n)))
rr.Body = append(rr.Body, buf[:n]...)
if hr != 0 || n == 0 {
break
}
}
comRelease(content)
}
var deferral unsafe.Pointer
comCall(ap, argsGetDeferral, uintptr(unsafe.Pointer(&deferral)))
comCall(ap, 1) // AddRef: args outlive this callback until the response is set
ctx, cancel := context.WithCancel(context.Background())
id := b.nextID.Add(1)
b.tasks.add(id, cancel)
t := &winTask{b: b, args: ap, deferral: deferral, stream: newGoStream()}
// WebView2 has no cancel notification for intercepted requests; the
// closest signal is the page dropping the response stream.
t.stream.onDrop = func() { b.tasks.cancel(id) }
go func() {
defer b.tasks.cancel(id)
b.opt.Resource(ctx, rr, t)
t.Close(nil)
}()
}
// winTask answers one intercepted request. Respond completes the deferral
// with a response whose body is a goStream; Write feeds that stream, so the
// page receives data as it is written.
type winTask struct {
b *winBackend
args unsafe.Pointer
deferral unsafe.Pointer
stream *goStream
mu sync.Mutex
responded bool
closed bool
}
func (t *winTask) Respond(status int, header http.Header) {
t.mu.Lock()
if t.responded {
t.mu.Unlock()
return
}
t.responded = true
t.mu.Unlock()
var hs []string
for k, v := range header {
for _, x := range v {
hs = append(hs, k+": "+x)
}
}
sort.Strings(hs)
reason := http.StatusText(status)
t.b.Dispatch(func() {
env := unsafe.Pointer(t.b.chromium.Environment())
r16, _ := windows.UTF16PtrFromString(reason)
h16, _ := windows.UTF16PtrFromString(strings.Join(hs, "\r\n"))
var resp unsafe.Pointer
hr := comCall(env, envCreateResponse, uintptr(t.stream.ptr()), uintptr(status),
uintptr(unsafe.Pointer(r16)), uintptr(unsafe.Pointer(h16)), uintptr(unsafe.Pointer(&resp)))
if hr == 0 && resp != nil {
comCall(t.args, argsPutResponse, uintptr(resp))
comRelease(resp)
} else if Debugf != nil {
Debugf("window: CreateWebResourceResponse failed: 0x%08x", hr)
}
comCall(t.deferral, deferralComplete)
comRelease(t.deferral)
comRelease(t.args)
t.stream.release() // our own reference; WebView2 holds its own
})
}
func (t *winTask) Write(p []byte) (int, error) {
t.mu.Lock()
responded := t.responded
t.mu.Unlock()
if !responded {
t.Respond(http.StatusOK, nil)
}
return t.stream.write(p)
}
func (t *winTask) Close(err error) {
t.mu.Lock()
if t.closed {
t.mu.Unlock()
return
}
t.closed = true
responded := t.responded
t.mu.Unlock()
if !responded {
if err != nil {
t.Respond(http.StatusBadGateway, nil)
} else {
t.Respond(http.StatusNoContent, nil)
}
}
t.stream.finish()
}
// ---- goStream: a COM IStream whose Read blocks on Go-written chunks -------
type istreamVtbl struct {
QueryInterface, AddRef, Release uintptr
Read, Write, Seek, SetSize, CopyTo, Commit, Revert, Lock, Unlock uintptr
Stat, Clone uintptr
}
type goStream struct {
vtbl *istreamVtbl // must be first: COM object layout
refs atomic.Int32
mu sync.Mutex
cond *sync.Cond
buf []byte
eof bool
pos uint64
pin runtime.Pinner
// onDrop runs when WebView2 released the last reference: the page no
// longer reads the body (finished or aborted).
onDrop func()
}
var (
streamVtbl *istreamVtbl
streamsMu sync.Mutex
liveStreams = map[uintptr]*goStream{}
iidIUnknown = windows.GUID{Data1: 0x00000000, Data2: 0x0000, Data3: 0x0000, Data4: [8]byte{0xC0, 0, 0, 0, 0, 0, 0, 0x46}}
iidSeqStrm = windows.GUID{Data1: 0x0c733a30, Data2: 0x2a1c, Data3: 0x11ce, Data4: [8]byte{0xad, 0xe5, 0x00, 0xaa, 0x00, 0x44, 0x77, 0x3d}}
iidIStream = windows.GUID{Data1: 0x0000000c, Data2: 0x0000, Data3: 0x0000, Data4: [8]byte{0xC0, 0, 0, 0, 0, 0, 0, 0x46}}
)
const (
sOK = 0
sFalse = 1
eNotImpl = 0x80004001
eNoIface = 0x80004002
stgInvFunc = 0x80030001
)
func initStreamVtbl() {
if streamVtbl != nil {
return
}
notImpl := windows.NewCallback(func(this uintptr) uintptr { return eNotImpl })
notImpl2 := windows.NewCallback(func(this, a uintptr) uintptr { return eNotImpl })
notImpl3 := windows.NewCallback(func(this, a, b uintptr) uintptr { return eNotImpl })
notImpl4 := windows.NewCallback(func(this, a, b, c uintptr) uintptr { return eNotImpl })
streamVtbl = &istreamVtbl{
QueryInterface: windows.NewCallback(func(this uintptr, riid *windows.GUID, out *uintptr) uintptr {
if *riid == iidIUnknown || *riid == iidSeqStrm || *riid == iidIStream {
*out = this
lookupStream(this).refs.Add(1)
return sOK
}
*out = 0
return eNoIface
}),
AddRef: windows.NewCallback(func(this uintptr) uintptr { return uintptr(lookupStream(this).refs.Add(1)) }),
Release: windows.NewCallback(func(this uintptr) uintptr {
s := lookupStream(this)
n := s.refs.Add(-1)
if n == 0 {
s.drop()
}
return uintptr(n)
}),
// WebView2 calls Read on a background thread and reads to EOF before
// the page sees any byte (measured: no incremental delivery, and
// E_PENDING fails the request). Blocking here is therefore fine,
// but it is not a streaming path.
Read: windows.NewCallback(func(this uintptr, pv *byte, cb uint32, pcbRead *uint32) uintptr {
n := lookupStream(this).read(unsafe.Slice(pv, cb))
if pcbRead != nil {
*pcbRead = uint32(n)
}
if n == 0 {
return sFalse
}
return sOK
}),
Write: notImpl4,
Seek: windows.NewCallback(func(this uintptr, move int64, origin uint32, newPos *uint64) uintptr {
s := lookupStream(this)
if origin == 1 && move == 0 { // STREAM_SEEK_CUR, 0: tell
if newPos != nil {
s.mu.Lock()
*newPos = s.pos
s.mu.Unlock()
}
return sOK
}
return stgInvFunc
}),
SetSize: notImpl2,
CopyTo: notImpl4,
Commit: notImpl2,
Revert: notImpl,
Lock: notImpl4,
Unlock: notImpl4,
Stat: notImpl3,
Clone: notImpl2,
}
}
func newGoStream() *goStream {
streamsMu.Lock()
initStreamVtbl()
s := &goStream{vtbl: streamVtbl}
s.cond = sync.NewCond(&s.mu)
s.refs.Store(1) // ours, released after the response was handed over
s.pin.Pin(s)
liveStreams[uintptr(unsafe.Pointer(s))] = s
streamsMu.Unlock()
return s
}
func lookupStream(p uintptr) *goStream {
streamsMu.Lock()
defer streamsMu.Unlock()
return liveStreams[p]
}
func (s *goStream) ptr() unsafe.Pointer { return unsafe.Pointer(s) }
func (s *goStream) release() {
if s.refs.Add(-1) == 0 {
s.drop()
}
}
func (s *goStream) drop() {
s.finish()
if s.onDrop != nil {
go s.onDrop()
}
streamsMu.Lock()
delete(liveStreams, uintptr(unsafe.Pointer(s)))
streamsMu.Unlock()
s.pin.Unpin()
}
func (s *goStream) write(p []byte) (int, error) {
s.mu.Lock()
defer s.mu.Unlock()
if s.eof {
return 0, context.Canceled
}
s.buf = append(s.buf, p...)
s.cond.Broadcast()
return len(p), nil
}
func (s *goStream) finish() {
s.mu.Lock()
s.eof = true
s.cond.Broadcast()
s.mu.Unlock()
}
// read blocks until data or EOF; it returns what is available (at most len
// p), so chunks reach the page as soon as they are written.
func (s *goStream) read(p []byte) int {
s.mu.Lock()
defer s.mu.Unlock()
for len(s.buf) == 0 && !s.eof {
s.cond.Wait()
}
n := copy(p, s.buf)
s.buf = s.buf[n:]
s.pos += uint64(n)
return n
}