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,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;
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user