-
Notifications
You must be signed in to change notification settings - Fork 64
/
webview.go
482 lines (425 loc) · 12 KB
/
webview.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
//go:build windows
// +build windows
package webview2
import (
"encoding/json"
"errors"
"log"
"reflect"
"strconv"
"sync"
"unsafe"
"github.com/jchv/go-webview2/internal/w32"
"github.com/jchv/go-webview2/pkg/edge"
"golang.org/x/sys/windows"
)
var (
windowContext = map[uintptr]interface{}{}
windowContextSync sync.RWMutex
)
func getWindowContext(wnd uintptr) interface{} {
windowContextSync.RLock()
defer windowContextSync.RUnlock()
return windowContext[wnd]
}
func setWindowContext(wnd uintptr, data interface{}) {
windowContextSync.Lock()
defer windowContextSync.Unlock()
windowContext[wnd] = data
}
type browser interface {
Embed(hwnd uintptr) bool
Resize()
Navigate(url string)
NavigateToString(htmlContent string)
Init(script string)
Eval(script string)
NotifyParentWindowPositionChanged() error
Focus()
}
type webview struct {
hwnd uintptr
mainthread uintptr
browser browser
autofocus bool
maxsz w32.Point
minsz w32.Point
m sync.Mutex
bindings map[string]interface{}
dispatchq []func()
}
type WindowOptions struct {
Title string
Width uint
Height uint
IconId uint
Center bool
}
type WebViewOptions struct {
Window unsafe.Pointer
Debug bool
// DataPath specifies the datapath for the WebView2 runtime to use for the
// browser instance.
DataPath string
// AutoFocus will try to keep the WebView2 widget focused when the window
// is focused.
AutoFocus bool
// WindowOptions customizes the window that is created to embed the
// WebView2 widget.
WindowOptions WindowOptions
}
// New creates a new webview in a new window.
func New(debug bool) WebView { return NewWithOptions(WebViewOptions{Debug: debug}) }
// NewWindow creates a new webview using an existing window.
//
// Deprecated: Use NewWithOptions.
func NewWindow(debug bool, window unsafe.Pointer) WebView {
return NewWithOptions(WebViewOptions{Debug: debug, Window: window})
}
// NewWithOptions creates a new webview using the provided options.
func NewWithOptions(options WebViewOptions) WebView {
w := &webview{}
w.bindings = map[string]interface{}{}
w.autofocus = options.AutoFocus
chromium := edge.NewChromium()
chromium.MessageCallback = w.msgcb
chromium.DataPath = options.DataPath
chromium.SetPermission(edge.CoreWebView2PermissionKindClipboardRead, edge.CoreWebView2PermissionStateAllow)
w.browser = chromium
w.mainthread, _, _ = w32.Kernel32GetCurrentThreadID.Call()
if !w.CreateWithOptions(options.WindowOptions) {
return nil
}
settings, err := chromium.GetSettings()
if err != nil {
log.Fatal(err)
}
// disable context menu
err = settings.PutAreDefaultContextMenusEnabled(options.Debug)
if err != nil {
log.Fatal(err)
}
// disable developer tools
err = settings.PutAreDevToolsEnabled(options.Debug)
if err != nil {
log.Fatal(err)
}
return w
}
type rpcMessage struct {
ID int `json:"id"`
Method string `json:"method"`
Params []json.RawMessage `json:"params"`
}
func jsString(v interface{}) string { b, _ := json.Marshal(v); return string(b) }
func (w *webview) msgcb(msg string) {
d := rpcMessage{}
if err := json.Unmarshal([]byte(msg), &d); err != nil {
log.Printf("invalid RPC message: %v", err)
return
}
id := strconv.Itoa(d.ID)
if res, err := w.callbinding(d); err != nil {
w.Dispatch(func() {
w.Eval("window._rpc[" + id + "].reject(" + jsString(err.Error()) + "); window._rpc[" + id + "] = undefined")
})
} else if b, err := json.Marshal(res); err != nil {
w.Dispatch(func() {
w.Eval("window._rpc[" + id + "].reject(" + jsString(err.Error()) + "); window._rpc[" + id + "] = undefined")
})
} else {
w.Dispatch(func() {
w.Eval("window._rpc[" + id + "].resolve(" + string(b) + "); window._rpc[" + id + "] = undefined")
})
}
}
func (w *webview) callbinding(d rpcMessage) (interface{}, error) {
w.m.Lock()
f, ok := w.bindings[d.Method]
w.m.Unlock()
if !ok {
return nil, nil
}
v := reflect.ValueOf(f)
isVariadic := v.Type().IsVariadic()
numIn := v.Type().NumIn()
if (isVariadic && len(d.Params) < numIn-1) || (!isVariadic && len(d.Params) != numIn) {
return nil, errors.New("function arguments mismatch")
}
args := []reflect.Value{}
for i := range d.Params {
var arg reflect.Value
if isVariadic && i >= numIn-1 {
arg = reflect.New(v.Type().In(numIn - 1).Elem())
} else {
arg = reflect.New(v.Type().In(i))
}
if err := json.Unmarshal(d.Params[i], arg.Interface()); err != nil {
return nil, err
}
args = append(args, arg.Elem())
}
errorType := reflect.TypeOf((*error)(nil)).Elem()
res := v.Call(args)
switch len(res) {
case 0:
// No results from the function, just return nil
return nil, nil
case 1:
// One result may be a value, or an error
if res[0].Type().Implements(errorType) {
if res[0].Interface() != nil {
return nil, res[0].Interface().(error)
}
return nil, nil
}
return res[0].Interface(), nil
case 2:
// Two results: first one is value, second is error
if !res[1].Type().Implements(errorType) {
return nil, errors.New("second return value must be an error")
}
if res[1].Interface() == nil {
return res[0].Interface(), nil
}
return res[0].Interface(), res[1].Interface().(error)
default:
return nil, errors.New("unexpected number of return values")
}
}
func wndproc(hwnd, msg, wp, lp uintptr) uintptr {
if w, ok := getWindowContext(hwnd).(*webview); ok {
switch msg {
case w32.WMMove, w32.WMMoving:
_ = w.browser.NotifyParentWindowPositionChanged()
case w32.WMNCLButtonDown:
_, _, _ = w32.User32SetFocus.Call(w.hwnd)
r, _, _ := w32.User32DefWindowProcW.Call(hwnd, msg, wp, lp)
return r
case w32.WMSize:
w.browser.Resize()
case w32.WMActivate:
if wp == w32.WAInactive {
break
}
if w.autofocus {
w.browser.Focus()
}
case w32.WMClose:
_, _, _ = w32.User32DestroyWindow.Call(hwnd)
case w32.WMDestroy:
w.Terminate()
case w32.WMGetMinMaxInfo:
lpmmi := (*w32.MinMaxInfo)(unsafe.Pointer(lp))
if w.maxsz.X > 0 && w.maxsz.Y > 0 {
lpmmi.PtMaxSize = w.maxsz
lpmmi.PtMaxTrackSize = w.maxsz
}
if w.minsz.X > 0 && w.minsz.Y > 0 {
lpmmi.PtMinTrackSize = w.minsz
}
default:
r, _, _ := w32.User32DefWindowProcW.Call(hwnd, msg, wp, lp)
return r
}
return 0
}
r, _, _ := w32.User32DefWindowProcW.Call(hwnd, msg, wp, lp)
return r
}
func (w *webview) Create(debug bool, window unsafe.Pointer) bool {
// This function signature stopped making sense a long time ago.
// It is but legacy cruft at this point.
return w.CreateWithOptions(WindowOptions{})
}
func (w *webview) CreateWithOptions(opts WindowOptions) bool {
var hinstance windows.Handle
_ = windows.GetModuleHandleEx(0, nil, &hinstance)
var icon uintptr
if opts.IconId == 0 {
// load default icon
icow, _, _ := w32.User32GetSystemMetrics.Call(w32.SystemMetricsCxIcon)
icoh, _, _ := w32.User32GetSystemMetrics.Call(w32.SystemMetricsCyIcon)
icon, _, _ = w32.User32LoadImageW.Call(uintptr(hinstance), 32512, icow, icoh, 0)
} else {
// load icon from resource
icon, _, _ = w32.User32LoadImageW.Call(uintptr(hinstance), uintptr(opts.IconId), 1, 0, 0, w32.LR_DEFAULTSIZE|w32.LR_SHARED)
}
className, _ := windows.UTF16PtrFromString("webview")
wc := w32.WndClassExW{
CbSize: uint32(unsafe.Sizeof(w32.WndClassExW{})),
HInstance: hinstance,
LpszClassName: className,
HIcon: windows.Handle(icon),
HIconSm: windows.Handle(icon),
LpfnWndProc: windows.NewCallback(wndproc),
}
_, _, _ = w32.User32RegisterClassExW.Call(uintptr(unsafe.Pointer(&wc)))
windowName, _ := windows.UTF16PtrFromString(opts.Title)
windowWidth := opts.Width
if windowWidth == 0 {
windowWidth = 640
}
windowHeight := opts.Height
if windowHeight == 0 {
windowHeight = 480
}
var posX, posY uint
if opts.Center {
// get screen size
screenWidth, _, _ := w32.User32GetSystemMetrics.Call(w32.SM_CXSCREEN)
screenHeight, _, _ := w32.User32GetSystemMetrics.Call(w32.SM_CYSCREEN)
// calculate window position
posX = (uint(screenWidth) - windowWidth) / 2
posY = (uint(screenHeight) - windowHeight) / 2
} else {
// use default position
posX = w32.CW_USEDEFAULT
posY = w32.CW_USEDEFAULT
}
w.hwnd, _, _ = w32.User32CreateWindowExW.Call(
0,
uintptr(unsafe.Pointer(className)),
uintptr(unsafe.Pointer(windowName)),
0xCF0000, // WS_OVERLAPPEDWINDOW
uintptr(posX),
uintptr(posY),
uintptr(windowWidth),
uintptr(windowHeight),
0,
0,
uintptr(hinstance),
0,
)
setWindowContext(w.hwnd, w)
_, _, _ = w32.User32ShowWindow.Call(w.hwnd, w32.SWShow)
_, _, _ = w32.User32UpdateWindow.Call(w.hwnd)
_, _, _ = w32.User32SetFocus.Call(w.hwnd)
if !w.browser.Embed(w.hwnd) {
return false
}
w.browser.Resize()
return true
}
func (w *webview) Destroy() {
_, _, _ = w32.User32PostMessageW.Call(w.hwnd, w32.WMClose, 0, 0)
}
func (w *webview) Run() {
var msg w32.Msg
for {
_, _, _ = w32.User32GetMessageW.Call(
uintptr(unsafe.Pointer(&msg)),
0,
0,
0,
)
if msg.Message == w32.WMApp {
w.m.Lock()
q := append([]func(){}, w.dispatchq...)
w.dispatchq = []func(){}
w.m.Unlock()
for _, v := range q {
v()
}
} else if msg.Message == w32.WMQuit {
return
}
r, _, _ := w32.User32GetAncestor.Call(uintptr(msg.Hwnd), w32.GARoot)
r, _, _ = w32.User32IsDialogMessage.Call(r, uintptr(unsafe.Pointer(&msg)))
if r != 0 {
continue
}
_, _, _ = w32.User32TranslateMessage.Call(uintptr(unsafe.Pointer(&msg)))
_, _, _ = w32.User32DispatchMessageW.Call(uintptr(unsafe.Pointer(&msg)))
}
}
func (w *webview) Terminate() {
_, _, _ = w32.User32PostQuitMessage.Call(0)
}
func (w *webview) Window() unsafe.Pointer {
return unsafe.Pointer(w.hwnd)
}
func (w *webview) Navigate(url string) {
w.browser.Navigate(url)
}
func (w *webview) SetHtml(html string) {
w.browser.NavigateToString(html)
}
func (w *webview) SetTitle(title string) {
_title, err := windows.UTF16FromString(title)
if err != nil {
_title, _ = windows.UTF16FromString("")
}
_, _, _ = w32.User32SetWindowTextW.Call(w.hwnd, uintptr(unsafe.Pointer(&_title[0])))
}
func (w *webview) SetSize(width int, height int, hints Hint) {
index := w32.GWLStyle
style, _, _ := w32.User32GetWindowLongPtrW.Call(w.hwnd, uintptr(index))
if hints == HintFixed {
style &^= (w32.WSThickFrame | w32.WSMaximizeBox)
} else {
style |= (w32.WSThickFrame | w32.WSMaximizeBox)
}
_, _, _ = w32.User32SetWindowLongPtrW.Call(w.hwnd, uintptr(index), style)
if hints == HintMax {
w.maxsz.X = int32(width)
w.maxsz.Y = int32(height)
} else if hints == HintMin {
w.minsz.X = int32(width)
w.minsz.Y = int32(height)
} else {
r := w32.Rect{}
r.Left = 0
r.Top = 0
r.Right = int32(width)
r.Bottom = int32(height)
_, _, _ = w32.User32AdjustWindowRect.Call(uintptr(unsafe.Pointer(&r)), w32.WSOverlappedWindow, 0)
_, _, _ = w32.User32SetWindowPos.Call(
w.hwnd, 0, uintptr(r.Left), uintptr(r.Top), uintptr(r.Right-r.Left), uintptr(r.Bottom-r.Top),
w32.SWPNoZOrder|w32.SWPNoActivate|w32.SWPNoMove|w32.SWPFrameChanged)
w.browser.Resize()
}
}
func (w *webview) Init(js string) {
w.browser.Init(js)
}
func (w *webview) Eval(js string) {
w.browser.Eval(js)
}
func (w *webview) Dispatch(f func()) {
w.m.Lock()
w.dispatchq = append(w.dispatchq, f)
w.m.Unlock()
_, _, _ = w32.User32PostThreadMessageW.Call(w.mainthread, w32.WMApp, 0, 0)
}
func (w *webview) Bind(name string, f interface{}) error {
v := reflect.ValueOf(f)
if v.Kind() != reflect.Func {
return errors.New("only functions can be bound")
}
if n := v.Type().NumOut(); n > 2 {
return errors.New("function may only return a value or a value+error")
}
w.m.Lock()
w.bindings[name] = f
w.m.Unlock()
w.Init("(function() { var name = " + jsString(name) + ";" + `
var RPC = window._rpc = (window._rpc || {nextSeq: 1});
window[name] = function() {
var seq = RPC.nextSeq++;
var promise = new Promise(function(resolve, reject) {
RPC[seq] = {
resolve: resolve,
reject: reject,
};
});
window.external.invoke(JSON.stringify({
id: seq,
method: name,
params: Array.prototype.slice.call(arguments),
}));
return promise;
}
})()`)
return nil
}