From dd3e549dd9716800528e8737627ed5fb2ed6be4e Mon Sep 17 00:00:00 2001 From: Ambroise Leclerc <6860842+ambroise-leclerc@users.noreply.github.com> Date: Mon, 23 Nov 2026 17:52:05 +0100 Subject: [PATCH 01/11] Share the secondary window registry and the interface session of the native frontends (#652) --- docs/CHANGELOG.md | 1 + docs/FRONTENDS.md | 2 +- include/webfront/frontend/WKWebView.hpp | 160 +++++------ include/webfront/frontend/WebKitGTK.hpp | 171 +++++------- include/webfront/frontend/WebView2.hpp | 172 +++++------- include/webfront/frontend/WindowRegistry.hpp | 168 ++++++++++++ test/unit/CMakeLists.txt | 2 +- test/unit/WindowRegistryTests.cpp | 266 +++++++++++++++++++ 8 files changed, 625 insertions(+), 317 deletions(-) create mode 100644 include/webfront/frontend/WindowRegistry.hpp create mode 100644 test/unit/WindowRegistryTests.cpp diff --git a/docs/CHANGELOG.md b/docs/CHANGELOG.md index 41744f64..4ffa6f45 100644 --- a/docs/CHANGELOG.md +++ b/docs/CHANGELOG.md @@ -50,6 +50,7 @@ in a native pseudoterminal, and a faster, less flashy start of the native window - Choose the colour of the WebKitGTK view under the page with `WindowOptions::background` (WebKitGTK; the other embedded frontends are listed here), and read the start-up milestones of a WebKitGTK view with `WEBFRONT_STARTUP_TRACE=1` (#611, `docs/WEBKITGTK.md`). ### Changed +- Share the registry of the secondary windows and the session of an `open()` between WebKitGTK, WKWebView and WebView2, tested on Linux with fake windows; WKWebView now clears a secondary window's hook before destroying it as WebView2 does, and WebView2 refuses a request once the first window closed even for an open page (#652, `docs/FRONTENDS.md`). - Reveal the WKWebView window when the document has loaded or after one second (#611, `docs/WKWEBVIEW.md`). - Reveal the WebView2 window after the first frame or one second (#611, `docs/WEBVIEW2.md`). - Show the WebKitGTK window when the page reports its first frame, or when a one-second timer fires, even if the page has not painted, instead of at once; the embedded pages, the starter and the examples use the cheap `sans-serif` and `monospace` font stacks (#611, `docs/WEBKITGTK.md`). diff --git a/docs/FRONTENDS.md b/docs/FRONTENDS.md index dea164fa..5f030c9b 100644 --- a/docs/FRONTENDS.md +++ b/docs/FRONTENDS.md @@ -17,7 +17,7 @@ A frontend is a type with: | `static constexpr Action action` | What `BasicWF` does once `open()` returns. | | `static void launch(address, port, page)` (optional) | Opens the interface and returns without waiting for it (the system browser spawns its opener command and does not wait for it to end). `BasicWF::start()` requires it; only a frontend without a window loop offers it (the system browser). A `launch(address, port, page, const ContentPolicy&)` overload is preferred when present; neither receives window options or the view-association proof. | | `static constexpr bool endsOnRequest` (optional) | `false` when `requestClose()` cannot end every session (`NativeOrBrowserFrontend` with the plain system browser as fallback); `webfront::UIThread` then refuses the frontend. | -| `static void openSecondaryWindow(address, port, file, policy, window, launch)` and `static bool closeSecondaryWindow(file)` (optional) | A second window beside the one `open()` runs (#616), callable from any thread while it runs; `invokeOnUIThread()` (UIExecutor.hpp) hops to the interface thread. Opening a page a secondary window already shows brings it to the front (a hidden window stays hidden and does not take the focus); the first window's end closes the others. A window is identified by the `file` string as given, query included. `WebKitGTKFrontend`, `WKWebViewFrontend` and `WebView2Frontend` implement it: `BasicWF::openSecondaryWindow()` throws `std::logic_error` for a frontend without it (CEF, the system browser), never opening a browser. `BasicWF::supportsSecondaryWindow` tells it from the frontend type; an optional `static bool secondaryWindowsAvailable()` tells it at run time, and `BasicWF::canShowSecondaryWindow()` combines both. `NativeOrBrowserFrontendFor` offers the functions only when its native frontend does, and reports them unavailable once it fell back to the system browser. The call waits for the interface thread (it runs at once on that thread): a `cppFunction` callback, which runs on the server's thread, schedules it with `app.uiExecutor()` instead of holding every exchange of the application while it waits. A window that cannot start throws the failure to the caller; one that fails to load later closes and writes the failure to stderr (the call has returned: nothing can throw it). A request that runs after the first window closed is refused with `std::logic_error`. A frontend whose first window cannot host another yet throws `frontend::WindowNotReady` (a `std::logic_error`): `BasicWF` and `invokeOnUIThreadWhenReady()` try again from another thread, and pass it to a caller on the interface thread. WebKitGTK shares the first window's network session (cookies, storage; downloads are tracked by the first window) and ignores `WindowOptions::media`. WKWebView shares its nonpersistent website data store and follows the first window's visibility (a hidden application shows no window and does not take the focus). WebView2 creates the second browser from the first window's environment, so the profile (storage, cookies) and the browser process are shared; it follows the first window's visibility, and has its own startup watchdog, with the first window's delay (the one `WebView2FrontendWithOptions` configured). A call made while the first window's environment is still being created waits for it (bounded by that window's watchdog); on the interface thread it throws `std::logic_error`. Placement is left to the toolkit. | +| `static void openSecondaryWindow(address, port, file, policy, window, launch)` and `static bool closeSecondaryWindow(file)` (optional) | A second window beside the one `open()` runs (#616), callable from any thread while it runs; `invokeOnUIThread()` (UIExecutor.hpp) hops to the interface thread. Opening a page a secondary window already shows brings it to the front (a hidden window stays hidden and does not take the focus); the first window's end closes the others. A window is identified by the `file` string as given, query included. `WebKitGTKFrontend`, `WKWebViewFrontend` and `WebView2Frontend` implement it: `BasicWF::openSecondaryWindow()` throws `std::logic_error` for a frontend without it (CEF, the system browser), never opening a browser. `BasicWF::supportsSecondaryWindow` tells it from the frontend type; an optional `static bool secondaryWindowsAvailable()` tells it at run time, and `BasicWF::canShowSecondaryWindow()` combines both. `NativeOrBrowserFrontendFor` offers the functions only when its native frontend does, and reports them unavailable once it fell back to the system browser. The call waits for the interface thread (it runs at once on that thread): a `cppFunction` callback, which runs on the server's thread, schedules it with `app.uiExecutor()` instead of holding every exchange of the application while it waits. A window that cannot start throws the failure to the caller; one that fails to load later closes and writes the failure to stderr (the call has returned: nothing can throw it). A request that runs after the first window closed is refused with `std::logic_error`. A frontend whose first window cannot host another yet throws `frontend::WindowNotReady` (a `std::logic_error`): `BasicWF` and `invokeOnUIThreadWhenReady()` try again from another thread, and pass it to a caller on the interface thread. WebKitGTK shares the first window's network session (cookies, storage; downloads are tracked by the first window) and ignores `WindowOptions::media`. WKWebView shares its nonpersistent website data store and follows the first window's visibility (a hidden application shows no window and does not take the focus). WebView2 creates the second browser from the first window's environment, so the profile (storage, cookies) and the browser process are shared; it follows the first window's visibility, and has its own startup watchdog, with the first window's delay (the one `WebView2FrontendWithOptions` configured). A call made while the first window's environment is still being created waits for it (bounded by that window's watchdog); on the interface thread it throws `std::logic_error`. Placement is left to the toolkit. The registry of the secondary windows and the session of an `open()` (attach, publish, clear the secondary windows, withdraw, close) are `frontend/WindowRegistry.hpp`'s `WindowRegistry` and `InterfaceSession`: a frontend supplies its session type and the hooks that depend on its toolkit (`scheduleReap`, `cancelReap`, `present`, `close`, and the `name` of its messages). | | `static bool requestClose()` (optional) | Asks, from any thread, the session that `open()` runs to end as if the user had closed the window; false when nothing is open. `BasicWF::requestClose()` forwards it only for the application whose `show()` owns that session (its thread is the frontend's published interface thread). A frontend with an executor takes `requestClose(std::optional)` and drops the request, on its interface thread, if another loop runs by then. | | `static constexpr bool requiresMainThread` (optional) | `open()` belongs to the process main thread; `webfront::UIThread` refuses the frontend at compile time. Undeclared means any thread. | diff --git a/include/webfront/frontend/WKWebView.hpp b/include/webfront/frontend/WKWebView.hpp index 2ce4f4ea..4d88a790 100644 --- a/include/webfront/frontend/WKWebView.hpp +++ b/include/webfront/frontend/WKWebView.hpp @@ -11,6 +11,7 @@ #include "UIExecutor.hpp" #include "Url.hpp" #include "Window.hpp" +#include "WindowRegistry.hpp" #include #include @@ -351,7 +352,7 @@ struct Session { id sharedDataStore = nullptr; std::function closedHook; bool receivedResponse = false, committed = false; - std::exception_ptr error; + std::exception_ptr failure; std::shared_ptr captureTarget = std::make_shared(); CaptureRegistration captureRegistration; @@ -498,8 +499,8 @@ struct Session { try { function(); } catch (...) { - if (!error) - error = std::current_exception(); + if (!failure) + failure = std::current_exception(); close(); } } @@ -678,8 +679,8 @@ struct Session { send(app, "run"); running = false; } - if (error) - std::rethrow_exception(error); + if (failure) + std::rethrow_exception(failure); } void navigationAction(id action, void (^decision)(long)) noexcept { @@ -1198,86 +1199,61 @@ inline Class viewClass() { 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; +inline void reapSecondaryWindows(); // defined with the registry, after Session + +// What the registry of the secondary windows (WindowRegistry.hpp) asks of AppKit: reaping is a block on the main queue. +struct WindowHooks { + static constexpr std::string_view name = "WKWebViewFrontend"; + + template + void scheduleReap(Registry&) { + dispatch_async_f( + dispatch_get_main_queue(), nullptr, +[](void*) { reapSecondaryWindows(); }); + } + void cancelReap() { } + void present(Session& session) { + // A hidden window stays hidden: ordering it to the front would show it. + if (session.options.visible) + send(session.window, "makeKeyAndOrderFront:", static_cast(nullptr)); + } + bool close(Session& session) { + session.close(); + return true; + } +}; +// All windows belong to the active AppKit session and are used on the main thread. +struct Windows : frontend::detail::WindowRegistry { 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 reapSecondaryWindows() { + Windows::instance().reap(); +} + 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); + Windows::instance().open( + std::string(page), + [&](Session& primary) { + // The first window's visibility and startup delay: a hidden application never shows a window or takes the focus. + options.visible = primary.options.visible; + options.startupTimeout = primary.options.startupTimeout; + auto child = std::make_shared(applicationUrl(address, port, page, options.launch.origin), std::move(options)); + child->secondary = true; + child->sharedDataStore = send(send(primary.view, "configuration"), "websiteDataStore"); + child->create(); + return child; + }, + [](Session& session, Session&) { + session.start(); + }); } 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; + return Windows::instance().close(std::string(page)); } inline void open(std::string_view address, std::string_view port, std::string_view file, const WKWebViewOptions& options) { @@ -1297,31 +1273,19 @@ inline void open(std::string_view address, std::string_view port, std::string_vi 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. + // also when run() throws or returns at once because the window already closed. The window is published once the + // loop is attached (this is the interface thread) and withdrawn before the session releases it. 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}; + frontend::detail::InterfaceSession interfaceSession( + host, + detail::wkwebview::windowHost(), + Windows::instance(), + window, + [&host] { + dispatch_async_f( + dispatch_get_main_queue(), &host, +[](void* context) { static_cast(context)->drain(); }); + }, + {.kind = NativeWindowKind::cocoa, .pointer = window.window, .portalParent = {}}); window.run(); } diff --git a/include/webfront/frontend/WebKitGTK.hpp b/include/webfront/frontend/WebKitGTK.hpp index 094700b6..94f7a895 100644 --- a/include/webfront/frontend/WebKitGTK.hpp +++ b/include/webfront/frontend/WebKitGTK.hpp @@ -13,6 +13,7 @@ #include "UIExecutor.hpp" #include "Url.hpp" #include "Window.hpp" +#include "WindowRegistry.hpp" #include "../ViewAssociation.hpp" #include "WebKitGTKPolicy.hpp" @@ -981,138 +982,96 @@ struct OpenOptions { ViewLaunch launch{}; }; -/// The windows of the application beside the first one (#616). Every member is used on the interface thread only. -struct Windows { - Session* primary = nullptr; - std::map> secondary; - std::vector> finished; // closed, destroyed from an idle callback - unsigned reaper = 0; +/// What the registry of the secondary windows (WindowRegistry.hpp) asks of GTK: reaping is an idle callback. +struct WindowHooks { + static constexpr std::string_view name = "WebKitGTKFrontend"; + unsigned reaper = 0; - static Windows& instance() { - static Windows windows; - return windows; - } - static int reap(void*) noexcept { - auto& windows = instance(); - windows.reaper = 0; - auto closed = std::move(windows.finished); - windows.finished.clear(); - closed.clear(); // destroys the sessions, outside of any of their own callbacks - return 0; - } - void retire(const std::string& page) { - const auto found = secondary.find(page); - if (found == secondary.end()) - return; - // open() returned long ago, so nothing else can report a page that failed (HTTP error, navigation timeout, web - // process lost): the failure is written, then the window is reaped. - if (found->second->failure) { - try { - std::rethrow_exception(found->second->failure); - } catch (const std::exception& error) { - std::fprintf(stderr, "WebKitGTKFrontend: the secondary window of '%s' closed: %s\n", page.c_str(), error.what()); - } catch (...) { - } - } - finished.push_back(std::move(found->second)); - secondary.erase(found); + template + void scheduleReap(Registry&) { if (!reaper) reaper = api().idleAddFull(200, reap, nullptr, nullptr); } - /// The first window ended: the others end with it, and nothing is left to reap. - void clear() { + void cancelReap() { if (reaper) api().sourceRemove(std::exchange(reaper, 0)); - auto windows = std::move(secondary); - secondary.clear(); - finished.clear(); - windows.clear(); - primary = nullptr; + } + void present(Session& session) { + api().windowPresent(session.window); + } + bool close(Session& session) { + session.close(); + return true; + } + static int reap(void*) noexcept; +}; + +/// The windows of the application beside the first one (#616). Every member is used on the interface thread only. +struct Windows : frontend::detail::WindowRegistry { + static Windows& instance() { + static Windows windows; + return windows; } }; +inline int WindowHooks::reap(void*) noexcept { + auto& windows = Windows::instance(); + windows.hooks.reaper = 0; + windows.reap(); // destroys the sessions, outside of any of their own callbacks + return 0; +} + /// On the interface thread: opens `file` in a window of its own, or brings the window already showing it to the front. inline void openSecondary(const std::string& address, const std::string& port, const std::string& file, OpenOptions options, SandboxMode mode) { - 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("WebKitGTKFrontend: no window of the application is open; show() it before opening another"); - if (const auto found = windows.secondary.find(file); found != windows.secondary.end()) { - api().windowPresent(found->second->window); - return; - } - auto session = std::make_unique(webfront::detail::BoundContentPolicy{applicationUrl(address, port, "", options.launch.origin), options.contentPolicy}, options.window); - session->secondary = true; - session->sharedNetwork = windows.primary->network; - session->launch = options.launch; - session->create(mode); - session->closedHook = [file] { - Windows::instance().retire(file); - }; - // 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() 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. - session->start(applicationUrl(address, port, file, options.launch.origin)); - if (session->closed) { - if (session->failure) - std::rethrow_exception(session->failure); - throw std::runtime_error("WebKitGTKFrontend: the secondary window of '" + file + "' closed while it started"); - } - windows.secondary[file] = std::move(session); + Windows::instance().open( + file, + [&](Session& primary) { + auto session = std::make_shared(webfront::detail::BoundContentPolicy{applicationUrl(address, port, "", options.launch.origin), options.contentPolicy}, options.window); + session->secondary = true; + session->sharedNetwork = primary.network; + session->launch = options.launch; + session->create(mode); + return session; + }, + [&](Session& session, Session&) { + session.start(applicationUrl(address, port, file, options.launch.origin)); + }); } /// On the interface thread: asks the secondary window showing `file` to close, as its user would. False when there is none. inline bool closeSecondary(const std::string& file) { - auto& windows = Windows::instance(); - const auto found = windows.secondary.find(file); - if (found == windows.secondary.end() || found->second->closed) - return false; - found->second->close(); - return true; + return Windows::instance().close(file); } inline void open(std::string_view address, std::string_view port, std::string_view file, const OpenOptions& options = {}, SandboxMode mode = SandboxMode::development) { initialize(mode); // One window per process: a second open() on the main thread is refused before it creates a window. - if (uiExecutorHostOf().executor().available()) - throw std::logic_error("WebKitGTKFrontend: open() is already running; a process opens one window at a time"); + frontend::detail::InterfaceSession::refuseSecond(uiExecutorHostOf(), WindowHooks::name); Session session(webfront::detail::BoundContentPolicy{applicationUrl(address, port, "", options.launch.origin), options.contentPolicy}, options.window); session.launch = options.launch; session.create(mode); if (options.configure) options.configure(session); - // g_idle_add_full is thread-safe and wakes the main context the loop of run() iterates. + // g_idle_add_full is thread-safe and wakes the main context the loop of run() iterates. GTK realizes the window at + // present(): run() then sets the X11 identifier, and the Wayland one arrives later. auto& host = uiExecutorHostOf(); - host.attach([&host] { - constexpr int defaultIdle = 200; // G_PRIORITY_DEFAULT_IDLE - api().idleAddFull( - defaultIdle, - +[](void* data) -> int { - static_cast(data)->drain(); - return 0; // G_SOURCE_REMOVE - }, - &host, - nullptr); - }); - // GTK realizes the window at present(): run() then sets the X11 identifier, and the Wayland one arrives later. - auto& windowHost = nativeWindowHostOf(); - windowHost.publish({.kind = NativeWindowKind::gtk, .pointer = session.window, .portalParent = {}}); - struct Closing { - UIExecutorHost& host; - NativeWindowHost& windowHost; - ~Closing() { - windowHost.retract(); - host.close(); - } - } closing{host, windowHost}; - auto& windows = Windows::instance(); - windows.primary = &session; - struct Others { - Windows& windows; - ~Others() { - windows.clear(); - } - } others{windows}; + frontend::detail::InterfaceSession interfaceSession( + host, + nativeWindowHostOf(), + Windows::instance(), + session, + [&host] { + constexpr int defaultIdle = 200; // G_PRIORITY_DEFAULT_IDLE + api().idleAddFull( + defaultIdle, + +[](void* data) -> int { + static_cast(data)->drain(); + return 0; // G_SOURCE_REMOVE + }, + &host, + nullptr); + }, + {.kind = NativeWindowKind::gtk, .pointer = session.window, .portalParent = {}}); session.run(applicationUrl(address, port, file, options.launch.origin)); } diff --git a/include/webfront/frontend/WebView2.hpp b/include/webfront/frontend/WebView2.hpp index 22708607..ec5a56f1 100644 --- a/include/webfront/frontend/WebView2.hpp +++ b/include/webfront/frontend/WebView2.hpp @@ -12,6 +12,7 @@ #include "UIExecutor.hpp" #include "Url.hpp" #include "Window.hpp" +#include "WindowRegistry.hpp" #include #include @@ -1017,50 +1018,39 @@ class Session : public std::enable_shared_from_this { } }; -/// The windows of the application beside the first one (#616). Every member is used on the interface thread only. -struct Windows { - Session* primary = nullptr; - std::map> secondary; - std::vector> finished; // closed, destroyed from a message of the first window +/// What the registry of the secondary windows (WindowRegistry.hpp) asks of Win32: reaping is a message to the first window. +struct WindowHooks { + static constexpr std::string_view name = "WebView2Frontend"; + template + void scheduleReap(Registry& windows) { + // Never destroyed in its own callback: the first window's procedure does it on its next message. + if (windows.primary && windows.primary->window) + PostMessageW(windows.primary->window, reapMessage, 0, 0); + } + void cancelReap() { } + void present(Session& session) { + // A hidden window stays hidden and does not take the focus. + if (const auto handle = session.window; handle && IsWindowVisible(handle)) { + if (IsIconic(handle)) + ShowWindow(handle, SW_RESTORE); + SetForegroundWindow(handle); + } + } + bool close(Session& session) { + if (!session.window) + return false; + SendMessageW(session.window, WM_CLOSE, 0, 0); // the same thread: closed and retired when this returns + return true; + } +}; + +/// The windows of the application beside the first one (#616). Every member is used on the interface thread only. +struct Windows : frontend::detail::WindowRegistry { 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; - // open() returned long ago, so nothing else can report a page that failed (navigation, runtime, process lost). - if (found->second->failure) { - try { - std::rethrow_exception(found->second->failure); - } catch (const std::exception& error) { - std::fprintf(stderr, "WebView2Frontend: the secondary window of '%s' closed: %s\n", page.c_str(), error.what()); - } catch (...) { - } - } - finished.push_back(std::move(found->second)); - secondary.erase(found); - // Never destroyed in its own callback: the first window's procedure does it on its next message. - if (primary && primary->window) - PostMessageW(primary->window, reapMessage, 0, 0); - } - void reap() { - auto closed = std::move(finished); - finished.clear(); - closed.clear(); - } - /// The first window ended: the others end with it. - void clear() { - auto windows = std::move(secondary); - secondary.clear(); - for (auto& [page, session] : windows) - session->closedHook = nullptr; - finished.clear(); - windows.clear(); - primary = nullptr; - } }; inline void reapSecondaryWindows() { @@ -1070,54 +1060,28 @@ inline void reapSecondaryWindows() { /// On the interface thread: opens `page` in a window of its own, or brings the window already showing it to the front. /// Throws WindowNotReady while the first window's environment is being created (show() has just started). inline void openSecondary(std::string_view address, std::string_view port, std::string_view page, const WebView2Options& options) { - auto& windows = Windows::instance(); - if (!windows.primary) - throw std::logic_error("WebView2Frontend: no window of the application is open; show() it before opening another"); - const std::string key(page); - if (const auto found = windows.secondary.find(key); found != windows.secondary.end()) { - // A hidden window stays hidden and does not take the focus. - if (const auto handle = found->second->window; handle && IsWindowVisible(handle)) { - if (IsIconic(handle)) - ShowWindow(handle, SW_RESTORE); - SetForegroundWindow(handle); - } - return; - } - if (windows.primary->closed) - throw std::logic_error("WebView2Frontend: no window of the application is open; show() it before opening another"); - if (!windows.primary->environment) - throw WindowNotReady("WebView2Frontend: the first window is not ready (its browser is being created); call it later"); - // The first window's delay, which the application configured (WebView2FrontendWithOptions), not this call's default. - auto session = std::make_shared(windows.primary->startupTimeout()); - session->secondary = true; - session->contentPolicy = webfront::detail::BoundContentPolicy{frontend::detail::applicationUrl(address, port, "", options.launch.origin), options.contentPolicy}; - session->viewLaunch = options.launch; - session->url = utf16(frontend::detail::applicationUrl(address, port, page, options.launch.origin)); - session->closedHook = [key] { - Windows::instance().retire(key); - }; - session->createWindow(windows.primary->shown(), options.window); - session->startSecondary(windows.primary->environment.Get()); - // 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 the start 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. - if (session->closed) { - if (session->failure) - std::rethrow_exception(session->failure); - throw std::runtime_error("WebView2Frontend: the secondary window of '" + key + "' closed while it started"); - } - windows.secondary[key] = std::move(session); + Windows::instance().open( + std::string(page), + [&](Session& primary) { + if (!primary.environment) + throw WindowNotReady("WebView2Frontend: the first window is not ready (its browser is being created); call it later"); + // The first window's delay, which the application configured (WebView2FrontendWithOptions), not this call's default. + auto session = std::make_shared(primary.startupTimeout()); + session->secondary = true; + session->contentPolicy = webfront::detail::BoundContentPolicy{frontend::detail::applicationUrl(address, port, "", options.launch.origin), options.contentPolicy}; + session->viewLaunch = options.launch; + session->url = utf16(frontend::detail::applicationUrl(address, port, page, options.launch.origin)); + session->createWindow(primary.shown(), options.window); + return session; + }, + [](Session& session, Session& primary) { + session.startSecondary(primary.environment.Get()); + }); } /// On the interface thread: closes the secondary window showing `page`, as its user would. False when there is none. inline bool closeSecondary(const std::string& page) { - auto& windows = Windows::instance(); - const auto found = windows.secondary.find(page); - if (found == windows.secondary.end() || found->second->closed || !found->second->window) - return false; - const auto session = found->second; // kept alive while the window procedure retires it - SendMessageW(session->window, WM_CLOSE, 0, 0); // the same thread: closed and retired when this returns - return true; + return Windows::instance().close(page); } inline void open(std::string_view address, @@ -1127,8 +1091,7 @@ inline void open(std::string_view address, const std::function& prepare = {}) { auto contentPolicy = webfront::detail::BoundContentPolicy{frontend::detail::applicationUrl(address, port, "", options.launch.origin), options.contentPolicy}; // One window per process: a second open() on the interface thread is refused before it creates anything. - if (uiExecutorHostOf().executor().available()) - throw std::logic_error("WebView2Frontend: open() is already running; a process opens one window at a time"); + frontend::detail::InterfaceSession::refuseSecond(uiExecutorHostOf(), WindowHooks::name); Apartment apartment; LPWSTR rawVersion = nullptr; const auto available = GetAvailableCoreWebView2BrowserVersionString(nullptr, &rawVersion); @@ -1147,32 +1110,19 @@ inline void open(std::string_view address, session->createWindow(options.visible, options.window); session->start(profile); // The wake posts to the window, which the pump of run() dispatches. A post that fails (a full message queue) throws: - // the host then fails the operations that relied on that notification instead of leaving them waiting. The guard is - // declared after the apartment and before run(), so the host closes on every exit, also by exception. - auto& host = uiExecutorHostOf(); - host.attach([window = session->window] { - if (!PostMessageW(window, drainMessage, 0, 0)) - throw std::runtime_error("WebView2: cannot wake the interface thread (the message queue is full)"); - }); - // Published on the interface thread (this one), withdrawn before the session destroys the window. - auto& windowHost = nativeWindowHostOf(); - windowHost.publish({.kind = NativeWindowKind::win32, .pointer = session->window, .portalParent = {}}); - struct Closing { - UIExecutorHost& host; - NativeWindowHost& windowHost; - ~Closing() { - windowHost.retract(); - host.close(); - } - } closing{host, windowHost}; - auto& windows = Windows::instance(); - windows.primary = session.get(); - struct Others { - Windows& windows; - ~Others() { - windows.clear(); - } - } others{windows}; + // the host then fails the operations that relied on that notification instead of leaving them waiting. The session + // is declared after the apartment and before run(), so the host closes on every exit, also by exception. The window + // is published on the interface thread (this one) and withdrawn before the session destroys it. + frontend::detail::InterfaceSession interfaceSession( + uiExecutorHostOf(), + nativeWindowHostOf(), + Windows::instance(), + *session, + [window = session->window] { + if (!PostMessageW(window, drainMessage, 0, 0)) + throw std::runtime_error("WebView2: cannot wake the interface thread (the message queue is full)"); + }, + {.kind = NativeWindowKind::win32, .pointer = session->window, .portalParent = {}}); session->run(); } diff --git a/include/webfront/frontend/WindowRegistry.hpp b/include/webfront/frontend/WindowRegistry.hpp new file mode 100644 index 00000000..67d52288 --- /dev/null +++ b/include/webfront/frontend/WindowRegistry.hpp @@ -0,0 +1,168 @@ +// SPDX-License-Identifier: Apache-2.0 OR CECILL-B +/// @brief The toolkit-independent part of the native frontends' windows: the registry of the secondary windows and the +/// session of one open() (#652, #616). +#pragma once + +#include "NativeWindow.hpp" +#include "UIExecutor.hpp" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace webfront::frontend::detail { + +/** + * @brief The windows of the application beside the first one. Every member is used on the interface thread only. + * + * `Session` is a frontend's window with a `bool closed`, a `std::exception_ptr failure` (why it closed, if it did not + * end normally) and a `std::function closedHook` that it calls once, from its own callback, when its window closes. + * + * `Hooks` holds what depends on the toolkit (it is a member, `hooks`, so it can keep state): + * - `static constexpr std::string_view name`: the frontend's name, the prefix of its messages; + * - `void scheduleReap(Registry&)`: arranges for `reap()` to run later, outside of any callback of the retired + * session (an idle callback, a queued block, a message of the first window); + * - `void cancelReap()`: withdraws what scheduleReap() arranged, when the first window ended; + * - `void present(Session&)`: brings the window to the front, as it should (a hidden one stays hidden); + * - `bool close(Session&)`: asks the window to close as its user would, false when it cannot. + */ +template +class WindowRegistry { +public: + /// The first window, `nullptr` when none runs. + Session* primary = nullptr; + std::map> secondary; + std::vector> finished; // closed, destroyed by reap() + Hooks hooks; + + /// A session closed (its closedHook): takes it out of the table, reports why it failed, and reaps it later. + void retire(const std::string& page) { + const auto found = secondary.find(page); + if (found == secondary.end()) + return; + // open() returned long ago, so nothing else can report a page that failed (navigation, runtime, process lost): + // the failure is written, then the window is reaped. + if (found->second->failure) { + try { + std::rethrow_exception(found->second->failure); + } catch (const std::exception& error) { + std::fprintf(stderr, "%.*s: the secondary window of '%s' closed: %s\n", static_cast(Hooks::name.size()), Hooks::name.data(), page.c_str(), error.what()); + } catch (...) { + } + } + finished.push_back(std::move(found->second)); + secondary.erase(found); + hooks.scheduleReap(*this); + } + + /// Destroys the sessions that closed, outside of any of their own callbacks (it is what scheduleReap() arranged). + void reap() { + auto closed = std::move(finished); + finished.clear(); + closed.clear(); + } + + /// The first window ended: the others end with it, and nothing is left to reap. The sessions leave the table before + /// they are destroyed, and their hook no longer retires them from it. + void clear() { + hooks.cancelReap(); + auto windows = std::move(secondary); + secondary.clear(); + for (auto& entry : windows) + entry.second->closedHook = nullptr; + finished.clear(); + windows.clear(); + primary = nullptr; + } + + /** + * @brief On the interface thread: opens `page` in a window of its own, or brings the window already showing it to the front. + * + * `create(Session& primary)` builds the window and returns a `std::shared_ptr`; `start(Session&, Session& primary)` + * starts its load and returns. Either may throw (a window whose creation or start throws is not registered, and its page + * can be opened again). Throws std::logic_error when the first window is not open: one that closed still runs its loop + * until the pass ends, and a window built now would be destroyed with it. + */ + template + void open(const std::string& page, Create&& create, Start&& start) { + if (!primary || primary->closed) + throw std::logic_error(std::string(Hooks::name) + ": no window of the application is open; show() it before opening another"); + if (const auto found = secondary.find(page); found != secondary.end()) { + hooks.present(*found->second); + return; + } + std::shared_ptr session = create(*primary); + session->closedHook = [this, page] { + retire(page); + }; + start(*session, *primary); + // One that closed during start() 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. + if (session->closed) { + if (session->failure) + std::rethrow_exception(session->failure); + throw std::runtime_error(std::string(Hooks::name) + ": the secondary window of '" + page + "' closed while it started"); + } + secondary[page] = std::move(session); + } + + /// On the interface thread: asks the secondary window showing `page` to close, as its user would. False when there is none. + bool close(const std::string& page) { + const auto found = secondary.find(page); + if (found == secondary.end() || found->second->closed) + return false; + const auto session = found->second; // kept alive while its callback retires it + return hooks.close(*session); + } +}; + +/** + * @brief What an open() holds from the moment its loop is attached until it returns, in the order that never leaves + * a dangling window: attached and published on construction; on destruction (also by exception) the secondary windows + * are cleared, then the window is withdrawn, then the host closes (pending operations complete stopped). + */ +template +class InterfaceSession { + UIExecutorHost& host; + NativeWindowHost& windowHost; + Registry& windows; + +public: + /// Refuses a second open() while one runs: a process opens one window at a time. + static void refuseSecond(const UIExecutorHost& host, std::string_view name) { + if (host.executor().available()) + throw std::logic_error(std::string(name) + ": open() is already running; a process opens one window at a time"); + } + + /// Attaches `wake` (thread-safe; makes the loop call host.drain()), publishes `handle` and registers `primary` + /// as the first window. Throws what attach() does (a loop is already attached) before anything is held. + InterfaceSession(UIExecutorHost& uiHost, NativeWindowHost& nativeHost, Registry& registry, typename std::remove_pointer_t& primary, std::function wake, NativeWindowHandle handle) + : host(uiHost), windowHost(nativeHost), windows(registry) { + host.attach(std::move(wake)); + try { + windowHost.publish(std::move(handle)); + windows.primary = &primary; + } catch (...) { + windowHost.retract(); + host.close(); + throw; + } + } + InterfaceSession(const InterfaceSession&) = delete; + InterfaceSession& operator=(const InterfaceSession&) = delete; + ~InterfaceSession() { + windows.clear(); + windowHost.retract(); + host.close(); + } +}; + +} // namespace webfront::frontend::detail diff --git a/test/unit/CMakeLists.txt b/test/unit/CMakeLists.txt index a18dc060..3652690b 100644 --- a/test/unit/CMakeLists.txt +++ b/test/unit/CMakeLists.txt @@ -61,7 +61,7 @@ list(APPEND TESTS_LIST FileSystemTests.cpp NativeFSTests.cpp DownloadsTests.cpp list(APPEND TESTS_LIST DefaultFSTests.cpp StdnetShutdownTests.cpp ProfileLeaseTests.cpp SafePathTests.cpp UISubscribersTests.cpp) list(APPEND TESTS_LIST ReadBindingTests.cpp ViewAssociationTests.cpp BroadcastTests.cpp WebFrontTests.cpp WebLinkTests.cpp CEFPathsTests.cpp CEFMacrosTests.cpp) list(APPEND TESTS_LIST DeveloperTests.cpp WfDriverTests.cpp AutomationTests.cpp AutomationChannelTests.cpp AutomationDiscoveryTests.cpp AutomationMcpHttpTests.cpp JasmineConsumerTests.cpp HostTests.cpp LifeTests.cpp HostLoopTests.cpp StructuredShutdownTests.cpp JsFunctionSenderTests.cpp ApplicationTaskTests.cpp DeferredCallTests.cpp) -list(APPEND TESTS_LIST Main.cpp ScenarioIsolation.cpp FrontendUrlTests.cpp ApplicationUrlTests.cpp FrontendContractTests.cpp UIExecutorTests.cpp NativeWindowTests.cpp CommandsTests.cpp EmbeddedCoreAssetsTests.cpp) +list(APPEND TESTS_LIST Main.cpp ScenarioIsolation.cpp FrontendUrlTests.cpp ApplicationUrlTests.cpp FrontendContractTests.cpp UIExecutorTests.cpp NativeWindowTests.cpp WindowRegistryTests.cpp CommandsTests.cpp EmbeddedCoreAssetsTests.cpp) if(WEBFRONT_USE_MDDLOG) list(APPEND TESTS_LIST MddlogLoggerTests.cpp MddlogTransportTests.cpp) endif() diff --git a/test/unit/WindowRegistryTests.cpp b/test/unit/WindowRegistryTests.cpp new file mode 100644 index 00000000..da75a12d --- /dev/null +++ b/test/unit/WindowRegistryTests.cpp @@ -0,0 +1,266 @@ +// SPDX-License-Identifier: Apache-2.0 OR CECILL-B +/// @brief The registry of the secondary windows and the session of one open(), shared by the native frontends (#652, #616). +#include +#include + +#include +#include +#include +#include +#include +#include +#include + +using namespace webfront::bdd; +using namespace webfront::frontend; + +namespace { +std::vector events; // what the fake toolkit was asked, in order + +// A window of a fake toolkit: it closes when asked, or by itself during its start. +struct FakeSession { + std::string page; + bool closed = false; + std::exception_ptr failure; + std::function closedHook; + bool inCallback = false; // true while its own closedHook runs + bool closeOnStart = false; + std::exception_ptr failOnStart; + + explicit FakeSession(std::string name = {}) : page(std::move(name)) { } + ~FakeSession() { + events.push_back("destroy " + page); + if (inCallback) + events.push_back("destroyed in its own callback"); + if (closedHook) + events.push_back("hook still set " + page); + } + void start() { + events.push_back("start " + page); + if (closeOnStart || failOnStart) { + failure = failOnStart; + close(); + } + } + void close() { + closed = true; + if (closedHook) { + inCallback = true; + closedHook(); + inCallback = false; + } + } +}; + +struct FakeHooks { + static constexpr std::string_view name = "FakeFrontend"; + int reapsScheduled = 0; + bool canClose = true; + + template + void scheduleReap(Registry&) { + ++reapsScheduled; + events.push_back("schedule reap"); + } + void cancelReap() { + events.push_back("cancel reap"); + } + void present(FakeSession& session) { + events.push_back("present " + session.page); + } + bool close(FakeSession& session) { + events.push_back("close " + session.page); + if (!canClose) + return false; + session.close(); + return true; + } +}; + +using Registry = detail::WindowRegistry; + +void openPage(Registry& windows, const std::string& page, bool closeOnStart = false, std::exception_ptr failOnStart = {}) { + windows.open( + page, + [&](FakeSession&) { + auto session = std::make_shared(page); + session->closeOnStart = closeOnStart; + session->failOnStart = failOnStart; + events.push_back("create " + page); + return session; + }, + [](FakeSession& session, FakeSession&) { + session.start(); + }); +} + +bool happened(const std::string& event) { + return std::ranges::find(events, event) != events.end(); +} + +struct RegistryTag; +struct SessionTag; +struct PublishTag; +} // namespace + +const Scenario secondaryWindowRegistry{"The registry of the secondary windows is shared by the native frontends", {"window-registry"}, [] { + given("a registry whose first window is open", [&] { + events.clear(); + Registry windows; + FakeSession first("first"); + windows.primary = &first; + + when("a page is opened", [&] { + openPage(windows, "a.html"); + then("the window is created, started and registered", [&] { + require(windows.secondary.size() == 1); + check(events == std::vector{"create a.html", "start a.html"}); + }); + andWhen("the same page is opened again", [&] { + openPage(windows, "a.html"); + then("the window already showing it comes to the front and nothing is created", [&] { + check(happened("present a.html")); + check(std::ranges::count(events, "create a.html") == 1); + check(windows.secondary.size() == 1); + }); + }); + andWhen("its window closes", [&] { + require(windows.close("a.html")); + then("it leaves the table, is destroyed later and not in its own callback", [&] { + check(windows.secondary.empty()); + check(windows.finished.size() == 1); + check(windows.hooks.reapsScheduled == 1); + check(!happened("destroy a.html")); + windows.reap(); + check(happened("destroy a.html")); + check(!happened("destroyed in its own callback")); + check(windows.finished.empty()); + }); + andWhen("the page is opened again", [&] { + windows.reap(); + openPage(windows, "a.html"); + then("it is a new window", [&] { + check(std::ranges::count(events, "create a.html") == 2); + check(windows.secondary.size() == 1); + }); + }); + }); + andWhen("closing is asked for a page nobody shows, or for one that cannot close", [&] { + windows.hooks.canClose = false; + then("it answers false", [&] { + check(!windows.close("b.html")); + check(!windows.close("a.html")); + }); + }); + }); + + when("a window closes by itself while it starts", [&] { + then("the caller learns why, and the page is not registered", [&] { + checkThrows([&] { + openPage(windows, "a.html", true, std::make_exception_ptr(std::runtime_error("navigation failed"))); + }); + check(windows.secondary.empty()); + }); + andWhen("it closed without a failure", [&] { + then("the caller still gets an error that names the page", [&] { + checkThrows([&] { openPage(windows, "b.html", true); }, contains("'b.html' closed while it started")); + check(windows.secondary.empty()); + }); + }); + andWhen("the page is opened once more", [&] { + windows.reap(); + openPage(windows, "a.html"); + then("it works", [&] { + check(windows.secondary.size() == 1); + }); + }); + }); + + when("the first window closes in the pass that handles the request", [&] { + first.closed = true; + then("nothing is built and the caller is told", [&] { + checkThrows([&] { openPage(windows, "a.html"); }, contains("FakeFrontend: no window of the application is open")); + check(!happened("create a.html")); + }); + }); + + when("the first window ends with secondary windows open", [&] { + openPage(windows, "a.html"); + openPage(windows, "b.html"); + require(windows.close("a.html")); + events.clear(); + windows.clear(); + then("the reap is withdrawn and every session is destroyed with its hook cleared", [&] { + check(events.front() == "cancel reap"); + check(happened("destroy a.html")); + check(happened("destroy b.html")); + check(!happened("hook still set b.html")); + check(windows.secondary.empty() && windows.finished.empty()); + check(windows.primary == nullptr); + }); + }); + windows.clear(); + }); + given("a registry without a first window", [&] { + Registry windows; + then("opening is refused", [&] { + checkThrows([&] { openPage(windows, "a.html"); }, contains("show() it before opening another")); + }); + }); +}}; + +const Scenario interfaceSessionOrder{"The session of an open() attaches, publishes and withdraws in order", {"window-registry"}, [] { + given("an open() that attaches its loop", [&] { + auto& host = uiExecutorHostOf(); + auto& windowHost = nativeWindowHostOf(); + int handle = 0; + Registry windows; + FakeSession first("first"); + const auto published = [&] { + return windowHost.window(); + }; + when("the session is held", [&] { + { + detail::InterfaceSession session(host, windowHost, windows, first, [] {}, {.kind = NativeWindowKind::gtk, .pointer = &handle, .portalParent = {}}); + then("the executor is available, the window published and the first window registered", [&] { + check(host.executor().available()); + check(windows.primary == &first); + }); + andWhen("another open() starts", [&] { + then("it is refused", [&] { + checkThrows([&] { detail::InterfaceSession::refuseSecond(host, "FakeFrontend"); }, + contains("FakeFrontend: open() is already running")); + }); + }); + openPage(windows, "a.html"); + events.clear(); + } + then("the secondary windows are cleared first, then the window is withdrawn and the host closed", [&] { + check(!events.empty() && events.front() == "cancel reap"); + check(windows.primary == nullptr && windows.secondary.empty()); + check(!host.executor().available()); + check(!published().get().has_value()); + }); + andWhen("a later open() starts", [&] { + then("it is accepted", [&] { + checkNothrow([&] { detail::InterfaceSession::refuseSecond(host, "FakeFrontend"); }); + }); + }); + }); + }); + given("a loop that is already attached", [&] { + auto& host = uiExecutorHostOf(); + host.attach([] {}); + Registry windows; + FakeSession first("first"); + int handle = 0; + then("a second session throws and leaves the first loop attached", [&] { + checkThrows([&] { + detail::InterfaceSession session(host, nativeWindowHostOf(), windows, first, [] {}, {.kind = NativeWindowKind::gtk, .pointer = &handle, .portalParent = {}}); + }); + check(host.executor().available()); + check(windows.primary == nullptr); + }); + host.close(); + }); +}}; From e028c43aa05b10547d8648a0fdc0423753708cc2 Mon Sep 17 00:00:00 2001 From: Ambroise Leclerc <6860842+ambroise-leclerc@users.noreply.github.com> Date: Mon, 23 Nov 2026 18:31:11 +0100 Subject: [PATCH 02/11] Factor the facade, presentation and startup trace of the native frontends (#652) --- docs/CHANGELOG.md | 3 +- docs/FRONTENDS.md | 12 +- .../webfront/frontend/EmbeddedFrontend.hpp | 161 ++++++++++++++++ include/webfront/frontend/Frontend.hpp | 66 ++----- include/webfront/frontend/StartupTrace.hpp | 129 +++++++++++++ include/webfront/frontend/WKWebView.hpp | 158 +++------------ include/webfront/frontend/WebKitGTK.hpp | 181 ++++-------------- include/webfront/frontend/WebView2.hpp | 181 ++++-------------- test/driver/TestFrontend.hpp | 27 +-- test/unit/WindowRegistryTests.cpp | 123 +++++++++++- test/web/WKWebViewLifecycle.cpp | 8 +- test/web/WebKitGTKLifecycle.cpp | 6 +- 12 files changed, 556 insertions(+), 499 deletions(-) create mode 100644 include/webfront/frontend/EmbeddedFrontend.hpp create mode 100644 include/webfront/frontend/StartupTrace.hpp diff --git a/docs/CHANGELOG.md b/docs/CHANGELOG.md index 4ffa6f45..092ceb39 100644 --- a/docs/CHANGELOG.md +++ b/docs/CHANGELOG.md @@ -50,7 +50,8 @@ in a native pseudoterminal, and a faster, less flashy start of the native window - Choose the colour of the WebKitGTK view under the page with `WindowOptions::background` (WebKitGTK; the other embedded frontends are listed here), and read the start-up milestones of a WebKitGTK view with `WEBFRONT_STARTUP_TRACE=1` (#611, `docs/WEBKITGTK.md`). ### Changed -- Share the registry of the secondary windows and the session of an `open()` between WebKitGTK, WKWebView and WebView2, tested on Linux with fake windows; WKWebView now clears a secondary window's hook before destroying it as WebView2 does, and WebView2 refuses a request once the first window closed even for an open page (#652, `docs/FRONTENDS.md`). +- WebKitGTK takes a `startupTimeout` (30 s by default, the message now in milliseconds), a secondary window of WKWebView and WebKitGTK starts with the first window's delay, WKWebView clears the hook of a secondary window before destroying it, and its messages name `WKWebViewFrontend` everywhere (#652). +- Write a native frontend from shared headers: `EmbeddedFrontend` (facade and every `open()` overload), `WindowRegistry`/`InterfaceSession`, `StartupTrace` and `Presentation`, tested on Linux with fake windows (#652, `docs/FRONTENDS.md`). - Reveal the WKWebView window when the document has loaded or after one second (#611, `docs/WKWEBVIEW.md`). - Reveal the WebView2 window after the first frame or one second (#611, `docs/WEBVIEW2.md`). - Show the WebKitGTK window when the page reports its first frame, or when a one-second timer fires, even if the page has not painted, instead of at once; the embedded pages, the starter and the examples use the cheap `sans-serif` and `monospace` font stacks (#611, `docs/WEBKITGTK.md`). diff --git a/docs/FRONTENDS.md b/docs/FRONTENDS.md index 5f030c9b..99aa2212 100644 --- a/docs/FRONTENDS.md +++ b/docs/FRONTENDS.md @@ -17,7 +17,7 @@ A frontend is a type with: | `static constexpr Action action` | What `BasicWF` does once `open()` returns. | | `static void launch(address, port, page)` (optional) | Opens the interface and returns without waiting for it (the system browser spawns its opener command and does not wait for it to end). `BasicWF::start()` requires it; only a frontend without a window loop offers it (the system browser). A `launch(address, port, page, const ContentPolicy&)` overload is preferred when present; neither receives window options or the view-association proof. | | `static constexpr bool endsOnRequest` (optional) | `false` when `requestClose()` cannot end every session (`NativeOrBrowserFrontend` with the plain system browser as fallback); `webfront::UIThread` then refuses the frontend. | -| `static void openSecondaryWindow(address, port, file, policy, window, launch)` and `static bool closeSecondaryWindow(file)` (optional) | A second window beside the one `open()` runs (#616), callable from any thread while it runs; `invokeOnUIThread()` (UIExecutor.hpp) hops to the interface thread. Opening a page a secondary window already shows brings it to the front (a hidden window stays hidden and does not take the focus); the first window's end closes the others. A window is identified by the `file` string as given, query included. `WebKitGTKFrontend`, `WKWebViewFrontend` and `WebView2Frontend` implement it: `BasicWF::openSecondaryWindow()` throws `std::logic_error` for a frontend without it (CEF, the system browser), never opening a browser. `BasicWF::supportsSecondaryWindow` tells it from the frontend type; an optional `static bool secondaryWindowsAvailable()` tells it at run time, and `BasicWF::canShowSecondaryWindow()` combines both. `NativeOrBrowserFrontendFor` offers the functions only when its native frontend does, and reports them unavailable once it fell back to the system browser. The call waits for the interface thread (it runs at once on that thread): a `cppFunction` callback, which runs on the server's thread, schedules it with `app.uiExecutor()` instead of holding every exchange of the application while it waits. A window that cannot start throws the failure to the caller; one that fails to load later closes and writes the failure to stderr (the call has returned: nothing can throw it). A request that runs after the first window closed is refused with `std::logic_error`. A frontend whose first window cannot host another yet throws `frontend::WindowNotReady` (a `std::logic_error`): `BasicWF` and `invokeOnUIThreadWhenReady()` try again from another thread, and pass it to a caller on the interface thread. WebKitGTK shares the first window's network session (cookies, storage; downloads are tracked by the first window) and ignores `WindowOptions::media`. WKWebView shares its nonpersistent website data store and follows the first window's visibility (a hidden application shows no window and does not take the focus). WebView2 creates the second browser from the first window's environment, so the profile (storage, cookies) and the browser process are shared; it follows the first window's visibility, and has its own startup watchdog, with the first window's delay (the one `WebView2FrontendWithOptions` configured). A call made while the first window's environment is still being created waits for it (bounded by that window's watchdog); on the interface thread it throws `std::logic_error`. Placement is left to the toolkit. The registry of the secondary windows and the session of an `open()` (attach, publish, clear the secondary windows, withdraw, close) are `frontend/WindowRegistry.hpp`'s `WindowRegistry` and `InterfaceSession`: a frontend supplies its session type and the hooks that depend on its toolkit (`scheduleReap`, `cancelReap`, `present`, `close`, and the `name` of its messages). | +| `static void openSecondaryWindow(address, port, file, policy, window, launch)` and `static bool closeSecondaryWindow(file)` (optional) | A second window beside the one `open()` runs (#616), callable from any thread while it runs; `invokeOnUIThread()` (UIExecutor.hpp) hops to the interface thread. Opening a page a secondary window already shows brings it to the front (a hidden window stays hidden and does not take the focus); the first window's end closes the others. A window is identified by the `file` string as given, query included. `WebKitGTKFrontend`, `WKWebViewFrontend` and `WebView2Frontend` implement it: `BasicWF::openSecondaryWindow()` throws `std::logic_error` for a frontend without it (CEF, the system browser), never opening a browser. `BasicWF::supportsSecondaryWindow` tells it from the frontend type; an optional `static bool secondaryWindowsAvailable()` tells it at run time, and `BasicWF::canShowSecondaryWindow()` combines both. `NativeOrBrowserFrontendFor` offers the functions only when its native frontend does, and reports them unavailable once it fell back to the system browser. The call waits for the interface thread (it runs at once on that thread): a `cppFunction` callback, which runs on the server's thread, schedules it with `app.uiExecutor()` instead of holding every exchange of the application while it waits. A window that cannot start throws the failure to the caller; one that fails to load later closes and writes the failure to stderr (the call has returned: nothing can throw it). A request that runs after the first window closed is refused with `std::logic_error`. A frontend whose first window cannot host another yet throws `frontend::WindowNotReady` (a `std::logic_error`): `BasicWF` and `invokeOnUIThreadWhenReady()` try again from another thread, and pass it to a caller on the interface thread. WebKitGTK shares the first window's network session (cookies, storage; downloads are tracked by the first window) and ignores `WindowOptions::media`. WKWebView shares its nonpersistent website data store and follows the first window's visibility (a hidden application shows no window and does not take the focus). WebView2 creates the second browser from the first window's environment, so the profile (storage, cookies) and the browser process are shared; it follows the first window's visibility, and has its own startup watchdog, with the first window's delay (the one `WebView2FrontendWithOptions` configured). A call made while the first window's environment is still being created waits for it (bounded by that window's watchdog); on the interface thread it throws `std::logic_error`. Placement is left to the toolkit. | | `static bool requestClose()` (optional) | Asks, from any thread, the session that `open()` runs to end as if the user had closed the window; false when nothing is open. `BasicWF::requestClose()` forwards it only for the application whose `show()` owns that session (its thread is the frontend's published interface thread). A frontend with an executor takes `requestClose(std::optional)` and drops the request, on its interface thread, if another loop runs by then. | | `static constexpr bool requiresMainThread` (optional) | `open()` belongs to the process main thread; `webfront::UIThread` refuses the frontend at compile time. Undeclared means any thread. | @@ -424,3 +424,13 @@ the native helper never selects CEF. | `WEBFRONT_EMBED_WKWEBVIEW` | OFF | Link the system Cocoa and WebKit frameworks for WKWebViewFrontend (macOS 13.3+ only) | | `WEBFRONT_EMBED_WEBKITGTK` | OFF | Enable the system WebKitGTK 6.0 embedded frontend (Linux only) | | `WEBFRONT_EMBED_CEF` | OFF | Download and link CEF so CEFFrontend is available (Windows, Linux x86_64 and aarch64, and macOS only). Other platforms fail at configure time | + +## Writing a native frontend + +WebKitGTK, WKWebView, WebView2 and CEF share their toolkit-independent logic in `include/webfront/frontend/`; a new native frontend declares only the calls of its toolkit. The shared parts are tested on Linux with fake windows (`test/unit/WindowRegistryTests.cpp`). + +- `EmbeddedFrontend.hpp`: `EmbeddedFrontend` gives `uiExecutor()`, `nativeWindow()`, `requestClose()`, `initialize()`, `openSecondaryWindow()`, `closeSecondaryWindow()` and every overload of `open()`. The frontend declares `Host` (the tag of its executor and window hosts), `Options` (`ViewOptions` has the `contentPolicy`, `window` and `launch` every frontend takes), `compiled`, `name` and `enable` (the message of a build without the engine), `secondaryWindows`, and the toolkit calls `openNative`, `closeNative`, `openSecondaryNative`, `closeSecondaryNative` (on the interface thread) and optionally `initializeNative`, `defaultOptions` and `waitsForFirstWindow`. Members that name the engine are instantiated only when `compiled` holds, so no `#if` surrounds them. A frontend without `initializeNative` throws from `initialize()` when it is not compiled; WebView2 declares an empty one, because its COM apartment belongs to each `open()`, and fails there. +- `WindowRegistry.hpp`: `WindowRegistry` is the table of the secondary windows (open, bring to the front, close, retire a window that closed, reap it outside its own callback, clear when the first window ends) and `InterfaceSession` is what an `open()` holds while its loop runs (attach, publish, then on every exit, also by exception: clear the secondary windows, withdraw the window, close the host). The hooks are `scheduleReap`, `cancelReap`, `present`, `close` and the `name` of the messages: an idle callback in WebKitGTK, a queued block in WKWebView, a message to the first window in WebView2. +- `StartupTrace.hpp`: `StartupTrace` (`WEBFRONT_STARTUP_TRACE=1`, with the one platform function that tells the age of the process) and `Presentation` (the window shows nearly transparent and becomes opaque once, at the page's first frame or after `Presentation::maximumDelayMs`; the frontend sets the opacity and runs the timer). + +The startup delay (`startupTimeout`) is an option of WKWebView, WebView2 and WebKitGTK (30 s by default, the same message when it expires); CEF has none. WKWebView and WebKitGTK start the secondary windows with the first window's delay, as WebView2 does. diff --git a/include/webfront/frontend/EmbeddedFrontend.hpp b/include/webfront/frontend/EmbeddedFrontend.hpp new file mode 100644 index 00000000..53e8fbc2 --- /dev/null +++ b/include/webfront/frontend/EmbeddedFrontend.hpp @@ -0,0 +1,161 @@ +// SPDX-License-Identifier: Apache-2.0 OR CECILL-B +/// @brief The static facade shared by the embedded frontends (#652): what a native frontend declares once, the base provides. +#pragma once + +#include "../ContentPolicy.hpp" +#include "../ViewAssociation.hpp" +#include "Action.hpp" +#include "CloseRequest.hpp" +#include "NativeWindow.hpp" +#include "UIExecutor.hpp" +#include "Window.hpp" + +#include +#include +#include +#include + +namespace webfront::frontend { + +/// The settings every embedded frontend takes when it opens a window; a frontend's own options start with these. +struct ViewOptions { + ContentPolicy contentPolicy{}; + WindowOptions window{}; + ViewLaunch launch{}; +}; + +/** + * @brief CRTP base of the embedded frontends: `uiExecutor()`, `nativeWindow()`, `requestClose()`, the second window, `initialize()` + * and every overload of `open()`, from the few members the frontend declares (docs/FRONTENDS.md): + * + * - `using Host = ...`: the type that names the process-wide hosts (UIExecutor.hpp, NativeWindow.hpp); + * - `static constexpr bool compiled`: the engine is part of this build; `static constexpr std::string_view name` and + * `unavailable` (what to configure) make the message of a frontend that is not; + * - `using Options`: the frontend's options (`contentPolicy`, `window` and `launch` at least; ViewOptions has them), and an + * optional `static Options defaultOptions()` for the ones a call starts from; + * - `static void openNative(address, port, file, const Options&)` and `closeNative(const NativeWindowHandle&)` (on the + * interface thread: the toolkit's own close request), and an optional `initializeNative()` (a frontend without one throws from initialize() when it is not compiled); + * - `static constexpr bool secondaryWindows`, and when true `openSecondaryNative(address, port, page, const Options&)` and + * `closeSecondaryNative(page) -> bool`, which run on the interface thread; `waitsForFirstWindow` (optional) tells that + * the call may come before the first window is ready (invokeOnUIThreadWhenReady). + * + * Members that name the engine are only instantiated when `compiled` holds, so they need no `#if` of their own. + */ +template +struct EmbeddedFrontend { + static constexpr Action action{Action::closeServerAfterOpen}; + + /// The interface thread while open() runs the toolkit's loop (see UIExecutor.hpp). + [[nodiscard]] static UIExecutor uiExecutor() { + return uiExecutorHostOf().executor(); + } + /// The window, readable on the interface thread while open() runs (see NativeWindow.hpp). + [[nodiscard]] static NativeWindow nativeWindow() { + return nativeWindowHostOf().window(); + } + + static void initialize() { + if constexpr (requires { Derived::initializeNative(); }) + Derived::initializeNative(); + else if constexpr (!Derived::compiled) + unavailable(); + } + + /// 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 constexpr (Derived::compiled) + return detail::requestWindowClose(uiExecutor(), nativeWindow(), [](const NativeWindowHandle& window) { + Derived::closeNative(window); + }, session); + else + return false; + } + + /// Opens `page` in a second window beside the one open() runs, or brings the window already showing it to the front + /// (#616). Callable from any thread while open() runs; throws std::logic_error when no window is open. + static void openSecondaryWindow(std::string_view address, std::string_view port, std::string_view page, const ContentPolicy& policy, + const WindowOptions& window, const ViewLaunch& launch) + requires(Derived::secondaryWindows) + { + if constexpr (!Derived::compiled) { + unavailable(); + } else { + auto options = optionsOf(policy, window, launch); + try { + onUIThread([&] { + Derived::openSecondaryNative(address, port, page, options); + }); + } catch (const UIExecutorUnavailable&) { + throw std::logic_error(std::string(Derived::name) + ": no window of the application is open; show() it before opening another"); + } + } + } + /// Closes the secondary window showing `page`, from any thread; false when none is open. + static bool closeSecondaryWindow([[maybe_unused]] std::string_view page) + requires(Derived::secondaryWindows) + { + if constexpr (Derived::compiled) { + bool closed = false; + try { + invokeOnUIThread(uiExecutor(), [&] { + closed = Derived::closeSecondaryNative(page); + }); + } catch (const UIExecutorUnavailable&) { + return false; + } + return closed; + } else { + return false; + } + } + + static void open(std::string_view port, std::string_view file) { + open("127.0.0.1", port, file); + } + template // dependent: the options type is only needed once the frontend is complete + static void open(std::string_view address, std::string_view port, std::string_view file, const typename D::Options& options = startingOptions()) { + if constexpr (Derived::compiled) + Derived::openNative(address, port, file, options); + else + unavailable(); + } + static void open(std::string_view address, std::string_view port, std::string_view file, const ContentPolicy& policy) { + open(address, port, file, optionsOf(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, optionsOf(policy, 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, optionsOf(policy, window, launch)); + } + +private: + template + static typename D::Options startingOptions() { + if constexpr (requires { Derived::defaultOptions(); }) + return Derived::defaultOptions(); + else + return typename Derived::Options{}; + } + template + static typename D::Options optionsOf(const ContentPolicy& policy, const WindowOptions& window, const ViewLaunch& launch) { + auto options = startingOptions(); + options.contentPolicy = policy; + options.window = window; + options.launch = launch; + return options; + } + template + static void onUIThread(Function&& function) { + if constexpr (requires { requires Derived::waitsForFirstWindow; }) + invokeOnUIThreadWhenReady(uiExecutor(), function); + else + invokeOnUIThread(uiExecutor(), function); + } + [[noreturn]] static void unavailable() { + throw std::runtime_error(std::string(Derived::name) + " is unavailable. " + std::string(Derived::enable)); + } +}; + +} // namespace webfront::frontend diff --git a/include/webfront/frontend/Frontend.hpp b/include/webfront/frontend/Frontend.hpp index 1a105152..c8f01b00 100644 --- a/include/webfront/frontend/Frontend.hpp +++ b/include/webfront/frontend/Frontend.hpp @@ -7,6 +7,7 @@ #include "CEF.hpp" #include "CloseRequest.hpp" #include "DefaultBrowser.hpp" +#include "EmbeddedFrontend.hpp" #include "NativeWebView.hpp" #include "NativeWindow.hpp" #include "UIExecutor.hpp" @@ -192,31 +193,14 @@ struct BrowserWithUILoopFrontend { } }; -struct CEFFrontend { - static constexpr Action action{Action::closeServerAfterOpen}; +struct CEFFrontend : EmbeddedFrontend { // CEF is initialized and run on the process main thread; another thread is not a qualified configuration. - static constexpr bool requiresMainThread = true; - - /// 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 { -#ifdef WEBFRONT_EMBED_CEF - return detail::requestWindowClose(uiExecutor(), nativeWindow(), [](const NativeWindowHandle& window) { - cef::closeBrowser(window.pointer); - }, session); -#else - return false; -#endif - } - - /// CEF's UI thread while open() runs its message loop (see UIExecutor.hpp). - [[nodiscard]] static UIExecutor uiExecutor() { - return uiExecutorHostOf().executor(); - } - - /// The application's CefBrowser, readable on CEF's UI thread while open() runs (see NativeWindow.hpp). - [[nodiscard]] static NativeWindow nativeWindow() { - return nativeWindowHostOf().window(); - } + static constexpr bool requiresMainThread = true; + static constexpr bool secondaryWindows = false; // (#616) + static constexpr bool compiled = true; // without CEF the functions of cef:: throw their own diagnostic + static constexpr std::string_view name = "CEFFrontend"; + using Host = CEFFrontend; + using Options = ViewOptions; static void initialize() { try { @@ -225,22 +209,13 @@ struct CEFFrontend { std::exit(e.exit_code()); } } - - static void open(std::string_view port, std::string_view file) { - cef::open(port, file); - } - static void open(std::string_view address, std::string_view port, std::string_view file) { - cef::open(address, port, file); - } - static void open(std::string_view address, std::string_view port, std::string_view file, const ContentPolicy& policy) { - cef::open(address, port, file, policy); - } - static void open(std::string_view address, std::string_view port, std::string_view file, const ContentPolicy& policy, const WindowOptions& window) { - cef::open(address, port, file, policy, window); + static void openNative(std::string_view address, std::string_view port, std::string_view file, const Options& options) { + cef::open(address, port, file, options.contentPolicy, options.window, options.launch); } - static void open(std::string_view address, std::string_view port, std::string_view file, const ContentPolicy& policy, const WindowOptions& window, - const ViewLaunch& launch) { - cef::open(address, port, file, policy, window, launch); + static void closeNative([[maybe_unused]] const NativeWindowHandle& window) { +#ifdef WEBFRONT_EMBED_CEF + cef::closeBrowser(window.pointer); +#endif } }; @@ -403,18 +378,9 @@ struct NativeOrBrowserFrontendFor { else Browser::open(port, file); } - static void open(std::string_view address, std::string_view port, std::string_view file) { - open(address, port, file, ContentPolicy{}, WindowOptions{}); - } - static void open(std::string_view address, std::string_view port, std::string_view file, const ContentPolicy& policy) { - open(address, port, file, policy, WindowOptions{}); - } - 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, policy, window, ViewLaunch{}); - } /// The launch proof goes to the native window only: the system browser is never given a secret (ADR-020). - static void open(std::string_view address, std::string_view port, std::string_view file, const ContentPolicy& policy, const WindowOptions& window, - const ViewLaunch& launch) { + static void open(std::string_view address, std::string_view port, std::string_view file, const ContentPolicy& policy = {}, const WindowOptions& window = {}, + const ViewLaunch& launch = {}) { if (usesNativeWindow()) detail::openWith(address, port, file, policy, window, launch); else diff --git a/include/webfront/frontend/StartupTrace.hpp b/include/webfront/frontend/StartupTrace.hpp new file mode 100644 index 00000000..8b8e55e3 --- /dev/null +++ b/include/webfront/frontend/StartupTrace.hpp @@ -0,0 +1,129 @@ +// SPDX-License-Identifier: Apache-2.0 OR CECILL-B +/// @brief The startup trace (WEBFRONT_STARTUP_TRACE=1) and the presentation of the native windows, shared by the native +/// frontends (#652). +#pragma once + +#include +#include +#include +#include +#include + +#if defined(_WIN32) + #include "../system/WindowsCompat.hpp" + #include +#elif defined(__APPLE__) + #include + #include + #include +#elif defined(__linux__) + #include + + #include + #include + #include +#endif + +namespace webfront::frontend::detail { + +/// Milliseconds since the process was executed, so that a trace covers the loading of the libraries and the toolkit's +/// initialization, not only the session; -1 when the platform does not tell. +[[nodiscard]] inline long long millisecondsSinceProcessStart() noexcept { +#if defined(_WIN32) + FILETIME creation{}, exit{}, kernel{}, user{}, now{}; + if (!GetProcessTimes(GetCurrentProcess(), &creation, &exit, &kernel, &user)) + return -1; + GetSystemTimeAsFileTime(&now); + ULARGE_INTEGER start{}, current{}; + start.LowPart = creation.dwLowDateTime; + start.HighPart = creation.dwHighDateTime; + current.LowPart = now.dwLowDateTime; + current.HighPart = now.dwHighDateTime; + return static_cast((current.QuadPart - start.QuadPart) / 10000); +#elif defined(__APPLE__) + 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; +#elif defined(__linux__) + try { // field 22 of /proc/self/stat (clock ticks since boot) against the uptime + std::ifstream stat("/proc/self/stat"); + std::string text; + std::getline(stat, text); + const auto close = text.rfind(')'); // the command name may contain spaces + if (close == std::string::npos) + return -1; + std::istringstream fields(text.substr(close + 2)); + std::string field; + for (int index = 3; index <= 22 && fields >> field; ++index) + if (index == 22) { + std::ifstream uptime("/proc/uptime"); + double seconds = 0; + uptime >> seconds; + return static_cast((seconds - std::stod(field) / static_cast(sysconf(_SC_CLK_TCK))) * 1000.0); + } + } catch (...) { + } + return -1; +#else + return -1; +#endif +} + +/// WEBFRONT_STARTUP_TRACE=1 reports the milestones of a view's start on standard error: one object per session, whose +/// creation is the origin of the session's own clock. +class StartupTrace { + std::chrono::steady_clock::time_point created = std::chrono::steady_clock::now(); + + [[nodiscard]] static bool enabled() noexcept { + static const bool value = [] { +#if defined(_MSC_VER) + char text[8]{}; + size_t length = 0; + return getenv_s(&length, text, sizeof text, "WEBFRONT_STARTUP_TRACE") == 0 && length > 1 && std::string_view{text} != "0"; +#else + const auto* text = std::getenv("WEBFRONT_STARTUP_TRACE"); + return text && *text && std::string_view{text} != "0"; +#endif + }(); + return value; + } + +public: + void operator()(const char* milestone) const noexcept { + if (enabled()) + std::fprintf(stderr, "WebFront startup: %s at %lld ms (session %lld ms)\n", milestone, millisecondsSinceProcessStart(), + static_cast(std::chrono::duration_cast(std::chrono::steady_clock::now() - created).count())); + } +}; + +/// The window appears nearly transparent and becomes opaque once, at the page's first frame or when the delay expires. +/// This decides; the frontend sets the opacity and runs the timer. +struct Presentation { + /// The window is made opaque at the latest this long after the load starts, painted or not. + static constexpr unsigned maximumDelayMs = 1000; + + bool shown = false; + bool byFrame = false; // the page's first frame, not the delay, made the window opaque + std::function windowShown; // test hook: called once the window is made opaque + + /// True for the first call only: the caller then shows the window and calls announce(). + [[nodiscard]] bool begin(bool frame) noexcept { + if (shown) + return false; + shown = true; + byFrame = frame; + return true; + } + void announce() const { + if (windowShown) + windowShown(); + } +}; + +} // namespace webfront::frontend::detail diff --git a/include/webfront/frontend/WKWebView.hpp b/include/webfront/frontend/WKWebView.hpp index 4d88a790..38192027 100644 --- a/include/webfront/frontend/WKWebView.hpp +++ b/include/webfront/frontend/WKWebView.hpp @@ -5,11 +5,13 @@ #include "Capture.hpp" #include "CloseRequest.hpp" #include "Downloads.hpp" +#include "EmbeddedFrontend.hpp" #include "../ViewAssociation.hpp" #include "ScriptDialogs.hpp" #include "NativeWindow.hpp" #include "UIExecutor.hpp" #include "Url.hpp" +#include "StartupTrace.hpp" #include "Window.hpp" #include "WindowRegistry.hpp" @@ -29,18 +31,8 @@ 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 +struct WKWebViewFrontend; // names the executor's host (UIExecutor.hpp) + /** @brief Per-opening options for the optional macOS frontend. */ struct WKWebViewOptions { @@ -336,15 +328,14 @@ struct Session { 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(); + frontend::detail::Presentation presentation; + frontend::detail::StartupTrace trace; id previousDelegate = nullptr, previousMenu = nullptr; long previousActivationPolicy = 0; bool installed = false, running = false, closed = false, loaded = false; @@ -402,34 +393,10 @@ struct Session { } } - /// 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) + if (closed || !window || !presentation.begin(byFrame)) return; - presented = true; - presentedByFrame = byFrame; if (presentTimer) { send(presentTimer, "invalidate"); send(presentTimer, "release"); @@ -438,8 +405,7 @@ struct Session { if (options.visible) send(window, "setAlphaValue:", 1.0); trace("window shown"); - if (windowShown) - windowShown(); + presentation.announce(); } /// Dismisses the panels attached to the window: their completion handlers run, so WebKit gets its answers. @@ -1275,10 +1241,10 @@ inline void open(std::string_view address, std::string_view port, std::string_vi // 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. The window is published once the // loop is attached (this is the interface thread) and withdrawn before the session releases it. - auto& host = executorHost(); + auto& host = uiExecutorHostOf(); frontend::detail::InterfaceSession interfaceSession( host, - detail::wkwebview::windowHost(), + nativeWindowHostOf(), Windows::instance(), window, [&host] { @@ -1301,99 +1267,33 @@ inline void requestSessionClose(void* window) { 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() { +struct WKWebViewFrontend : EmbeddedFrontend { + static constexpr bool requiresMainThread = true; // AppKit + static constexpr bool secondaryWindows = true; + static constexpr std::string_view name = "WKWebViewFrontend"; + static constexpr std::string_view enable = "Configure on macOS with -DWEBFRONT_EMBED_WKWEBVIEW=ON"; + using Host = WKWebViewFrontend; + using Options = WKWebViewOptions; #if defined(WEBFRONT_EMBED_WKWEBVIEW) && defined(__APPLE__) + static constexpr bool compiled = true; + static void initializeNative() { 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__) + static void openNative(std::string_view address, std::string_view port, std::string_view file, const Options& options) { 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 closeNative(const NativeWindowHandle& window) { + detail::wkwebview::requestSessionClose(window.pointer); } - 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 openSecondaryNative(std::string_view address, std::string_view port, std::string_view page, const Options& options) { + detail::wkwebview::openSecondary(address, port, page, options); } - 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}); + static bool closeSecondaryNative(std::string_view page) { + return detail::wkwebview::closeSecondary(page); } +#else + static constexpr bool compiled = false; +#endif }; } // namespace webfront::frontend diff --git a/include/webfront/frontend/WebKitGTK.hpp b/include/webfront/frontend/WebKitGTK.hpp index 94f7a895..13e5f7a6 100644 --- a/include/webfront/frontend/WebKitGTK.hpp +++ b/include/webfront/frontend/WebKitGTK.hpp @@ -6,12 +6,14 @@ #include "Capture.hpp" #include "CloseRequest.hpp" #include "DefaultBrowser.hpp" +#include "EmbeddedFrontend.hpp" #include "Downloads.hpp" #include "NativeWindow.hpp" #include "ProfileLease.hpp" #include "ScriptDialogs.hpp" #include "UIExecutor.hpp" #include "Url.hpp" +#include "StartupTrace.hpp" #include "Window.hpp" #include "WindowRegistry.hpp" #include "../ViewAssociation.hpp" @@ -342,6 +344,7 @@ struct Session : FailureState { std::function navigationCancelled; /// Per-launch proof of this view (ADR-020), given at the start of the top-level documents of the application's origin. ViewLaunch launch; + std::chrono::milliseconds startupTimeout{30000}; // the initial document must load within this interval /// A window opened beside the application's own (#616): it shares the network session (cookies, storage and downloads) /// of the first one, runs no loop of its own and reports its closing to `closedHook` instead of ending the loop. Api::Object sharedNetwork = nullptr; @@ -371,11 +374,9 @@ struct Session : FailureState { bool initialNavigation = true; unsigned navigationTimer = 0; unsigned presentTimer = 0; // presents the window anyway when the first frame is late - bool presented = false; bool firstNotified = false; // the page's first notification of the session came, whenever it did - bool shownByFrame = false; // the page's first frame, not the delay, made the window opaque - std::function windowShown; // test hook: called once the window is made opaque - std::chrono::steady_clock::time_point created = std::chrono::steady_clock::now(); + frontend::detail::Presentation presentation; + frontend::detail::StartupTrace trace; unsigned portalTimer = 0; // retries the Wayland export until the toplevel can be exported int portalAttempts = 0; std::uint64_t portalGeneration = 0; // the publication this session's identifier belongs to @@ -387,8 +388,6 @@ struct Session : FailureState { std::shared_ptr captureTarget = std::make_shared(); CaptureRegistration captureRegistration; - /// The window is presented at the latest this long after the load starts, painted or not. - static constexpr unsigned maximumPresentDelayMs = 1000; explicit Session(webfront::detail::BoundContentPolicy rules, WindowOptions settings = {}) : policy(std::move(rules)), windowOptions(resolveWindow(std::move(settings))) {} @@ -547,40 +546,6 @@ struct Session : FailureState { /// The window is mapped at once but fully transparent: WebKit paints, and animation frames run, only in a mapped view, so /// the first frame can be awaited. Without a compositing manager the opacity is ignored and the window shows as before. - /// Milliseconds since the process was executed (field 22 of /proc/self/stat against the uptime), so that the trace of a - /// start covers the loading of the libraries and the toolkit's initialization, not only the session. - static long long millisecondsSinceExec() { - try { - std::ifstream stat("/proc/self/stat"); - std::string text; - std::getline(stat, text); - const auto close = text.rfind(')'); // the command name may contain spaces - if (close == std::string::npos) - return -1; - std::istringstream fields(text.substr(close + 2)); - std::string field; - for (int index = 3; index <= 22 && fields >> field; ++index) - if (index == 22) { - std::ifstream uptime("/proc/uptime"); - double seconds = 0; - uptime >> seconds; - const double ticks = static_cast(sysconf(_SC_CLK_TCK)); - return static_cast((seconds - std::stod(field) / ticks) * 1000.0); - } - } catch (...) { - } - return -1; - } - /// WEBFRONT_STARTUP_TRACE=1 reports the milestones of the view's start, in milliseconds since the process was executed. - void trace(const char* milestone) const { - 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())); - } void presentHidden() { a.widgetOpacity(window, 0.01); // GTK does not draw a widget at 0, and WebKit would wait for a frame forever a.windowPresent(window); @@ -589,20 +554,17 @@ struct Session : FailureState { } /// Shows the window once the page painted its first frame, or when the delay expired. void presentWindow(bool byFrame) { - if (presented || closed) + if (closed || !presentation.begin(byFrame)) return; - presented = true; - shownByFrame = byFrame; stopPresentTimer(); a.widgetOpacity(window, 1.0); trace("window shown"); - if (windowShown) - windowShown(); + presentation.announce(); } static void onFirstFrame(Api::Object, Api::Object, Session* self) noexcept { if (!self->firstNotified) { // a reload injects the probe again: only the first notification is a milestone self->firstNotified = true; - self->trace(self->presented ? "first frame (after the delay)" : "first frame"); + self->trace(self->presentation.shown ? "first frame (after the delay)" : "first frame"); } self->guard([self] { self->presentWindow(true); @@ -899,7 +861,7 @@ struct Session : FailureState { static int onNavigationTimeout(void* data) noexcept { auto* self = static_cast(data); self->navigationTimer = 0; - self->failAndClose("initial navigation timed out after 30 seconds; check the local server"); + self->failAndClose("initial navigation timed out after " + std::to_string(self->startupTimeout.count()) + " milliseconds; check the local server"); return 0; } @@ -956,8 +918,8 @@ struct Session : FailureState { rethrowIfFailed(); if (closed) return; - navigationTimer = a.timeoutAdd(30'000, onNavigationTimeout, this); - presentTimer = a.timeoutAdd(maximumPresentDelayMs, onPresentTimeout, this); + navigationTimer = a.timeoutAdd(static_cast(startupTimeout.count()), onNavigationTimeout, this); + presentTimer = a.timeoutAdd(frontend::detail::Presentation::maximumDelayMs, onPresentTimeout, this); presentHidden(); trace("load started"); a.load(view, url.c_str()); @@ -968,8 +930,8 @@ struct Session : FailureState { /// Starts the load of a secondary window and returns: the loop of the application's own window drives it. void start(const std::string& url) { - navigationTimer = a.timeoutAdd(30'000, onNavigationTimeout, this); - presentTimer = a.timeoutAdd(maximumPresentDelayMs, onPresentTimeout, this); + navigationTimer = a.timeoutAdd(static_cast(startupTimeout.count()), onNavigationTimeout, this); + presentTimer = a.timeoutAdd(frontend::detail::Presentation::maximumDelayMs, onPresentTimeout, this); presentHidden(); a.load(view, url.c_str()); } @@ -980,6 +942,7 @@ struct OpenOptions { WindowOptions window{}; std::function configure{}; ViewLaunch launch{}; + std::chrono::milliseconds startupTimeout{30000}; // the initial document must load within this interval }; /// What the registry of the secondary windows (WindowRegistry.hpp) asks of GTK: reaping is an idle callback. @@ -1030,6 +993,7 @@ inline void openSecondary(const std::string& address, const std::string& port, c session->secondary = true; session->sharedNetwork = primary.network; session->launch = options.launch; + session->startupTimeout = primary.startupTimeout; // the first window's delay session->create(mode); return session; }, @@ -1048,7 +1012,8 @@ inline void open(std::string_view address, std::string_view port, std::string_vi // One window per process: a second open() on the main thread is refused before it creates a window. frontend::detail::InterfaceSession::refuseSecond(uiExecutorHostOf(), WindowHooks::name); Session session(webfront::detail::BoundContentPolicy{applicationUrl(address, port, "", options.launch.origin), options.contentPolicy}, options.window); - session.launch = options.launch; + session.launch = options.launch; + session.startupTimeout = options.startupTimeout; session.create(mode); if (options.configure) options.configure(session); @@ -1082,107 +1047,41 @@ namespace webfront::frontend { /** @brief Optional Linux WebKitGTK 6.0 window. Construct and open on the process main thread. */ template -struct BasicWebKitGTKFrontend { +struct BasicWebKitGTKFrontend : EmbeddedFrontend> { static constexpr detail::webkitgtk::SandboxMode sandboxMode = Mode; - /// The main thread while open() runs the GLib loop (see UIExecutor.hpp). - [[nodiscard]] static UIExecutor uiExecutor() { - return uiExecutorHostOf().executor(); - } - - /// The GtkWindow, readable on the main thread while open() runs (see NativeWindow.hpp). - [[nodiscard]] static NativeWindow nativeWindow() { - return nativeWindowHostOf().window(); - } - - static constexpr Action action{Action::closeServerAfterOpen}; - static constexpr bool requiresMainThread = true; // GTK is initialized and run on the process main thread - - /// 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 { + static constexpr bool requiresMainThread = true; // GTK is initialized and run on the process main thread + static constexpr bool secondaryWindows = true; // they share the first window's network session + static constexpr std::string_view name = "WebKitGTKFrontend"; + static constexpr std::string_view enable = "Configure on Linux with -DWEBFRONT_EMBED_WEBKITGTK=ON"; #if defined(WEBFRONT_EMBED_WEBKITGTK) && defined(__linux__) - return detail::requestWindowClose(uiExecutor(), nativeWindow(), [](const NativeWindowHandle& window) { - // gtk_window_close ignores a window that is not realized, and the window is presented only after the first frame: - // a request made before that must still end the session, so the close-request signal is emitted itself. - int handled = 0; - detail::webkitgtk::api().emitByName(window.pointer, "close-request", &handled); - }, session); + static constexpr bool compiled = true; + using Options = detail::webkitgtk::OpenOptions; #else - return false; + static constexpr bool compiled = false; + using Options = ViewOptions; #endif - } - /// Opens `page` in a second window beside the one open() runs, or brings the window already showing that page to the - /// front (#616). Callable from any thread while open() runs; it returns once the window exists, and throws - /// std::logic_error when no window is open. The window shares the application's network session: its cookies, - /// storage and downloads (tracked by the first window). Its `WindowOptions::media` is that of the first window. A window - /// that cannot start throws its failure. - 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_WEBKITGTK) && defined(__linux__) - try { - invokeOnUIThread(uiExecutor(), [&] { - detail::webkitgtk::openSecondary(std::string(address), std::string(port), std::string(page), - {.contentPolicy = policy, .window = window, .launch = launch}, Mode); - }); - } catch (const UIExecutorUnavailable&) { - throw std::logic_error("WebKitGTKFrontend: no window of the application is open; show() it before opening another"); - } -#else - initialize(); -#endif - } + using Host = WebKitGTKHost; - /// Asks the secondary window showing `page` to close, from any thread; false when none is open. - static bool closeSecondaryWindow([[maybe_unused]] std::string_view page) { -#if defined(WEBFRONT_EMBED_WEBKITGTK) && defined(__linux__) - bool closed = false; - try { - invokeOnUIThread(uiExecutor(), [&] { - closed = detail::webkitgtk::closeSecondary(std::string(page)); - }); - } catch (const UIExecutorUnavailable&) { - return false; - } - return closed; -#else - return false; -#endif - } - - static void initialize() { #if defined(WEBFRONT_EMBED_WEBKITGTK) && defined(__linux__) + static void initializeNative() { detail::webkitgtk::initialize(Mode); -#else - throw std::runtime_error("WebKitGTKFrontend is unavailable. Configure on Linux with -DWEBFRONT_EMBED_WEBKITGTK=ON"); -#endif } - static void open(std::string_view port, std::string_view page) { - open("127.0.0.1", port, page); + static void openNative(std::string_view address, std::string_view port, std::string_view page, const Options& options) { + detail::webkitgtk::open(address, port, page, options, Mode); } - static void open(std::string_view address, std::string_view port, std::string_view page, const ContentPolicy& policy = {}) { - open(address, port, page, policy, WindowOptions{}); + static void closeNative(const NativeWindowHandle& window) { + // gtk_window_close ignores a window that is not realized, and the window is presented only after the first frame: + // a request made before that must still end the session, so the close-request signal is emitted itself. + int handled = 0; + detail::webkitgtk::api().emitByName(window.pointer, "close-request", &handled); } - static void open(std::string_view address, std::string_view port, std::string_view page, const ContentPolicy& policy, const WindowOptions& window) { -#if defined(WEBFRONT_EMBED_WEBKITGTK) && defined(__linux__) - detail::webkitgtk::open(address, port, page, {.contentPolicy = policy, .window = window}, Mode); -#else - (void)window; - (void)address; - (void)port; - (void)page; - (void)policy; - initialize(); -#endif + static void openSecondaryNative(std::string_view address, std::string_view port, std::string_view page, const Options& options) { + detail::webkitgtk::openSecondary(std::string(address), std::string(port), std::string(page), options, Mode); } - static void open(std::string_view address, std::string_view port, std::string_view page, const ContentPolicy& policy, const WindowOptions& window, - const ViewLaunch& launch) { -#if defined(WEBFRONT_EMBED_WEBKITGTK) && defined(__linux__) - detail::webkitgtk::open(address, port, page, {.contentPolicy = policy, .window = window, .launch = launch}, Mode); -#else - (void)launch; - open(address, port, page, policy, window); -#endif + static bool closeSecondaryNative(std::string_view page) { + return detail::webkitgtk::closeSecondary(std::string(page)); } +#endif }; } // namespace webfront::frontend diff --git a/include/webfront/frontend/WebView2.hpp b/include/webfront/frontend/WebView2.hpp index ec5a56f1..059d4b6e 100644 --- a/include/webfront/frontend/WebView2.hpp +++ b/include/webfront/frontend/WebView2.hpp @@ -6,11 +6,13 @@ #include "Capture.hpp" #include "CloseRequest.hpp" #include "DefaultBrowser.hpp" +#include "EmbeddedFrontend.hpp" #include "../ViewAssociation.hpp" #include "ScriptDialogs.hpp" #include "NativeWindow.hpp" #include "UIExecutor.hpp" #include "Url.hpp" +#include "StartupTrace.hpp" #include "Window.hpp" #include "WindowRegistry.hpp" @@ -505,29 +507,10 @@ class Session : public std::enable_shared_from_this { std::wstring className; HBRUSH backgroundBrush = nullptr; bool visibleWindow = false; - bool presented = false; + frontend::detail::Presentation presentation; UINT_PTR presentTimer = 0; - const std::chrono::steady_clock::time_point createdAt = std::chrono::steady_clock::now(); + frontend::detail::StartupTrace trace; - void trace(const char* milestone) const { - wchar_t value[8]{}; - const auto length = GetEnvironmentVariableW(L"WEBFRONT_STARTUP_TRACE", value, 8); - if (!length || (length == 1 && value[0] == L'0')) - return; - FILETIME creation{}, exit{}, kernel{}, user{}, now{}; - long long elapsed = -1; - if (GetProcessTimes(GetCurrentProcess(), &creation, &exit, &kernel, &user)) { - GetSystemTimeAsFileTime(&now); - ULARGE_INTEGER start{}, current{}; - start.LowPart = creation.dwLowDateTime; - start.HighPart = creation.dwHighDateTime; - current.LowPart = now.dwLowDateTime; - current.HighPart = now.dwHighDateTime; - elapsed = static_cast((current.QuadPart - start.QuadPart) / 10000); - } - std::fprintf(stderr, "WebFront startup: %s at %lld ms (session %lld ms)\n", milestone, elapsed, - static_cast(std::chrono::duration_cast(std::chrono::steady_clock::now() - createdAt).count())); - } // Bound to the window and handled by its procedure, so that the delay also runs during the system's modal loops // (moving or resizing by the title bar), which dispatch window messages without going through dispatchNextMessage(). static constexpr UINT_PTR presentTimerId = 0x5746; @@ -538,9 +521,8 @@ class Session : public std::enable_shared_from_this { presentTimer = 0; } void presentWindow() noexcept { - if (presented || closed) + if (closed || !presentation.begin(false)) return; - presented = true; stopPresentTimer(); if (visibleWindow && window) { SetLayeredWindowAttributes(window, 0, 255, LWA_ALPHA); @@ -859,7 +841,7 @@ class Session : public std::enable_shared_from_this { const std::unique_ptr message(raw, CoTaskMemFree); if (std::wstring_view{message.get()} == L"webfront:first-frame") { if (const auto self = weak.lock()) { - if (!self->presented) // a reload injects the probe again: only the first is a milestone + if (!self->presentation.shown) // a reload injects the probe again: only the first is a milestone self->trace("first frame"); self->presentWindow(); } @@ -1131,141 +1113,46 @@ inline void open(std::string_view address, namespace webfront::frontend { -/** @brief Optional Windows embedded frontend. open() owns an STA and blocks until the window closes. */ -struct WebView2Frontend { - static constexpr Action action{Action::closeServerAfterOpen}; - // open() makes its calling thread an STA and pumps its messages there: any thread that is not already MTA. - static constexpr bool requiresMainThread = false; +struct WebView2Frontend; // names the executor's host (UIExecutor.hpp) - /// 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 { +/** @brief What WebView2Frontend and WebView2FrontendWithOptions share: the WebView2 calls the facade needs. */ +struct WebView2Native { + static constexpr bool requiresMainThread = false; // open() makes its calling thread an STA and pumps its messages there + static constexpr bool secondaryWindows = true; + static constexpr bool waitsForFirstWindow = true; // just after show() started, the first environment is being created + static constexpr std::string_view name = "WebView2Frontend"; + static constexpr std::string_view enable = "Configure on Windows with -DWEBFRONT_EMBED_WEBVIEW2=ON"; + using Host = WebView2Frontend; // the hosts are those of WebView2Frontend whichever options provider configures it + using Options = WebView2Options; + /// Nothing to initialize: the COM apartment belongs to each open(), so a build without the engine fails there. + static void initializeNative() { } #if defined(WEBFRONT_EMBED_WEBVIEW2) && defined(_WIN32) - return detail::requestWindowClose(uiExecutor(), nativeWindow(), [](const NativeWindowHandle& window) { - PostMessageW(static_cast(window.pointer), WM_CLOSE, 0, 0); - }, session); -#else - return false; -#endif - } - - /// The thread of the window's message pump while open() runs (see UIExecutor.hpp). - [[nodiscard]] static UIExecutor uiExecutor() { - return uiExecutorHostOf().executor(); - } - - /// The HWND of the window, readable on that thread while open() runs (see NativeWindow.hpp). - [[nodiscard]] static NativeWindow nativeWindow() { - return nativeWindowHostOf().window(); + static constexpr bool compiled = true; + static void openNative(std::string_view address, std::string_view port, std::string_view file, const Options& options) { + detail::webview2::open(address, port, file, options); } - - /// Opens `page` in a second window beside the one open() runs, or brings the window already showing that page to the - /// front (#616). Callable from any thread while open() runs; it returns once the window exists, and throws - /// std::logic_error when no window is open. The window shares the environment of the first: its profile (cookies, - /// storage) and its browser process. A call made while that environment is being created waits for it, except on the - /// interface thread, where it throws std::logic_error. A window that cannot start throws its failure. - 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_WEBVIEW2) && defined(_WIN32) - try { - // Just after show() started, the first window's environment is still being created: a caller on another thread - // waits for it. The first window's watchdog bounds the wait: it closes the window if the runtime never answers, - // and the call is then refused. - invokeOnUIThreadWhenReady(uiExecutor(), [&] { - detail::webview2::openSecondary(address, port, page, WebView2Options{.contentPolicy = policy, .window = window, .launch = launch}); - }); - } catch (const UIExecutorUnavailable&) { - throw std::logic_error("WebView2Frontend: no window of the application is open; show() it before opening another"); - } -#else - throw std::runtime_error("WebView2Frontend is unavailable. Configure on Windows with -DWEBFRONT_EMBED_WEBVIEW2=ON"); -#endif + static void closeNative(const NativeWindowHandle& window) { + PostMessageW(static_cast(window.pointer), WM_CLOSE, 0, 0); } - - /// Closes the secondary window showing `page`, from any thread; false when none is open. - static bool closeSecondaryWindow([[maybe_unused]] std::string_view page) { -#if defined(WEBFRONT_EMBED_WEBVIEW2) && defined(_WIN32) - bool closed = false; - try { - invokeOnUIThread(uiExecutor(), [&] { - closed = detail::webview2::closeSecondary(std::string(page)); - }); - } catch (const UIExecutorUnavailable&) { - return false; - } - return closed; -#else - return false; -#endif + static void openSecondaryNative(std::string_view address, std::string_view port, std::string_view page, const Options& options) { + detail::webview2::openSecondary(address, port, page, options); } - - static void initialize() { } - - static void open(std::string_view port, std::string_view file) { - open("127.0.0.1", port, file); + static bool closeSecondaryNative(std::string_view page) { + return detail::webview2::closeSecondary(std::string(page)); } - - static void open(std::string_view address, std::string_view port, std::string_view file, const WebView2Options& options = {}) { -#if defined(WEBFRONT_EMBED_WEBVIEW2) && defined(_WIN32) - detail::webview2::open(address, port, file, options); #else - (void)address; - (void)port; - (void)file; - (void)options; - throw std::runtime_error("WebView2Frontend is unavailable. Configure on Windows with -DWEBFRONT_EMBED_WEBVIEW2=ON"); + static constexpr bool compiled = false; #endif - } - template Policy> - static void open(std::string_view address, std::string_view port, std::string_view file, const Policy& policy) { - WebView2Options options; - options.contentPolicy = policy; - open(address, port, file, options); - } - static void open(std::string_view address, std::string_view port, std::string_view file, const ContentPolicy& policy, const WindowOptions& window) { - WebView2Options options; - options.contentPolicy = policy; - options.window = window; - open(address, port, file, options); - } - static void open(std::string_view address, std::string_view port, std::string_view file, const ContentPolicy& policy, const WindowOptions& window, - const ViewLaunch& launch) { - WebView2Options options; - options.contentPolicy = policy; - options.window = window; - options.launch = launch; - open(address, port, file, options); - } }; +/** @brief Optional Windows embedded frontend. open() owns an STA and blocks until the window closes. */ +struct WebView2Frontend : WebView2Native, EmbeddedFrontend { }; + /** @brief Configured WebView2 frontend. OptionsProvider::get() returns per-opening WebView2Options. */ template -struct WebView2FrontendWithOptions : WebView2Frontend { - static void open(std::string_view port, std::string_view page) { - open("127.0.0.1", port, page); - } - static void open(std::string_view address, std::string_view port, std::string_view page) { - WebView2Frontend::open(address, port, page, OptionsProvider::get()); - } - template Policy> - static void open(std::string_view address, std::string_view port, std::string_view page, const Policy& policy) { - auto options = OptionsProvider::get(); - options.contentPolicy = policy; - WebView2Frontend::open(address, port, page, options); - } - static void open(std::string_view address, std::string_view port, std::string_view page, const ContentPolicy& policy, const WindowOptions& window) { - auto options = OptionsProvider::get(); - options.contentPolicy = policy; - options.window = window; - WebView2Frontend::open(address, port, page, options); - } - static void open(std::string_view address, std::string_view port, std::string_view page, const ContentPolicy& policy, const WindowOptions& window, - const ViewLaunch& launch) { - auto options = OptionsProvider::get(); - options.contentPolicy = policy; - options.window = window; - options.launch = launch; - WebView2Frontend::open(address, port, page, options); +struct WebView2FrontendWithOptions : WebView2Native, EmbeddedFrontend> { + static WebView2Options defaultOptions() { + return OptionsProvider::get(); } }; diff --git a/test/driver/TestFrontend.hpp b/test/driver/TestFrontend.hpp index 2636a98f..b52435d3 100644 --- a/test/driver/TestFrontend.hpp +++ b/test/driver/TestFrontend.hpp @@ -25,24 +25,15 @@ struct TestFrontend : Frontend { // The launch proof reaches the engine as it does in an application: the suite runs the same association. static void open(std::string_view address, std::string_view port, std::string_view page, const ContentPolicy& policy, const WindowOptions& window, const ViewLaunch& launch) { - if constexpr (std::is_same_v) { - frontend::WKWebViewOptions options; - options.contentPolicy = policy; - options.window = window; - options.launch = launch; - options.visible = visibleWindows; - Frontend::open(address, port, page, options); - } else if constexpr (std::is_same_v) { - frontend::WebView2Options options; - options.contentPolicy = policy; - options.window = window; - options.visible = visibleWindows; - options.launch = launch; - Frontend::open(address, port, page, options); - } else { - // Linux engines use one Xvfb display around a complete suite; their native windows stay real. - Frontend::open(address, port, page, policy, window, launch); - } + // Rendering stays visible where the frontend can hide its window; the Linux engines use one Xvfb display around a + // complete suite and their native windows stay real. + typename Frontend::Options options{}; + options.contentPolicy = policy; + options.window = window; + options.launch = launch; + if constexpr (requires { options.visible = visibleWindows; }) + options.visible = visibleWindows; + Frontend::open(address, port, page, options); } }; } // namespace webfront::testdriver diff --git a/test/unit/WindowRegistryTests.cpp b/test/unit/WindowRegistryTests.cpp index da75a12d..0934443e 100644 --- a/test/unit/WindowRegistryTests.cpp +++ b/test/unit/WindowRegistryTests.cpp @@ -1,6 +1,9 @@ // SPDX-License-Identifier: Apache-2.0 OR CECILL-B /// @brief The registry of the secondary windows and the session of one open(), shared by the native frontends (#652, #616). #include +#include +#include +#include #include #include @@ -12,6 +15,7 @@ #include using namespace webfront::bdd; +using namespace webfront; using namespace webfront::frontend; namespace { @@ -77,7 +81,7 @@ struct FakeHooks { } }; -using Registry = detail::WindowRegistry; +using Registry = frontend::detail::WindowRegistry; void openPage(Registry& windows, const std::string& page, bool closeOnStart = false, std::exception_ptr failOnStart = {}) { windows.open( @@ -221,14 +225,14 @@ const Scenario interfaceSessionOrder{"The session of an open() attaches, publish }; when("the session is held", [&] { { - detail::InterfaceSession session(host, windowHost, windows, first, [] {}, {.kind = NativeWindowKind::gtk, .pointer = &handle, .portalParent = {}}); + frontend::detail::InterfaceSession session(host, windowHost, windows, first, [] {}, {.kind = NativeWindowKind::gtk, .pointer = &handle, .portalParent = {}}); then("the executor is available, the window published and the first window registered", [&] { check(host.executor().available()); check(windows.primary == &first); }); andWhen("another open() starts", [&] { then("it is refused", [&] { - checkThrows([&] { detail::InterfaceSession::refuseSecond(host, "FakeFrontend"); }, + checkThrows([&] { frontend::detail::InterfaceSession::refuseSecond(host, "FakeFrontend"); }, contains("FakeFrontend: open() is already running")); }); }); @@ -243,7 +247,7 @@ const Scenario interfaceSessionOrder{"The session of an open() attaches, publish }); andWhen("a later open() starts", [&] { then("it is accepted", [&] { - checkNothrow([&] { detail::InterfaceSession::refuseSecond(host, "FakeFrontend"); }); + checkNothrow([&] { frontend::detail::InterfaceSession::refuseSecond(host, "FakeFrontend"); }); }); }); }); @@ -256,7 +260,7 @@ const Scenario interfaceSessionOrder{"The session of an open() attaches, publish int handle = 0; then("a second session throws and leaves the first loop attached", [&] { checkThrows([&] { - detail::InterfaceSession session(host, nativeWindowHostOf(), windows, first, [] {}, {.kind = NativeWindowKind::gtk, .pointer = &handle, .portalParent = {}}); + frontend::detail::InterfaceSession session(host, nativeWindowHostOf(), windows, first, [] {}, {.kind = NativeWindowKind::gtk, .pointer = &handle, .portalParent = {}}); }); check(host.executor().available()); check(windows.primary == nullptr); @@ -264,3 +268,112 @@ const Scenario interfaceSessionOrder{"The session of an open() attaches, publish host.close(); }); }}; + +namespace { +struct FakeHost; +struct UnavailableHost; + +// A native frontend as a toolkit declares it: the facade supplies the rest. +struct FakeFrontend : EmbeddedFrontend { + static constexpr bool requiresMainThread = false; + static constexpr bool secondaryWindows = true; + static constexpr bool compiled = true; + static constexpr std::string_view name = "FakeFrontend"; + static constexpr std::string_view enable = "Configure it."; + using Host = FakeHost; + using Options = ViewOptions; + static inline std::vector opened; + static void openNative(std::string_view address, std::string_view port, std::string_view file, const Options& options) { + opened.push_back(std::string(address) + ":" + std::string(port) + "/" + std::string(file) + (options.window.title.empty() ? "" : " " + options.window.title) + + (options.launch.secret.empty() ? "" : " launched")); + } + static void closeNative(const NativeWindowHandle&) { } + static void openSecondaryNative(std::string_view, std::string_view, std::string_view, const Options&) { } + static bool closeSecondaryNative(std::string_view) { return true; } +}; + +struct AbsentFrontend : EmbeddedFrontend { + static constexpr bool secondaryWindows = true; + static constexpr bool compiled = false; + static constexpr std::string_view name = "AbsentFrontend"; + static constexpr std::string_view enable = "Configure on Nowhere with -DNOWHERE=ON"; + using Host = UnavailableHost; + using Options = ViewOptions; +}; + +struct SingleWindowFrontend : EmbeddedFrontend { + static constexpr bool secondaryWindows = false; + static constexpr bool compiled = true; + static constexpr std::string_view name = "SingleWindowFrontend"; + using Host = SingleWindowFrontend; + using Options = ViewOptions; + static void openNative(std::string_view, std::string_view, std::string_view, const Options&) { } + static void closeNative(const NativeWindowHandle&) { } +}; + +template +constexpr bool offersSecondaryWindow = requires(std::string_view text, const ContentPolicy& policy, const WindowOptions& window, const ViewLaunch& launch) { + Frontend::openSecondaryWindow(text, text, text, policy, window, launch); + Frontend::closeSecondaryWindow(text); +}; +static_assert(offersSecondaryWindow && !offersSecondaryWindow); +static_assert(FrontendType && FrontendType && FrontendType); +} // namespace + +const Scenario embeddedFrontendFacade{"The facade of the embedded frontends gives every overload of open()", {"window-registry"}, [] { + given("a frontend that declares its toolkit calls", [&] { + FakeFrontend::opened.clear(); + when("it is opened with every form the application uses", [&] { + FakeFrontend::open("9000", "a.html"); + FakeFrontend::open("1.2.3.4", "9001", "b.html"); + FakeFrontend::open("1.2.3.4", "9002", "c.html", ContentPolicy{}); + FakeFrontend::open("1.2.3.4", "9003", "d.html", ContentPolicy{}, WindowOptions{.title = "T"}); + FakeFrontend::open("1.2.3.4", "9004", "e.html", ContentPolicy{}, WindowOptions{}, ViewLaunch{"secret", "origin"}); + FakeFrontend::open("1.2.3.4", "9005", "f.html", ViewOptions{.window = {.title = "O"}}); + then("each reaches the toolkit with its settings", [&] { + check(FakeFrontend::opened == std::vector{"127.0.0.1:9000/a.html", "1.2.3.4:9001/b.html", "1.2.3.4:9002/c.html", + "1.2.3.4:9003/d.html T", "1.2.3.4:9004/e.html launched", "1.2.3.4:9005/f.html O"}); + }); + }); + when("no window is open", [&] { + then("nothing can be closed, and a second window is refused with the frontend's name", [&] { + check(!FakeFrontend::requestClose()); + check(!FakeFrontend::closeSecondaryWindow("a.html")); + checkThrows([&] { FakeFrontend::openSecondaryWindow("127.0.0.1", "9000", "a.html", {}, {}, {}); }, + contains("FakeFrontend: no window of the application is open")); + }); + }); + }); + given("a frontend whose engine is not part of the build", [&] { + then("every entry point explains what to enable", [&] { + const auto message = equals("AbsentFrontend is unavailable. Configure on Nowhere with -DNOWHERE=ON"); + checkThrows([&] { AbsentFrontend::initialize(); }, message); + checkThrows([&] { AbsentFrontend::open("9000", "a.html"); }, message); + checkThrows([&] { AbsentFrontend::openSecondaryWindow("127.0.0.1", "9000", "a.html", {}, {}, {}); }, message); + check(!AbsentFrontend::requestClose()); + }); + }); +}}; + +const Scenario windowPresentation{"A window is made opaque once, by the first frame or by the delay", {"window-registry"}, [] { + given("a presentation", [&] { + frontend::detail::Presentation presentation; + int announced = 0; + presentation.windowShown = [&] { ++announced; }; + when("the delay expires and then the page paints", [&] { + check(presentation.begin(false)); + presentation.announce(); + check(!presentation.begin(true)); + then("it was shown once, by the delay", [&] { + check(announced == 1 && presentation.shown && !presentation.byFrame); + }); + }); + when("the first frame comes first", [&] { + check(presentation.begin(true)); + check(!presentation.begin(false)); + then("the frame made it opaque", [&] { + check(presentation.byFrame); + }); + }); + }); +}}; diff --git a/test/web/WKWebViewLifecycle.cpp b/test/web/WKWebViewLifecycle.cpp index 3d8f1465..4291993a 100644 --- a/test/web/WKWebViewLifecycle.cpp +++ b/test/web/WKWebViewLifecycle.cpp @@ -305,10 +305,10 @@ void committedNavigation() { send(session.delegate, "webView:didCommitNavigation:", session.view, static_cast(nullptr)); session.rejectNavigation("initial navigation was denied by contentPolicy"); send(session.delegate, "webView:didFailNavigation:withError:", session.view, static_cast(nullptr), static_cast(nullptr)); - require(notified && !session.loaded && !session.closed && !session.error, "A denied later navigation closed the committed document"); + require(notified && !session.loaded && !session.closed && !session.failure, "A denied later navigation closed the committed document"); Session initial("http://127.0.0.1:9002/", {.visible = false}); initial.rejectNavigation("initial navigation was denied by contentPolicy"); - require(initial.closed && initial.error, "A denied initial navigation was not reported"); + require(initial.closed && initial.failure, "A denied initial navigation was not reported"); } void agentApplication() { @@ -658,14 +658,14 @@ void loadRevealPresentation(bool delayOnly) { require(!send(send(session.view, "valueForKey:", key.get()), "boolValue"), "The view still paints its own background"); } double shownAlpha = 0; - session.windowShown = [&] { + session.presentation.windowShown = [&] { shownAlpha = send(session.window, "alphaValue"); session.close(); }; session.start(); session.run(); require(shownAlpha == 1.0, "The window was not made opaque"); - require(session.presentedByFrame != delayOnly, delayOnly ? "The load revealed the window although it was disabled" : "The window waited for the delay instead of the document load"); + require(session.presentation.byFrame != delayOnly, delayOnly ? "The load revealed the window although it was disabled" : "The window waited for the delay instead of the document load"); // The displayed pixels are not read: cacheDisplayInRect renders neither the window's fill nor the web content (it reads black), // and capturing the screen needs a permission the CI does not have. The state that produces them is checked instead: the // window's colour, and the view no longer painting its own background (above). diff --git a/test/web/WebKitGTKLifecycle.cpp b/test/web/WebKitGTKLifecycle.cpp index 8b3ea655..87f43a22 100644 --- a/test/web/WebKitGTKLifecycle.cpp +++ b/test/web/WebKitGTKLifecycle.cpp @@ -544,7 +544,7 @@ void mediaOptOutIsScoped() { // The documented window: process-wide until the load starts, so the opt-out is visible to the application here. const auto during = std::getenv("GST_PLUGIN_SYSTEM_PATH_1_0"); exposedAtStart = during && std::string_view(during) == session.mediaPlugins.string(); - session.windowShown = [&] { + session.presentation.windowShown = [&] { shown = true; }; }; @@ -599,9 +599,9 @@ void mediaOptOutIsScoped() { void firstFramePresentation(bool noFrame) { bool shown = false, byFrame = false; ScenarioFrontend::configure = [&](gtk::Session& session) { - session.windowShown = [&] { + session.presentation.windowShown = [&] { shown = true; - byFrame = session.shownByFrame; + byFrame = session.presentation.byFrame; }; }; ScenarioFrontend::finished = [&](gtk::Session&) { From e6f2a9a498797e95f052c0c175bb43720a25c38a Mon Sep 17 00:00:00 2001 From: Ambroise Leclerc <6860842+ambroise-leclerc@users.noreply.github.com> Date: Mon, 23 Nov 2026 18:45:48 +0100 Subject: [PATCH 03/11] Use the renamed failure field in the WKWebView navigation decision (#652) --- include/webfront/frontend/WKWebView.hpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/include/webfront/frontend/WKWebView.hpp b/include/webfront/frontend/WKWebView.hpp index 38192027..cec75d13 100644 --- a/include/webfront/frontend/WKWebView.hpp +++ b/include/webfront/frontend/WKWebView.hpp @@ -933,7 +933,7 @@ struct Session { } } }); - decision(error ? 0 : policy); + decision(failure ? 0 : policy); } }; From e3fe586bdf7bc358d2ba93f964b8aa2dac778bca Mon Sep 17 00:00:00 2001 From: Ambroise Leclerc <6860842+ambroise-leclerc@users.noreply.github.com> Date: Mon, 23 Nov 2026 18:52:31 +0100 Subject: [PATCH 04/11] Name the namespace of the fake frontends so clang does not flag their constants (#652) --- test/unit/WindowRegistryTests.cpp | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/test/unit/WindowRegistryTests.cpp b/test/unit/WindowRegistryTests.cpp index 0934443e..57815f45 100644 --- a/test/unit/WindowRegistryTests.cpp +++ b/test/unit/WindowRegistryTests.cpp @@ -269,7 +269,7 @@ const Scenario interfaceSessionOrder{"The session of an open() attaches, publish }); }}; -namespace { +namespace window_registry_fakes { // named, not anonymous: the clang warning for unused constants of anonymous types struct FakeHost; struct UnavailableHost; @@ -318,7 +318,8 @@ constexpr bool offersSecondaryWindow = requires(std::string_view text, const Con }; static_assert(offersSecondaryWindow && !offersSecondaryWindow); static_assert(FrontendType && FrontendType && FrontendType); -} // namespace +} // namespace window_registry_fakes +using namespace window_registry_fakes; const Scenario embeddedFrontendFacade{"The facade of the embedded frontends gives every overload of open()", {"window-registry"}, [] { given("a frontend that declares its toolkit calls", [&] { From d3ab8d037ed716d4f70dbfff3d099a49628ba196 Mon Sep 17 00:00:00 2001 From: Ambroise Leclerc <6860842+ambroise-leclerc@users.noreply.github.com> Date: Mon, 23 Nov 2026 19:07:43 +0100 Subject: [PATCH 05/11] Keep the configured options a call does not override; address the review remarks (#652) --- docs/CHANGELOG.md | 2 +- .../webfront/frontend/EmbeddedFrontend.hpp | 17 +++--- include/webfront/frontend/WindowRegistry.hpp | 7 ++- test/unit/WindowRegistryTests.cpp | 54 ++++++++++++++++++- 4 files changed, 70 insertions(+), 10 deletions(-) diff --git a/docs/CHANGELOG.md b/docs/CHANGELOG.md index 092ceb39..840ef971 100644 --- a/docs/CHANGELOG.md +++ b/docs/CHANGELOG.md @@ -50,7 +50,7 @@ in a native pseudoterminal, and a faster, less flashy start of the native window - Choose the colour of the WebKitGTK view under the page with `WindowOptions::background` (WebKitGTK; the other embedded frontends are listed here), and read the start-up milestones of a WebKitGTK view with `WEBFRONT_STARTUP_TRACE=1` (#611, `docs/WEBKITGTK.md`). ### Changed -- WebKitGTK takes a `startupTimeout` (30 s by default, the message now in milliseconds), a secondary window of WKWebView and WebKitGTK starts with the first window's delay, WKWebView clears the hook of a secondary window before destroying it, and its messages name `WKWebViewFrontend` everywhere (#652). +- WebKitGTK takes a `startupTimeout` (30 s by default), and WebView2 refuses a secondary window once the first one closed, even for a page already open (#652). - Write a native frontend from shared headers: `EmbeddedFrontend` (facade and every `open()` overload), `WindowRegistry`/`InterfaceSession`, `StartupTrace` and `Presentation`, tested on Linux with fake windows (#652, `docs/FRONTENDS.md`). - Reveal the WKWebView window when the document has loaded or after one second (#611, `docs/WKWEBVIEW.md`). - Reveal the WebView2 window after the first frame or one second (#611, `docs/WEBVIEW2.md`). diff --git a/include/webfront/frontend/EmbeddedFrontend.hpp b/include/webfront/frontend/EmbeddedFrontend.hpp index 53e8fbc2..87d219b2 100644 --- a/include/webfront/frontend/EmbeddedFrontend.hpp +++ b/include/webfront/frontend/EmbeddedFrontend.hpp @@ -80,7 +80,7 @@ struct EmbeddedFrontend { if constexpr (!Derived::compiled) { unavailable(); } else { - auto options = optionsOf(policy, window, launch); + auto options = optionsOf(policy, &window, &launch); try { onUIThread([&] { Derived::openSecondaryNative(address, port, page, options); @@ -120,14 +120,14 @@ struct EmbeddedFrontend { unavailable(); } static void open(std::string_view address, std::string_view port, std::string_view file, const ContentPolicy& policy) { - open(address, port, file, optionsOf(policy, {}, {})); + open(address, port, file, optionsOf(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, optionsOf(policy, window, {})); + open(address, port, file, optionsOf(policy, &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, optionsOf(policy, window, launch)); + open(address, port, file, optionsOf(policy, &window, &launch)); } private: @@ -139,11 +139,14 @@ struct EmbeddedFrontend { return typename Derived::Options{}; } template - static typename D::Options optionsOf(const ContentPolicy& policy, const WindowOptions& window, const ViewLaunch& launch) { + static typename D::Options optionsOf(const ContentPolicy& policy, const WindowOptions* window = nullptr, const ViewLaunch* launch = nullptr) { + // The settings of the arguments the caller gave replace the configured ones; the others stay as configured. auto options = startingOptions(); options.contentPolicy = policy; - options.window = window; - options.launch = launch; + if (window) + options.window = *window; + if (launch) + options.launch = *launch; return options; } template diff --git a/include/webfront/frontend/WindowRegistry.hpp b/include/webfront/frontend/WindowRegistry.hpp index 67d52288..ee347fee 100644 --- a/include/webfront/frontend/WindowRegistry.hpp +++ b/include/webfront/frontend/WindowRegistry.hpp @@ -42,6 +42,7 @@ class WindowRegistry { std::map> secondary; std::vector> finished; // closed, destroyed by reap() Hooks hooks; + bool clearing = false; // clear() is destroying the windows /// A session closed (its closedHook): takes it out of the table, reports why it failed, and reaps it later. void retire(const std::string& page) { @@ -73,6 +74,7 @@ class WindowRegistry { /// The first window ended: the others end with it, and nothing is left to reap. The sessions leave the table before /// they are destroyed, and their hook no longer retires them from it. void clear() { + clearing = true; hooks.cancelReap(); auto windows = std::move(secondary); secondary.clear(); @@ -80,7 +82,8 @@ class WindowRegistry { entry.second->closedHook = nullptr; finished.clear(); windows.clear(); - primary = nullptr; + primary = nullptr; + clearing = false; } /** @@ -93,6 +96,8 @@ class WindowRegistry { */ template void open(const std::string& page, Create&& create, Start&& start) { + if (clearing) + return; // asked by the teardown of a window of a session that is ending: an exception would end the process if (!primary || primary->closed) throw std::logic_error(std::string(Hooks::name) + ": no window of the application is open; show() it before opening another"); if (const auto found = secondary.find(page); found != secondary.end()) { diff --git a/test/unit/WindowRegistryTests.cpp b/test/unit/WindowRegistryTests.cpp index 57815f45..8f60be0f 100644 --- a/test/unit/WindowRegistryTests.cpp +++ b/test/unit/WindowRegistryTests.cpp @@ -30,10 +30,13 @@ struct FakeSession { bool inCallback = false; // true while its own closedHook runs bool closeOnStart = false; std::exception_ptr failOnStart; + static inline std::function destroyProbe; // runs in every destructor: what a window's teardown can observe explicit FakeSession(std::string name = {}) : page(std::move(name)) { } ~FakeSession() { events.push_back("destroy " + page); + if (destroyProbe) + destroyProbe(); if (inCallback) events.push_back("destroyed in its own callback"); if (closedHook) @@ -162,7 +165,7 @@ const Scenario secondaryWindowRegistry{"The registry of the secondary windows is then("the caller learns why, and the page is not registered", [&] { checkThrows([&] { openPage(windows, "a.html", true, std::make_exception_ptr(std::runtime_error("navigation failed"))); - }); + }, contains("navigation failed")); check(windows.secondary.empty()); }); andWhen("it closed without a failure", [&] { @@ -188,6 +191,19 @@ const Scenario secondaryWindowRegistry{"The registry of the secondary windows is }); }); + when("a window opens a page while the others are destroyed", [&] { + openPage(windows, "a.html"); + FakeSession::destroyProbe = [&] { + openPage(windows, "late.html"); // a destructor cannot be refused by an exception: it is ignored + }; + windows.clear(); + FakeSession::destroyProbe = nullptr; + then("no window outlives the session", [&] { + check(windows.secondary.empty()); + check(!happened("create late.html")); + }); + }); + when("the first window ends with secondary windows open", [&] { openPage(windows, "a.html"); openPage(windows, "b.html"); @@ -195,6 +211,7 @@ const Scenario secondaryWindowRegistry{"The registry of the secondary windows is events.clear(); windows.clear(); then("the reap is withdrawn and every session is destroyed with its hook cleared", [&] { + require(!events.empty()); check(events.front() == "cancel reap"); check(happened("destroy a.html")); check(happened("destroy b.html")); @@ -229,6 +246,9 @@ const Scenario interfaceSessionOrder{"The session of an open() attaches, publish then("the executor is available, the window published and the first window registered", [&] { check(host.executor().available()); check(windows.primary == &first); + const auto window = published().get(); + require(window.has_value()); + check(window->pointer == &handle); }); andWhen("another open() starts", [&] { then("it is refused", [&] { @@ -238,9 +258,15 @@ const Scenario interfaceSessionOrder{"The session of an open() attaches, publish }); openPage(windows, "a.html"); events.clear(); + FakeSession::destroyProbe = [&] { // the secondary windows are destroyed while the window is still published + if (!published().get().has_value() || !host.executor().available()) + events.push_back("withdrawn too early"); + }; } + FakeSession::destroyProbe = nullptr; then("the secondary windows are cleared first, then the window is withdrawn and the host closed", [&] { check(!events.empty() && events.front() == "cancel reap"); + check(happened("destroy a.html") && !happened("withdrawn too early")); check(windows.primary == nullptr && windows.secondary.empty()); check(!host.executor().available()); check(!published().get().has_value()); @@ -292,6 +318,23 @@ struct FakeFrontend : EmbeddedFrontend { static bool closeSecondaryNative(std::string_view) { return true; } }; +// A frontend whose options come from a provider (WebView2FrontendWithOptions): a call overrides only what it passes. +struct ConfiguredFrontend : EmbeddedFrontend { + static constexpr bool secondaryWindows = false; + static constexpr bool compiled = true; + static constexpr std::string_view name = "ConfiguredFrontend"; + using Host = ConfiguredFrontend; + using Options = ViewOptions; + static inline std::vector opened; + static ViewOptions defaultOptions() { + return {.window = {.title = "configured"}, .launch = {"configured-secret", "configured-origin"}}; + } + static void openNative(std::string_view, std::string_view, std::string_view file, const Options& options) { + opened.push_back(std::string(file) + " " + options.window.title + " " + options.launch.secret); + } + static void closeNative(const NativeWindowHandle&) { } +}; + struct AbsentFrontend : EmbeddedFrontend { static constexpr bool secondaryWindows = true; static constexpr bool compiled = false; @@ -345,6 +388,15 @@ const Scenario embeddedFrontendFacade{"The facade of the embedded frontends give }); }); }); + given("a frontend configured by a provider", [&] { + ConfiguredFrontend::opened.clear(); + ConfiguredFrontend::open("127.0.0.1", "9000", "a.html", ContentPolicy{}); + ConfiguredFrontend::open("127.0.0.1", "9000", "b.html", ContentPolicy{}, WindowOptions{.title = "own"}); + ConfiguredFrontend::open("127.0.0.1", "9000", "c.html", ContentPolicy{}, WindowOptions{.title = "own"}, ViewLaunch{"own-secret", ""}); + then("a call replaces only the settings it passes", [&] { + check(ConfiguredFrontend::opened == std::vector{"a.html configured configured-secret", "b.html own configured-secret", "c.html own own-secret"}); + }); + }); given("a frontend whose engine is not part of the build", [&] { then("every entry point explains what to enable", [&] { const auto message = equals("AbsentFrontend is unavailable. Configure on Nowhere with -DNOWHERE=ON"); From 7b7aca2039554f387bbcc427597ebe1ad1c1fb8e Mon Sep 17 00:00:00 2001 From: Ambroise Leclerc <6860842+ambroise-leclerc@users.noreply.github.com> Date: Mon, 23 Nov 2026 19:14:12 +0100 Subject: [PATCH 06/11] Open every native window from one ViewOptions whose test injections reach the secondary windows (#652) --- docs/CHANGELOG.md | 1 + docs/FRONTENDS.md | 4 +- .../webfront/frontend/EmbeddedFrontend.hpp | 40 +++++++++++++++++-- include/webfront/frontend/WKWebView.hpp | 27 ++----------- include/webfront/frontend/WebKitGTK.hpp | 40 +++++++++++++++---- include/webfront/frontend/WebView2.hpp | 15 ++----- 6 files changed, 78 insertions(+), 49 deletions(-) diff --git a/docs/CHANGELOG.md b/docs/CHANGELOG.md index 840ef971..ed208e94 100644 --- a/docs/CHANGELOG.md +++ b/docs/CHANGELOG.md @@ -51,6 +51,7 @@ in a native pseudoterminal, and a faster, less flashy start of the native window ### Changed - WebKitGTK takes a `startupTimeout` (30 s by default), and WebView2 refuses a secondary window once the first one closed, even for a page already open (#652). +- Open every native window from one `ViewOptions` (`WKWebViewOptions` and `WebView2Options` are aliases), whose test injections reach the secondary windows too (#652, `docs/FRONTENDS.md`). - Write a native frontend from shared headers: `EmbeddedFrontend` (facade and every `open()` overload), `WindowRegistry`/`InterfaceSession`, `StartupTrace` and `Presentation`, tested on Linux with fake windows (#652, `docs/FRONTENDS.md`). - Reveal the WKWebView window when the document has loaded or after one second (#611, `docs/WKWEBVIEW.md`). - Reveal the WebView2 window after the first frame or one second (#611, `docs/WEBVIEW2.md`). diff --git a/docs/FRONTENDS.md b/docs/FRONTENDS.md index 99aa2212..74b4f650 100644 --- a/docs/FRONTENDS.md +++ b/docs/FRONTENDS.md @@ -429,8 +429,8 @@ the native helper never selects CEF. WebKitGTK, WKWebView, WebView2 and CEF share their toolkit-independent logic in `include/webfront/frontend/`; a new native frontend declares only the calls of its toolkit. The shared parts are tested on Linux with fake windows (`test/unit/WindowRegistryTests.cpp`). -- `EmbeddedFrontend.hpp`: `EmbeddedFrontend` gives `uiExecutor()`, `nativeWindow()`, `requestClose()`, `initialize()`, `openSecondaryWindow()`, `closeSecondaryWindow()` and every overload of `open()`. The frontend declares `Host` (the tag of its executor and window hosts), `Options` (`ViewOptions` has the `contentPolicy`, `window` and `launch` every frontend takes), `compiled`, `name` and `enable` (the message of a build without the engine), `secondaryWindows`, and the toolkit calls `openNative`, `closeNative`, `openSecondaryNative`, `closeSecondaryNative` (on the interface thread) and optionally `initializeNative`, `defaultOptions` and `waitsForFirstWindow`. Members that name the engine are instantiated only when `compiled` holds, so no `#if` surrounds them. A frontend without `initializeNative` throws from `initialize()` when it is not compiled; WebView2 declares an empty one, because its COM apartment belongs to each `open()`, and fails there. +- `EmbeddedFrontend.hpp`: `EmbeddedFrontend` gives `uiExecutor()`, `nativeWindow()`, `requestClose()`, `initialize()`, `openSecondaryWindow()`, `closeSecondaryWindow()` and every overload of `open()`. The frontend declares `Host` (the tag of its executor and window hosts), `Options` (`ViewOptions`, which every native frontend takes: `startupTimeout`, `userDataFolder` (WebView2), `contentPolicy`, `window`, `visible`, `launch` and the test injections `chooseFiles`, `downloadDirectory`, `downloadFinished`, `answerScriptDialog`; a frontend ignores what its toolkit has no use for, and `WKWebViewOptions` and `WebView2Options` are aliases of it), `compiled`, `name` and `enable` (the message of a build without the engine), `secondaryWindows`, and the toolkit calls `openNative`, `closeNative`, `openSecondaryNative`, `closeSecondaryNative` (on the interface thread) and optionally `initializeNative`, `defaultOptions` and `waitsForFirstWindow`. Members that name the engine are instantiated only when `compiled` holds, so no `#if` surrounds them. A frontend without `initializeNative` throws from `initialize()` when it is not compiled; WebView2 declares an empty one, because its COM apartment belongs to each `open()`, and fails there. - `WindowRegistry.hpp`: `WindowRegistry` is the table of the secondary windows (open, bring to the front, close, retire a window that closed, reap it outside its own callback, clear when the first window ends) and `InterfaceSession` is what an `open()` holds while its loop runs (attach, publish, then on every exit, also by exception: clear the secondary windows, withdraw the window, close the host). The hooks are `scheduleReap`, `cancelReap`, `present`, `close` and the `name` of the messages: an idle callback in WebKitGTK, a queued block in WKWebView, a message to the first window in WebView2. - `StartupTrace.hpp`: `StartupTrace` (`WEBFRONT_STARTUP_TRACE=1`, with the one platform function that tells the age of the process) and `Presentation` (the window shows nearly transparent and becomes opaque once, at the page's first frame or after `Presentation::maximumDelayMs`; the frontend sets the opacity and runs the timer). -The startup delay (`startupTimeout`) is an option of WKWebView, WebView2 and WebKitGTK (30 s by default, the same message when it expires); CEF has none. WKWebView and WebKitGTK start the secondary windows with the first window's delay, as WebView2 does. +The startup delay (`startupTimeout`) is an option of WKWebView, WebView2 and WebKitGTK (30 s by default, the same message when it expires); CEF has none. WKWebView and WebKitGTK start the secondary windows with the first window's delay and test injections, as WebView2 does. diff --git a/include/webfront/frontend/EmbeddedFrontend.hpp b/include/webfront/frontend/EmbeddedFrontend.hpp index 87d219b2..4daa6164 100644 --- a/include/webfront/frontend/EmbeddedFrontend.hpp +++ b/include/webfront/frontend/EmbeddedFrontend.hpp @@ -7,21 +7,53 @@ #include "Action.hpp" #include "CloseRequest.hpp" #include "NativeWindow.hpp" +#include "ScriptDialogs.hpp" #include "UIExecutor.hpp" #include "Window.hpp" +#include +#include +#include #include #include #include #include +#include namespace webfront::frontend { -/// The settings every embedded frontend takes when it opens a window; a frontend's own options start with these. +/// What an embedded frontend is asked when it opens a window, the same for the first window and the secondary ones. A +/// frontend honours the settings that its toolkit has (a field it has no use for is ignored) and its own startup deadline. struct ViewOptions { - ContentPolicy contentPolicy{}; - WindowOptions window{}; - ViewLaunch launch{}; + /// The initial document must finish loading within this interval; no bridge connection is required. + std::chrono::milliseconds startupTimeout{30000}; + /// WebView2 only: the profile folder; empty keeps the default. + std::filesystem::path userDataFolder{}; + ContentPolicy contentPolicy{}; + WindowOptions window{}; + /// WKWebView and WebView2: keep the native window hidden and avoid activating the application. + bool visible{true}; + /// Test injections (WKWebView, WebKitGTK): answers `` without a dialog (an empty list cancels). + std::function()> chooseFiles{}; + /// Test injection: a non-empty folder receives downloads without a save panel. + std::filesystem::path downloadDirectory{}; + /// Test injection: called with the destination of each finished download. + std::function downloadFinished{}; + /// Test injection: answers `alert`, `confirm` and `prompt` without a box (WKWebView, WebKitGTK, WebView2). + ScriptDialogHandler answerScriptDialog{}; + /// 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{}; + + /// A secondary window is built from the first one's: its visibility, its startup deadline and its test injections. + void inherit(const ViewOptions& first) { + visible = first.visible; + startupTimeout = first.startupTimeout; + chooseFiles = first.chooseFiles; + downloadDirectory = first.downloadDirectory; + downloadFinished = first.downloadFinished; + answerScriptDialog = first.answerScriptDialog; + } }; /** diff --git a/include/webfront/frontend/WKWebView.hpp b/include/webfront/frontend/WKWebView.hpp index cec75d13..0e76de12 100644 --- a/include/webfront/frontend/WKWebView.hpp +++ b/include/webfront/frontend/WKWebView.hpp @@ -34,28 +34,8 @@ namespace webfront::frontend { struct WKWebViewFrontend; // names the executor's host (UIExecutor.hpp) -/** @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{}; -}; +/** @brief Per-opening options for the optional macOS frontend (the common ViewOptions). */ +using WKWebViewOptions = ViewOptions; } // namespace webfront::frontend @@ -1205,8 +1185,7 @@ inline void openSecondary(std::string_view address, std::string_view port, std:: std::string(page), [&](Session& primary) { // The first window's visibility and startup delay: a hidden application never shows a window or takes the focus. - options.visible = primary.options.visible; - options.startupTimeout = primary.options.startupTimeout; + options.inherit(primary.options); auto child = std::make_shared(applicationUrl(address, port, page, options.launch.origin), std::move(options)); child->secondary = true; child->sharedDataStore = send(send(primary.view, "configuration"), "websiteDataStore"); diff --git a/include/webfront/frontend/WebKitGTK.hpp b/include/webfront/frontend/WebKitGTK.hpp index 13e5f7a6..690a495b 100644 --- a/include/webfront/frontend/WebKitGTK.hpp +++ b/include/webfront/frontend/WebKitGTK.hpp @@ -943,8 +943,25 @@ struct OpenOptions { std::function configure{}; ViewLaunch launch{}; std::chrono::milliseconds startupTimeout{30000}; // the initial document must load within this interval + // The test injections of ViewOptions, for the first window and for the secondary ones. + std::function()> chooseFiles{}; + std::filesystem::path downloadDirectory{}; + std::function downloadFinished{}; + ScriptDialogHandler answerScriptDialog{}; }; +/// The options a frontend receives, as the session of a window takes them. +inline OpenOptions openOptionsOf(const ViewOptions& view) { + return {.contentPolicy = view.contentPolicy, + .window = view.window, + .launch = view.launch, + .startupTimeout = view.startupTimeout, + .chooseFiles = view.chooseFiles, + .downloadDirectory = view.downloadDirectory, + .downloadFinished = view.downloadFinished, + .answerScriptDialog = view.answerScriptDialog}; +} + /// What the registry of the secondary windows (WindowRegistry.hpp) asks of GTK: reaping is an idle callback. struct WindowHooks { static constexpr std::string_view name = "WebKitGTKFrontend"; @@ -992,8 +1009,12 @@ inline void openSecondary(const std::string& address, const std::string& port, c auto session = std::make_shared(webfront::detail::BoundContentPolicy{applicationUrl(address, port, "", options.launch.origin), options.contentPolicy}, options.window); session->secondary = true; session->sharedNetwork = primary.network; - session->launch = options.launch; - session->startupTimeout = primary.startupTimeout; // the first window's delay + session->launch = options.launch; + session->startupTimeout = primary.startupTimeout; // the first window's delay and test injections + session->chooseFiles = primary.chooseFiles; + session->downloadDirectory = primary.downloadDirectory; + session->downloadFinished = primary.downloadFinished; + session->answerScriptDialog = primary.answerScriptDialog; session->create(mode); return session; }, @@ -1012,8 +1033,12 @@ inline void open(std::string_view address, std::string_view port, std::string_vi // One window per process: a second open() on the main thread is refused before it creates a window. frontend::detail::InterfaceSession::refuseSecond(uiExecutorHostOf(), WindowHooks::name); Session session(webfront::detail::BoundContentPolicy{applicationUrl(address, port, "", options.launch.origin), options.contentPolicy}, options.window); - session.launch = options.launch; - session.startupTimeout = options.startupTimeout; + session.launch = options.launch; + session.startupTimeout = options.startupTimeout; + session.chooseFiles = options.chooseFiles; + session.downloadDirectory = options.downloadDirectory; + session.downloadFinished = options.downloadFinished; + session.answerScriptDialog = options.answerScriptDialog; session.create(mode); if (options.configure) options.configure(session); @@ -1055,11 +1080,10 @@ struct BasicWebKitGTKFrontend : EmbeddedFrontend> { static constexpr std::string_view enable = "Configure on Linux with -DWEBFRONT_EMBED_WEBKITGTK=ON"; #if defined(WEBFRONT_EMBED_WEBKITGTK) && defined(__linux__) static constexpr bool compiled = true; - using Options = detail::webkitgtk::OpenOptions; #else static constexpr bool compiled = false; - using Options = ViewOptions; #endif + using Options = ViewOptions; using Host = WebKitGTKHost; #if defined(WEBFRONT_EMBED_WEBKITGTK) && defined(__linux__) @@ -1067,7 +1091,7 @@ struct BasicWebKitGTKFrontend : EmbeddedFrontend> { detail::webkitgtk::initialize(Mode); } static void openNative(std::string_view address, std::string_view port, std::string_view page, const Options& options) { - detail::webkitgtk::open(address, port, page, options, Mode); + detail::webkitgtk::open(address, port, page, detail::webkitgtk::openOptionsOf(options), Mode); } static void closeNative(const NativeWindowHandle& window) { // gtk_window_close ignores a window that is not realized, and the window is presented only after the first frame: @@ -1076,7 +1100,7 @@ struct BasicWebKitGTKFrontend : EmbeddedFrontend> { detail::webkitgtk::api().emitByName(window.pointer, "close-request", &handled); } static void openSecondaryNative(std::string_view address, std::string_view port, std::string_view page, const Options& options) { - detail::webkitgtk::openSecondary(std::string(address), std::string(port), std::string(page), options, Mode); + detail::webkitgtk::openSecondary(std::string(address), std::string(port), std::string(page), detail::webkitgtk::openOptionsOf(options), Mode); } static bool closeSecondaryNative(std::string_view page) { return detail::webkitgtk::closeSecondary(std::string(page)); diff --git a/include/webfront/frontend/WebView2.hpp b/include/webfront/frontend/WebView2.hpp index 059d4b6e..19d9afcc 100644 --- a/include/webfront/frontend/WebView2.hpp +++ b/include/webfront/frontend/WebView2.hpp @@ -27,17 +27,8 @@ namespace webfront::frontend { -/** @brief Per-opening runtime deadline, persistent profile directory and embedded-content rules. */ -struct WebView2Options { - std::chrono::milliseconds startupTimeout{std::chrono::seconds{30}}; - std::filesystem::path userDataFolder{}; - ContentPolicy contentPolicy{}; - WindowOptions window{}; - /** @brief Keep the native window hidden while retaining the real controller and message loop. */ - bool visible{true}; - /** @brief Per-launch proof of this view (ADR-020), given to top-level documents of the application's origin at their creation. */ - ViewLaunch launch{}; -}; +/** @brief Per-opening runtime deadline, persistent profile directory and embedded-content rules (the common ViewOptions). */ +using WebView2Options = ViewOptions; } // namespace webfront::frontend @@ -1053,6 +1044,7 @@ inline void openSecondary(std::string_view address, std::string_view port, std:: session->contentPolicy = webfront::detail::BoundContentPolicy{frontend::detail::applicationUrl(address, port, "", options.launch.origin), options.contentPolicy}; session->viewLaunch = options.launch; session->url = utf16(frontend::detail::applicationUrl(address, port, page, options.launch.origin)); + session->answerScriptDialog = primary.answerScriptDialog; session->createWindow(primary.shown(), options.window); return session; }, @@ -1085,6 +1077,7 @@ inline void open(std::string_view address, session->contentPolicy = std::move(contentPolicy); session->viewLaunch = options.launch; session->url = utf16(frontend::detail::applicationUrl(address, port, file, options.launch.origin)); + session->answerScriptDialog = options.answerScriptDialog; if (prepare) prepare(*session); const auto profile = options.userDataFolder.empty() ? userDataFolder() : std::filesystem::absolute(options.userDataFolder); From 31e11cce13ca34376bb70501378a6f7dc35ad6c8 Mon Sep 17 00:00:00 2001 From: Ambroise Leclerc <6860842+ambroise-leclerc@users.noreply.github.com> Date: Mon, 23 Nov 2026 19:46:20 +0100 Subject: [PATCH 07/11] Keep the member order of WKWebViewOptions and refuse a startup deadline a timer cannot hold (#652) --- docs/CHANGELOG.md | 1 + include/webfront/frontend/EmbeddedFrontend.hpp | 16 ++++++++++++++-- include/webfront/frontend/WebKitGTK.hpp | 5 +++-- test/unit/WindowRegistryTests.cpp | 11 +++++++++++ 4 files changed, 29 insertions(+), 4 deletions(-) diff --git a/docs/CHANGELOG.md b/docs/CHANGELOG.md index ed208e94..069950bf 100644 --- a/docs/CHANGELOG.md +++ b/docs/CHANGELOG.md @@ -11,6 +11,7 @@ these entries stays in the GitHub releases and the Git history. ## Unreleased ### Breaking +- `WebView2Options` is now `ViewOptions`, shared with WKWebView: `userDataFolder` moves after `launch`, so a positional initialization of `WebView2Options` stops compiling; use designated initializers (#652, `docs/FRONTENDS.md`). - `webfront/automation/Enable.hpp` no longer compiles with `WEBFRONT_DISTRIBUTION`: gate `enableAutomation` out of the distribution build, as the guide already advised (#632, ADR-025). - `webfront-agent` is removed with its JSON CLI, MCP on stdio, `--serve`, `--attach`, `--list` and `--print-mcp-config`, as are `WEBFRONT_BUILD_AUTOMATION`, `WEBFRONT_AUTOMATION_FRONTEND` and `webfront_add_agent()`: connect the MCP client to the URL the application prints (#632, ADR-025, `docs/AUTOMATION.md`). - `AutomationOptions::listen` becomes `directory` and may stay empty (a private directory named after the session is created), `Automation::endpoint()` becomes `directory()`, and the JSON-lines attachment channel (`ChannelServer`, `ChannelClient`) is gone (#632). diff --git a/include/webfront/frontend/EmbeddedFrontend.hpp b/include/webfront/frontend/EmbeddedFrontend.hpp index 4daa6164..5883c60b 100644 --- a/include/webfront/frontend/EmbeddedFrontend.hpp +++ b/include/webfront/frontend/EmbeddedFrontend.hpp @@ -14,6 +14,7 @@ #include #include #include +#include #include #include #include @@ -22,13 +23,21 @@ namespace webfront::frontend { +namespace detail { +/// A startup deadline a toolkit timer can hold: positive and below 2^31 milliseconds. A negative or huge count would +/// otherwise wrap around when it becomes the unsigned argument of the timer. +[[nodiscard]] inline unsigned timerMilliseconds(std::chrono::milliseconds timeout, std::string_view frontend) { + if (timeout.count() < 1 || timeout.count() > std::numeric_limits::max()) + throw std::invalid_argument(std::string(frontend) + ": startupTimeout must be between 1 and " + std::to_string(std::numeric_limits::max()) + " milliseconds"); + return static_cast(timeout.count()); +} +} // namespace detail + /// What an embedded frontend is asked when it opens a window, the same for the first window and the secondary ones. A /// frontend honours the settings that its toolkit has (a field it has no use for is ignored) and its own startup deadline. struct ViewOptions { /// The initial document must finish loading within this interval; no bridge connection is required. std::chrono::milliseconds startupTimeout{30000}; - /// WebView2 only: the profile folder; empty keeps the default. - std::filesystem::path userDataFolder{}; ContentPolicy contentPolicy{}; WindowOptions window{}; /// WKWebView and WebView2: keep the native window hidden and avoid activating the application. @@ -44,6 +53,9 @@ struct ViewOptions { /// 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{}; + /// WebView2 only: the profile folder; empty keeps the default. Last, so the members before it keep the order that + /// WKWebViewOptions had. + std::filesystem::path userDataFolder{}; /// A secondary window is built from the first one's: its visibility, its startup deadline and its test injections. void inherit(const ViewOptions& first) { diff --git a/include/webfront/frontend/WebKitGTK.hpp b/include/webfront/frontend/WebKitGTK.hpp index 690a495b..25cec08c 100644 --- a/include/webfront/frontend/WebKitGTK.hpp +++ b/include/webfront/frontend/WebKitGTK.hpp @@ -918,7 +918,7 @@ struct Session : FailureState { rethrowIfFailed(); if (closed) return; - navigationTimer = a.timeoutAdd(static_cast(startupTimeout.count()), onNavigationTimeout, this); + navigationTimer = a.timeoutAdd(frontend::detail::timerMilliseconds(startupTimeout, "WebKitGTKFrontend"), onNavigationTimeout, this); presentTimer = a.timeoutAdd(frontend::detail::Presentation::maximumDelayMs, onPresentTimeout, this); presentHidden(); trace("load started"); @@ -930,7 +930,7 @@ struct Session : FailureState { /// Starts the load of a secondary window and returns: the loop of the application's own window drives it. void start(const std::string& url) { - navigationTimer = a.timeoutAdd(static_cast(startupTimeout.count()), onNavigationTimeout, this); + navigationTimer = a.timeoutAdd(frontend::detail::timerMilliseconds(startupTimeout, "WebKitGTKFrontend"), onNavigationTimeout, this); presentTimer = a.timeoutAdd(frontend::detail::Presentation::maximumDelayMs, onPresentTimeout, this); presentHidden(); a.load(view, url.c_str()); @@ -1032,6 +1032,7 @@ inline void open(std::string_view address, std::string_view port, std::string_vi initialize(mode); // One window per process: a second open() on the main thread is refused before it creates a window. frontend::detail::InterfaceSession::refuseSecond(uiExecutorHostOf(), WindowHooks::name); + (void)frontend::detail::timerMilliseconds(options.startupTimeout, WindowHooks::name); // refused before a window exists Session session(webfront::detail::BoundContentPolicy{applicationUrl(address, port, "", options.launch.origin), options.contentPolicy}, options.window); session.launch = options.launch; session.startupTimeout = options.startupTimeout; diff --git a/test/unit/WindowRegistryTests.cpp b/test/unit/WindowRegistryTests.cpp index 8f60be0f..95898fac 100644 --- a/test/unit/WindowRegistryTests.cpp +++ b/test/unit/WindowRegistryTests.cpp @@ -430,3 +430,14 @@ const Scenario windowPresentation{"A window is made opaque once, by the first fr }); }); }}; + +const Scenario startupTimeoutRange{"A startup deadline a timer cannot hold is refused", {"window-registry"}, [] { + using std::chrono::milliseconds; + then("a positive deadline is kept", [&] { + check(frontend::detail::timerMilliseconds(milliseconds{30000}, "FakeFrontend") == 30000u); + }); + then("zero, negative and oversized deadlines are refused with the frontend's name", [&] { + for (const auto bad : {milliseconds{0}, milliseconds{-1}, milliseconds{-86400000}, milliseconds{4294967296LL}}) + checkThrows([&] { (void)frontend::detail::timerMilliseconds(bad, "FakeFrontend"); }, contains("FakeFrontend: startupTimeout must be between 1 and")); + }); +}}; From 335bf485ba8d711c292bfc6ed469d317b10ee218 Mon Sep 17 00:00:00 2001 From: Ambroise Leclerc <6860842+ambroise-leclerc@users.noreply.github.com> Date: Mon, 23 Nov 2026 21:38:01 +0100 Subject: [PATCH 08/11] Read the startup trace variable at any length and tidy the native frontend headers (#652) - StartupTrace reads WEBFRONT_STARTUP_TRACE with _dupenv_s on MSVC: a value longer than seven characters no longer disables the trace. - The changelog says that a designated initialization of ViewOptions must write userDataFolder last. - Sort the new includes, drop the ones the shared trace made unused, and explain the empty cancelReap() of WKWebView and WebView2. --- docs/CHANGELOG.md | 2 +- include/webfront/frontend/StartupTrace.hpp | 6 ++++-- include/webfront/frontend/WKWebView.hpp | 6 ++---- include/webfront/frontend/WebKitGTK.hpp | 6 ++---- include/webfront/frontend/WebView2.hpp | 4 ++-- 5 files changed, 11 insertions(+), 13 deletions(-) diff --git a/docs/CHANGELOG.md b/docs/CHANGELOG.md index 069950bf..89f45756 100644 --- a/docs/CHANGELOG.md +++ b/docs/CHANGELOG.md @@ -11,7 +11,7 @@ these entries stays in the GitHub releases and the Git history. ## Unreleased ### Breaking -- `WebView2Options` is now `ViewOptions`, shared with WKWebView: `userDataFolder` moves after `launch`, so a positional initialization of `WebView2Options` stops compiling; use designated initializers (#652, `docs/FRONTENDS.md`). +- `WebView2Options` is now `ViewOptions`, shared with WKWebView: `userDataFolder` moves after `launch`, so a positional initialization of `WebView2Options` stops compiling, and so does a designated one that writes `.userDataFolder` before `.contentPolicy`, `.window`, `.visible` or `.launch` (write it last) (#652, `docs/FRONTENDS.md`). - `webfront/automation/Enable.hpp` no longer compiles with `WEBFRONT_DISTRIBUTION`: gate `enableAutomation` out of the distribution build, as the guide already advised (#632, ADR-025). - `webfront-agent` is removed with its JSON CLI, MCP on stdio, `--serve`, `--attach`, `--list` and `--print-mcp-config`, as are `WEBFRONT_BUILD_AUTOMATION`, `WEBFRONT_AUTOMATION_FRONTEND` and `webfront_add_agent()`: connect the MCP client to the URL the application prints (#632, ADR-025, `docs/AUTOMATION.md`). - `AutomationOptions::listen` becomes `directory` and may stay empty (a private directory named after the session is created), `Automation::endpoint()` becomes `directory()`, and the JSON-lines attachment channel (`ChannelServer`, `ChannelClient`) is gone (#632). diff --git a/include/webfront/frontend/StartupTrace.hpp b/include/webfront/frontend/StartupTrace.hpp index 8b8e55e3..e36c9046 100644 --- a/include/webfront/frontend/StartupTrace.hpp +++ b/include/webfront/frontend/StartupTrace.hpp @@ -83,9 +83,11 @@ class StartupTrace { [[nodiscard]] static bool enabled() noexcept { static const bool value = [] { #if defined(_MSC_VER) - char text[8]{}; + char* text = nullptr; // any length: a buffer too small for the value would read as "not set" size_t length = 0; - return getenv_s(&length, text, sizeof text, "WEBFRONT_STARTUP_TRACE") == 0 && length > 1 && std::string_view{text} != "0"; + const bool set = _dupenv_s(&text, &length, "WEBFRONT_STARTUP_TRACE") == 0 && text && *text && std::string_view{text} != "0"; + std::free(text); + return set; #else const auto* text = std::getenv("WEBFRONT_STARTUP_TRACE"); return text && *text && std::string_view{text} != "0"; diff --git a/include/webfront/frontend/WKWebView.hpp b/include/webfront/frontend/WKWebView.hpp index 0e76de12..6e1c4449 100644 --- a/include/webfront/frontend/WKWebView.hpp +++ b/include/webfront/frontend/WKWebView.hpp @@ -8,10 +8,10 @@ #include "EmbeddedFrontend.hpp" #include "../ViewAssociation.hpp" #include "ScriptDialogs.hpp" +#include "StartupTrace.hpp" #include "NativeWindow.hpp" #include "UIExecutor.hpp" #include "Url.hpp" -#include "StartupTrace.hpp" #include "Window.hpp" #include "WindowRegistry.hpp" @@ -59,8 +59,6 @@ using WKWebViewOptions = ViewOptions; #include #include #include - #include - #include #include namespace webfront::frontend::detail::wkwebview { @@ -1156,7 +1154,7 @@ struct WindowHooks { dispatch_async_f( dispatch_get_main_queue(), nullptr, +[](void*) { reapSecondaryWindows(); }); } - void cancelReap() { } + void cancelReap() { } // nothing is pending that clear() must withdraw: a late reap() finds the registry empty void present(Session& session) { // A hidden window stays hidden: ordering it to the front would show it. if (session.options.visible) diff --git a/include/webfront/frontend/WebKitGTK.hpp b/include/webfront/frontend/WebKitGTK.hpp index 25cec08c..57a17a76 100644 --- a/include/webfront/frontend/WebKitGTK.hpp +++ b/include/webfront/frontend/WebKitGTK.hpp @@ -6,14 +6,14 @@ #include "Capture.hpp" #include "CloseRequest.hpp" #include "DefaultBrowser.hpp" -#include "EmbeddedFrontend.hpp" #include "Downloads.hpp" +#include "EmbeddedFrontend.hpp" #include "NativeWindow.hpp" #include "ProfileLease.hpp" #include "ScriptDialogs.hpp" +#include "StartupTrace.hpp" #include "UIExecutor.hpp" #include "Url.hpp" -#include "StartupTrace.hpp" #include "Window.hpp" #include "WindowRegistry.hpp" #include "../ViewAssociation.hpp" @@ -21,8 +21,6 @@ #include #include -#include -#include #include #include #include diff --git a/include/webfront/frontend/WebView2.hpp b/include/webfront/frontend/WebView2.hpp index 19d9afcc..1a88ffb1 100644 --- a/include/webfront/frontend/WebView2.hpp +++ b/include/webfront/frontend/WebView2.hpp @@ -9,10 +9,10 @@ #include "EmbeddedFrontend.hpp" #include "../ViewAssociation.hpp" #include "ScriptDialogs.hpp" +#include "StartupTrace.hpp" #include "NativeWindow.hpp" #include "UIExecutor.hpp" #include "Url.hpp" -#include "StartupTrace.hpp" #include "Window.hpp" #include "WindowRegistry.hpp" @@ -1001,7 +1001,7 @@ struct WindowHooks { if (windows.primary && windows.primary->window) PostMessageW(windows.primary->window, reapMessage, 0, 0); } - void cancelReap() { } + void cancelReap() { } // nothing is pending that clear() must withdraw: a late reap() finds the registry empty void present(Session& session) { // A hidden window stays hidden and does not take the focus. if (const auto handle = session.window; handle && IsWindowVisible(handle)) { From a34f1cb4960d8105ae853e069ec3fc237d5f784f Mon Sep 17 00:00:00 2001 From: Ambroise Leclerc <6860842+ambroise-leclerc@users.noreply.github.com> Date: Mon, 23 Nov 2026 22:01:09 +0100 Subject: [PATCH 09/11] Answer the review of the shared native windows (#652) - A secondary window starts from default options: the application's options provider is no longer asked for it. - open() on the registry tells it was refused while the session ends, with a word on standard error. - InterfaceSession withdraws a window only when its own publish succeeded. - The startup trace variable is read at each milestone again, from the Win32 environment block on Windows. - The beforeunload limitation of WKWebView and what startupTimeout bounds in each engine are documented on ViewOptions. - Tests: a non-default policy reaches the engine, the provider is not asked for a secondary window. --- .../webfront/frontend/EmbeddedFrontend.hpp | 20 +++++- include/webfront/frontend/StartupTrace.hpp | 19 +++--- include/webfront/frontend/WindowRegistry.hpp | 20 ++++-- test/unit/WindowRegistryTests.cpp | 67 +++++++++++++++++-- 4 files changed, 99 insertions(+), 27 deletions(-) diff --git a/include/webfront/frontend/EmbeddedFrontend.hpp b/include/webfront/frontend/EmbeddedFrontend.hpp index 5883c60b..e8818944 100644 --- a/include/webfront/frontend/EmbeddedFrontend.hpp +++ b/include/webfront/frontend/EmbeddedFrontend.hpp @@ -36,7 +36,9 @@ namespace detail { /// What an embedded frontend is asked when it opens a window, the same for the first window and the secondary ones. A /// frontend honours the settings that its toolkit has (a field it has no use for is ignored) and its own startup deadline. struct ViewOptions { - /// The initial document must finish loading within this interval; no bridge connection is required. + /// The initial navigation must succeed within this interval; no bridge connection is required. What ends the wait + /// depends on the engine: WKWebView, the end of the load; WebKitGTK, the commit of the navigation (resources still + /// loading are not waited for); WebView2, the creation of its browser, before the navigation starts. std::chrono::milliseconds startupTimeout{30000}; ContentPolicy contentPolicy{}; WindowOptions window{}; @@ -48,7 +50,9 @@ struct ViewOptions { std::filesystem::path downloadDirectory{}; /// Test injection: called with the destination of each finished download. std::function downloadFinished{}; - /// Test injection: answers `alert`, `confirm` and `prompt` without a box (WKWebView, WebKitGTK, WebView2). + /// Test injection: answers `alert`, `confirm` and `prompt` without a box (WKWebView, WebKitGTK, WebView2). WKWebView + /// does not handle `beforeunload` (its public WKUIDelegate has no method for it): a page that relies on it can lose + /// unsaved changes on navigation or close, and WebFront does not confirm it. ScriptDialogHandler answerScriptDialog{}; /// 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. @@ -124,7 +128,7 @@ struct EmbeddedFrontend { if constexpr (!Derived::compiled) { unavailable(); } else { - auto options = optionsOf(policy, &window, &launch); + auto options = secondaryOptionsOf(policy, window, launch); try { onUIThread([&] { Derived::openSecondaryNative(address, port, page, options); @@ -193,6 +197,16 @@ struct EmbeddedFrontend { options.launch = *launch; return options; } + // A secondary window takes the first window's settings (ViewOptions::inherit, or the engine's own session), so it starts + // from default options: the application's provider is not asked, and its failure cannot stop a window that is only brought to the front. + template + static typename D::Options secondaryOptionsOf(const ContentPolicy& policy, const WindowOptions& window, const ViewLaunch& launch) { + typename D::Options options{}; + options.contentPolicy = policy; + options.window = window; + options.launch = launch; + return options; + } template static void onUIThread(Function&& function) { if constexpr (requires { requires Derived::waitsForFirstWindow; }) diff --git a/include/webfront/frontend/StartupTrace.hpp b/include/webfront/frontend/StartupTrace.hpp index e36c9046..91ce449e 100644 --- a/include/webfront/frontend/StartupTrace.hpp +++ b/include/webfront/frontend/StartupTrace.hpp @@ -80,20 +80,17 @@ namespace webfront::frontend::detail { class StartupTrace { std::chrono::steady_clock::time_point created = std::chrono::steady_clock::now(); + /// Read at each milestone, not once: an application may set the variable between two openings. On Windows the process + /// environment block is read, which SetEnvironmentVariableW changes and the C runtime's copy does not follow. [[nodiscard]] static bool enabled() noexcept { - static const bool value = [] { -#if defined(_MSC_VER) - char* text = nullptr; // any length: a buffer too small for the value would read as "not set" - size_t length = 0; - const bool set = _dupenv_s(&text, &length, "WEBFRONT_STARTUP_TRACE") == 0 && text && *text && std::string_view{text} != "0"; - std::free(text); - return set; +#if defined(_WIN32) + wchar_t text[2] = {}; + const DWORD length = GetEnvironmentVariableW(L"WEBFRONT_STARTUP_TRACE", text, 2); // a longer value returns its size: not "0" + return length > 0 && !(length == 1 && text[0] == L'0'); #else - const auto* text = std::getenv("WEBFRONT_STARTUP_TRACE"); - return text && *text && std::string_view{text} != "0"; + const auto* text = std::getenv("WEBFRONT_STARTUP_TRACE"); + return text && *text && std::string_view{text} != "0"; #endif - }(); - return value; } public: diff --git a/include/webfront/frontend/WindowRegistry.hpp b/include/webfront/frontend/WindowRegistry.hpp index ee347fee..f1308994 100644 --- a/include/webfront/frontend/WindowRegistry.hpp +++ b/include/webfront/frontend/WindowRegistry.hpp @@ -92,17 +92,21 @@ class WindowRegistry { * `create(Session& primary)` builds the window and returns a `std::shared_ptr`; `start(Session&, Session& primary)` * starts its load and returns. Either may throw (a window whose creation or start throws is not registered, and its page * can be opened again). Throws std::logic_error when the first window is not open: one that closed still runs its loop - * until the pass ends, and a window built now would be destroyed with it. + * until the pass ends, and a window built now would be destroyed with it. False, with a word on standard error, when + * the session is ending (clear() runs): the request comes from the teardown of a window, which an exception would + * turn into the end of the process, so it is refused without one. */ template - void open(const std::string& page, Create&& create, Start&& start) { - if (clearing) - return; // asked by the teardown of a window of a session that is ending: an exception would end the process + bool open(const std::string& page, Create&& create, Start&& start) { + if (clearing) { + std::fprintf(stderr, "%.*s: the window of '%s' was not opened: the session is ending\n", static_cast(Hooks::name.size()), Hooks::name.data(), page.c_str()); + return false; + } if (!primary || primary->closed) throw std::logic_error(std::string(Hooks::name) + ": no window of the application is open; show() it before opening another"); if (const auto found = secondary.find(page); found != secondary.end()) { hooks.present(*found->second); - return; + return true; } std::shared_ptr session = create(*primary); session->closedHook = [this, page] { @@ -117,6 +121,7 @@ class WindowRegistry { throw std::runtime_error(std::string(Hooks::name) + ": the secondary window of '" + page + "' closed while it started"); } secondary[page] = std::move(session); + return true; } /// On the interface thread: asks the secondary window showing `page` to close, as its user would. False when there is none. @@ -152,11 +157,14 @@ class InterfaceSession { InterfaceSession(UIExecutorHost& uiHost, NativeWindowHost& nativeHost, Registry& registry, typename std::remove_pointer_t& primary, std::function wake, NativeWindowHandle handle) : host(uiHost), windowHost(nativeHost), windows(registry) { host.attach(std::move(wake)); + bool published = false; try { windowHost.publish(std::move(handle)); + published = true; windows.primary = &primary; } catch (...) { - windowHost.retract(); + if (published) // only what this constructor did: a publish that threw left another window's handle in place + windowHost.retract(); host.close(); throw; } diff --git a/test/unit/WindowRegistryTests.cpp b/test/unit/WindowRegistryTests.cpp index 95898fac..f423d832 100644 --- a/test/unit/WindowRegistryTests.cpp +++ b/test/unit/WindowRegistryTests.cpp @@ -86,8 +86,8 @@ struct FakeHooks { using Registry = frontend::detail::WindowRegistry; -void openPage(Registry& windows, const std::string& page, bool closeOnStart = false, std::exception_ptr failOnStart = {}) { - windows.open( +bool openPage(Registry& windows, const std::string& page, bool closeOnStart = false, std::exception_ptr failOnStart = {}) { + return windows.open( page, [&](FakeSession&) { auto session = std::make_shared(page); @@ -193,12 +193,14 @@ const Scenario secondaryWindowRegistry{"The registry of the secondary windows is when("a window opens a page while the others are destroyed", [&] { openPage(windows, "a.html"); + bool lateOpened = true; FakeSession::destroyProbe = [&] { - openPage(windows, "late.html"); // a destructor cannot be refused by an exception: it is ignored + lateOpened = openPage(windows, "late.html"); // a destructor cannot be refused by an exception: it is told false }; windows.clear(); FakeSession::destroyProbe = nullptr; - then("no window outlives the session", [&] { + then("no window outlives the session, and the request is told it was refused", [&] { + check(!lateOpened); check(windows.secondary.empty()); check(!happened("create late.html")); }); @@ -311,10 +313,13 @@ struct FakeFrontend : EmbeddedFrontend { static inline std::vector opened; static void openNative(std::string_view address, std::string_view port, std::string_view file, const Options& options) { opened.push_back(std::string(address) + ":" + std::string(port) + "/" + std::string(file) + (options.window.title.empty() ? "" : " " + options.window.title) + - (options.launch.secret.empty() ? "" : " launched")); + (options.launch.secret.empty() ? "" : " launched") + (options.contentPolicy.devToolsEnabled ? "" : " nodevtools")); } static void closeNative(const NativeWindowHandle&) { } - static void openSecondaryNative(std::string_view, std::string_view, std::string_view, const Options&) { } + static inline std::vector openedSecondary; + static void openSecondaryNative(std::string_view, std::string_view, std::string_view page, const Options& options) { + openedSecondary.push_back(std::string(page) + (options.contentPolicy.devToolsEnabled ? "" : " nodevtools") + " " + options.window.title + " " + options.launch.secret); + } static bool closeSecondaryNative(std::string_view) { return true; } }; @@ -335,6 +340,27 @@ struct ConfiguredFrontend : EmbeddedFrontend { static void closeNative(const NativeWindowHandle&) { } }; +// A configured frontend with secondary windows (WebView2FrontendWithOptions): a secondary window does not ask the provider. +struct ConfiguredSecondaryFrontend : EmbeddedFrontend { + static constexpr bool secondaryWindows = true; + static constexpr bool compiled = true; + static constexpr std::string_view name = "ConfiguredSecondaryFrontend"; + using Host = ConfiguredSecondaryFrontend; + using Options = ViewOptions; + static inline int providerCalls = 0; + static inline std::vector openedSecondary; + static ViewOptions defaultOptions() { + ++providerCalls; + throw std::runtime_error("the provider failed"); + } + static void openNative(std::string_view, std::string_view, std::string_view, const Options&) { } + static void closeNative(const NativeWindowHandle&) { } + static void openSecondaryNative(std::string_view, std::string_view, std::string_view page, const Options& options) { + openedSecondary.push_back(std::string(page) + " " + options.window.title + " " + options.launch.secret); + } + static bool closeSecondaryNative(std::string_view) { return true; } +}; + struct AbsentFrontend : EmbeddedFrontend { static constexpr bool secondaryWindows = true; static constexpr bool compiled = false; @@ -374,9 +400,11 @@ const Scenario embeddedFrontendFacade{"The facade of the embedded frontends give FakeFrontend::open("1.2.3.4", "9003", "d.html", ContentPolicy{}, WindowOptions{.title = "T"}); FakeFrontend::open("1.2.3.4", "9004", "e.html", ContentPolicy{}, WindowOptions{}, ViewLaunch{"secret", "origin"}); FakeFrontend::open("1.2.3.4", "9005", "f.html", ViewOptions{.window = {.title = "O"}}); + FakeFrontend::open("1.2.3.4", "9006", "g.html", ContentPolicy{.devToolsEnabled = false}); then("each reaches the toolkit with its settings", [&] { check(FakeFrontend::opened == std::vector{"127.0.0.1:9000/a.html", "1.2.3.4:9001/b.html", "1.2.3.4:9002/c.html", - "1.2.3.4:9003/d.html T", "1.2.3.4:9004/e.html launched", "1.2.3.4:9005/f.html O"}); + "1.2.3.4:9003/d.html T", "1.2.3.4:9004/e.html launched", "1.2.3.4:9005/f.html O", + "1.2.3.4:9006/g.html nodevtools"}); }); }); when("no window is open", [&] { @@ -397,6 +425,31 @@ const Scenario embeddedFrontendFacade{"The facade of the embedded frontends give check(ConfiguredFrontend::opened == std::vector{"a.html configured configured-secret", "b.html own configured-secret", "c.html own own-secret"}); }); }); + given("a configured frontend with a window open", [&] { + auto& host = uiExecutorHostOf(); + host.attach([] {}); // this thread is the interface thread: the calls run on it + ConfiguredSecondaryFrontend::providerCalls = 0; + ConfiguredSecondaryFrontend::openedSecondary.clear(); + FakeFrontend::openedSecondary.clear(); + when("a secondary window is opened", [&] { + ConfiguredSecondaryFrontend::openSecondaryWindow("127.0.0.1", "9000", "a.html", ContentPolicy{}, WindowOptions{.title = "second"}, ViewLaunch{"secret", ""}); + then("the provider is not asked, and the call's settings arrive", [&] { + check(ConfiguredSecondaryFrontend::providerCalls == 0); + check(ConfiguredSecondaryFrontend::openedSecondary == std::vector{"a.html second secret"}); + }); + }); + host.close(); + }); + given("a frontend with a window open and a policy of its own", [&] { + auto& host = uiExecutorHostOf(); + host.attach([] {}); + FakeFrontend::openedSecondary.clear(); + FakeFrontend::openSecondaryWindow("127.0.0.1", "9000", "a.html", ContentPolicy{.devToolsEnabled = false}, WindowOptions{.title = "T"}, ViewLaunch{"s", ""}); + then("the secondary window receives the policy", [&] { + check(FakeFrontend::openedSecondary == std::vector{"a.html nodevtools T s"}); + }); + host.close(); + }); given("a frontend whose engine is not part of the build", [&] { then("every entry point explains what to enable", [&] { const auto message = equals("AbsentFrontend is unavailable. Configure on Nowhere with -DNOWHERE=ON"); From a0cebc9d8be0e4ff8f86e963c29c06ae2cddb727 Mon Sep 17 00:00:00 2001 From: Ambroise Leclerc <6860842+ambroise-leclerc@users.noreply.github.com> Date: Mon, 23 Nov 2026 22:59:49 +0100 Subject: [PATCH 10/11] Bring an open secondary window forward even when the first one is closing; check the startup deadline for every frontend; start the test driver from the configured options (#652) --- include/webfront/frontend/EmbeddedFrontend.hpp | 13 +++++++++---- include/webfront/frontend/WindowRegistry.hpp | 6 +++--- test/driver/TestFrontend.hpp | 18 +++++++++++------- test/unit/WindowRegistryTests.cpp | 18 ++++++++++++++++++ 4 files changed, 41 insertions(+), 14 deletions(-) diff --git a/include/webfront/frontend/EmbeddedFrontend.hpp b/include/webfront/frontend/EmbeddedFrontend.hpp index e8818944..b07cfda6 100644 --- a/include/webfront/frontend/EmbeddedFrontend.hpp +++ b/include/webfront/frontend/EmbeddedFrontend.hpp @@ -78,7 +78,7 @@ struct ViewOptions { * * - `using Host = ...`: the type that names the process-wide hosts (UIExecutor.hpp, NativeWindow.hpp); * - `static constexpr bool compiled`: the engine is part of this build; `static constexpr std::string_view name` and - * `unavailable` (what to configure) make the message of a frontend that is not; + * `enable` (what to configure) make the message of a frontend that is not; * - `using Options`: the frontend's options (`contentPolicy`, `window` and `launch` at least; ViewOptions has them), and an * optional `static Options defaultOptions()` for the ones a call starts from; * - `static void openNative(address, port, file, const Options&)` and `closeNative(const NativeWindowHandle&)` (on the @@ -162,9 +162,12 @@ struct EmbeddedFrontend { } template // dependent: the options type is only needed once the frontend is complete static void open(std::string_view address, std::string_view port, std::string_view file, const typename D::Options& options = startingOptions()) { - if constexpr (Derived::compiled) + if constexpr (Derived::compiled) { + // One rule for every frontend: a deadline no toolkit timer can hold is refused before any window exists. + if constexpr (requires { options.startupTimeout; }) + (void)detail::timerMilliseconds(options.startupTimeout, Derived::name); Derived::openNative(address, port, file, options); - else + } else unavailable(); } static void open(std::string_view address, std::string_view port, std::string_view file, const ContentPolicy& policy) { @@ -178,7 +181,7 @@ struct EmbeddedFrontend { open(address, port, file, optionsOf(policy, &window, &launch)); } -private: + /// The options a call starts from: the frontend's configured ones, or the default ones. template static typename D::Options startingOptions() { if constexpr (requires { Derived::defaultOptions(); }) @@ -186,6 +189,8 @@ struct EmbeddedFrontend { else return typename Derived::Options{}; } + +private: template static typename D::Options optionsOf(const ContentPolicy& policy, const WindowOptions* window = nullptr, const ViewLaunch* launch = nullptr) { // The settings of the arguments the caller gave replace the configured ones; the others stay as configured. diff --git a/include/webfront/frontend/WindowRegistry.hpp b/include/webfront/frontend/WindowRegistry.hpp index f1308994..be526ff9 100644 --- a/include/webfront/frontend/WindowRegistry.hpp +++ b/include/webfront/frontend/WindowRegistry.hpp @@ -91,7 +91,7 @@ class WindowRegistry { * * `create(Session& primary)` builds the window and returns a `std::shared_ptr`; `start(Session&, Session& primary)` * starts its load and returns. Either may throw (a window whose creation or start throws is not registered, and its page - * can be opened again). Throws std::logic_error when the first window is not open: one that closed still runs its loop + * can be opened again). A page already showing a window is brought to the front. Throws std::logic_error when a new window is needed and the first window is not open: one that closed still runs its loop * until the pass ends, and a window built now would be destroyed with it. False, with a word on standard error, when * the session is ending (clear() runs): the request comes from the teardown of a window, which an exception would * turn into the end of the process, so it is refused without one. @@ -102,12 +102,12 @@ class WindowRegistry { std::fprintf(stderr, "%.*s: the window of '%s' was not opened: the session is ending\n", static_cast(Hooks::name.size()), Hooks::name.data(), page.c_str()); return false; } - if (!primary || primary->closed) - throw std::logic_error(std::string(Hooks::name) + ": no window of the application is open; show() it before opening another"); if (const auto found = secondary.find(page); found != secondary.end()) { hooks.present(*found->second); return true; } + if (!primary || primary->closed) + throw std::logic_error(std::string(Hooks::name) + ": no window of the application is open; show() it before opening another"); std::shared_ptr session = create(*primary); session->closedHook = [this, page] { retire(page); diff --git a/test/driver/TestFrontend.hpp b/test/driver/TestFrontend.hpp index b52435d3..23f6dfd0 100644 --- a/test/driver/TestFrontend.hpp +++ b/test/driver/TestFrontend.hpp @@ -27,13 +27,17 @@ struct TestFrontend : Frontend { const ViewLaunch& launch) { // Rendering stays visible where the frontend can hide its window; the Linux engines use one Xvfb display around a // complete suite and their native windows stay real. - typename Frontend::Options options{}; - options.contentPolicy = policy; - options.window = window; - options.launch = launch; - if constexpr (requires { options.visible = visibleWindows; }) - options.visible = visibleWindows; - Frontend::open(address, port, page, options); + if constexpr (requires { Frontend::startingOptions(); }) { + auto options = Frontend::startingOptions(); // the provider's settings, then the ones of the call + options.contentPolicy = policy; + options.window = window; + options.launch = launch; + if constexpr (requires { options.visible = visibleWindows; }) + options.visible = visibleWindows; + Frontend::open(address, port, page, options); + } else { + Frontend::open(address, port, page, policy, window, launch); + } } }; } // namespace webfront::testdriver diff --git a/test/unit/WindowRegistryTests.cpp b/test/unit/WindowRegistryTests.cpp index f423d832..355d5433 100644 --- a/test/unit/WindowRegistryTests.cpp +++ b/test/unit/WindowRegistryTests.cpp @@ -191,6 +191,17 @@ const Scenario secondaryWindowRegistry{"The registry of the secondary windows is }); }); + when("the first window closes while a secondary one still shows the page", [&] { + openPage(windows, "a.html"); + events.clear(); + first.closed = true; + then("asking for that page brings its window to the front instead of failing", [&] { + openPage(windows, "a.html"); + check(!happened("create a.html")); + check(windows.secondary.size() == 1); + }); + }); + when("a window opens a page while the others are destroyed", [&] { openPage(windows, "a.html"); bool lateOpened = true; @@ -489,6 +500,13 @@ const Scenario startupTimeoutRange{"A startup deadline a timer cannot hold is re then("a positive deadline is kept", [&] { check(frontend::detail::timerMilliseconds(milliseconds{30000}, "FakeFrontend") == 30000u); }); + then("a facade refuses them before any window is opened", [&] { + FakeFrontend::opened.clear(); + ViewOptions options; + options.startupTimeout = milliseconds{-1}; + checkThrows([&] { FakeFrontend::open("127.0.0.1", "9000", "a.html", options); }, contains("FakeFrontend: startupTimeout must be between 1 and")); + check(FakeFrontend::opened.empty()); + }); then("zero, negative and oversized deadlines are refused with the frontend's name", [&] { for (const auto bad : {milliseconds{0}, milliseconds{-1}, milliseconds{-86400000}, milliseconds{4294967296LL}}) checkThrows([&] { (void)frontend::detail::timerMilliseconds(bad, "FakeFrontend"); }, contains("FakeFrontend: startupTimeout must be between 1 and")); From 5b69690f40c27ddd0e41fd1e6768cc0d0fc435dd Mon Sep 17 00:00:00 2001 From: Ambroise Leclerc <6860842+ambroise-leclerc@users.noreply.github.com> Date: Mon, 23 Nov 2026 23:30:05 +0100 Subject: [PATCH 11/11] Word the startup deadline error so the WKWebView lifecycle case still matches it; drop the duplicate check (#652) --- include/webfront/frontend/EmbeddedFrontend.hpp | 2 +- include/webfront/frontend/WKWebView.hpp | 2 -- test/unit/WindowRegistryTests.cpp | 4 ++-- 3 files changed, 3 insertions(+), 5 deletions(-) diff --git a/include/webfront/frontend/EmbeddedFrontend.hpp b/include/webfront/frontend/EmbeddedFrontend.hpp index b07cfda6..b7885256 100644 --- a/include/webfront/frontend/EmbeddedFrontend.hpp +++ b/include/webfront/frontend/EmbeddedFrontend.hpp @@ -28,7 +28,7 @@ namespace detail { /// otherwise wrap around when it becomes the unsigned argument of the timer. [[nodiscard]] inline unsigned timerMilliseconds(std::chrono::milliseconds timeout, std::string_view frontend) { if (timeout.count() < 1 || timeout.count() > std::numeric_limits::max()) - throw std::invalid_argument(std::string(frontend) + ": startupTimeout must be between 1 and " + std::to_string(std::numeric_limits::max()) + " milliseconds"); + throw std::invalid_argument(std::string(frontend) + ": startupTimeout must be positive and at most " + std::to_string(std::numeric_limits::max()) + " milliseconds"); return static_cast(timeout.count()); } } // namespace detail diff --git a/include/webfront/frontend/WKWebView.hpp b/include/webfront/frontend/WKWebView.hpp index 6e1c4449..5d781b5a 100644 --- a/include/webfront/frontend/WKWebView.hpp +++ b/include/webfront/frontend/WKWebView.hpp @@ -285,8 +285,6 @@ inline CaptureProvider captureProvider(std::shared_ptr target) { 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; diff --git a/test/unit/WindowRegistryTests.cpp b/test/unit/WindowRegistryTests.cpp index 355d5433..8bcbc051 100644 --- a/test/unit/WindowRegistryTests.cpp +++ b/test/unit/WindowRegistryTests.cpp @@ -504,11 +504,11 @@ const Scenario startupTimeoutRange{"A startup deadline a timer cannot hold is re FakeFrontend::opened.clear(); ViewOptions options; options.startupTimeout = milliseconds{-1}; - checkThrows([&] { FakeFrontend::open("127.0.0.1", "9000", "a.html", options); }, contains("FakeFrontend: startupTimeout must be between 1 and")); + checkThrows([&] { FakeFrontend::open("127.0.0.1", "9000", "a.html", options); }, contains("FakeFrontend: startupTimeout must be positive and at most")); check(FakeFrontend::opened.empty()); }); then("zero, negative and oversized deadlines are refused with the frontend's name", [&] { for (const auto bad : {milliseconds{0}, milliseconds{-1}, milliseconds{-86400000}, milliseconds{4294967296LL}}) - checkThrows([&] { (void)frontend::detail::timerMilliseconds(bad, "FakeFrontend"); }, contains("FakeFrontend: startupTimeout must be between 1 and")); + checkThrows([&] { (void)frontend::detail::timerMilliseconds(bad, "FakeFrontend"); }, contains("FakeFrontend: startupTimeout must be positive and at most")); }); }};