diff --git a/docs/CHANGELOG.md b/docs/CHANGELOG.md index 41744f64..89f45756 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, 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). @@ -50,6 +51,9 @@ 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), 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`). - 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..74b4f650 100644 --- a/docs/FRONTENDS.md +++ b/docs/FRONTENDS.md @@ -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`, 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 and test injections, as WebView2 does. diff --git a/include/webfront/frontend/EmbeddedFrontend.hpp b/include/webfront/frontend/EmbeddedFrontend.hpp new file mode 100644 index 00000000..b7885256 --- /dev/null +++ b/include/webfront/frontend/EmbeddedFrontend.hpp @@ -0,0 +1,227 @@ +// 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 "ScriptDialogs.hpp" +#include "UIExecutor.hpp" +#include "Window.hpp" + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +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 positive and at most " + 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 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{}; + /// 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). 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. + 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) { + visible = first.visible; + startupTimeout = first.startupTimeout; + chooseFiles = first.chooseFiles; + downloadDirectory = first.downloadDirectory; + downloadFinished = first.downloadFinished; + answerScriptDialog = first.answerScriptDialog; + } +}; + +/** + * @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 + * `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 + * 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 = secondaryOptionsOf(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) { + // 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 + 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)); + } + + /// 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(); }) + return Derived::defaultOptions(); + 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. + auto options = startingOptions(); + options.contentPolicy = policy; + if (window) + options.window = *window; + if (launch) + 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; }) + 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..91ce449e --- /dev/null +++ b/include/webfront/frontend/StartupTrace.hpp @@ -0,0 +1,128 @@ +// 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(); + + /// 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 { +#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"; +#endif + } + +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 2ce4f4ea..5d781b5a 100644 --- a/include/webfront/frontend/WKWebView.hpp +++ b/include/webfront/frontend/WKWebView.hpp @@ -5,12 +5,15 @@ #include "Capture.hpp" #include "CloseRequest.hpp" #include "Downloads.hpp" +#include "EmbeddedFrontend.hpp" #include "../ViewAssociation.hpp" #include "ScriptDialogs.hpp" +#include "StartupTrace.hpp" #include "NativeWindow.hpp" #include "UIExecutor.hpp" #include "Url.hpp" #include "Window.hpp" +#include "WindowRegistry.hpp" #include #include @@ -28,41 +31,11 @@ namespace webfront::frontend { -namespace detail::wkwebview { -/// The interface thread of the window: attached for the duration of open(), on the main thread. -inline UIExecutorHost& executorHost() { - static UIExecutorHost host; - return host; -} -/// The NSWindow, published to consumers while open() runs (see NativeWindow.hpp). -inline NativeWindowHost& windowHost() { - static NativeWindowHost host{executorHost().executor()}; - return host; -} -} // namespace detail::wkwebview - -/** @brief Per-opening options for the optional macOS frontend. */ -struct WKWebViewOptions { - /** @brief The initial document must finish loading within this interval; no bridge connection is required. */ - std::chrono::milliseconds startupTimeout{30000}; - ContentPolicy contentPolicy{}; - WindowOptions window{}; - /** @brief Keep the native window hidden and avoid activating the application. A WindowServer is still required. */ - bool visible{true}; - /** @brief Test injection: answers `` without a dialog (an empty list cancels). Unset shows the system panel. */ - std::function()> chooseFiles{}; - /** @brief Test injection: a non-empty folder receives downloads without a save panel. */ - std::filesystem::path downloadDirectory{}; - /** @brief Test injection: called with the destination of each finished download. */ - std::function downloadFinished{}; - /** @brief Test injection: answers `alert`, `confirm` and `prompt` without a box. Unset shows an NSAlert sheet on the window. - * `beforeunload` is not handled by WKWebView: the public WKUIDelegate has no method for it, and it does not reach the confirm - * method. A page that relies on it can lose unsaved changes on navigation or close; WebFront does not confirm it. */ - ScriptDialogHandler answerScriptDialog{}; - /** @brief Per-launch proof of this view (ADR-020): given to documents of the application's origin only, at the start of - * the document, for WebFront.js to present in its handshake. Set by WebFront; empty gives the view no association. */ - ViewLaunch launch{}; -}; +struct WKWebViewFrontend; // names the executor's host (UIExecutor.hpp) + + +/** @brief Per-opening options for the optional macOS frontend (the common ViewOptions). */ +using WKWebViewOptions = ViewOptions; } // namespace webfront::frontend @@ -86,8 +59,6 @@ struct WKWebViewOptions { #include #include #include - #include - #include #include namespace webfront::frontend::detail::wkwebview { @@ -314,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; @@ -335,15 +304,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; @@ -351,7 +319,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; @@ -401,34 +369,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"); @@ -437,8 +381,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. @@ -498,8 +441,8 @@ struct Session { try { function(); } catch (...) { - if (!error) - error = std::current_exception(); + if (!failure) + failure = std::current_exception(); close(); } } @@ -678,8 +621,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 { @@ -966,7 +909,7 @@ struct Session { } } }); - decision(error ? 0 : policy); + decision(failure ? 0 : policy); } }; @@ -1198,86 +1141,60 @@ 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() { } // 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) + 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.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"); + 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 +1214,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. - 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}; + // 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 = uiExecutorHostOf(); + frontend::detail::InterfaceSession interfaceSession( + host, + nativeWindowHostOf(), + 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(); } @@ -1337,99 +1242,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 094700b6..57a17a76 100644 --- a/include/webfront/frontend/WebKitGTK.hpp +++ b/include/webfront/frontend/WebKitGTK.hpp @@ -7,19 +7,20 @@ #include "CloseRequest.hpp" #include "DefaultBrowser.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 "Window.hpp" +#include "WindowRegistry.hpp" #include "../ViewAssociation.hpp" #include "WebKitGTKPolicy.hpp" #include #include -#include -#include #include #include #include @@ -341,6 +342,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; @@ -370,11 +372,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 @@ -386,8 +386,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))) {} @@ -546,40 +544,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); @@ -588,20 +552,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); @@ -898,7 +859,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; } @@ -955,8 +916,8 @@ struct Session : FailureState { rethrowIfFailed(); if (closed) return; - navigationTimer = a.timeoutAdd(30'000, onNavigationTimeout, this); - presentTimer = a.timeoutAdd(maximumPresentDelayMs, onPresentTimeout, this); + navigationTimer = a.timeoutAdd(frontend::detail::timerMilliseconds(startupTimeout, "WebKitGTKFrontend"), onNavigationTimeout, this); + presentTimer = a.timeoutAdd(frontend::detail::Presentation::maximumDelayMs, onPresentTimeout, this); presentHidden(); trace("load started"); a.load(view, url.c_str()); @@ -967,8 +928,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(frontend::detail::timerMilliseconds(startupTimeout, "WebKitGTKFrontend"), onNavigationTimeout, this); + presentTimer = a.timeoutAdd(frontend::detail::Presentation::maximumDelayMs, onPresentTimeout, this); presentHidden(); a.load(view, url.c_str()); } @@ -979,140 +940,127 @@ struct OpenOptions { WindowOptions window{}; 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 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; +/// 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}; +} - 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); +/// 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; + + 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->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; + }, + [&](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); + (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.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); - // 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)); } @@ -1123,107 +1071,40 @@ 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; #else - return false; + static constexpr bool compiled = false; #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 Options = ViewOptions; + 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, detail::webkitgtk::openOptionsOf(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), detail::webkitgtk::openOptionsOf(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 22708607..1a88ffb1 100644 --- a/include/webfront/frontend/WebView2.hpp +++ b/include/webfront/frontend/WebView2.hpp @@ -6,12 +6,15 @@ #include "Capture.hpp" #include "CloseRequest.hpp" #include "DefaultBrowser.hpp" +#include "EmbeddedFrontend.hpp" #include "../ViewAssociation.hpp" #include "ScriptDialogs.hpp" +#include "StartupTrace.hpp" #include "NativeWindow.hpp" #include "UIExecutor.hpp" #include "Url.hpp" #include "Window.hpp" +#include "WindowRegistry.hpp" #include #include @@ -24,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 @@ -504,29 +498,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; @@ -537,9 +512,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); @@ -858,7 +832,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(); } @@ -1017,49 +991,38 @@ 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"; - static Windows& instance() { - static Windows windows; - return windows; + 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 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 (...) { - } + 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)) { + if (IsIconic(handle)) + ShowWindow(handle, SW_RESTORE); + SetForegroundWindow(handle); } - 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(); + 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 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; +}; + +/// 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; } }; @@ -1070,54 +1033,29 @@ 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->answerScriptDialog = primary.answerScriptDialog; + 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 +1065,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); @@ -1140,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); @@ -1147,32 +1085,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(); } @@ -1181,141 +1106,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 + 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); } - - /// The thread of the window's message pump while open() runs (see UIExecutor.hpp). - [[nodiscard]] static UIExecutor uiExecutor() { - return uiExecutorHostOf().executor(); + static void closeNative(const NativeWindowHandle& window) { + PostMessageW(static_cast(window.pointer), WM_CLOSE, 0, 0); } - - /// The HWND of the window, readable on that thread while open() runs (see NativeWindow.hpp). - [[nodiscard]] static NativeWindow nativeWindow() { - return nativeWindowHostOf().window(); + 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); } - - /// 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 bool closeSecondaryNative(std::string_view page) { + return detail::webview2::closeSecondary(std::string(page)); } - - /// 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; + static constexpr bool compiled = false; #endif - } - - static void initialize() { } - - static void open(std::string_view port, std::string_view file) { - open("127.0.0.1", port, file); - } - - 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"); -#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/include/webfront/frontend/WindowRegistry.hpp b/include/webfront/frontend/WindowRegistry.hpp new file mode 100644 index 00000000..be526ff9 --- /dev/null +++ b/include/webfront/frontend/WindowRegistry.hpp @@ -0,0 +1,181 @@ +// 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; + 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) { + 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() { + clearing = true; + hooks.cancelReap(); + auto windows = std::move(secondary); + secondary.clear(); + for (auto& entry : windows) + entry.second->closedHook = nullptr; + finished.clear(); + windows.clear(); + primary = nullptr; + clearing = false; + } + + /** + * @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). 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. + */ + template + 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 (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); + }; + 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); + return true; + } + + /// 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)); + bool published = false; + try { + windowHost.publish(std::move(handle)); + published = true; + windows.primary = &primary; + } catch (...) { + if (published) // only what this constructor did: a publish that threw left another window's handle in place + 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/driver/TestFrontend.hpp b/test/driver/TestFrontend.hpp index 2636a98f..23f6dfd0 100644 --- a/test/driver/TestFrontend.hpp +++ b/test/driver/TestFrontend.hpp @@ -25,22 +25,17 @@ 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; + // 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. + 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; - 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; + if constexpr (requires { options.visible = visibleWindows; }) + options.visible = visibleWindows; 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); } } 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..8bcbc051 --- /dev/null +++ b/test/unit/WindowRegistryTests.cpp @@ -0,0 +1,514 @@ +// 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 +#include +#include +#include + +using namespace webfront::bdd; +using namespace webfront; +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; + 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) + 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 = frontend::detail::WindowRegistry; + +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); + 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"))); + }, contains("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 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; + FakeSession::destroyProbe = [&] { + 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, and the request is told it was refused", [&] { + check(!lateOpened); + 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"); + require(windows.close("a.html")); + 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")); + 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", [&] { + { + 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); + const auto window = published().get(); + require(window.has_value()); + check(window->pointer == &handle); + }); + andWhen("another open() starts", [&] { + then("it is refused", [&] { + checkThrows([&] { frontend::detail::InterfaceSession::refuseSecond(host, "FakeFrontend"); }, + contains("FakeFrontend: open() is already running")); + }); + }); + 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()); + }); + andWhen("a later open() starts", [&] { + then("it is accepted", [&] { + checkNothrow([&] { frontend::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([&] { + frontend::detail::InterfaceSession session(host, nativeWindowHostOf(), windows, first, [] {}, {.kind = NativeWindowKind::gtk, .pointer = &handle, .portalParent = {}}); + }); + check(host.executor().available()); + check(windows.primary == nullptr); + }); + host.close(); + }); +}}; + +namespace window_registry_fakes { // named, not anonymous: the clang warning for unused constants of anonymous types +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") + (options.contentPolicy.devToolsEnabled ? "" : " nodevtools")); + } + static void closeNative(const NativeWindowHandle&) { } + 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; } +}; + +// 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&) { } +}; + +// 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; + 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 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", [&] { + 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"}}); + 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:9006/g.html nodevtools"}); + }); + }); + 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 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 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"); + 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); + }); + }); + }); +}}; + +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("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 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 positive and at most")); + }); +}}; 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&) {