#pragma once #include "../ContentPolicy.hpp" #include "Action.hpp" #include "Capture.hpp" #include "CloseRequest.hpp" #include "Downloads.hpp" #include "../ViewAssociation.hpp" #include "ScriptDialogs.hpp" #include "NativeWindow.hpp" #include "UIExecutor.hpp" #include "Url.hpp" #include "Window.hpp" #include #include #include #include #include #include #include #include #include #include #include #include #include namespace webfront::frontend { namespace detail::wkwebview { /// The interface thread of the window: attached for the duration of open(), on the main thread. inline UIExecutorHost& executorHost() { static UIExecutorHost host; return host; } /// The NSWindow, published to consumers while open() runs (see NativeWindow.hpp). inline NativeWindowHost& windowHost() { static NativeWindowHost host{executorHost().executor()}; return host; } } // namespace detail::wkwebview /** @brief Per-opening options for the optional macOS frontend. */ struct WKWebViewOptions { /** @brief The initial document must finish loading within this interval; no bridge connection is required. */ std::chrono::milliseconds startupTimeout{30000}; ContentPolicy contentPolicy{}; WindowOptions window{}; /** @brief Keep the native window hidden and avoid activating the application. A WindowServer is still required. */ bool visible{true}; /** @brief Test injection: answers `` without a dialog (an empty list cancels). Unset shows the system panel. */ std::function()> chooseFiles{}; /** @brief Test injection: a non-empty folder receives downloads without a save panel. */ std::filesystem::path downloadDirectory{}; /** @brief Test injection: called with the destination of each finished download. */ std::function downloadFinished{}; /** @brief Test injection: answers `alert`, `confirm` and `prompt` without a box. Unset shows an NSAlert sheet on the window. * `beforeunload` is not handled by WKWebView: the public WKUIDelegate has no method for it, and it does not reach the confirm * method. A page that relies on it can lose unsaved changes on navigation or close; WebFront does not confirm it. */ ScriptDialogHandler answerScriptDialog{}; /** @brief Per-launch proof of this view (ADR-020): given to documents of the application's origin only, at the start of * the document, for WebFront.js to present in its handshake. Set by WebFront; empty gives the view no association. */ ViewLaunch launch{}; }; } // namespace webfront::frontend #if defined(WEBFRONT_EMBED_WKWEBVIEW) && defined(__APPLE__) #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include namespace webfront::frontend::detail::wkwebview { // Use the public Objective-C runtime from C++: no .mm translation unit, ARC, or Cocoa Objective-C headers. // Clang's Blocks extension supplies the typed WebKit decision-handler ABI. template Result send(id object, const char* selector, Args... args) { return reinterpret_cast(objc_msgSend)(object, sel_registerName(selector), args...); } inline id type(const char* name) { auto result = reinterpret_cast(objc_getClass(name)); if (!result) throw std::runtime_error(std::string("WKWebView: unavailable Cocoa class ") + name); return result; } class Object { public: explicit Object(id value = nullptr) : value(value) { } Object(const Object&) = delete; Object& operator=(const Object&) = delete; ~Object() { send(value, "release"); } id get() const { return value; } private: id value; }; inline id text(std::string_view value) { return send(send(type("NSString"), "alloc"), "initWithBytes:length:encoding:", value.data(), value.size(), 4UL); } inline std::string utf8(id value) { const auto bytes = send(value, "UTF8String"); return bytes ? bytes : ""; } inline void requireMainThread() { if (!pthread_main_np()) throw std::runtime_error("WKWebView: construct the application and call show()/open() on the main thread"); } inline void initialize() { requireMainThread(); struct Version { long major, minor, patch; }; Object pool(send(type("NSAutoreleasePool"), "new")); if (!send(send(type("NSProcessInfo"), "processInfo"), "isOperatingSystemAtLeastVersion:", Version{13, 3, 0})) throw std::runtime_error("WKWebView: macOS 13.3 or newer is required"); } inline long applicationActivationPolicy() { Object agentKey(text("LSUIElement")); const auto agent = send(send(type("NSBundle"), "mainBundle"), "objectForInfoDictionaryKey:", agentKey.get()); return send(agent, "boolValue") ? 1L : 0L; // Accessory for agent bundles, Regular otherwise. } struct MenuCommand { const char* title; const char* action; const char* key; }; struct Session; inline Session* session(id object) noexcept { void* pointer = nullptr; object_getInstanceVariable(object, "webfrontSession", &pointer); return static_cast(pointer); } inline void attach(id object, Session* pointer) noexcept { object_setInstanceVariable(object, "webfrontSession", pointer); } inline void addSessionIvar(Class cls) { if (!class_addIvar(cls, "webfrontSession", sizeof(Session*), static_cast(std::countr_zero(alignof(Session*))), "^v")) throw std::runtime_error("WKWebView: cannot register session storage"); } template void addMethod(Class cls, const char* selector, Function function, const char* signature) { if (!class_addMethod(cls, sel_registerName(selector), reinterpret_cast(function), signature)) throw std::runtime_error(std::string("WKWebView: cannot register ") + selector); } inline Class delegateClass(); inline Class viewClass(); inline bool opening = false; // AppKit sessions are main-thread-only and cannot nest. template Class registerClass(const char* name, Class base, Configure configure) { if (auto existing = objc_lookUpClass(name)) return existing; auto created = objc_allocateClassPair(base, name, 0); if (!created) { if (auto existing = objc_lookUpClass(name)) return existing; throw std::runtime_error(std::string("WKWebView: cannot register ") + name); } try { addSessionIvar(created); configure(created); } catch (...) { objc_disposeClassPair(created); throw; } objc_registerClassPair(created); return created; } inline bool successfulHttpStatus(long status) { return status >= 200 && status < 400; } /// The view as seen by capture requests: read and cleared only on the main thread, so a request that outlives the /// window finds it null. struct CaptureJob; struct CaptureTarget { id view = nullptr; PendingCaptures pending; // Requests nobody has answered yet, queued or in flight. }; struct CaptureJob { std::shared_ptr target; std::promise done; }; inline void answer(CaptureJob& job, CaptureResult result) noexcept { try { job.done.set_value(std::move(result)); } catch (...) { } // Already answered: a closing window may have answered before the engine did. } /// The window is going away: no pending request waits for an answer that will never come. inline void abandonCaptures(CaptureTarget& target) noexcept { target.view = nullptr; for (const auto& job : target.pending.close()) answer(*job, std::unexpected("the window is closed")); } // The PNG of an NSImage through NSBitmapImageRep (NSBitmapImageFileTypePNG = 4). inline CaptureResult pngBytes(id image) { const auto tiff = send(image, "TIFFRepresentation"); if (!tiff) return std::unexpected("cannot read the snapshot pixels"); const auto representation = send(type("NSBitmapImageRep"), "imageRepWithData:", tiff); if (!representation) return std::unexpected("cannot decode the snapshot"); const auto png = send(representation, "representationUsingType:properties:", 4UL, send(type("NSDictionary"), "dictionary")); if (!png) return std::unexpected("cannot encode the snapshot as PNG"); const auto bytes = send(png, "bytes"); const auto size = send(png, "length"); return std::vector(bytes, bytes + size); } // Runs on the main thread, where AppKit sessions live. inline void startCapture(void* data) noexcept { std::unique_ptr> owner{static_cast*>(data)}; const auto job = *owner; try { if (!job->target->view) { answer(*job, std::unexpected("the window is closed")); return; } auto handler = ^(id image, id error) { try { job->target->pending.untrack(job); if (!image) { const auto reason = error ? utf8(send(error, "localizedDescription")) : std::string("the engine returned no image"); answer(*job, std::unexpected("snapshot failed: " + reason)); } else { answer(*job, pngBytes(image)); } } catch (...) { try { job->done.set_exception(std::current_exception()); } catch (...) { } } }; // A nil configuration snapshots the visible bounds of the view. // The engine keeps its own copy until the handler ran; the call never depends on the stack block surviving it. const auto heapHandler = Block_copy(handler); try { send(job->target->view, "takeSnapshotWithConfiguration:completionHandler:", static_cast(nullptr), heapHandler); } catch (...) { job->target->pending.untrack(job); Block_release(heapHandler); throw; } Block_release(heapHandler); } catch (...) { try { job->done.set_exception(std::current_exception()); } catch (...) { } } } inline CaptureProvider captureProvider(std::shared_ptr target) { return [target = std::move(target)](std::chrono::milliseconds timeout) -> CaptureResult { auto job = std::make_shared(CaptureJob{target, {}}); auto future = job->done.get_future(); if (!target->pending.track(job)) return std::unexpected("the window is closed"); dispatch_async_f(dispatch_get_main_queue(), new std::shared_ptr(job), startCapture); const auto answered = future.wait_for(timeout) == std::future_status::ready; target->pending.untrack(job); // Whatever the outcome, a finished request is not kept until the window closes. if (!answered) { return std::unexpected("the window did not answer within the capture timeout"); } return future.get(); }; } struct Session { explicit Session(std::string url, WKWebViewOptions options = {}) : url(std::move(url)), options(std::move(options)), contentPolicy(this->url, this->options.contentPolicy) { if (this->options.startupTimeout.count() <= 0) throw std::invalid_argument("WKWebView: startupTimeout must be positive"); } std::string url; WKWebViewOptions options; webfront::detail::BoundContentPolicy contentPolicy; std::function navigationCancelled; struct PendingDownload { std::unique_ptr staging; std::filesystem::path target; bool reserved; bool replace; }; frontend::detail::DownloadReservations reservations; std::map downloadDestinations; // WKDownload -> its paths, until it ends. /// What the answers of a system panel hold instead of `this`: AppKit may deliver one after the session is gone. std::shared_ptr alive = std::make_shared(this); id app = nullptr, window = nullptr, view = nullptr, delegate = nullptr, timer = nullptr; /// The window is shown nearly transparent and made opaque at the page's first frame, or when this timer expires. id presentTimer = nullptr; bool presented = false, presentedByFrame = false; /// Test hook: false does not show the window when the document finishes loading, so only the delay can. bool revealOnLoad = true; /// Seconds before the window is shown even if the document has not loaded. A test lengthens it so that a slow /// first launch of the web content process cannot make the delay win against the load it observes. double presentDelay = 1.0; /// Test hook: called on the main thread when the window has been made opaque. std::function windowShown; const std::chrono::steady_clock::time_point created = std::chrono::steady_clock::now(); id previousDelegate = nullptr, previousMenu = nullptr; long previousActivationPolicy = 0; bool installed = false, running = false, closed = false, loaded = false; bool secondary = false; id sharedDataStore = nullptr; std::function closedHook; bool receivedResponse = false, committed = false; std::exception_ptr error; std::shared_ptr captureTarget = std::make_shared(); CaptureRegistration captureRegistration; ~Session() { *alive = nullptr; endSheets(); // Each open panel answers "cancel" now, while the view still exists to receive it. abandonDownloads(); captureRegistration = {}; abandonCaptures(*captureTarget); if (timer) { send(timer, "invalidate"); send(timer, "release"); } if (presentTimer) { send(presentTimer, "invalidate"); send(presentTimer, "release"); } if (view) { send(view, "setNavigationDelegate:", static_cast(nullptr)); send(view, "setUIDelegate:", static_cast(nullptr)); send(view, "stopLoading"); attach(view, nullptr); } if (window) { send(window, "setDelegate:", static_cast(nullptr)); send(window, "close"); send(window, "release"); } send(view, "release"); if (installed) { send(app, "setDelegate:", previousDelegate); if (previousMenu) { send(app, "setMainMenu:", previousMenu); } else { // AppKit ignores setMainMenu:nil. Install an empty menu so our Quit item // cannot survive its delegate, including a close before the first run(). Object emptyMenu(send(type("NSMenu"), "new")); send(app, "setMainMenu:", emptyMenu.get()); } send(app, "setActivationPolicy:", previousActivationPolicy); } send(previousMenu, "release"); send(previousDelegate, "release"); if (delegate) { attach(delegate, nullptr); send(delegate, "release"); } } /// Milliseconds since the process was executed, so the trace covers the loading of the frameworks too. static long long millisecondsSinceExec() noexcept { int mib[4] = {CTL_KERN, KERN_PROC, KERN_PROC_PID, static_cast(getpid())}; kinfo_proc info{}; std::size_t size = sizeof(info); if (sysctl(mib, 4, &info, &size, nullptr, 0) != 0) return -1; const timeval started = info.kp_proc.p_un.__p_starttime; timeval now{}; gettimeofday(&now, nullptr); return static_cast(now.tv_sec - started.tv_sec) * 1000 + (now.tv_usec - started.tv_usec) / 1000; } /// WEBFRONT_STARTUP_TRACE=1 reports the milestones of the view's start on standard error. void trace(const char* milestone) const noexcept { static const bool enabled = [] { const auto* value = std::getenv("WEBFRONT_STARTUP_TRACE"); return value && *value && std::string_view{value} != "0"; }(); if (enabled) std::fprintf(stderr, "WebFront startup: %s at %lld ms (session %lld ms)\n", milestone, millisecondsSinceExec(), static_cast(std::chrono::duration_cast(std::chrono::steady_clock::now() - created).count())); } /// Makes the window opaque, once: at the page's first frame, or when the delay has expired. void presentWindow(bool byFrame) { if (presented || closed || !window) return; presented = true; presentedByFrame = byFrame; if (presentTimer) { send(presentTimer, "invalidate"); send(presentTimer, "release"); presentTimer = nullptr; } if (options.visible) send(window, "setAlphaValue:", 1.0); trace("window shown"); if (windowShown) windowShown(); } /// Dismisses the panels attached to the window: their completion handlers run, so WebKit gets its answers. void endSheets() noexcept { if (!window) return; const auto sheets = send(window, "sheets"); const auto count = send(sheets, "count"); for (auto index = count; index > 0; --index) send(window, "endSheet:", send(sheets, "objectAtIndex:", index - 1)); } /// Cancels the downloads still running and removes the incomplete files they were writing. void abandonDownloads() noexcept { auto pending = std::exchange(downloadDestinations, {}); // Their failure callbacks must find nothing to settle. for (const auto& [download, paths] : pending) { send(download, "cancel:", static_cast(nullptr)); if (paths.reserved) reservations.release(paths.target); } } void close() noexcept { if (secondary && closed) return; // the primary window repeats its stop request: the loop may have started since the first call closed = true; if (secondary) { if (window) send(window, "orderOut:", static_cast(nullptr)); if (closedHook) { try { closedHook(); } catch (...) {} } return; } if (!running) return; send(app, "stop:", static_cast(nullptr)); // stop: takes effect after an event. A close from a WebKit callback/timer must wake run. auto event = send(type("NSEvent"), "otherEventWithType:location:modifierFlags:timestamp:windowNumber:context:subtype:data1:data2:", 15UL, CGPoint{0, 0}, 0UL, 0.0, 0L, static_cast(nullptr), static_cast(0), 0L, 0L); send(app, "postEvent:atStart:", event, static_cast(true)); } template void guard(Function&& function) noexcept { try { function(); } catch (...) { if (!error) error = std::current_exception(); close(); } } void fail(std::string message) noexcept { guard([&] { throw std::runtime_error("WKWebView: " + message); }); } void rejectNavigation(std::string_view diagnostic) { if (!committed) fail(std::string(diagnostic)); else if (navigationCancelled) navigationCancelled(); } void addMenuItem(id menu, const MenuCommand& command, id target = nullptr) { Object label(text(command.title)); Object shortcut(text(command.key)); Object item( send(send(type("NSMenuItem"), "alloc"), "initWithTitle:action:keyEquivalent:", label.get(), sel_registerName(command.action), shortcut.get())); send(item.get(), "setTarget:", target); send(menu, "addItem:", item.get()); } void installMenu() { Object menu(send(type("NSMenu"), "new")); for (const auto title : {"Application", "Edit"}) { Object label(text(title)); Object parent(send(type("NSMenuItem"), "new")); send(parent.get(), "setTitle:", label.get()); Object submenu(send(send(type("NSMenu"), "alloc"), "initWithTitle:", label.get())); if (std::string_view(title) == "Application") { addMenuItem(submenu.get(), {"Quit", "webfrontQuit:", "q"}, delegate); } else { addMenuItem(submenu.get(), {"Cut", "cut:", "x"}); addMenuItem(submenu.get(), {"Copy", "copy:", "c"}); addMenuItem(submenu.get(), {"Paste", "paste:", "v"}); addMenuItem(submenu.get(), {"Select All", "selectAll:", "a"}); } send(parent.get(), "setSubmenu:", submenu.get()); send(menu.get(), "addItem:", parent.get()); } send(app, "setMainMenu:", menu.get()); } void create() { app = send(type("NSApplication"), "sharedApplication"); if (!secondary && send(app, "isRunning")) throw std::runtime_error("WKWebView: open() owns the AppKit event loop; call it outside an existing NSApplication run loop"); if (!secondary) { previousDelegate = send(send(app, "delegate"), "retain"); previousMenu = send(send(app, "mainMenu"), "retain"); previousActivationPolicy = send(app, "activationPolicy"); delegate = send(reinterpret_cast(delegateClass()), "new"); attach(delegate, this); installed = true; send(app, "setDelegate:", delegate); send(app, "setActivationPolicy:", options.visible ? applicationActivationPolicy() : 2L); installMenu(); send(app, "finishLaunching"); } else { delegate = send(reinterpret_cast(delegateClass()), "new"); attach(delegate, this); } Object configuration(send(type("WKWebViewConfiguration"), "new")); send(configuration.get(), "setWebsiteDataStore:", sharedDataStore ? sharedDataStore : send(type("WKWebsiteDataStore"), "nonPersistentDataStore")); // Hidden content otherwise suspends once its load event completes. Use the public macOS 14+ preference // so asynchronous bridge/Worker work and close requests keep progressing without a visible native window. if (!options.visible) { const auto preferences = send(configuration.get(), "preferences"); const auto selector = sel_registerName("setInactiveSchedulingPolicy:"); if (!send(preferences, "respondsToSelector:", selector)) throw std::runtime_error("WKWebView: hidden sessions require macOS 14 or later (inactiveSchedulingPolicy)"); send(preferences, "setInactiveSchedulingPolicy:", 2L); // WKInactiveSchedulingPolicyNone } if (!options.launch.secret.empty()) { // At the start of every document, in the main frame only: the script itself checks the origin. Object source(text(::webfront::detail::viewSecretScript(options.launch.secret, options.launch.origin))); Object script(send(send(type("WKUserScript"), "alloc"), "initWithSource:injectionTime:forMainFrameOnly:", source.get(), 0L, static_cast(true))); send(send(configuration.get(), "userContentController"), "addUserScript:", script.get()); } // Deliver script-created popup attempts to the delegates, which always cancel unmanaged views. send(send(configuration.get(), "preferences"), "setJavaScriptCanOpenWindowsAutomatically:", static_cast(true)); const auto windowOptions = frontend::detail::resolveWindow(options.window); const CGRect bounds{ { 0, 0}, {static_cast(windowOptions.width), static_cast(windowOptions.height)} }; view = send(send(reinterpret_cast(viewClass()), "alloc"), "initWithFrame:configuration:", bounds, configuration.get()); if (!view) throw std::runtime_error("WKWebView: cannot create web view"); attach(view, this); captureTarget->view = view; captureTarget->pending.open(); if (!secondary) captureRegistration = CaptureRegistration{captureProvider(captureTarget)}; send(view, "setAutoresizingMask:", 18UL); // NSViewWidthSizable | NSViewHeightSizable send(view, "setInspectable:", static_cast(options.contentPolicy.devToolsEnabled)); send(view, "setNavigationDelegate:", delegate); send(view, "setUIDelegate:", delegate); window = send(send(type("NSWindow"), "alloc"), "initWithContentRect:styleMask:backing:defer:", bounds, 15UL, 2UL, static_cast(false)); if (!window) throw std::runtime_error("WKWebView: cannot create window (a WindowServer session is required)"); send(window, "setReleasedWhenClosed:", static_cast(false)); if (const auto color = frontend::detail::parseBackground(windowOptions.background)) { const auto native = send(type("NSColor"), "colorWithSRGBRed:green:blue:alpha:", static_cast((*color)[0]), static_cast((*color)[1]), static_cast((*color)[2]), static_cast((*color)[3])); send(window, "setBackgroundColor:", native); // A translucent colour is only seen through if the window is not opaque: without this AppKit fills the window as // if the alpha were 1. Opaque colours keep the default opaque window, which is cheaper to composite. if ((*color)[3] < 1.0f) send(window, "setOpaque:", static_cast(false)); if (send(view, "respondsToSelector:", sel_registerName("setUnderPageBackgroundColor:"))) // macOS 12 send(view, "setUnderPageBackgroundColor:", native); // behind the page, e.g. when scrolling past its edge // The view paints its own white behind a page that does not paint: stop it, so the window's colour shows through // before the load and behind a transparent page. WebKit offers no public API for it: the `drawsBackground` key is // set only when this runtime answers to its setter, never by calling an unknown key. if (send(view, "respondsToSelector:", sel_registerName("_setDrawsBackground:")) || send(view, "respondsToSelector:", sel_registerName("setDrawsBackground:"))) { Object key(text("drawsBackground")); send(view, "setValue:forKey:", send(type("NSNumber"), "numberWithBool:", static_cast(false)), key.get()); } } send(window, "setDelegate:", delegate); Object title(text(windowOptions.title)); send(window, "setTitle:", title.get()); send(window, "setContentView:", view); send(window, "makeFirstResponder:", view); send(window, "center"); trace("view created"); if (options.visible) { // Nearly transparent, not hidden: an occluded window would suspend the page's animation frames. send(window, "setAlphaValue:", 0.01); send(window, "makeKeyAndOrderFront:", static_cast(nullptr)); send(app, "activateIgnoringOtherApps:", static_cast(true)); } } void start() { timer = send(send(type("NSTimer"), "scheduledTimerWithTimeInterval:target:selector:userInfo:repeats:", std::chrono::duration(options.startupTimeout).count(), delegate, sel_registerName("webfrontTimeout:"), static_cast(nullptr), static_cast(false)), "retain"); if (options.visible) { presentTimer = send(send(type("NSTimer"), "timerWithTimeInterval:target:selector:userInfo:repeats:", presentDelay, delegate, sel_registerName("webfrontPresent:"), static_cast(nullptr), static_cast(false)), "retain"); // Common modes: the delay also runs while the system tracks a window move or resize. Object mode(text("kCFRunLoopCommonModes")); send(send(type("NSRunLoop"), "currentRunLoop"), "addTimer:forMode:", presentTimer, mode.get()); } trace("load started"); Object urlText(text(url)); auto nativeUrl = send(type("NSURL"), "URLWithString:", urlText.get()); if (!nativeUrl) throw std::runtime_error("WKWebView: invalid application URL"); if (!send(view, "loadRequest:", send(type("NSURLRequest"), "requestWithURL:", nativeUrl))) fail("initial navigation failed to start"); } void run() { if (!closed) { running = true; send(app, "run"); running = false; } if (error) std::rethrow_exception(error); } void navigationAction(id action, void (^decision)(long)) noexcept { long policy = 0; // WKNavigationActionPolicyCancel guard([&] { const auto frame = send(action, "targetFrame"); if (!frame) return; // No public WebKit user-activation flag: conservatively block every popup. if (!send(frame, "isMainFrame")) { policy = 1; return; } const auto destination = utf8(send(send(send(action, "request"), "URL"), "absoluteString")); if (contentPolicy.allowsNavigation(destination)) { policy = 1; // WKNavigationActionPolicyAllow // and generated Blobs: WKNavigationActionPolicyDownload (macOS 11.3). if (send(action, "respondsToSelector:", sel_registerName("shouldPerformDownload")) && send(action, "shouldPerformDownload")) policy = 2; } else rejectNavigation("initial navigation was denied by contentPolicy"); }); decision(policy); // Exactly once, including after a C++ exception. } /// The address a frame is judged by: always its security origin, never the address of its request. A sandboxed frame /// without allow-same-origin loads the application's own URL yet has an opaque origin (empty protocol and host, judged as /// no address, so never the application's). A frame the page creates without a document of its own (`about:blank`, /// `about:srcdoc`) inherits its creator's origin, which is what the policy has to see. static std::string effectiveFrameUrl(id frame) { const auto origin = send(frame, "securityOrigin"); const auto protocol = utf8(send(origin, "protocol")); const auto host = utf8(send(origin, "host")); if (protocol.empty() || host.empty()) return {}; const auto port = send(origin, "port"); return protocol + "://" + host + (port > 0 ? ":" + std::to_string(port) : "") + "/"; } /// : the system panel as a sheet of the window, or the test injection. The handler runs exactly once. void chooseFilesForPage(id parameters, id frame, void (^completion)(id)) noexcept { id result = nullptr; // NSArray*; nil cancels. bool deferred = false; guard([&] { // Only the application's own origin may open a chooser, not every origin that navigation admits. if (!contentPolicy.isApplicationOrigin(effectiveFrameUrl(frame))) return; if (options.chooseFiles) { const auto files = options.chooseFiles(); if (files.empty()) return; const auto urls = send(type("NSMutableArray"), "array"); for (const auto& file : files) { Object path(text(file)); send(urls, "addObject:", send(type("NSURL"), "fileURLWithPath:", path.get())); } result = urls; return; } const auto panel = send(type("NSOpenPanel"), "openPanel"); send(panel, "setAllowsMultipleSelection:", send(parameters, "allowsMultipleSelection")); // chooses a folder, and only a folder. const auto directories = send(parameters, "allowsDirectories"); send(panel, "setCanChooseDirectories:", directories); send(panel, "setCanChooseFiles:", static_cast(!directories)); auto handler = Block_copy(completion); bool retained = false; try { send(panel, "retain"); retained = true; void (^finished)(long) = ^(long response) { handler(response == 1 ? send(panel, "URLs") : nullptr); // NSModalResponseOK send(panel, "release"); Block_release(handler); }; send(panel, "beginSheetModalForWindow:completionHandler:", window, finished); } catch (...) { if (retained) send(panel, "release"); Block_release(handler); // The panel never took the handler: `completion` answers below. throw; } deferred = true; }); if (!deferred) completion(result); } /// `alert`, `confirm` and `prompt` (WKUIDelegate): an NSAlert sheet of the window, or the test injection. `answer` runs exactly once, /// with a dismissed answer when the page's origin is not the application's, when the window closes, or when the box cannot be shown. void runScriptDialog(ScriptDialog dialog, id frame, std::function answer) noexcept { ScriptDialogAnswer result; // Dismissed. bool deferred = false; guard([&] { if (!contentPolicy.isApplicationOrigin(effectiveFrameUrl(frame))) return; if (options.answerScriptDialog) { result = options.answerScriptDialog(dialog); return; } const id alert = send(send(type("NSAlert"), "alloc"), "init"); // Owned until the sheet answers. id field = nullptr; bool retained = true; try { { Object message(text(dialog.message)); send(alert, "setMessageText:", message.get()); } const bool confirming = dialog.kind != ScriptDialog::Kind::alert; { Object accept(text("OK")); send(alert, "addButtonWithTitle:", accept.get()); // NSAlertFirstButtonReturn (1000). } if (confirming) { Object cancel(text("Cancel")); send(alert, "addButtonWithTitle:", cancel.get()); } if (dialog.kind == ScriptDialog::Kind::prompt) { field = send(send(type("NSTextField"), "alloc"), "initWithFrame:", CGRect{{0, 0}, {300, 24}}); Object value(text(dialog.defaultText)); send(field, "setStringValue:", value.get()); send(alert, "setAccessoryView:", field); send(alert, "layout"); send(send(alert, "window"), "setInitialFirstResponder:", field); } auto shared = std::make_shared>(std::move(answer)); void (^finished)(long) = ^(long response) { ScriptDialogAnswer reply; reply.accepted = response == 1000; // endSheet: at window close reports NSModalResponseCancel. if (reply.accepted && field) reply.text = utf8(send(field, "stringValue")); (*shared)(std::move(reply)); if (field) send(field, "release"); send(alert, "release"); }; try { send(alert, "beginSheetModalForWindow:completionHandler:", window, finished); } catch (...) { // The call failed to dispatch, so the block never runs and never releases: this function still owns // the alert and the field (released below) and answers dismissed. answer = std::move(*shared); throw; } retained = false; // The sheet started: the block owns the alert and the field until it answers. } catch (...) { if (retained) { if (field) send(field, "release"); send(alert, "release"); } throw; } deferred = true; }); if (!deferred) answer(std::move(result)); } /// A WKDownload needs a destination that does not exist: the test folder, or the user's choice in a save panel. void chooseDownloadDestination(id download, const std::string& suggested, void (^completion)(id)) noexcept { id result = nullptr; // NSURL*; nil cancels the download. bool deferred = false; guard([&] { if (!options.downloadDirectory.empty()) { std::filesystem::create_directories(options.downloadDirectory); // WebKit needs the folder to exist. std::filesystem::path destination; try { destination = reservations.reserve(options.downloadDirectory, suggested); } catch (const std::filesystem::filesystem_error&) { return; // No candidate is free: nil cancels this download without stopping the session. } std::unique_ptr staging; try { staging = std::make_unique(destination.parent_path()); } catch (...) { reservations.release(destination); throw; } const auto temporary = staging->path(); downloadDestinations[download] = {std::move(staging), destination, true, false}; Object path(text(temporary.string())); result = send(type("NSURL"), "fileURLWithPath:", path.get()); return; } const auto panel = send(type("NSSavePanel"), "savePanel"); Object name(text(std::filesystem::path(suggested).filename().string())); send(panel, "setNameFieldStringValue:", name.get()); auto handler = Block_copy(completion); bool retained = false; auto token = alive; // Not `this`: the window may close, and the session end, while the panel is open. const id key = download; // By value: the panel answers after this lambda and its references are gone. try { send(panel, "retain"); retained = true; void (^finished)(long) = ^(long response) { id chosen = response == 1 ? send(panel, "URL") : nullptr; // NSModalResponseOK if (chosen && !*token) chosen = nullptr; // The session is gone: nobody could move the file afterwards. try { if (chosen) { const std::filesystem::path target = utf8(send(chosen, "path")); std::error_code code; const bool replace = std::filesystem::exists(target, code); if (code) throw std::filesystem::filesystem_error("Cannot inspect download target", target, code); auto& sessionReservations = (*token)->reservations; if (!sessionReservations.reserveExact(target)) throw std::filesystem::filesystem_error("Another download is writing this target", target, std::make_error_code(std::errc::file_exists)); try { auto staging = std::make_unique(target.parent_path()); const auto temporary = staging->path(); Object path(text(temporary.string())); chosen = send(type("NSURL"), "fileURLWithPath:", path.get()); (*token)->downloadDestinations[key] = {std::move(staging), target, true, replace}; } catch (...) { sessionReservations.release(target); throw; } } } catch (const std::filesystem::filesystem_error&) { chosen = nullptr; // No staging, or the target is taken: answer WebKit once, without crossing the AppKit block. } handler(chosen); send(panel, "release"); Block_release(handler); }; send(panel, "beginSheetModalForWindow:completionHandler:", window, finished); } catch (...) { if (retained) send(panel, "release"); Block_release(handler); // The panel never took the handler: `completion` answers below. throw; } deferred = true; }); if (!deferred) completion(result); } void downloadEnded(id download, bool completed) noexcept { const auto found = downloadDestinations.find(download); if (found == downloadDestinations.end()) return; const auto pending = std::move(found->second); downloadDestinations.erase(found); if (completed && !pending.staging->finish(pending.target, pending.replace)) { completed = false; std::fprintf(stderr, "WebFront: the download could not be installed at %s\n", pending.target.string().c_str()); } if (pending.reserved) reservations.release(pending.target); if (completed && options.downloadFinished) guard([&] { options.downloadFinished(pending.target.string()); }); } void navigationResponse(id response, void (^decision)(long)) noexcept { long policy = 1; // WKNavigationResponsePolicyAllow guard([&] { if (!send(response, "isForMainFrame")) return; const auto http = send(response, "response"); // Server redirects do not necessarily produce another navigation-action callback. if (!contentPolicy.allowsNavigation(utf8(send(send(http, "URL"), "absoluteString")))) { policy = 0; rejectNavigation("initial navigation response was denied by contentPolicy"); return; } // A response the engine cannot display (an attachment, an archive) is saved, not shown. if (committed) { if (!send(response, "canShowMIMEType")) policy = 2; // WKNavigationResponsePolicyDownload return; } if (send(http, "respondsToSelector:", sel_registerName("statusCode"))) { const auto status = send(http, "statusCode"); if (!successfulHttpStatus(status)) { policy = 0; fail("initial navigation failed (HTTP " + std::to_string(status) + ")"); } else { receivedResponse = true; } } }); decision(error ? 0 : policy); } }; inline void sessionClosed(id self, SEL, id) { if (auto s = session(self)) s->close(); } inline unsigned long applicationShouldTerminate(id self, SEL selector, id app) { sessionClosed(self, selector, app); return 0; // NSTerminateCancel: never terminate the embedding process. } inline BOOL terminateAfterLastWindow(id, SEL, id) { return false; } inline void startupTimedOut(id self, SEL, id) { if (auto s = session(self)) s->fail("initial navigation timed out after " + std::to_string(s->options.startupTimeout.count()) + " milliseconds"); } inline void presentDelayExpired(id self, SEL, id) { if (auto s = session(self)) { s->trace("present delay expired"); s->guard([&] { s->presentWindow(false); }); } } inline void navigationFinished(id self, SEL, id, id) { if (auto s = session(self)) { if (!s->receivedResponse) { // Some WebKit versions finish an internal error document without reporting // didFailNavigation. Such a document must not disable the startup deadline. s->fail("initial navigation failed without an HTTP response"); } else { s->loaded = true; send(s->timer, "invalidate"); if (s->revealOnLoad) { s->trace("document loaded"); s->guard([&] { s->presentWindow(true); }); } } } } inline void navigationCommitted(id self, SEL, id, id) { if (auto s = session(self)) s->committed = true; } inline void navigationFailed(id self, id error) { if (auto s = session(self); s && !s->closed && !s->committed) { s->guard([&] { s->fail("initial navigation failed (" + utf8(send(error, "localizedDescription")) + ")"); }); } } inline void contentProcessTerminated(id self, SEL, id) { if (auto s = session(self)) s->fail("web content process terminated"); } inline void addApplicationMethods(Class cls) { addMethod(cls, "windowWillClose:", sessionClosed, "v@:@"); addMethod(cls, "webViewDidClose:", sessionClosed, "v@:@"); addMethod(cls, "webfrontQuit:", sessionClosed, "v@:@"); addMethod(cls, "applicationShouldTerminate:", applicationShouldTerminate, "Q@:@"); addMethod(cls, "applicationShouldTerminateAfterLastWindowClosed:", terminateAfterLastWindow, "B@:@"); addMethod(cls, "webfrontTimeout:", startupTimedOut, "v@:@"); addMethod(cls, "webfrontPresent:", presentDelayExpired, "v@:@"); } inline void addNavigationMethods(Class cls) { addMethod( cls, "webView:decidePolicyForNavigationAction:decisionHandler:", +[](id self, SEL, id, id action, void (^decision)(long)) { if (auto s = session(self)) s->navigationAction(action, decision); else decision(0); }, "v@:@@@?"); addMethod( cls, "webView:decidePolicyForNavigationResponse:decisionHandler:", +[](id self, SEL, id, id response, void (^decision)(long)) { if (auto s = session(self)) s->navigationResponse(response, decision); else decision(0); }, "v@:@@@?"); addMethod( cls, "webView:createWebViewWithConfiguration:forNavigationAction:windowFeatures:", +[](id, SEL, id, id, id, id) -> id { return nullptr; }, "@@:@@@@"); // File chooser (WKUIDelegate) and downloads (WKNavigationDelegate, WKDownloadDelegate), issue #451. addMethod( cls, "webView:runOpenPanelWithParameters:initiatedByFrame:completionHandler:", +[](id self, SEL, id, id parameters, id frame, void (^completion)(id)) { if (auto s = session(self)) s->chooseFilesForPage(parameters, frame, completion); else completion(nullptr); }, "v@:@@@@?"); // JavaScript dialogs (WKUIDelegate), issue #452. Without these WebKit answers nothing and the page's call does not return. addMethod( cls, "webView:runJavaScriptAlertPanelWithMessage:initiatedByFrame:completionHandler:", +[](id self, SEL, id, id message, id frame, void (^completion)()) { auto handler = Block_copy(completion); auto done = [handler](ScriptDialogAnswer) { handler(); Block_release(handler); }; if (auto s = session(self)) s->runScriptDialog({ScriptDialog::Kind::alert, utf8(message), {}}, frame, done); else done({}); }, "v@:@@@@?"); addMethod( cls, "webView:runJavaScriptConfirmPanelWithMessage:initiatedByFrame:completionHandler:", +[](id self, SEL, id, id message, id frame, void (^completion)(BOOL)) { auto handler = Block_copy(completion); auto done = [handler](ScriptDialogAnswer reply) { handler(static_cast(reply.accepted)); Block_release(handler); }; if (auto s = session(self)) s->runScriptDialog({ScriptDialog::Kind::confirm, utf8(message), {}}, frame, done); else done({}); }, "v@:@@@@?"); addMethod( cls, "webView:runJavaScriptTextInputPanelWithPrompt:defaultText:initiatedByFrame:completionHandler:", +[](id self, SEL, id, id message, id defaultText, id frame, void (^completion)(id)) { auto handler = Block_copy(completion); auto done = [handler](ScriptDialogAnswer reply) { Object value(reply.accepted ? text(reply.text) : nullptr); handler(value.get()); // nil is the prompt's null. Block_release(handler); }; if (auto s = session(self)) s->runScriptDialog({ScriptDialog::Kind::prompt, utf8(message), defaultText ? utf8(defaultText) : std::string{}}, frame, done); else done({}); }, "v@:@@@@@?"); const auto becameDownload = +[](id self, SEL, id, id, id download) { send(download, "setDelegate:", self); }; addMethod(cls, "webView:navigationAction:didBecomeDownload:", becameDownload, "v@:@@@"); addMethod(cls, "webView:navigationResponse:didBecomeDownload:", becameDownload, "v@:@@@"); addMethod( cls, "download:decideDestinationUsingResponse:suggestedFilename:completionHandler:", +[](id self, SEL, id download, id, id suggested, void (^completion)(id)) { if (auto s = session(self)) s->chooseDownloadDestination(download, utf8(suggested), completion); else completion(nullptr); }, "v@:@@@@?"); addMethod( cls, "downloadDidFinish:", +[](id self, SEL, id download) { if (auto s = session(self)) s->downloadEnded(download, true); }, "v@:@"); addMethod( cls, "download:didFailWithError:resumeData:", +[](id self, SEL, id download, id, id) { if (auto s = session(self)) s->downloadEnded(download, false); }, "v@:@@@"); addMethod(cls, "webView:didFinishNavigation:", navigationFinished, "v@:@@"); addMethod(cls, "webView:didCommitNavigation:", navigationCommitted, "v@:@@"); const auto failed = +[](id self, SEL, id, id, id error) { navigationFailed(self, error); }; addMethod(cls, "webView:didFailProvisionalNavigation:withError:", failed, "v@:@@@"); addMethod(cls, "webView:didFailNavigation:withError:", failed, "v@:@@@"); addMethod(cls, "webViewWebContentProcessDidTerminate:", contentProcessTerminated, "v@:@"); } inline Class delegateClass() { static Class cls = registerClass("WebFrontWKDelegate_v1", reinterpret_cast(type("NSObject")), [](Class result) { addApplicationMethods(result); addNavigationMethods(result); }); return cls; } inline Class viewClass() { static Class cls = registerClass("WebFrontWKView_v1", reinterpret_cast(type("WKWebView")), [](Class result) { addMethod( result, "willOpenMenu:withEvent:", +[](id self, SEL selector, id menu, id event) { // WebKit may isa-swizzle the view for KVO. Start at WKWebView itself, // rather than the dynamic object's superclass (which could be our class). objc_super parent{self, reinterpret_cast(type("WKWebView"))}; reinterpret_cast(objc_msgSendSuper)(&parent, selector, menu, event); if (auto s = session(self); s && !s->options.contentPolicy.contextMenusEnabled) send(menu, "removeAllItems"); }, "v@:@@"); }); return cls; } // All windows belong to the active AppKit session and are used on the main thread. struct Windows { Session* primary = nullptr; std::map> secondary; std::vector> finished; static Windows& instance() { static Windows windows; return windows; } void retire(const std::string& page) { const auto found = secondary.find(page); if (found == secondary.end()) return; // run() returned long ago for this window, so nothing else can report a page that failed to load. if (found->second->error) { try { std::rethrow_exception(found->second->error); } catch (const std::exception& failure) { std::fprintf(stderr, "WKWebViewFrontend: the secondary window of '%s' closed: %s\n", page.c_str(), failure.what()); } catch (...) {} } finished.push_back(std::move(found->second)); secondary.erase(found); dispatch_async_f( dispatch_get_main_queue(), nullptr, +[](void*) { auto retired = std::move(instance().finished); retired.clear(); }); } void clear() { secondary.clear(); finished.clear(); primary = nullptr; } }; inline void openSecondary(std::string_view address, std::string_view port, std::string_view page, WKWebViewOptions options) { auto& windows = Windows::instance(); // A first window that closed still runs its loop until the pass ends: a window built now would be destroyed with it. if (!windows.primary || windows.primary->closed) throw std::logic_error("WKWebView: no application window is open"); std::string key(page); if (const auto found = windows.secondary.find(key); found != windows.secondary.end()) { // A hidden window stays hidden: ordering it to the front would show it. if (found->second->options.visible) send(found->second->window, "makeKeyAndOrderFront:", static_cast(nullptr)); return; } // The first window's visibility and startup delay: a hidden application never shows a window or takes the focus. options.visible = windows.primary->options.visible; options.startupTimeout = windows.primary->options.startupTimeout; auto child = std::make_unique(applicationUrl(address, port, page, options.launch.origin), std::move(options)); child->secondary = true; child->sharedDataStore = send(send(windows.primary->view, "configuration"), "websiteDataStore"); child->create(); child->closedHook = [key] { Windows::instance().retire(key); }; // Registered only once started: a window whose start throws is not left in the table, and its page can be opened again. // One that closed during start() already retired itself from a table that did not hold it yet, without a word: the // caller is still waiting, so the failure is thrown to it. child->start(); if (child->closed) { if (child->error) std::rethrow_exception(child->error); throw std::runtime_error("WKWebView: the secondary window of '" + key + "' closed while it started"); } windows.secondary[key] = std::move(child); } inline bool closeSecondary(std::string_view page) { auto& windows = Windows::instance(); const auto found = windows.secondary.find(std::string(page)); if (found == windows.secondary.end() || found->second->closed) return false; found->second->close(); return true; } inline void open(std::string_view address, std::string_view port, std::string_view file, const WKWebViewOptions& options) { initialize(); if (opening) throw std::runtime_error("WKWebView: nested open() calls are unsupported"); struct Opening { Opening() { opening = true; } ~Opening() { opening = false; } } openingScope; Object pool(send(type("NSAutoreleasePool"), "new")); Session window(applicationUrl(address, port, file, options.launch.origin), options); window.create(); window.start(); // The AppKit loop drains the main queue: a wake is a block on it. Closing completes pending operations stopped, // also when run() throws or returns at once because the window already closed. auto& host = executorHost(); host.attach([&host] { dispatch_async_f( dispatch_get_main_queue(), &host, +[](void* context) { static_cast(context)->drain(); }); }); // Published once the loop is attached (this is the interface thread), withdrawn before the session releases the window. auto& windowHost = detail::wkwebview::windowHost(); windowHost.publish({.kind = NativeWindowKind::cocoa, .pointer = window.window, .portalParent = {}}); struct Closing { UIExecutorHost& host; NativeWindowHost& windowHost; ~Closing() { windowHost.retract(); host.close(); } } closing{host, windowHost}; auto& windows = Windows::instance(); windows.primary = &window; struct Others { Windows& windows; ~Others() { windows.clear(); } } others{windows}; window.run(); } /// A host's close request, on the main thread: the session ends as it does for the Quit menu item, through the /// window's delegate (none once the session is being released). inline void requestSessionClose(void* window) { send(send(static_cast(window), "delegate"), "webfrontQuit:", static_cast(nullptr)); } } // namespace webfront::frontend::detail::wkwebview #endif namespace webfront::frontend { /** @brief Optional macOS embedded window. Main thread only; see docs/WKWEBVIEW.md. */ struct WKWebViewFrontend { static constexpr Action action{Action::closeServerAfterOpen}; static constexpr bool requiresMainThread = true; // AppKit /// Asks the window to close, from any thread; false when no window is open (see CloseRequest.hpp). static bool requestClose([[maybe_unused]] std::optional session = std::nullopt) noexcept { #if defined(WEBFRONT_EMBED_WKWEBVIEW) && defined(__APPLE__) return detail::requestWindowClose(uiExecutor(), nativeWindow(), [](const NativeWindowHandle& window) { detail::wkwebview::requestSessionClose(window.pointer); }, session); #else return false; #endif } static void openSecondaryWindow([[maybe_unused]] std::string_view address, [[maybe_unused]] std::string_view port, [[maybe_unused]] std::string_view page, [[maybe_unused]] const ContentPolicy& policy, [[maybe_unused]] const WindowOptions& window, [[maybe_unused]] const ViewLaunch& launch) { #if defined(WEBFRONT_EMBED_WKWEBVIEW) && defined(__APPLE__) try { invokeOnUIThread(uiExecutor(), [&] { detail::wkwebview::openSecondary(address, port, page, WKWebViewOptions{.contentPolicy = policy, .window = window, .launch = launch}); }); } catch (const UIExecutorUnavailable&) { throw std::logic_error("WKWebView: no application window is open"); } #else initialize(); #endif } static bool closeSecondaryWindow([[maybe_unused]] std::string_view page) { #if defined(WEBFRONT_EMBED_WKWEBVIEW) && defined(__APPLE__) bool closed = false; try { invokeOnUIThread(uiExecutor(), [&] { closed = detail::wkwebview::closeSecondary(page); }); } catch (const UIExecutorUnavailable&) { return false; } return closed; #else return false; #endif } static void initialize() { #if defined(WEBFRONT_EMBED_WKWEBVIEW) && defined(__APPLE__) detail::wkwebview::initialize(); #else throw std::runtime_error("WKWebViewFrontend is unavailable. Configure on macOS with -DWEBFRONT_EMBED_WKWEBVIEW=ON"); #endif } /// The main thread while open() runs the AppKit loop (see UIExecutor.hpp). [[nodiscard]] static UIExecutor uiExecutor() { return detail::wkwebview::executorHost().executor(); } /// The NSWindow, readable on the main thread while open() runs (see NativeWindow.hpp). [[nodiscard]] static NativeWindow nativeWindow() { return detail::wkwebview::windowHost().window(); } static void open(std::string_view port, std::string_view file) { open("127.0.0.1", port, file); } template requires std::same_as, WKWebViewOptions> static void open(std::string_view address, std::string_view port, std::string_view file, Options&& options) { #if defined(WEBFRONT_EMBED_WKWEBVIEW) && defined(__APPLE__) detail::wkwebview::open(address, port, file, options); #else (void)address; (void)port; (void)file; (void)options; initialize(); #endif } static void open(std::string_view address, std::string_view port, std::string_view file, const ContentPolicy& policy = {}) { open(address, port, file, WKWebViewOptions{.contentPolicy = policy}); } static void open(std::string_view address, std::string_view port, std::string_view file, const ContentPolicy& policy, const WindowOptions& window) { open(address, port, file, WKWebViewOptions{.contentPolicy = policy, .window = window}); } static void open(std::string_view address, std::string_view port, std::string_view file, const ContentPolicy& policy, const WindowOptions& window, const ViewLaunch& launch) { open(address, port, file, WKWebViewOptions{.contentPolicy = policy, .window = window, .launch = launch}); } }; } // namespace webfront::frontend