gui: native WebView host as nested module yetano.dev/yetano/core/gui
Extracted from prototypes/yetano-webview (AP1): packages assets, document, bridge and window (macOS Cocoa/WKWebView via cgo, Windows Win32/WebView2 pure Go). No local HTTP listener or port: assets go through the WebView's resource handler, app routes through the native message binding. Own go.mod and gui/vX.Y.Z tags keep cgo and the WebView dependencies out of the main core module. Adds backend-free tests for the window's dispatch/destroy guards and a yet-gui migration guide. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
90132e2d76
commit
8c63d42a27
27 files changed
+4849
-3
No files matched your search
@@ -0,0 +1,21 @@
|
||||
#ifndef YETANO_WINDOW_DARWIN_H
|
||||
#define YETANO_WINDOW_DARWIN_H
|
||||
#include <stdint.h>
|
||||
|
||||
void *yt_create(uintptr_t goHandle, const char *title, int width, int height, int debug, const char *scheme);
|
||||
void yt_add_script(void *h, const char *js);
|
||||
void yt_navigate(void *h, const char *url);
|
||||
void yt_eval(void *h, const char *js);
|
||||
void yt_dispatch(uintptr_t fn);
|
||||
void yt_run(void);
|
||||
void yt_stop(void);
|
||||
void yt_destroy(void *h);
|
||||
void yt_task_respond(void *h, long tid, int status, const char *headersJSON, const char *url);
|
||||
void yt_task_data(void *h, long tid, const void *data, int n);
|
||||
void yt_task_finish(void *h, long tid, const char *err);
|
||||
void yt_snapshot(void *h, const char *path);
|
||||
void yt_set_appearance(void *h, int mode);
|
||||
void yt_accent_color(char *buf, int n);
|
||||
void yt_set_app_icon(const void *png, int n);
|
||||
|
||||
#endif
|
||||
@@ -0,0 +1,282 @@
|
||||
//go:build darwin
|
||||
|
||||
// Native macOS host: NSWindow + WKWebView with
|
||||
// - a WKScriptMessageHandler "yetano" (page -> Go messages),
|
||||
// - document-start WKUserScripts,
|
||||
// - a WKURLSchemeHandler for the "yetano" scheme (native resources, streaming),
|
||||
// - main-queue dispatch for Go closures.
|
||||
// Everything here runs on the main thread; calls from Go goroutines are
|
||||
// marshalled with dispatch_async onto the main queue.
|
||||
#import <Cocoa/Cocoa.h>
|
||||
#import <WebKit/WebKit.h>
|
||||
#include "darwin.h"
|
||||
|
||||
// Implemented in Go (window_darwin.go).
|
||||
extern void ytGoMessage(uintptr_t h, const char *msg);
|
||||
extern void ytGoSchemeStart(uintptr_t h, long id, const char *method, const char *url, const char *headers, const void *body, int n);
|
||||
extern void ytGoSchemeStop(uintptr_t h, long id);
|
||||
extern void ytGoDispatch(uintptr_t fn);
|
||||
extern void ytGoClosed(uintptr_t h);
|
||||
extern void ytGoSnapshotDone(uintptr_t h, const char *err);
|
||||
|
||||
@interface YTHost : NSObject <WKScriptMessageHandler, WKURLSchemeHandler, NSWindowDelegate>
|
||||
@property (assign) uintptr_t goHandle;
|
||||
@property (strong) NSWindow *window;
|
||||
@property (strong) WKWebView *webview;
|
||||
@property (strong) NSMutableDictionary<NSNumber *, id<WKURLSchemeTask>> *tasks;
|
||||
@property (assign) long nextTask;
|
||||
@property (assign) BOOL closed;
|
||||
@end
|
||||
|
||||
@implementation YTHost
|
||||
|
||||
- (void)userContentController:(WKUserContentController *)ucc didReceiveScriptMessage:(WKScriptMessage *)message {
|
||||
if (self.closed || ![message.body isKindOfClass:[NSString class]]) return;
|
||||
ytGoMessage(self.goHandle, [(NSString *)message.body UTF8String]);
|
||||
}
|
||||
|
||||
- (void)webView:(WKWebView *)webView startURLSchemeTask:(id<WKURLSchemeTask>)task {
|
||||
long tid = ++self.nextTask;
|
||||
self.tasks[@(tid)] = task;
|
||||
NSURLRequest *req = task.request;
|
||||
NSData *body = req.HTTPBody;
|
||||
if (!body && req.HTTPBodyStream) {
|
||||
NSMutableData *buf = [NSMutableData data];
|
||||
NSInputStream *s = req.HTTPBodyStream;
|
||||
[s open];
|
||||
uint8_t chunk[65536];
|
||||
NSInteger n;
|
||||
while ((n = [s read:chunk maxLength:sizeof chunk]) > 0) [buf appendBytes:chunk length:(NSUInteger)n];
|
||||
[s close];
|
||||
body = buf;
|
||||
}
|
||||
NSDictionary *hdr = req.allHTTPHeaderFields ?: @{};
|
||||
NSData *hj = [NSJSONSerialization dataWithJSONObject:hdr options:0 error:nil];
|
||||
NSString *hs = [[NSString alloc] initWithData:hj encoding:NSUTF8StringEncoding];
|
||||
ytGoSchemeStart(self.goHandle, tid, [(req.HTTPMethod ?: @"GET") UTF8String], [req.URL.absoluteString UTF8String],
|
||||
[hs UTF8String], body.bytes, (int)body.length);
|
||||
}
|
||||
|
||||
- (void)webView:(WKWebView *)webView stopURLSchemeTask:(id<WKURLSchemeTask>)task {
|
||||
NSNumber *key = nil;
|
||||
for (NSNumber *k in self.tasks) {
|
||||
if (self.tasks[k] == task) { key = k; break; }
|
||||
}
|
||||
if (!key) return;
|
||||
[self.tasks removeObjectForKey:key];
|
||||
ytGoSchemeStop(self.goHandle, key.longValue);
|
||||
}
|
||||
|
||||
- (void)windowWillClose:(NSNotification *)n {
|
||||
if (self.closed) return;
|
||||
ytGoClosed(self.goHandle);
|
||||
yt_stop();
|
||||
}
|
||||
|
||||
@end
|
||||
|
||||
static NSString *str(const char *s) { return [NSString stringWithUTF8String:s ?: ""]; }
|
||||
|
||||
static void ensureApp(void) {
|
||||
static BOOL done = NO;
|
||||
if (done) return;
|
||||
done = YES;
|
||||
[NSApplication sharedApplication];
|
||||
[NSApp setActivationPolicy:NSApplicationActivationPolicyRegular];
|
||||
// Minimal menu: Quit and the Edit actions (copy/paste need them).
|
||||
NSMenu *bar = [NSMenu new];
|
||||
NSMenuItem *appItem = [NSMenuItem new];
|
||||
[bar addItem:appItem];
|
||||
NSMenu *appMenu = [NSMenu new];
|
||||
[appMenu addItemWithTitle:@"Quit" action:@selector(terminate:) keyEquivalent:@"q"];
|
||||
appItem.submenu = appMenu;
|
||||
NSMenuItem *editItem = [NSMenuItem new];
|
||||
[bar addItem:editItem];
|
||||
NSMenu *edit = [[NSMenu alloc] initWithTitle:@"Edit"];
|
||||
[edit addItemWithTitle:@"Cut" action:@selector(cut:) keyEquivalent:@"x"];
|
||||
[edit addItemWithTitle:@"Copy" action:@selector(copy:) keyEquivalent:@"c"];
|
||||
[edit addItemWithTitle:@"Paste" action:@selector(paste:) keyEquivalent:@"v"];
|
||||
[edit addItemWithTitle:@"Select All" action:@selector(selectAll:) keyEquivalent:@"a"];
|
||||
editItem.submenu = edit;
|
||||
NSApp.mainMenu = bar;
|
||||
[NSApp finishLaunching];
|
||||
}
|
||||
|
||||
void *yt_create(uintptr_t goHandle, const char *title, int width, int height, int debug, const char *scheme) {
|
||||
@autoreleasepool {
|
||||
ensureApp();
|
||||
YTHost *host = [YTHost new];
|
||||
host.goHandle = goHandle;
|
||||
host.tasks = [NSMutableDictionary dictionary];
|
||||
|
||||
WKWebViewConfiguration *cfg = [WKWebViewConfiguration new];
|
||||
[cfg.userContentController addScriptMessageHandler:host name:@"yetano"];
|
||||
if (scheme && scheme[0]) [cfg setURLSchemeHandler:host forURLScheme:str(scheme)];
|
||||
if (debug) [cfg.preferences setValue:@YES forKey:@"developerExtrasEnabled"];
|
||||
|
||||
NSRect frame = NSMakeRect(0, 0, width, height);
|
||||
host.webview = [[WKWebView alloc] initWithFrame:frame configuration:cfg];
|
||||
if (@available(macOS 13.3, *)) { if (debug) host.webview.inspectable = YES; }
|
||||
|
||||
host.window = [[NSWindow alloc] initWithContentRect:frame
|
||||
styleMask:NSWindowStyleMaskTitled | NSWindowStyleMaskClosable |
|
||||
NSWindowStyleMaskMiniaturizable | NSWindowStyleMaskResizable
|
||||
backing:NSBackingStoreBuffered
|
||||
defer:NO];
|
||||
host.window.releasedWhenClosed = NO;
|
||||
host.window.title = str(title);
|
||||
host.window.contentView = host.webview;
|
||||
host.window.delegate = host;
|
||||
[host.window center];
|
||||
[host.window makeKeyAndOrderFront:nil];
|
||||
[NSApp activateIgnoringOtherApps:YES];
|
||||
return (__bridge_retained void *)host;
|
||||
}
|
||||
}
|
||||
|
||||
void yt_add_script(void *h, const char *js) {
|
||||
YTHost *host = (__bridge YTHost *)h;
|
||||
WKUserScript *s = [[WKUserScript alloc] initWithSource:str(js)
|
||||
injectionTime:WKUserScriptInjectionTimeAtDocumentStart
|
||||
forMainFrameOnly:YES];
|
||||
[host.webview.configuration.userContentController addUserScript:s];
|
||||
}
|
||||
|
||||
void yt_navigate(void *h, const char *url) {
|
||||
YTHost *host = (__bridge YTHost *)h;
|
||||
[host.webview loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:str(url)]]];
|
||||
}
|
||||
|
||||
void yt_eval(void *h, const char *js) {
|
||||
YTHost *host = (__bridge YTHost *)h;
|
||||
if (host.closed) return;
|
||||
[host.webview evaluateJavaScript:str(js) completionHandler:nil];
|
||||
}
|
||||
|
||||
static void runGo(void *fn) { ytGoDispatch((uintptr_t)fn); }
|
||||
|
||||
void yt_dispatch(uintptr_t fn) { dispatch_async_f(dispatch_get_main_queue(), (void *)fn, runGo); }
|
||||
|
||||
void yt_run(void) {
|
||||
@autoreleasepool { [NSApp run]; }
|
||||
}
|
||||
|
||||
void yt_stop(void) {
|
||||
[NSApp stop:nil];
|
||||
// stop: takes effect after the next event; post one.
|
||||
NSEvent *e = [NSEvent otherEventWithType:NSEventTypeApplicationDefined location:NSZeroPoint modifierFlags:0
|
||||
timestamp:0 windowNumber:0 context:nil subtype:0 data1:0 data2:0];
|
||||
[NSApp postEvent:e atStart:YES];
|
||||
}
|
||||
|
||||
void yt_destroy(void *h) {
|
||||
YTHost *host = (__bridge_transfer YTHost *)h; // balances __bridge_retained
|
||||
host.closed = YES;
|
||||
for (NSNumber *k in host.tasks.allKeys) {
|
||||
// Remaining tasks are failed so WebKit does not wait forever.
|
||||
id<WKURLSchemeTask> t = host.tasks[k];
|
||||
@try { [t didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorCancelled userInfo:nil]]; } @catch (id e) {}
|
||||
}
|
||||
[host.tasks removeAllObjects];
|
||||
[host.webview stopLoading];
|
||||
[host.webview.configuration.userContentController removeScriptMessageHandlerForName:@"yetano"];
|
||||
[host.webview.configuration.userContentController removeAllUserScripts];
|
||||
host.window.delegate = nil;
|
||||
[host.window orderOut:nil];
|
||||
host.window.contentView = nil;
|
||||
[host.window close];
|
||||
host.webview = nil;
|
||||
host.window = nil;
|
||||
}
|
||||
|
||||
// --- scheme task responses (called from Go, any thread) --------------------
|
||||
|
||||
static void onTask(void *h, long tid, void (^block)(id<WKURLSchemeTask>)) {
|
||||
YTHost *host = (__bridge YTHost *)h;
|
||||
dispatch_async(dispatch_get_main_queue(), ^{
|
||||
id<WKURLSchemeTask> t = host.tasks[@(tid)];
|
||||
if (!t || host.closed) return; // stopped meanwhile: must not be touched
|
||||
block(t);
|
||||
});
|
||||
}
|
||||
|
||||
void yt_task_respond(void *h, long tid, int status, const char *headersJSON, const char *url) {
|
||||
NSData *hj = [str(headersJSON) dataUsingEncoding:NSUTF8StringEncoding];
|
||||
NSDictionary *hdr = [NSJSONSerialization JSONObjectWithData:hj options:0 error:nil];
|
||||
NSURL *u = [NSURL URLWithString:str(url)];
|
||||
onTask(h, tid, ^(id<WKURLSchemeTask> t) {
|
||||
NSHTTPURLResponse *r = [[NSHTTPURLResponse alloc] initWithURL:u statusCode:status HTTPVersion:@"HTTP/1.1" headerFields:hdr];
|
||||
[t didReceiveResponse:r];
|
||||
});
|
||||
}
|
||||
|
||||
void yt_task_data(void *h, long tid, const void *data, int n) {
|
||||
NSData *d = [NSData dataWithBytes:data length:(NSUInteger)n]; // copied before returning to Go
|
||||
onTask(h, tid, ^(id<WKURLSchemeTask> t) { [t didReceiveData:d]; });
|
||||
}
|
||||
|
||||
void yt_task_finish(void *h, long tid, const char *err) {
|
||||
NSString *e = err ? str(err) : nil;
|
||||
YTHost *host = (__bridge YTHost *)h;
|
||||
onTask(h, tid, ^(id<WKURLSchemeTask> t) {
|
||||
if (e) {
|
||||
[t didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorUnknown
|
||||
userInfo:@{NSLocalizedDescriptionKey : e}]];
|
||||
} else {
|
||||
[t didFinish];
|
||||
}
|
||||
[host.tasks removeObjectForKey:@(tid)];
|
||||
});
|
||||
}
|
||||
|
||||
// --- snapshot: render the web view into a PNG file (main thread) ---------
|
||||
|
||||
void yt_snapshot(void *h, const char *path) {
|
||||
YTHost *host = (__bridge YTHost *)h;
|
||||
NSString *p = str(path);
|
||||
uintptr_t gh = host.goHandle;
|
||||
[host.webview takeSnapshotWithConfiguration:nil completionHandler:^(NSImage *img, NSError *error) {
|
||||
if (!img) { ytGoSnapshotDone(gh, [(error.localizedDescription ?: @"snapshot failed") UTF8String]); return; }
|
||||
CGImageRef cg = [img CGImageForProposedRect:NULL context:nil hints:nil];
|
||||
NSBitmapImageRep *rep = [[NSBitmapImageRep alloc] initWithCGImage:cg];
|
||||
NSData *png = [rep representationUsingType:NSBitmapImageFileTypePNG properties:@{}];
|
||||
NSError *werr = nil;
|
||||
if (![png writeToFile:p options:NSDataWritingAtomic error:&werr]) {
|
||||
ytGoSnapshotDone(gh, [werr.localizedDescription UTF8String]);
|
||||
return;
|
||||
}
|
||||
ytGoSnapshotDone(gh, NULL);
|
||||
}];
|
||||
}
|
||||
|
||||
// --- appearance ------------------------------------------------------------
|
||||
|
||||
// yt_set_appearance: 0 = follow the system, 1 = light, 2 = dark. Changes the
|
||||
// title bar and what the page sees as prefers-color-scheme.
|
||||
void yt_set_appearance(void *h, int mode) {
|
||||
YTHost *host = (__bridge YTHost *)h;
|
||||
NSAppearance *a = nil;
|
||||
if (mode == 1) a = [NSAppearance appearanceNamed:NSAppearanceNameAqua];
|
||||
if (mode == 2) a = [NSAppearance appearanceNamed:NSAppearanceNameDarkAqua];
|
||||
host.window.appearance = a;
|
||||
}
|
||||
|
||||
// yt_accent_color writes the user's accent color as "#RRGGBB" into buf.
|
||||
void yt_accent_color(char *buf, int n) {
|
||||
@autoreleasepool {
|
||||
NSColor *c = [[NSColor controlAccentColor] colorUsingColorSpace:[NSColorSpace sRGBColorSpace]];
|
||||
if (!c) { buf[0] = 0; return; }
|
||||
snprintf(buf, (size_t)n, "#%02X%02X%02X", (int)lround(c.redComponent * 255), (int)lround(c.greenComponent * 255), (int)lround(c.blueComponent * 255));
|
||||
}
|
||||
}
|
||||
|
||||
// yt_set_app_icon sets the Dock icon from PNG bytes, unless the process runs
|
||||
// from an app bundle (which brings its own icon).
|
||||
void yt_set_app_icon(const void *png, int n) {
|
||||
@autoreleasepool {
|
||||
ensureApp();
|
||||
if ([[NSBundle mainBundle] bundleIdentifier] != nil) return;
|
||||
NSImage *img = [[NSImage alloc] initWithData:[NSData dataWithBytes:png length:(NSUInteger)n]];
|
||||
if (img) NSApp.applicationIconImage = img;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,241 @@
|
||||
// Package window is a narrow native WebView host:
|
||||
//
|
||||
// - macOS: own Cocoa host (darwin.m): NSWindow + WKWebView, cgo
|
||||
// - Windows: own Win32 host on github.com/jchv/go-webview2/pkg/edge
|
||||
// (WebView2 COM, pure Go)
|
||||
//
|
||||
// It offers exactly what the program needs: one message channel page -> Go
|
||||
// (window.__yetano_post), document-start scripts, Eval, UI-thread Dispatch
|
||||
// and a native resource handler for the app origin (BaseURL), which serves
|
||||
// the entry document, assets and local routes without any network listener,
|
||||
// with streaming response bodies.
|
||||
//
|
||||
// Thread rules: New, Init, Navigate, Run and Destroy run on the thread that
|
||||
// locked itself in this package's init (the main goroutine). Dispatch is safe
|
||||
// from any goroutine; Eval only inside a dispatched function. After Destroy,
|
||||
// Dispatch and queued closures are no-ops.
|
||||
package window
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"net/http"
|
||||
"sync"
|
||||
)
|
||||
|
||||
// ResourceRequest is a request from the WebView for the app origin.
|
||||
type ResourceRequest struct {
|
||||
Method string
|
||||
URL string // absolute, e.g. "yetano://app/assets/x.css" or "https://yetano.invalid/rpc/add"
|
||||
Header http.Header
|
||||
Body []byte
|
||||
}
|
||||
|
||||
// ResourceWriter answers one ResourceRequest. Respond is called once, then
|
||||
// any number of Write calls (each is delivered to the page as it comes:
|
||||
// streaming), then Close. All methods are safe from any goroutine.
|
||||
type ResourceWriter interface {
|
||||
Respond(status int, header http.Header)
|
||||
Write(p []byte) (int, error)
|
||||
Close(err error)
|
||||
}
|
||||
|
||||
// ResourceHandler serves app-origin requests. ctx ends when the page drops
|
||||
// the request (where the backend reports that) or the window is destroyed.
|
||||
type ResourceHandler func(ctx context.Context, req *ResourceRequest, w ResourceWriter)
|
||||
|
||||
// Options for a new window.
|
||||
type Options struct {
|
||||
Title string
|
||||
Width int
|
||||
Height int
|
||||
Debug bool // developer tools
|
||||
DataPath string // WebView2 user data folder (Windows)
|
||||
OnMessage func(msg string)
|
||||
Resource ResourceHandler // nil: no native resource handler
|
||||
}
|
||||
|
||||
type backend interface {
|
||||
Init(js string)
|
||||
Navigate(url string)
|
||||
Run()
|
||||
Terminate()
|
||||
Dispatch(f func())
|
||||
Eval(js string)
|
||||
Destroy()
|
||||
}
|
||||
|
||||
// Window is a guarded native WebView window.
|
||||
type Window struct {
|
||||
mu sync.Mutex
|
||||
b backend
|
||||
alive bool
|
||||
name string
|
||||
base string
|
||||
dropped int
|
||||
}
|
||||
|
||||
// Debugf, if set, receives backend diagnostics.
|
||||
var Debugf func(format string, args ...any)
|
||||
|
||||
// ErrUnsupported is returned on platforms without a backend.
|
||||
var ErrUnsupported = errors.New("window: no native WebView backend for this platform")
|
||||
|
||||
// postShim defines window.__yetano_post on top of the backend's native
|
||||
// message channel. It is installed before any other init script.
|
||||
const postShimDarwin = `window.__yetano_post=function(m){window.webkit.messageHandlers.yetano.postMessage(JSON.stringify(m));return Promise.resolve();};`
|
||||
const postShimWindows = `window.__yetano_post=function(m){window.chrome.webview.postMessage(JSON.stringify(m));return Promise.resolve();};`
|
||||
|
||||
// New creates the native window. On failure it returns an error and nothing
|
||||
// has to be cleaned up.
|
||||
func New(opt Options) (*Window, error) {
|
||||
if opt.Width == 0 {
|
||||
opt.Width, opt.Height = 1100, 820
|
||||
}
|
||||
b, name, base, err := newBackend(opt)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &Window{b: b, alive: true, name: name, base: base}, nil
|
||||
}
|
||||
|
||||
// Backend names the native backend.
|
||||
func (w *Window) Backend() string { return w.name }
|
||||
|
||||
// BaseURL is the app origin served by the resource handler, without
|
||||
// trailing slash ("yetano://app", "https://yetano.invalid").
|
||||
func (w *Window) BaseURL() string { return w.base }
|
||||
|
||||
// Init adds a document-start script (every navigation, before page scripts).
|
||||
func (w *Window) Init(js string) { w.b.Init(js) }
|
||||
|
||||
// Navigate loads url.
|
||||
func (w *Window) Navigate(url string) { w.b.Navigate(url) }
|
||||
|
||||
// Run runs the UI loop until Terminate or the user closes the window.
|
||||
func (w *Window) Run() { w.b.Run() }
|
||||
|
||||
// Dispatch queues f on the UI thread. After Destroy it is dropped.
|
||||
func (w *Window) Dispatch(f func()) {
|
||||
w.mu.Lock()
|
||||
defer w.mu.Unlock()
|
||||
if !w.alive {
|
||||
w.dropped++
|
||||
return
|
||||
}
|
||||
w.b.Dispatch(func() {
|
||||
w.mu.Lock()
|
||||
alive := w.alive
|
||||
w.mu.Unlock()
|
||||
if alive {
|
||||
f()
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// Eval runs js in the page; only on the UI thread.
|
||||
func (w *Window) Eval(js string) {
|
||||
w.mu.Lock()
|
||||
alive := w.alive
|
||||
w.mu.Unlock()
|
||||
if alive {
|
||||
w.b.Eval(js)
|
||||
}
|
||||
}
|
||||
|
||||
// Terminate ends Run from any goroutine.
|
||||
func (w *Window) Terminate() { w.Dispatch(func() { w.b.Terminate() }) }
|
||||
|
||||
// Destroy releases the native window. Idempotent; on the UI thread after Run.
|
||||
func (w *Window) Destroy() {
|
||||
w.mu.Lock()
|
||||
if !w.alive {
|
||||
w.mu.Unlock()
|
||||
return
|
||||
}
|
||||
w.alive = false
|
||||
w.mu.Unlock()
|
||||
w.b.Destroy()
|
||||
}
|
||||
|
||||
// snapshotter is implemented by backends that can render the page to PNG.
|
||||
type snapshotter interface {
|
||||
Snapshot(path string, done func(error))
|
||||
}
|
||||
|
||||
// Snapshot renders the current page into a PNG file (UI thread). done runs
|
||||
// on the UI thread. Backends without support report an error.
|
||||
func (w *Window) Snapshot(path string, done func(error)) {
|
||||
s, ok := w.b.(snapshotter)
|
||||
if !ok {
|
||||
done(errors.New("window: snapshot not supported by " + w.name))
|
||||
return
|
||||
}
|
||||
s.Snapshot(path, done)
|
||||
}
|
||||
|
||||
// appearancer is implemented by backends whose window chrome (title bar)
|
||||
// can follow the page's light/dark choice.
|
||||
type appearancer interface {
|
||||
SetAppearance(mode string)
|
||||
}
|
||||
|
||||
// SetAppearance makes the native window chrome light ("light"), dark
|
||||
// ("dark") or follow the system (anything else). UI thread. A no-op where
|
||||
// unsupported.
|
||||
func (w *Window) SetAppearance(mode string) {
|
||||
if a, ok := w.b.(appearancer); ok {
|
||||
a.SetAppearance(mode)
|
||||
}
|
||||
}
|
||||
|
||||
// SetAppIcon sets the application icon shown by the OS (macOS Dock) from
|
||||
// PNG bytes when the program does not run from an app bundle. Windows takes
|
||||
// the icon from the executable's resources instead. Call before New.
|
||||
func SetAppIcon(png []byte) { setAppIcon(png) }
|
||||
|
||||
// AccentColor is the user's system accent color as "#RRGGBB", or "" if
|
||||
// unknown. Safe to call before a window exists.
|
||||
func AccentColor() string { return accentColor() }
|
||||
|
||||
// DroppedDispatches counts Dispatch calls that arrived after Destroy.
|
||||
func (w *Window) DroppedDispatches() int {
|
||||
w.mu.Lock()
|
||||
defer w.mu.Unlock()
|
||||
return w.dropped
|
||||
}
|
||||
|
||||
// taskTable tracks running resource requests so Destroy can cancel them.
|
||||
type taskTable struct {
|
||||
mu sync.Mutex
|
||||
tasks map[int64]context.CancelFunc
|
||||
}
|
||||
|
||||
func (t *taskTable) add(id int64, c context.CancelFunc) {
|
||||
t.mu.Lock()
|
||||
if t.tasks == nil {
|
||||
t.tasks = map[int64]context.CancelFunc{}
|
||||
}
|
||||
t.tasks[id] = c
|
||||
t.mu.Unlock()
|
||||
}
|
||||
|
||||
func (t *taskTable) cancel(id int64) {
|
||||
t.mu.Lock()
|
||||
c := t.tasks[id]
|
||||
delete(t.tasks, id)
|
||||
t.mu.Unlock()
|
||||
if c != nil {
|
||||
c()
|
||||
}
|
||||
}
|
||||
|
||||
func (t *taskTable) cancelAll() {
|
||||
t.mu.Lock()
|
||||
cs := t.tasks
|
||||
t.tasks = nil
|
||||
t.mu.Unlock()
|
||||
for _, c := range cs {
|
||||
c()
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,283 @@
|
||||
//go:build darwin && cgo
|
||||
|
||||
package window
|
||||
|
||||
/*
|
||||
#cgo CFLAGS: -x objective-c -fobjc-arc
|
||||
#cgo LDFLAGS: -framework Cocoa -framework WebKit
|
||||
#include <stdlib.h>
|
||||
#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) })
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
//go:build !(darwin && cgo) && !windows
|
||||
|
||||
package window
|
||||
|
||||
func newBackend(Options) (backend, string, string, error) { return nil, "", "", ErrUnsupported }
|
||||
|
||||
func accentColor() string { return "" }
|
||||
|
||||
func setAppIcon([]byte) {}
|
||||
@@ -0,0 +1,75 @@
|
||||
package window
|
||||
|
||||
import (
|
||||
"context"
|
||||
"testing"
|
||||
)
|
||||
|
||||
// fakeBackend queues dispatched functions like a real UI loop (run them
|
||||
// with drain) and records calls.
|
||||
type fakeBackend struct {
|
||||
queue []func()
|
||||
evals []string
|
||||
destroyed int
|
||||
}
|
||||
|
||||
func (f *fakeBackend) drain() {
|
||||
for len(f.queue) > 0 {
|
||||
g := f.queue[0]
|
||||
f.queue = f.queue[1:]
|
||||
g()
|
||||
}
|
||||
}
|
||||
|
||||
func (f *fakeBackend) Init(string) {}
|
||||
func (f *fakeBackend) Navigate(string) {}
|
||||
func (f *fakeBackend) Run() {}
|
||||
func (f *fakeBackend) Terminate() {}
|
||||
func (f *fakeBackend) Dispatch(g func()) { f.queue = append(f.queue, g) }
|
||||
func (f *fakeBackend) Eval(js string) { f.evals = append(f.evals, js) }
|
||||
func (f *fakeBackend) Destroy() { f.destroyed++ }
|
||||
|
||||
func TestDispatchAfterDestroyIsDropped(t *testing.T) {
|
||||
fb := &fakeBackend{}
|
||||
w := &Window{b: fb, alive: true, name: "fake"}
|
||||
ran := 0
|
||||
w.Dispatch(func() { ran++; w.Eval("a") })
|
||||
w.Dispatch(func() { ran++ })
|
||||
fb.drain()
|
||||
w.Dispatch(func() { ran++ }) // queued, Destroy comes first
|
||||
w.Destroy()
|
||||
fb.drain()
|
||||
w.Destroy() // idempotent
|
||||
w.Dispatch(func() { ran++ })
|
||||
w.Eval("b")
|
||||
if ran != 2 || len(fb.evals) != 1 || fb.destroyed != 1 || w.DroppedDispatches() != 1 || len(fb.queue) != 0 {
|
||||
t.Fatalf("ran=%d evals=%v destroyed=%d dropped=%d", ran, fb.evals, fb.destroyed, w.DroppedDispatches())
|
||||
}
|
||||
}
|
||||
|
||||
func TestSnapshotUnsupported(t *testing.T) {
|
||||
w := &Window{b: &fakeBackend{}, alive: true, name: "fake"}
|
||||
var got error
|
||||
w.Snapshot("x.png", func(err error) { got = err })
|
||||
if got == nil {
|
||||
t.Fatal("expected an error from a backend without snapshot support")
|
||||
}
|
||||
w.SetAppearance("dark") // no-op without support, must not panic
|
||||
}
|
||||
|
||||
func TestTaskTableCancel(t *testing.T) {
|
||||
var tt taskTable
|
||||
ctx1, c1 := context.WithCancel(context.Background())
|
||||
ctx2, c2 := context.WithCancel(context.Background())
|
||||
tt.add(1, c1)
|
||||
tt.add(2, c2)
|
||||
tt.cancel(1)
|
||||
if ctx1.Err() == nil || ctx2.Err() != nil {
|
||||
t.Fatal("cancel(1) must cancel only task 1")
|
||||
}
|
||||
tt.cancel(1) // unknown id: no-op
|
||||
tt.cancelAll()
|
||||
if ctx2.Err() == nil {
|
||||
t.Fatal("cancelAll must cancel the remaining tasks")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,705 @@
|
||||
//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
|
||||
}
|
||||
Reference in new issue
Block a user