//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 #import #import #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); extern void ytGoFrame(uintptr_t h, int x, int y, int w, int hgt, int zoomed); extern void ytGoFileDone(uintptr_t h, const char *path); // YTWebView takes the first mouse click in an inactive window: without // it the click only activates the window, so a page (a dialog shown at // start) looks dead until clicked twice. @interface YTWebView : WKWebView @end @implementation YTWebView - (BOOL)acceptsFirstMouse:(NSEvent *)event { return YES; } @end @interface YTHost : NSObject @property (assign) uintptr_t goHandle; @property (strong) NSWindow *window; @property (strong) WKWebView *webview; @property (strong) NSMutableDictionary> *tasks; @property (assign) long nextTask; @property (assign) BOOL closed; @property (assign) NSRect normalFrame; // the last frame while not zoomed @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)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)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); } // The frame is reported after every move and resize; while zoomed, the // normal frame underneath is kept, so un-zooming returns to it. - (void)reportFrame { if (self.closed || !self.window) return; BOOL zoomed = self.window.isZoomed; if (!zoomed) self.normalFrame = self.window.frame; NSRect f = self.normalFrame; if (f.size.width <= 0) return; ytGoFrame(self.goHandle, (int)f.origin.x, (int)f.origin.y, (int)f.size.width, (int)f.size.height, zoomed ? 1 : 0); } - (void)windowDidMove:(NSNotification *)n { [self reportFrame]; } - (void)windowDidResize:(NSNotification *)n { [self reportFrame]; } - (void)windowWillClose:(NSNotification *)n { [self reportFrame]; 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]; } // onScreen: at least a 120 x 60 point piece of the frame (with its title // bar) is on a connected screen -- a frame saved on a display that is // gone is not restored off screen. static BOOL onScreen(NSRect f) { for (NSScreen *s in [NSScreen screens]) { NSRect i = NSIntersectionRect(f, s.visibleFrame); if (i.size.width >= 120 && i.size.height >= 60) return YES; } return NO; } void *yt_create(uintptr_t goHandle, const char *title, int width, int height, int debug, const char *scheme, int hasFrame, int fx, int fy, int fw, int fh, int zoomed) { @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 = [[YTWebView 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; NSRect saved = NSMakeRect(fx, fy, fw, fh); BOOL restore = hasFrame && onScreen(saved); if (restore) { [host.window setFrame:saved display:NO]; } else { [host.window center]; } host.normalFrame = host.window.frame; host.window.delegate = host; [host.window makeKeyAndOrderFront:nil]; if (restore && zoomed && !host.window.isZoomed) [host.window zoom: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 reportFrame]; // a window ended by Terminate, not closed by the user host.closed = YES; for (NSNumber *k in host.tasks.allKeys) { // Remaining tasks are failed so WebKit does not wait forever. id 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)) { YTHost *host = (__bridge YTHost *)h; dispatch_async(dispatch_get_main_queue(), ^{ id 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 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 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 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; } } // --- file dialogs ------------------------------------------------------------ // yt_file_dialog shows an open (save = 0) or save panel as a sheet on the // window. dir: the folder to start in, name: a save panel's suggested file // name, types: allowed file extensions, comma-separated ("" = any). The // chosen path, or NULL when cancelled, goes to ytGoFileDone. void yt_file_dialog(void *h, int save, const char *title, const char *dir, const char *name, const char *types) { YTHost *host = (__bridge YTHost *)h; uintptr_t gh = host.goHandle; NSSavePanel *panel; if (save) { panel = [NSSavePanel savePanel]; if (name && name[0]) panel.nameFieldStringValue = str(name); } else { NSOpenPanel *open = [NSOpenPanel openPanel]; open.canChooseFiles = YES; open.canChooseDirectories = NO; open.allowsMultipleSelection = NO; open.resolvesAliases = YES; panel = open; } if (title && title[0]) { panel.title = str(title); panel.message = str(title); } if (dir && dir[0]) panel.directoryURL = [NSURL fileURLWithPath:str(dir) isDirectory:YES]; if (types && types[0]) { NSMutableArray *uts = [NSMutableArray array]; for (NSString *ext in [str(types) componentsSeparatedByString:@","]) { UTType *t = [UTType typeWithFilenameExtension:ext]; if (t) [uts addObject:t]; } if (uts.count) panel.allowedContentTypes = uts; } [panel beginSheetModalForWindow:host.window completionHandler:^(NSModalResponse r) { if (r != NSModalResponseOK || !panel.URL) { ytGoFileDone(gh, NULL); return; } ytGoFileDone(gh, panel.URL.path.fileSystemRepresentation); }]; }