//go:build darwin && cgo package window /* #cgo CFLAGS: -x objective-c -fobjc-arc #cgo LDFLAGS: -framework Cocoa -framework WebKit #include #include "darwin.h" */ import "C" import ( "context" "encoding/json" "net/http" "runtime" "runtime/cgo" "sync" "unsafe" ) // Cocoa requires the UI on the main thread: keep the main goroutine there. func init() { runtime.LockOSThread() } // Scheme and host of the app origin on macOS. WKURLSchemeHandler cannot // take over http/https, so the app gets its own scheme. const darwinScheme = "yetano" type darwinBackend struct { h unsafe.Pointer // retained YTHost handle cgo.Handle // -> *darwinBackend, given to ObjC opt Options tasks taskTable mu sync.RWMutex // guards h against Destroy while a goroutine calls into ObjC snapDone func(error) } // with runs f with the live host pointer, or not at all after Destroy. func (b *darwinBackend) with(f func(h unsafe.Pointer)) bool { b.mu.RLock() defer b.mu.RUnlock() if b.h == nil { return false } f(b.h) return true } func newBackend(opt Options) (backend, string, string, error) { b := &darwinBackend{opt: opt} b.handle = cgo.NewHandle(b) title := C.CString(opt.Title) defer C.free(unsafe.Pointer(title)) scheme := C.CString("") if opt.Resource != nil { C.free(unsafe.Pointer(scheme)) scheme = C.CString(darwinScheme) } defer C.free(unsafe.Pointer(scheme)) debug := 0 if opt.Debug { debug = 1 } b.h = C.yt_create(C.uintptr_t(b.handle), title, C.int(opt.Width), C.int(opt.Height), C.int(debug), scheme) if b.h == nil { b.handle.Delete() return nil, "", "", errUnavailable("WKWebView could not be created") } b.Init(postShimDarwin) return b, "cocoa/WKWebView", darwinScheme + "://app", nil } type errUnavailable string func (e errUnavailable) Error() string { return "window: " + string(e) } func cstr(s string) *C.char { return C.CString(s) } func (b *darwinBackend) Init(js string) { c := cstr(js) defer C.free(unsafe.Pointer(c)) C.yt_add_script(b.h, c) } func (b *darwinBackend) Navigate(url string) { c := cstr(url) defer C.free(unsafe.Pointer(c)) C.yt_navigate(b.h, c) } func (b *darwinBackend) Eval(js string) { c := cstr(js) defer C.free(unsafe.Pointer(c)) C.yt_eval(b.h, c) } func (b *darwinBackend) Run() { C.yt_run() } func (b *darwinBackend) Terminate() { C.yt_stop() } func (b *darwinBackend) Dispatch(f func()) { C.yt_dispatch(C.uintptr_t(cgo.NewHandle(f))) } func (b *darwinBackend) Destroy() { b.tasks.cancelAll() b.mu.Lock() h := b.h b.h = nil b.mu.Unlock() C.yt_destroy(h) // The handle stays valid: ObjC may still deliver an already queued // message; the callbacks check b.h. } //export ytGoDispatch func ytGoDispatch(fn C.uintptr_t) { h := cgo.Handle(fn) f := h.Value().(func()) h.Delete() f() } //export ytGoMessage func ytGoMessage(h C.uintptr_t, msg *C.char) { b := cgo.Handle(h).Value().(*darwinBackend) if b.opt.OnMessage != nil && b.with(func(unsafe.Pointer) {}) { b.opt.OnMessage(C.GoString(msg)) } } // Snapshot renders the page into a PNG file; done runs on the UI thread. func (b *darwinBackend) Snapshot(path string, done func(error)) { b.mu.Lock() b.snapDone = done b.mu.Unlock() c := cstr(path) defer C.free(unsafe.Pointer(c)) b.with(func(h unsafe.Pointer) { C.yt_snapshot(h, c) }) } // SetAppearance: "light", "dark", or anything else to follow the system. func (b *darwinBackend) SetAppearance(mode string) { m := 0 switch mode { case "light": m = 1 case "dark": m = 2 } b.with(func(h unsafe.Pointer) { C.yt_set_appearance(h, C.int(m)) }) } func setAppIcon(png []byte) { if len(png) > 0 { C.yt_set_app_icon(unsafe.Pointer(&png[0]), C.int(len(png))) } } func accentColor() string { var buf [16]C.char C.yt_accent_color(&buf[0], C.int(len(buf))) return C.GoString(&buf[0]) } //export ytGoSnapshotDone func ytGoSnapshotDone(h C.uintptr_t, err *C.char) { b := cgo.Handle(h).Value().(*darwinBackend) b.mu.Lock() done := b.snapDone b.snapDone = nil b.mu.Unlock() if done == nil { return } if err != nil { done(errUnavailable("snapshot: " + C.GoString(err))) return } done(nil) } //export ytGoClosed func ytGoClosed(h C.uintptr_t) {} //export ytGoSchemeStart func ytGoSchemeStart(h C.uintptr_t, id C.long, method, url, headers *C.char, body unsafe.Pointer, n C.int) { b := cgo.Handle(h).Value().(*darwinBackend) req := &ResourceRequest{Method: C.GoString(method), URL: C.GoString(url), Header: http.Header{}} var hm map[string]string _ = json.Unmarshal([]byte(C.GoString(headers)), &hm) for k, v := range hm { req.Header.Set(k, v) } if n > 0 { req.Body = C.GoBytes(body, n) } ctx, cancel := context.WithCancel(context.Background()) tid := int64(id) b.tasks.add(tid, cancel) w := &darwinTask{b: b, id: tid, url: req.URL} go func() { defer b.tasks.cancel(tid) b.opt.Resource(ctx, req, w) w.Close(nil) }() } //export ytGoSchemeStop func ytGoSchemeStop(h C.uintptr_t, id C.long) { cgo.Handle(h).Value().(*darwinBackend).tasks.cancel(int64(id)) } // darwinTask forwards a response to the WKURLSchemeTask. The ObjC side drops // calls for tasks that WebKit already stopped. type darwinTask struct { b *darwinBackend id int64 url string mu sync.Mutex responded bool done bool } func (t *darwinTask) Respond(status int, header http.Header) { t.mu.Lock() defer t.mu.Unlock() if t.responded || t.done { return } t.responded = true hm := map[string]string{} for k, v := range header { if len(v) > 0 { hm[k] = v[0] } } hj, _ := json.Marshal(hm) ch, cu := cstr(string(hj)), cstr(t.url) defer C.free(unsafe.Pointer(ch)) defer C.free(unsafe.Pointer(cu)) t.b.with(func(h unsafe.Pointer) { C.yt_task_respond(h, C.long(t.id), C.int(status), ch, cu) }) } func (t *darwinTask) Write(p []byte) (int, error) { t.mu.Lock() defer t.mu.Unlock() if t.done { return 0, context.Canceled } if !t.responded { t.mu.Unlock() t.Respond(http.StatusOK, nil) t.mu.Lock() } if len(p) > 0 && !t.b.with(func(h unsafe.Pointer) { C.yt_task_data(h, C.long(t.id), unsafe.Pointer(&p[0]), C.int(len(p))) }) { return 0, context.Canceled } return len(p), nil } func (t *darwinTask) Close(err error) { t.mu.Lock() if t.done { t.mu.Unlock() return } responded := t.responded t.mu.Unlock() if !responded && err == nil { t.Respond(http.StatusNoContent, nil) } t.mu.Lock() defer t.mu.Unlock() t.done = true var ce *C.char if err != nil { ce = cstr(err.Error()) defer C.free(unsafe.Pointer(ce)) } t.b.with(func(h unsafe.Pointer) { C.yt_task_finish(h, C.long(t.id), ce) }) }