diff --git a/cmake/Frontends.cmake b/cmake/Frontends.cmake index 158a1491..e3be7621 100644 --- a/cmake/Frontends.cmake +++ b/cmake/Frontends.cmake @@ -439,7 +439,7 @@ function(webfront_add_browser_tests target frontend assets_directory lifecycle_t set(lifecycle_command "${XVFB_RUN_EXECUTABLE}" -a ${lifecycle_command}) endif() set(lifecycle_modes no-bridge early-close rejected-ready navigation-failure path-encoding content-policy navigation-allow-list view-association stage-report) - list(APPEND lifecycle_modes ui-executor native-window second-open host-close) + list(APPEND lifecycle_modes ui-executor native-window second-open host-close second-window) # CEF neither supports nor checks a secondary thread: nothing to observe there (docs/HOST_INTEGRATION.md). if(NOT frontend STREQUAL "CEF") list(APPEND lifecycle_modes host-thread) diff --git a/cmake/WKWebViewSupport.cmake b/cmake/WKWebViewSupport.cmake index 7daf2dbc..1ddeb91f 100644 --- a/cmake/WKWebViewSupport.cmake +++ b/cmake/WKWebViewSupport.cmake @@ -18,7 +18,7 @@ function(webfront_add_wkwebview_tests) add_executable(wkwebview_lifecycle "${webtest_source_dir}/WKWebViewLifecycle.cpp" "${webtest_source_dir}/WKWebViewHeaderConsumer.cpp") target_link_libraries(wkwebview_lifecycle PRIVATE WebFront WebFront_warnings WebFront_options) - foreach(mode repeated-show main-thread native-close quit navigation-diagnostic startup-timeout settings translucent-background hidden-scheduling redirect-policy missing-response committed-navigation agent-application download choose-file cancel-choose replaced-download choose-in-blank choose-in-srcdoc close-with-open-panel close-with-save-panel script-dialogs close-with-script-dialog sandboxed-script-dialog load-reveal present-timeout) + foreach(mode repeated-show main-thread native-close quit navigation-diagnostic startup-timeout settings translucent-background hidden-scheduling hidden-secondary redirect-policy missing-response committed-navigation agent-application download choose-file cancel-choose replaced-download choose-in-blank choose-in-srcdoc close-with-open-panel close-with-save-panel script-dialogs close-with-script-dialog sandboxed-script-dialog load-reveal present-timeout) add_test(NAME WKWebViewLifecycle-${mode} COMMAND wkwebview_lifecycle ${mode}) webfront_set_browser_test_properties("WKWebViewLifecycle-${mode}" "${webtest_source_dir}" 90) endforeach() diff --git a/cmake/WebView2Support.cmake b/cmake/WebView2Support.cmake index 2229dbd1..81e76eaf 100644 --- a/cmake/WebView2Support.cmake +++ b/cmake/WebView2Support.cmake @@ -66,7 +66,8 @@ function(webfront_add_webview2_tests) target_link_libraries(webview2_lifecycle PRIVATE WebFront WebFront_warnings WebFront_options) foreach(mode repeated-show native-early-close navigation-diagnostic mta missing-runtime closed-startup-timeout failed-startup-timeout late-navigation-failure runtime-ready - file-choose file-cancel file-download script-dialogs first-frame present-timeout) + file-choose file-cancel file-download script-dialogs first-frame present-timeout + secondary-startup-timeout) add_test(NAME WebView2Lifecycle-${mode} COMMAND webview2_lifecycle ${mode}) webfront_set_browser_test_properties("WebView2Lifecycle-${mode}" "${webtest_source_dir}" 45) endforeach() diff --git a/docs/CHANGELOG.md b/docs/CHANGELOG.md index deb750bc..41744f64 100644 --- a/docs/CHANGELOG.md +++ b/docs/CHANGELOG.md @@ -17,6 +17,7 @@ these entries stays in the GitHub releases and the Git history. - The CEF profile is now `cef_cache/`, not `cef_cache`: an application starts with an empty profile (localStorage, cookies); to keep the data, move the old contents of `cef_cache` into `cef_cache/` once (#617, `docs/HOST_INTEGRATION.md`). ### Added +- Open a second native window with `app.openSecondaryWindow(page, WindowOptions)` (WebKitGTK, WKWebView, WebView2; elsewhere `std::logic_error`, which `app.canShowSecondaryWindow()` predicts): it shares the server, the `cppFunction`s, the `jsFunction` subscribers and the view proof of the first window; `app.requestClose(page)` closes it, and closing the first closes the others (#616, `docs/FRONTENDS.md`). - Write your own scenarios with the public `webfront::bdd` framework: ``, the `WebFront::Bdd` target, the installable `WebFrontBdd` package and `webfront_bdd_discover_tests()` (prefix, properties, shards) replace the internal `test/unit/Bdd.hpp` and `bdd_discover_tests`, and follow WebFront's versions (#647, `docs/BDD.md`). - Configure a stable MCP port and application-supplied Bearer token, or explicitly disable authentication for trusted development (#637, ADR-026, `docs/AUTOMATION.md`). - Connect an MCP client to the application itself: `enableAutomation(app, {.grants = {...}})` serves MCP over Streamable HTTP on a loopback port of its own, prints its URL and writes a private `mcp.json` with the URL and a session Bearer token, so several applications run side by side with no other program (#632, ADR-025, `docs/AUTOMATION.md`). diff --git a/docs/FRONTENDS.md b/docs/FRONTENDS.md index 3d0b556d..dea164fa 100644 --- a/docs/FRONTENDS.md +++ b/docs/FRONTENDS.md @@ -17,6 +17,7 @@ A frontend is a type with: | `static constexpr Action action` | What `BasicWF` does once `open()` returns. | | `static void launch(address, port, page)` (optional) | Opens the interface and returns without waiting for it (the system browser spawns its opener command and does not wait for it to end). `BasicWF::start()` requires it; only a frontend without a window loop offers it (the system browser). A `launch(address, port, page, const ContentPolicy&)` overload is preferred when present; neither receives window options or the view-association proof. | | `static constexpr bool endsOnRequest` (optional) | `false` when `requestClose()` cannot end every session (`NativeOrBrowserFrontend` with the plain system browser as fallback); `webfront::UIThread` then refuses the frontend. | +| `static void openSecondaryWindow(address, port, file, policy, window, launch)` and `static bool closeSecondaryWindow(file)` (optional) | A second window beside the one `open()` runs (#616), callable from any thread while it runs; `invokeOnUIThread()` (UIExecutor.hpp) hops to the interface thread. Opening a page a secondary window already shows brings it to the front (a hidden window stays hidden and does not take the focus); the first window's end closes the others. A window is identified by the `file` string as given, query included. `WebKitGTKFrontend`, `WKWebViewFrontend` and `WebView2Frontend` implement it: `BasicWF::openSecondaryWindow()` throws `std::logic_error` for a frontend without it (CEF, the system browser), never opening a browser. `BasicWF::supportsSecondaryWindow` tells it from the frontend type; an optional `static bool secondaryWindowsAvailable()` tells it at run time, and `BasicWF::canShowSecondaryWindow()` combines both. `NativeOrBrowserFrontendFor` offers the functions only when its native frontend does, and reports them unavailable once it fell back to the system browser. The call waits for the interface thread (it runs at once on that thread): a `cppFunction` callback, which runs on the server's thread, schedules it with `app.uiExecutor()` instead of holding every exchange of the application while it waits. A window that cannot start throws the failure to the caller; one that fails to load later closes and writes the failure to stderr (the call has returned: nothing can throw it). A request that runs after the first window closed is refused with `std::logic_error`. A frontend whose first window cannot host another yet throws `frontend::WindowNotReady` (a `std::logic_error`): `BasicWF` and `invokeOnUIThreadWhenReady()` try again from another thread, and pass it to a caller on the interface thread. WebKitGTK shares the first window's network session (cookies, storage; downloads are tracked by the first window) and ignores `WindowOptions::media`. WKWebView shares its nonpersistent website data store and follows the first window's visibility (a hidden application shows no window and does not take the focus). WebView2 creates the second browser from the first window's environment, so the profile (storage, cookies) and the browser process are shared; it follows the first window's visibility, and has its own startup watchdog, with the first window's delay (the one `WebView2FrontendWithOptions` configured). A call made while the first window's environment is still being created waits for it (bounded by that window's watchdog); on the interface thread it throws `std::logic_error`. Placement is left to the toolkit. | | `static bool requestClose()` (optional) | Asks, from any thread, the session that `open()` runs to end as if the user had closed the window; false when nothing is open. `BasicWF::requestClose()` forwards it only for the application whose `show()` owns that session (its thread is the frontend's published interface thread). A frontend with an executor takes `requestClose(std::optional)` and drops the request, on its interface thread, if another loop runs by then. | | `static constexpr bool requiresMainThread` (optional) | `open()` belongs to the process main thread; `webfront::UIThread` refuses the frontend at compile time. Undeclared means any thread. | @@ -209,6 +210,7 @@ Registry order determines the initial cache default: the first enabled embedded - `path-encoding`: load `encoded path #.html` and verify that its query and fragment survived. - `content-policy`: block a popup and a foreign-origin top-level navigation while keeping the original page alive. - `navigation-allow-list`: permit the same top-level destination through the explicit navigation allow-list. +- `second-window` (#616): a second window shares storage, a `cppFunction` and a pushed `jsFunction` with the first and carries the embedded-view proof; the same page again opens nothing; closing the second leaves the first usable and it can reopen; closing the first closes the second; a window opened as soon as the loop runs, before the first page connected, opens; a request that runs in the pass where the first window closed is refused (WebKitGTK, WKWebView). Frontends without the capability must refuse with `std::logic_error`. - `host-close`: a host thread exchanges with the page while `show()` runs, then `requestClose()` ends the session; a request before and after the window is refused. - `host-thread` (not CEF): `webfront::UIThread` runs the application on a secondary thread where the frontend allows it; elsewhere a window opened on a secondary thread must be refused with the main-thread diagnostic. - `view-association`: the page of the view connects with the secret of the launch and `UI::isEmbeddedView()` is true; a second connection of that page, from the same loopback address and without the secret, is not associated. @@ -272,7 +274,7 @@ The handle carries `kind` (`win32`: `HWND`, `cocoa`: `NSWindow*`, `gtk`: `GtkWin Call it inside an operation scheduled with `app.uiExecutor()` and do not keep the pointer. The window stays published until the loop ends, including after the user closed it, so check the object with the toolkit when that matters (`IsWindow`, `-[NSWindow isVisible]`). -The connection's window is the frontend's single window, reached through the association of ADR-020 rule 3 (`ui.isEmbeddedView()`); the +The connection's window is the frontend's primary window, reached through the association of ADR-020 rule 3 (`ui.isEmbeddedView()`). For a secondary connection, `ui.nativeWindow()` also identifies the primary window; per-secondary-window native handles are not implemented. The system browser never has one. `portalParent` is the `parent_window` of the desktop portals: under WebKitGTK `x11:` when the window is on X11, `wayland:` once `gdk_wayland_toplevel_export_handle` succeeds (either is tried every 100 ms for 5 s after the window is presented, until the surface exists and can be exported; empty until then); it is empty on Windows and macOS. A frontend author calls `nativeWindowHostOf().publish(...)` on the interface diff --git a/docs/PROJECT_STATUS.md b/docs/PROJECT_STATUS.md index e34f248e..40db4fcd 100644 --- a/docs/PROJECT_STATUS.md +++ b/docs/PROJECT_STATUS.md @@ -27,6 +27,9 @@ WebFront is a header-only C++23 HTTP/WebSocket core plus a standalone developer system browser, `app.requestClose()` from another thread, or `webfront::UIThread` where the frontend accepts a secondary thread (WebView2); a host loop cannot share the main thread with an embedded window. See [host integration](HOST_INTEGRATION.md). + A second native window of the same application (`app.openSecondaryWindow()`, #616) exists on WebKitGTK, WKWebView and WebView2; CEF + and the system browser refuse it with `std::logic_error` (`app.canShowSecondaryWindow()` tells it beforehand, also after `NativeOrBrowserFrontend` fell back to the browser), and the position of the window is left to the toolkit. The call waits + for the interface thread: a `cppFunction` callback runs it on `app.uiExecutor()` rather than hold the server's thread. - **Native pseudoterminals (opt-in).** `webfront::Pty` uses a Unix PTY on Linux and macOS or ConPTY on Windows 10 version 1809 and later. The page adapter requires a loopback bind and the application’s own browser origin. See the [PTY guide and standalone example](PTY.md). - **Developer environment.** `NativeApp::bootstrap("developer")` loads the verified, pinned environment selected by `DeveloperReleaseData.hpp`. Its terminal provides `wf init`, `create`, diff --git a/include/webfront/WebFront.hpp b/include/webfront/WebFront.hpp index 4507d476..34ab45c1 100644 --- a/include/webfront/WebFront.hpp +++ b/include/webfront/WebFront.hpp @@ -1136,7 +1136,7 @@ class BasicWF { } } } showing{*this}; - // A frontend that can be asked to close shows one window at a time: a show() that did not take the ownership must + // A frontend that can be asked to close has one primary session at a time: a show() that did not take the ownership must // not open one that nobody could close (the first may end before this one attaches, and the frontend would accept it). if constexpr (frontend::endsOnRequest) { if (!showing.owns) @@ -1302,6 +1302,109 @@ class BasicWF { } } + /// Whether the frontend type can show a second window of the application (see openSecondaryWindow()). A frontend that + /// chooses at run time, as NativeOrBrowserFrontend does, may still refuse it: canShowSecondaryWindow() tells. + static constexpr bool supportsSecondaryWindow = + requires(std::string_view text, const ContentPolicy& policy, const WindowOptions& window, const ViewLaunch& launch) { + Frontend::openSecondaryWindow(text, text, text, policy, window, launch); + { Frontend::uiExecutor() } -> std::same_as; + }; + + /** @brief Whether openSecondaryWindow() can open a window with the frontend chosen at run time, once show() runs: false + * when the frontend type cannot (supportsSecondaryWindow), and for NativeOrBrowserFrontend once it fell back to the system + * browser (the frontend is initialized when the first application is constructed). Use it to offer the action or not. + */ + [[nodiscard]] static bool canShowSecondaryWindow() { + if constexpr (!supportsSecondaryWindow) + return false; + else if constexpr (requires { { Frontend::secondaryWindowsAvailable() } -> std::convertible_to; }) + return Frontend::secondaryWindowsAvailable(); + else + return true; + } + + /** @brief Opens `page` in a second native window beside the one show() runs, served by the same server (#616). + * + * The page reaches the same `cppFunction`s and the same `jsFunction` subscribers as the first one (each window is + * one more connected browser: `onUIStarted` and `subscribeUIStarted` see it), and receives the same view-association + * proof, so it is an embedded view of this application and not an external browser. The title, the size and the + * background come from `options` (an empty background takes the application's). Opening a page that a secondary + * window already shows brings that window to the front instead of opening another. A window is identified by the page + * string exactly as given, query included: "a.html?x=1" and "a.html?x=2" are two windows, and requestClose(page) takes + * the string that opened it. Closing the window of show() closes the others with it; closing a secondary window leaves + * the rest running. A window that cannot start (its view refuses the navigation) throws the failure to the caller; a page + * that fails to load later closes its window and the failure is written to stderr: this call has returned by then, so + * nothing can throw it. The window follows the first one's visibility: a hidden application shows none. + * + * Callable from any thread while show() runs, and it waits for the interface thread: it returns once the window exists + * (on the interface thread itself it runs at once). Called from a `cppFunction` callback, it holds the server's thread + * until then, and with it every exchange of the application, also while a modal dialog keeps the interface thread busy; + * there, run it on the interface thread instead (an operation scheduled with `app.uiExecutor()`), where it does not wait. + * Under WebView2, a call made just after show() started waits until the first window's browser is created; on the + * interface thread that call throws std::logic_error instead. Throws std::logic_error when this application is not + * showing a window (also once the first window has closed), and when the frontend cannot show a second window (today the + * WebKitGTK, WKWebView and WebView2 frontends can; the system browser and CEF refuse; canShowSecondaryWindow() tells it + * beforehand). Window placement is left to the toolkit. + */ + void openSecondaryWindow(std::string_view page, WindowOptions options = {}) { + if constexpr (supportsSecondaryWindow) { + // One read: its parity and the session this call is bound to are those of the same instant. A second read could + // land in a show() that started after the first one ended, and bind the call to a session it was not made for. + const auto epoch = showEpoch.load(); + if (epoch % 2 == 0) + throw std::logic_error("webfront::BasicWF::openSecondaryWindow(): this application is not showing a window; call show() first"); + const auto executor = Frontend::uiExecutor(); + const auto session = executor.session(); + if (!session || session->thread != showThread.load() || showEpoch.load() != epoch) + throw std::logic_error("webfront::BasicWF::openSecondaryWindow(): this application has no active interface session"); + if (options.background.empty()) + options.background = windowOptions.background; + try { + // Called on the interface thread, the frontend cannot wait for its first window to become ready: a caller on + // another thread tries again while it is not (WebView2 just after show() started). + frontend::invokeOnUIThreadWhenReady(executor, [&] { + if (showEpoch.load() != epoch || executor.session() != session) + throw std::logic_error("webfront::BasicWF::openSecondaryWindow(): the interface session has ended"); + Frontend::openSecondaryWindow(httpAddress, httpPort, page, contentPolicy, options, + ViewLaunch{viewSecret, detail::browserOrigin(httpAddress, httpPort, networking::secureTransport)}); + }); + } catch (const frontend::UIExecutorUnavailable&) { + throw std::logic_error("webfront::BasicWF::openSecondaryWindow(): the interface session has ended"); + } + } else { + throw std::logic_error("webfront::BasicWF::openSecondaryWindow(): this frontend cannot show a second window of the application"); + } + } + + /** @brief Asks the secondary window showing `page` to close, as if the user had closed it; callable from any thread. + * Returns false when no such window is open (or the frontend has none). The window of show() ends with + * requestClose(). Unlike requestClose(), it waits for the interface thread, as openSecondaryWindow() does: from a + * `cppFunction` callback, run it on the interface thread instead. + */ + bool requestClose(std::string_view page) { + if constexpr (supportsSecondaryWindow && requires { { Frontend::closeSecondaryWindow(page) } -> std::same_as; }) { + const auto epoch = showEpoch.load(); + if (epoch % 2 == 0) + return false; + const auto executor = Frontend::uiExecutor(); + const auto session = executor.session(); + if (!session || session->thread != showThread.load() || showEpoch.load() != epoch) + return false; + bool closed = false; + try { + frontend::invokeOnUIThread(executor, [&] { + if (showEpoch.load() == epoch && executor.session() == session) + closed = Frontend::closeSecondaryWindow(page); + }); + } catch (const frontend::UIExecutorUnavailable&) { + return false; + } + return closed; + } else { + return false; + } + } + protected: /// For the developer application: its document root is the project that wf builds, which is the development path. void useDeveloperEnvironment() noexcept { diff --git a/include/webfront/frontend/Frontend.hpp b/include/webfront/frontend/Frontend.hpp index 8cedf28c..1a105152 100644 --- a/include/webfront/frontend/Frontend.hpp +++ b/include/webfront/frontend/Frontend.hpp @@ -60,6 +60,9 @@ namespace webfront::frontend { * closed the window; it returns false when nothing is open to receive the request. BasicWF::requestClose() forwards it. * A frontend that publishes its interface thread (uiExecutor()) declares `requestClose(std::optional)` instead: * BasicWF passes the session it owns, and the request is dropped on the interface thread if another loop runs by then. + * Optional static openSecondaryWindow() and closeSecondaryWindow() show a second window of the application (#616). An + * optional static bool secondaryWindowsAvailable() tells at run time whether that frontend, as initialized, can show one + * (NativeOrBrowserFrontend cannot once it fell back to the system browser); undeclared means it always can. * An optional static constexpr bool requiresMainThread tells that open() belongs to the process main thread * (frontend::requiresMainThread); webfront::UIThread refuses such a frontend at compile time. * An optional open(address, port, file) overload receives the configured address; build URLs with @@ -369,6 +372,31 @@ struct NativeOrBrowserFrontendFor { } } + /// A second window beside the first (#616): the native window's, or a refusal when the system browser was chosen. The + /// system browser is never asked to open one: it would be an external browser, without the proof of an embedded view. + /// Offered only when the native frontend offers it; secondaryWindowsAvailable() tells which way initialize() decided. + static void openSecondaryWindow(std::string_view address, std::string_view port, std::string_view file, const ContentPolicy& policy, + const WindowOptions& window, const ViewLaunch& launch) + requires requires { Native::openSecondaryWindow(address, port, file, policy, window, launch); } + { + if (!usesNativeWindow()) + throw std::logic_error("the system browser cannot show a second window of the application"); + Native::openSecondaryWindow(address, port, file, policy, window, launch); + } + [[nodiscard]] static bool closeSecondaryWindow(std::string_view file) + requires requires { { Native::closeSecondaryWindow(file) } -> std::same_as; } + { + return usesNativeWindow() && Native::closeSecondaryWindow(file); + } + /// Whether openSecondaryWindow() can open a window: false once initialize() chose the system browser. + [[nodiscard]] static bool secondaryWindowsAvailable() + requires requires(std::string_view text, const ContentPolicy& policy, const WindowOptions& window, const ViewLaunch& launch) { + Native::openSecondaryWindow(text, text, text, policy, window, launch); + } + { + return usesNativeWindow(); + } + static void open(std::string_view port, std::string_view file) { if (usesNativeWindow()) Native::open(port, file); diff --git a/include/webfront/frontend/UIExecutor.hpp b/include/webfront/frontend/UIExecutor.hpp index fc133585..d2c579cd 100644 --- a/include/webfront/frontend/UIExecutor.hpp +++ b/include/webfront/frontend/UIExecutor.hpp @@ -15,16 +15,19 @@ #include "../networking/Tasks.hpp" #include +#include #include #include #include #include #include #include +#include #include #include #include #include +#include #include #include #include @@ -399,4 +402,83 @@ template return host; } +/// @brief Thrown on the interface thread by a frontend's `openSecondaryWindow` while its first window cannot host another +/// yet (WebView2 creates its environment after open() started). invokeOnUIThreadWhenReady() tries again from another +/// thread; on the interface thread it reaches the caller, as the std::logic_error it is. +class WindowNotReady : public std::logic_error { +public: + explicit WindowNotReady(const std::string& message) : std::logic_error(message) { } +}; + +namespace detail { + +/// One blocking invocation (invokeOnUIThread): deletes itself when its operation completes, whatever the outcome. +template +struct UIInvocation { + struct Receiver { + using receiver_concept = ex::receiver_tag; + UIInvocation* self; + void finish(std::exception_ptr error) noexcept { + auto completion = std::move(self->done); + delete self; + completion.set_value(std::move(error)); + } + void set_value() noexcept { + std::exception_ptr error; + try { + self->function(); + } catch (...) { + error = std::current_exception(); + } + finish(std::move(error)); + } + void set_error(std::exception_ptr) noexcept { + finish(std::make_exception_ptr(UIExecutorUnavailable{})); + } + void set_stopped() noexcept { + finish(std::make_exception_ptr(UIExecutorUnavailable{})); + } + }; + Function function; + std::promise done; + ex::connect_result_t().schedule()), Receiver> operation; + UIInvocation(const UIExecutor& loop, Function work) : function(std::move(work)), operation(ex::connect(loop.schedule(), Receiver{this})) { } +}; + +} // namespace detail + +/// @brief Runs `function` on the interface thread and waits for it, from any other thread (#616). Called on the interface +/// thread itself it runs the function at once (waiting there would never end). An exception of the function is rethrown to +/// the caller; `UIExecutorUnavailable` is thrown when no loop runs, or when it closes before the function started. +/// Never call it from a thread the interface thread waits for. +template +void invokeOnUIThread(const UIExecutor& executor, Function function) { + if (executor.onUIThread()) { + function(); + return; + } + auto* invocation = new detail::UIInvocation(executor, std::move(function)); + auto answer = invocation->done.get_future(); + ex::start(invocation->operation); + if (auto error = answer.get()) + std::rethrow_exception(error); +} + +/// @brief invokeOnUIThread(), run again every 10 ms while `function` throws WindowNotReady (#646). The interface thread +/// cannot wait for itself: there, WindowNotReady reaches the caller. The frontend bounds the wait: a first window that +/// never becomes ready closes, and the call then fails as invokeOnUIThread() does. +template +void invokeOnUIThreadWhenReady(const UIExecutor& executor, Function function) { + for (;;) { + try { + invokeOnUIThread(executor, function); + return; + } catch (const WindowNotReady&) { + if (executor.onUIThread()) + throw; + } + std::this_thread::sleep_for(std::chrono::milliseconds(10)); + } +} + } // namespace webfront::frontend diff --git a/include/webfront/frontend/WKWebView.hpp b/include/webfront/frontend/WKWebView.hpp index e22c5d17..2ce4f4ea 100644 --- a/include/webfront/frontend/WKWebView.hpp +++ b/include/webfront/frontend/WKWebView.hpp @@ -347,6 +347,9 @@ struct Session { id previousDelegate = nullptr, previousMenu = nullptr; long previousActivationPolicy = 0; bool installed = false, running = false, closed = false, loaded = false; + bool secondary = false; + id sharedDataStore = nullptr; + std::function closedHook; bool receivedResponse = false, committed = false; std::exception_ptr error; std::shared_ptr captureTarget = std::make_shared(); @@ -459,7 +462,19 @@ struct Session { } void close() noexcept { + if (secondary && closed) + return; // the primary window repeats its stop request: the loop may have started since the first call closed = true; + if (secondary) { + if (window) + send(window, "orderOut:", static_cast(nullptr)); + if (closedHook) { + try { + closedHook(); + } catch (...) {} + } + return; + } if (!running) return; send(app, "stop:", static_cast(nullptr)); @@ -534,21 +549,26 @@ struct Session { void create() { app = send(type("NSApplication"), "sharedApplication"); - if (send(app, "isRunning")) + if (!secondary && send(app, "isRunning")) throw std::runtime_error("WKWebView: open() owns the AppKit event loop; call it outside an existing NSApplication run loop"); - previousDelegate = send(send(app, "delegate"), "retain"); - previousMenu = send(send(app, "mainMenu"), "retain"); - previousActivationPolicy = send(app, "activationPolicy"); - delegate = send(reinterpret_cast(delegateClass()), "new"); - attach(delegate, this); - installed = true; - send(app, "setDelegate:", delegate); - send(app, "setActivationPolicy:", options.visible ? applicationActivationPolicy() : 2L); - installMenu(); - send(app, "finishLaunching"); + if (!secondary) { + previousDelegate = send(send(app, "delegate"), "retain"); + previousMenu = send(send(app, "mainMenu"), "retain"); + previousActivationPolicy = send(app, "activationPolicy"); + delegate = send(reinterpret_cast(delegateClass()), "new"); + attach(delegate, this); + installed = true; + send(app, "setDelegate:", delegate); + send(app, "setActivationPolicy:", options.visible ? applicationActivationPolicy() : 2L); + installMenu(); + send(app, "finishLaunching"); + } else { + delegate = send(reinterpret_cast(delegateClass()), "new"); + attach(delegate, this); + } Object configuration(send(type("WKWebViewConfiguration"), "new")); - send(configuration.get(), "setWebsiteDataStore:", send(type("WKWebsiteDataStore"), "nonPersistentDataStore")); + send(configuration.get(), "setWebsiteDataStore:", sharedDataStore ? sharedDataStore : send(type("WKWebsiteDataStore"), "nonPersistentDataStore")); // Hidden content otherwise suspends once its load event completes. Use the public macOS 14+ preference // so asynchronous bridge/Worker work and close requests keep progressing without a visible native window. if (!options.visible) { @@ -577,7 +597,8 @@ struct Session { attach(view, this); captureTarget->view = view; captureTarget->pending.open(); - captureRegistration = CaptureRegistration{captureProvider(captureTarget)}; + if (!secondary) + captureRegistration = CaptureRegistration{captureProvider(captureTarget)}; send(view, "setAutoresizingMask:", 18UL); // NSViewWidthSizable | NSViewHeightSizable send(view, "setInspectable:", static_cast(options.contentPolicy.devToolsEnabled)); send(view, "setNavigationDelegate:", delegate); @@ -1177,6 +1198,88 @@ 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; + + static Windows& instance() { + static Windows windows; + return windows; + } + void retire(const std::string& page) { + const auto found = secondary.find(page); + if (found == secondary.end()) + return; + // run() returned long ago for this window, so nothing else can report a page that failed to load. + if (found->second->error) { + try { + std::rethrow_exception(found->second->error); + } catch (const std::exception& failure) { + std::fprintf(stderr, "WKWebViewFrontend: the secondary window of '%s' closed: %s\n", page.c_str(), failure.what()); + } catch (...) {} + } + finished.push_back(std::move(found->second)); + secondary.erase(found); + dispatch_async_f( + dispatch_get_main_queue(), + nullptr, + +[](void*) { + auto retired = std::move(instance().finished); + retired.clear(); + }); + } + void clear() { + secondary.clear(); + finished.clear(); + primary = nullptr; + } +}; + +inline void openSecondary(std::string_view address, std::string_view port, std::string_view page, WKWebViewOptions options) { + auto& windows = Windows::instance(); + // A first window that closed still runs its loop until the pass ends: a window built now would be destroyed with it. + if (!windows.primary || windows.primary->closed) + throw std::logic_error("WKWebView: no application window is open"); + std::string key(page); + if (const auto found = windows.secondary.find(key); found != windows.secondary.end()) { + // A hidden window stays hidden: ordering it to the front would show it. + if (found->second->options.visible) + send(found->second->window, "makeKeyAndOrderFront:", static_cast(nullptr)); + return; + } + // The first window's visibility and startup delay: a hidden application never shows a window or takes the focus. + options.visible = windows.primary->options.visible; + options.startupTimeout = windows.primary->options.startupTimeout; + auto child = std::make_unique(applicationUrl(address, port, page, options.launch.origin), std::move(options)); + child->secondary = true; + child->sharedDataStore = send(send(windows.primary->view, "configuration"), "websiteDataStore"); + child->create(); + child->closedHook = [key] { + Windows::instance().retire(key); + }; + // Registered only once started: a window whose start throws is not left in the table, and its page can be opened again. + // One that closed during start() already retired itself from a table that did not hold it yet, without a word: the + // caller is still waiting, so the failure is thrown to it. + child->start(); + if (child->closed) { + if (child->error) + std::rethrow_exception(child->error); + throw std::runtime_error("WKWebView: the secondary window of '" + key + "' closed while it started"); + } + windows.secondary[key] = std::move(child); +} + +inline bool closeSecondary(std::string_view page) { + auto& windows = Windows::instance(); + const auto found = windows.secondary.find(std::string(page)); + if (found == windows.secondary.end() || found->second->closed) + return false; + found->second->close(); + return true; +} + inline void open(std::string_view address, std::string_view port, std::string_view file, const WKWebViewOptions& options) { initialize(); if (opening) @@ -1211,6 +1314,14 @@ inline void open(std::string_view address, std::string_view port, std::string_vi host.close(); } } closing{host, windowHost}; + auto& windows = Windows::instance(); + windows.primary = &window; + struct Others { + Windows& windows; + ~Others() { + windows.clear(); + } + } others{windows}; window.run(); } @@ -1241,6 +1352,40 @@ struct WKWebViewFrontend { #endif } + static void openSecondaryWindow([[maybe_unused]] std::string_view address, + [[maybe_unused]] std::string_view port, + [[maybe_unused]] std::string_view page, + [[maybe_unused]] const ContentPolicy& policy, + [[maybe_unused]] const WindowOptions& window, + [[maybe_unused]] const ViewLaunch& launch) { +#if defined(WEBFRONT_EMBED_WKWEBVIEW) && defined(__APPLE__) + try { + invokeOnUIThread(uiExecutor(), [&] { + detail::wkwebview::openSecondary(address, port, page, WKWebViewOptions{.contentPolicy = policy, .window = window, .launch = launch}); + }); + } catch (const UIExecutorUnavailable&) { + throw std::logic_error("WKWebView: no application window is open"); + } +#else + initialize(); +#endif + } + static bool closeSecondaryWindow([[maybe_unused]] std::string_view page) { +#if defined(WEBFRONT_EMBED_WKWEBVIEW) && defined(__APPLE__) + bool closed = false; + try { + invokeOnUIThread(uiExecutor(), [&] { + closed = detail::wkwebview::closeSecondary(page); + }); + } catch (const UIExecutorUnavailable&) { + return false; + } + return closed; +#else + return false; +#endif + } + static void initialize() { #if defined(WEBFRONT_EMBED_WKWEBVIEW) && defined(__APPLE__) detail::wkwebview::initialize(); diff --git a/include/webfront/frontend/WebKitGTK.hpp b/include/webfront/frontend/WebKitGTK.hpp index 21374555..094700b6 100644 --- a/include/webfront/frontend/WebKitGTK.hpp +++ b/include/webfront/frontend/WebKitGTK.hpp @@ -23,6 +23,7 @@ #include #include #include +#include #include #include #include @@ -85,6 +86,7 @@ class Api { void (*windowChild)(Object, Object) = symbol("gtk_window_set_child"); void (*widgetOpacity)(Object, double) = symbol("gtk_widget_set_opacity"); void (*windowPresent)(Object) = symbol("gtk_window_present"); + void (*widgetVisible)(Object, int) = symbol("gtk_widget_set_visible"); void (*windowDestroy)(Object) = symbol("gtk_window_destroy"); Object (*loopNew)(Object, int) = symbol("g_main_loop_new"); void (*loopRun)(Object) = symbol("g_main_loop_run"); @@ -339,6 +341,11 @@ 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; + /// 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; + bool secondary = false; + std::function closedHook; /// Download folder; empty selects the user's XDG download folder, else the home folder. std::filesystem::path downloadDirectory; /// Test injection: answers without a dialog (an empty list cancels). Unset shows the system dialog. @@ -442,9 +449,20 @@ struct Session : FailureState { } void close() noexcept { - closed = true; + const bool first = !closed; + closed = true; mediaScope.reset(); a.loopQuit(loop); + // A secondary window is destroyed later, from an idle callback: it disappears now, so that the close request that + // reported it closed is not answered while the window is still on screen. + if (first && secondary && window) + a.widgetVisible(window, 0); + if (first && closedHook) { + try { + closedHook(); + } catch (...) { + } + } } void failAndClose(std::string_view message) noexcept { FailureState::fail(message); @@ -483,7 +501,7 @@ struct Session : FailureState { trace("session creation"); const auto data = profileDirectory("XDG_DATA_HOME", ".local/share"); const auto cache = profileDirectory("XDG_CACHE_HOME", ".cache"); - if (!windowOptions.media) { + if (!windowOptions.media && !secondary) { mediaPlugins = data / "no-media-plugins"; mediaRegistry = data / "no-media-registry.bin"; // never rewrite the user's own registry std::filesystem::create_directories(mediaPlugins); @@ -492,8 +510,9 @@ struct Session : FailureState { // the first load is requested: the variables stay set from here until the page reports that its load started (or // the delay expires), then are restored. The environment is process-wide, so the application is exposed during that // window, as docs/WEBKITGTK.md says; a web process launched later (a process swap) runs without the restriction. - mediaScope.emplace(mediaEnvironment()); - network = a.networkNew(data.c_str(), cache.c_str()); + if (!secondary) + mediaScope.emplace(mediaEnvironment()); + network = sharedNetwork ? a.refSink(sharedNetwork) : a.networkNew(data.c_str(), cache.c_str()); Api::Object context; { DevelopmentSandboxEnvironment environment(mode); @@ -510,11 +529,14 @@ struct Session : FailureState { installViewAssociation(); installFirstFrameProbe(); registerHandlers(); - downloadStartedHandler = a.connect(network, "download-started", reinterpret_cast(onDownloadStarted), this, nullptr, 0); + // The network session is shared: its downloads are tracked once, by the application's own window. + if (!secondary) + downloadStartedHandler = a.connect(network, "download-started", reinterpret_cast(onDownloadStarted), this, nullptr, 0); trace("view created"); captureTarget->view = view; captureTarget->pending.open(); - captureRegistration = CaptureRegistration{captureProvider(captureTarget)}; + if (!secondary) + captureRegistration = CaptureRegistration{captureProvider(captureTarget)}; } void applyBackground() { @@ -561,7 +583,8 @@ struct Session : FailureState { 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); - startPortalExport(); + if (!secondary) // the portal identifier is that of the application's own window + startPortalExport(); } /// Shows the window once the page painted its first frame, or when the delay expired. void presentWindow(bool byFrame) { @@ -941,6 +964,14 @@ struct Session : FailureState { a.loopRun(loop); rethrowIfFailed(); } + + /// 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); + presentHidden(); + a.load(view, url.c_str()); + } }; struct OpenOptions { @@ -950,6 +981,96 @@ struct OpenOptions { ViewLaunch launch{}; }; +/// The windows of the application beside the first one (#616). Every member is used on the interface thread only. +struct Windows { + Session* primary = nullptr; + std::map> secondary; + std::vector> finished; // closed, destroyed from an idle callback + unsigned reaper = 0; + + 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); + 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() { + if (reaper) + api().sourceRemove(std::exchange(reaper, 0)); + auto windows = std::move(secondary); + secondary.clear(); + finished.clear(); + windows.clear(); + primary = nullptr; + } +}; + +/// 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); +} + +/// 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; +} + 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. @@ -984,6 +1105,14 @@ inline void open(std::string_view address, std::string_view port, std::string_vi host.close(); } } closing{host, windowHost}; + auto& windows = Windows::instance(); + windows.primary = &session; + struct Others { + Windows& windows; + ~Others() { + windows.clear(); + } + } others{windows}; session.run(applicationUrl(address, port, file, options.launch.origin)); } @@ -1022,6 +1151,45 @@ struct BasicWebKitGTKFrontend { return 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 + } + + /// 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__) detail::webkitgtk::initialize(Mode); diff --git a/include/webfront/frontend/WebView2.hpp b/include/webfront/frontend/WebView2.hpp index 57bd84a8..22708607 100644 --- a/include/webfront/frontend/WebView2.hpp +++ b/include/webfront/frontend/WebView2.hpp @@ -17,6 +17,7 @@ #include #include #include +#include #include #include #include @@ -158,6 +159,9 @@ inline std::filesystem::path userDataFolder() { /// Posted to the window to make its STA start the queued capture requests. inline constexpr UINT captureMessage = WM_APP + 0x4C1; inline constexpr UINT drainMessage = WM_APP + 0x4C3; // UIExecutor: run what the interface thread was asked +inline constexpr UINT reapMessage = WM_APP + 0x4C4; // secondary windows (#616): destroy those that closed + +inline void reapSecondaryWindows(); // defined with the registry of the windows, after Session struct CaptureJob { std::promise done; @@ -270,6 +274,10 @@ class Session : public std::enable_shared_from_this { throw std::invalid_argument("WebView2: startup timeout must be between 1 and USER_TIMER_MAXIMUM milliseconds"); startupTimeoutMilliseconds = static_cast(timeout.count()); } + /// The delay of the watchdog, as given at construction. + [[nodiscard]] std::chrono::milliseconds startupTimeout() const noexcept { + return std::chrono::milliseconds{startupTimeoutMilliseconds}; + } HWND window = nullptr; Microsoft::WRL::ComPtr environment; Microsoft::WRL::ComPtr controller; @@ -288,6 +296,10 @@ class Session : public std::enable_shared_from_this { ScriptDialogHandler answerScriptDialog; bool closed = false; UINT_PTR startupTimer = 0; + // A window opened beside the application's own (#616): it shares the environment (profile, browser process) of the first, + // runs no loop of its own and reports its closing to closedHook, once, instead of ending the session. + bool secondary = false; + std::function closedHook; std::shared_ptr captureQueue = std::make_shared(); CaptureRegistration captureRegistration; @@ -359,6 +371,12 @@ class Session : public std::enable_shared_from_this { view.Reset(); controller.Reset(); environment.Reset(); + if (closedHook) { + auto hook = std::exchange(closedHook, {}); + try { + hook(); + } catch (...) { } + } } void fail() noexcept { @@ -435,7 +453,9 @@ class Session : public std::enable_shared_from_this { if (!window) throw std::runtime_error("WebView2: cannot create window"); // Bounds initialization errors and an unresponsive runtime must not leave an empty window forever. - startupTimer = SetTimer(nullptr, 0, startupTimeoutMilliseconds, nullptr); + // A secondary window is not pumped by a session of its own: its watchdog belongs to the window, whose procedure runs + // whichever loop dispatches it. + startupTimer = secondary ? SetTimer(window, startupTimerId, startupTimeoutMilliseconds, nullptr) : SetTimer(nullptr, 0, startupTimeoutMilliseconds, nullptr); if (!startupTimer) throw std::runtime_error("WebView2: cannot start startup timer"); if (visible) { @@ -450,6 +470,17 @@ class Session : public std::enable_shared_from_this { } } + /// Whether the window is shown (the first window's choice, which a secondary window follows). + [[nodiscard]] bool shown() const noexcept { + return visibleWindow; + } + + /// A secondary window: the browser of the first window's environment, which has no creation of its own to wait for. + void startSecondary(ICoreWebView2Environment* shared) { + environment = shared; + createController(); + } + void start(const std::filesystem::path& profile, EnvironmentFactory createEnvironment = CreateCoreWebView2EnvironmentWithOptions) { auto weak = weak_from_this(); const auto started = createEnvironment( @@ -499,6 +530,7 @@ class Session : public std::enable_shared_from_this { // 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; + static constexpr UINT_PTR startupTimerId = 0x5747; void stopPresentTimer() noexcept { if (presentTimer && window) KillTimer(window, presentTimer); @@ -541,11 +573,20 @@ class Session : public std::enable_shared_from_this { } void stopStartupTimer() noexcept { - if (startupTimer) - KillTimer(nullptr, startupTimer); + if (startupTimer && (!secondary || window)) + KillTimer(secondary ? window : nullptr, startupTimer); startupTimer = 0; } + void secondaryStartupTimedOut() noexcept { + presentWindow(); // nothing invisible is left to interact with + try { + throw std::runtime_error(std::format("WebView2: runtime startup timed out after {} milliseconds", startupTimeoutMilliseconds)); + } catch (...) { + fail(); + } + } + void checkStartupTimeout(const MSG& message) { // close() and fail() clear the timer, including messages queued before KillTimer(). if (!startupTimer) @@ -729,6 +770,9 @@ class Session : public std::enable_shared_from_this { case drainMessage: uiExecutorHostOf().drain(); return true; + case reapMessage: + reapSecondaryWindows(); + return true; case WM_CLOSE: close(); DestroyWindow(handle); @@ -750,6 +794,10 @@ class Session : public std::enable_shared_from_this { SetWindowLongPtrW(handle, GWLP_USERDATA, reinterpret_cast(self)); self->window = handle; } + if (self && self->secondary && message == WM_TIMER && wParam == startupTimerId && self->startupTimer) { + self->secondaryStartupTimedOut(); + return 0; + } if (self && message == WM_TIMER && wParam == presentTimerId && self->presentTimer) { self->trace("present delay expired"); self->presentWindow(); @@ -914,7 +962,8 @@ class Session : public std::enable_shared_from_this { if (GetFocus() == window) restoreFocus(); captureQueue->open(window); - captureRegistration = CaptureRegistration{captureProvider(captureQueue)}; + if (!secondary) // the capture of the application is that of its own window + captureRegistration = CaptureRegistration{captureProvider(captureQueue)}; if (viewReady) viewReady(); installViewAssociationThenNavigate(view.Get()); @@ -968,6 +1017,109 @@ 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 + + static Windows& instance() { + static Windows windows; + return windows; + } + void retire(const std::string& page) { + const auto found = secondary.find(page); + if (found == secondary.end()) + return; + // open() returned long ago, so nothing else can report a page that failed (navigation, runtime, process lost). + if (found->second->failure) { + try { + std::rethrow_exception(found->second->failure); + } catch (const std::exception& error) { + std::fprintf(stderr, "WebView2Frontend: the secondary window of '%s' closed: %s\n", page.c_str(), error.what()); + } catch (...) { + } + } + finished.push_back(std::move(found->second)); + secondary.erase(found); + // Never destroyed in its own callback: the first window's procedure does it on its next message. + if (primary && primary->window) + PostMessageW(primary->window, reapMessage, 0, 0); + } + void reap() { + auto closed = std::move(finished); + finished.clear(); + closed.clear(); + } + /// The first window ended: the others end with it. + void clear() { + auto windows = std::move(secondary); + secondary.clear(); + for (auto& [page, session] : windows) + session->closedHook = nullptr; + finished.clear(); + windows.clear(); + primary = nullptr; + } +}; + +inline void reapSecondaryWindows() { + Windows::instance().reap(); +} + +/// 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); +} + +/// 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; +} + inline void open(std::string_view address, std::string_view port, std::string_view file, @@ -1013,6 +1165,14 @@ inline void open(std::string_view address, host.close(); } } closing{host, windowHost}; + auto& windows = Windows::instance(); + windows.primary = session.get(); + struct Others { + Windows& windows; + ~Others() { + windows.clear(); + } + } others{windows}; session->run(); } @@ -1048,6 +1208,47 @@ struct WebView2Frontend { return nativeWindowHostOf().window(); } + /// 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 + } + + /// Closes the secondary window showing `page`, from any thread; false when none is open. + static bool closeSecondaryWindow([[maybe_unused]] std::string_view page) { +#if defined(WEBFRONT_EMBED_WEBVIEW2) && defined(_WIN32) + bool closed = false; + try { + invokeOnUIThread(uiExecutor(), [&] { + closed = detail::webview2::closeSecondary(std::string(page)); + }); + } catch (const UIExecutorUnavailable&) { + return false; + } + return closed; +#else + return false; +#endif + } + static void initialize() { } static void open(std::string_view port, std::string_view file) { diff --git a/test/cmake/CheckFrontendGenerators.cmake b/test/cmake/CheckFrontendGenerators.cmake index 95f4a8fc..a280f20c 100644 --- a/test/cmake/CheckFrontendGenerators.cmake +++ b/test/cmake/CheckFrontendGenerators.cmake @@ -20,7 +20,7 @@ foreach(generator Ninja "Ninja Multi-Config" Ninja) endif() webfront_read_frontend_tests("${directory}" tests) string(JSON count LENGTH "${tests}" tests) - if(NOT count EQUAL 16) - message(FATAL_ERROR "${generator}: expected Jasmine, fourteen shared lifecycle cases and the engine test (no start-up case: the fixture does not declare STARTUP_TRACE), got ${count}") + if(NOT count EQUAL 17) + message(FATAL_ERROR "${generator}: expected Jasmine, fifteen shared lifecycle cases and the engine test (no start-up case: the fixture does not declare STARTUP_TRACE), got ${count}") endif() endforeach() diff --git a/test/cmake/CheckFrontendSelection.cmake b/test/cmake/CheckFrontendSelection.cmake index 2d3060e5..cc8c094c 100644 --- a/test/cmake/CheckFrontendSelection.cmake +++ b/test/cmake/CheckFrontendSelection.cmake @@ -437,13 +437,13 @@ foreach(case webkitgtk-display webkitgtk-linux cef-linux cef-macos cef-windows c continue() endif() if(case STREQUAL "webview2-windows") - set(expected_count 18) # with StartupTime-cold and -warm (#611) + set(expected_count 19) # with StartupTime-cold and -warm (#611) elseif(case STREQUAL "extension") - set(expected_count 16) # an engine without STARTUP_TRACE has no start-up case + set(expected_count 17) # an engine without STARTUP_TRACE has no start-up case elseif(case STREQUAL "cef-linux") - set(expected_count 14) # no host-thread case: CEF has no secondary-thread path to observe + set(expected_count 15) # no host-thread case: CEF has no secondary-thread path to observe else() - set(expected_count 17) + set(expected_count 18) endif() if(NOT count EQUAL expected_count) list(APPEND failures "${case}: expected ${expected_count} tests, got ${count}") diff --git a/test/cmake/frontends/CMakeLists.txt b/test/cmake/frontends/CMakeLists.txt index ad2a0099..bd9049d4 100644 --- a/test/cmake/frontends/CMakeLists.txt +++ b/test/cmake/frontends/CMakeLists.txt @@ -88,7 +88,7 @@ elseif(CASE STREQUAL "webkitgtk-linux") include("${ROOT}/test/cmake/WebKitGTKTestEnvironment.cmake") function(webfront_add_webkitgtk_tests) list(LENGTH ARGN shared_count) - if(NOT shared_count EQUAL 17 OR NOT "WebFrontWebKitGTKIntegration" IN_LIST ARGN) + if(NOT shared_count EQUAL 18 OR NOT "WebFrontWebKitGTKIntegration" IN_LIST ARGN) message(FATAL_ERROR "WebKitGTK setup must receive every shared test, including Jasmine") endif() foreach(test IN LISTS ARGN) diff --git a/test/unit/FrontendContractTests.cpp b/test/unit/FrontendContractTests.cpp index 80a3a4e6..31adfd39 100644 --- a/test/unit/FrontendContractTests.cpp +++ b/test/unit/FrontendContractTests.cpp @@ -1184,6 +1184,262 @@ const Scenario nativeOrBrowserFrontendForwards{"NativeOrBrowserFrontend forwards }); }}; +namespace { +struct SecondaryContractFrontend : SharedWindowFrontend { + static inline int opened = 0; + static inline int closed = 0; + /// Run once, when BasicWF asks for the executor: after it has captured the session of its show(). + static inline std::function beforeExecutor; + [[nodiscard]] static frontend::UIExecutor uiExecutor() { + if (auto hook = std::exchange(beforeExecutor, {})) + hook(); + return SharedWindowFrontend::uiExecutor(); + } + static void openSecondaryWindow(std::string_view, std::string_view, std::string_view, const ContentPolicy&, const WindowOptions&, const ViewLaunch&) { + ++opened; + } + static bool closeSecondaryWindow(std::string_view) { + ++closed; + return true; + } +}; +} + +const Scenario secondaryOwnership{"Only the owner can operate secondary windows", [] { + given("two applications sharing a frontend", [&] { + using Shared = SecondaryContractFrontend; + Shared::opened = 0; + Shared::closed = 0; + HostApp owner; + const auto state = ContractIoContext::current; + HostApp other; + std::atomic done{false}; + std::atomic success{false}; + Shared::insideOpen = [&] { + try { + owner.openSecondaryWindow("one.html"); + const bool closed = owner.requestClose("one.html"); + bool refused = false; + try { other.openSecondaryWindow("one.html"); } catch (const std::logic_error&) { refused = true; } + success = closed && refused && !other.requestClose("one.html"); + } catch (...) { } + ContractIoContext::current = state; + done = true; + }; + std::jthread showing([&] { owner.show(); }); + requireEventually([&] { return done.load(); }); + then("only the owning application reaches the frontend", [&] { + check(success); + check(Shared::opened == 1); + check(Shared::closed == 1); + }); + requireEventually([&] { return windowOpen(state); }); + { + std::lock_guard lock(state->mutex); + state->closeWindow = true; + state->changed.notify_all(); + } + showing.join(); + Shared::insideOpen = nullptr; + }); +}}; + +const Scenario secondaryStaleSession{"A secondary window is never opened in a session that started after the call did", [] { + given("a call made during the show() of one application, whose show() ends and another starts before it is delivered", [&] { + using Shared = SecondaryContractFrontend; + Shared::opened = 0; + Shared::closed = 0; + HostApp owner; + const auto ownerState = ContractIoContext::current; + HostApp later; + const auto laterState = ContractIoContext::current; + ContractIoContext::current = ownerState; + std::jthread ownerShow([&] { owner.show(); }); + requireEventually([&] { return windowOpen(ownerState); }); + std::jthread laterShow; + Shared::beforeExecutor = [&] { + { + std::lock_guard lock(ownerState->mutex); + ownerState->closeWindow = true; + ownerState->changed.notify_all(); + } + ownerShow.join(); + ContractIoContext::current = laterState; + laterShow = std::jthread([&] { later.show(); }); + requireEventually([&] { return windowOpen(laterState); }); + }; + bool refused = false; + try { + owner.openSecondaryWindow("one.html"); + } catch (const std::logic_error&) { + refused = true; + } + then("the call is refused and the later session received nothing", [&] { + check(refused); + check(Shared::opened == 0); + check(!owner.requestClose("one.html")); + check(Shared::closed == 0); + }); + { + std::lock_guard lock(laterState->mutex); + laterState->closeWindow = true; + laterState->changed.notify_all(); + } + }); +}}; + +namespace { +// A frontend whose first window cannot host a second one for its first `refusals` attempts, as WebView2 while its +// environment is being created (#646). Its loop drains the interface-thread executor until the test closes the window. +struct NotReadyFrontend : ContractFrontend { + static inline std::atomic refusals = 0; + static inline std::atomic attempts = 0; + static inline std::atomic opened = 0; + static inline std::function insideOpen; // run on the interface thread once the session exists + + [[nodiscard]] static frontend::UIExecutor uiExecutor() { + return frontend::uiExecutorHostOf().executor(); + } + static void open(std::string_view, std::string_view) { + auto& host = frontend::uiExecutorHostOf(); + host.attach([] { }); + struct Detach { + ~Detach() { + frontend::uiExecutorHostOf().close(); + } + } detach; + const auto state = ContractIoContext::current; + { + std::lock_guard lock(state->mutex); + state->openThread = std::this_thread::get_id(); + state->frontendEntered = true; + state->windowCreated = true; + state->changed.notify_all(); + } + if (insideOpen) + insideOpen(); + for (;;) { + host.drain(); + std::unique_lock lock(state->mutex); + if (state->changed.wait_for(lock, std::chrono::milliseconds(1), [&] { return state->closeWindow; })) + return; + } + } + static void openSecondaryWindow(std::string_view, std::string_view, std::string_view, const ContentPolicy&, const WindowOptions&, const ViewLaunch&) { + ++attempts; + if (refusals > 0) { + --refusals; + throw frontend::WindowNotReady("the first window is not ready"); + } + ++opened; + } + static bool closeSecondaryWindow(std::string_view) { + return false; + } +}; +} // namespace + +const Scenario secondaryWaitsForFirstWindow{"A second window requested while the first is not ready waits for it (#646)", [] { + given("an application whose first window refuses a second one for its first attempts", [&] { + using Frontend = NotReadyFrontend; + Frontend::attempts = 0; + Frontend::opened = 0; + HostApp app; + static_assert(HostApp::supportsSecondaryWindow); + const auto state = ContractIoContext::current; + bool refusedOnInterfaceThread = false; + Frontend::insideOpen = [&] { + Frontend::refusals = 1; + try { + app.openSecondaryWindow("one.html"); + } catch (const frontend::WindowNotReady&) { + refusedOnInterfaceThread = true; + } + Frontend::refusals = 3; + }; + // Closes the window on every exit, also by a failed requirement, so that show() returns before the join. + struct CloseWindow { + std::shared_ptr state; + ~CloseWindow() { + std::lock_guard lock(state->mutex); + state->closeWindow = true; + state->changed.notify_all(); + Frontend::insideOpen = nullptr; + } + }; + std::jthread showing([&] { app.show(); }); + CloseWindow close{state}; + requireEventually([&] { return windowOpen(state); }); + when("another thread asks for a second window", [&] { + app.openSecondaryWindow("one.html"); + then("the call tries again until the window opens; the interface thread, which cannot wait, is refused", [&] { + check(refusedOnInterfaceThread); + check(Frontend::opened == 1); + check(Frontend::attempts == 5); // one on the interface thread, three refused and the one that opened + }); + }); + }); +}}; + +const Scenario secondWindowRefused{"A frontend without a second window refuses openSecondaryWindow with an exception", [] { + given("an application whose frontend shows one window", [&] { + HostApp> app; + static_assert(!HostApp>::supportsSecondaryWindow); + then("the call is refused before and while a window is open, and no close request finds a window", [&] { + requireThrows([&] { app.openSecondaryWindow("other.html"); }); + check(!app.requestClose("other.html")); + const auto state = ContractIoContext::current; + std::jthread show([&] { app.show(); }); + requireEventually([&] { return windowOpen(state); }); + requireThrows([&] { app.openSecondaryWindow("other.html"); }); + check(!app.requestClose("other.html")); + check(app.requestClose()); + }); + }); + given("the native-or-browser frontend whose native window cannot show a second one", [&] { + using Either = frontend::NativeOrBrowserFrontendFor, DeafFrontend>; + // It does not claim a capacity its native frontend lacks (#646). + static_assert(!HostApp::supportsSecondaryWindow); + then("the application reports that it cannot show one", [&] { + check(!HostApp::canShowSecondaryWindow()); + }); + }); +}}; + +namespace { +// Native frontends that can show a second window; the second cannot initialize, so the system browser replaces it. +struct SecondaryNative : NotReadyFrontend { }; +struct UnavailableSecondaryNative : NotReadyFrontend { + static void initialize() { + throw std::runtime_error("no display"); + } +}; +} // namespace + +const Scenario secondaryAvailability{"Whether a second window can be shown follows the frontend chosen at run time (#646)", [] { + given("a native-or-browser frontend whose native window can show a second one", [&] { + using Native = frontend::NativeOrBrowserFrontendFor; + using Fallback = frontend::NativeOrBrowserFrontendFor; + static_assert(HostApp::supportsSecondaryWindow && HostApp::supportsSecondaryWindow); + Native::initialize(); + Fallback::initialize(); + then("it can when the native window is used, and cannot once it fell back to the system browser", [&] { + check(Native::usesNativeWindow()); + check(HostApp::canShowSecondaryWindow()); + check(!Fallback::usesNativeWindow()); + check(!HostApp::canShowSecondaryWindow()); + requireThrows([&] { Fallback::openSecondaryWindow("127.0.0.1", "9002", "other.html", ContentPolicy{}, WindowOptions{}, ViewLaunch{}); }); + check(!Fallback::closeSecondaryWindow("other.html")); + }); + }); + given("frontends without a choice at run time", [&] { + then("a frontend that shows a second window can, one that cannot does not", [&] { + check(HostApp::canShowSecondaryWindow()); + check(!HostApp>::canShowSecondaryWindow()); + }); + }); +}}; + const Scenario uIThreadStop{"UIThread::stop reports a window that does not close", [] { given("a window that ignores close requests", [&] { UIThread> ui(WebFrontConfig{}, [](auto&) { }); diff --git a/test/unit/UIExecutorTests.cpp b/test/unit/UIExecutorTests.cpp index eddb0aea..8c5370b1 100644 --- a/test/unit/UIExecutorTests.cpp +++ b/test/unit/UIExecutorTests.cpp @@ -851,3 +851,36 @@ const Scenario passInterface{"A pass of the interface thread runs a bounded batc host.close(); }); }}; + +const Scenario invokeBlocking{"invokeOnUIThread runs a function on the interface thread and waits for it", [] { + given("a frontend loop attached to an executor", [&] { + FakeLoop loop; + loop.start(); + const auto executor = loop.host.executor(); + when("another thread invokes a function", [&] { + std::thread::id ran; + invokeOnUIThread(executor, [&] { ran = std::this_thread::get_id(); }); + then("it ran on the interface thread, and had finished when the call returned", [&] { + check(ran == loop.uiThread); + }); + }); + when("the function throws", [&] { + then("the caller receives the exception", [&] { + requireThrows([&] { invokeOnUIThread(executor, [] { throw std::logic_error("refused"); }); }); + }); + }); + when("the interface thread itself invokes a function", [&] { + bool nested = false; + invokeOnUIThread(executor, [&] { invokeOnUIThread(executor, [&] { nested = true; }); }); + then("it runs at once instead of waiting for itself", [&] { + check(nested); + }); + }); + when("the loop has closed", [&] { + loop.stop(); + then("the call reports the missing interface thread", [&] { + requireThrows([&] { invokeOnUIThread(executor, [] { }); }); + }); + }); + }); +}}; diff --git a/test/web/FrontendLifecycle.cpp b/test/web/FrontendLifecycle.cpp index 96677e3d..1ae8fd56 100644 --- a/test/web/FrontendLifecycle.cpp +++ b/test/web/FrontendLifecycle.cpp @@ -643,6 +643,282 @@ int checkHostClose() { return 0; } +// A second window of the application (#616): both pages share the C++ functions and the pushed calls of one application; +// closing the second leaves the first usable, closing the first closes the second. A frontend that cannot show a second +// window must refuse the call with an exception instead of opening a browser. +constexpr const char* secondPage = "second-window.html?name=editor"; +constexpr const char* earlyPage = "second-window.html?name=early"; + +class SecondWindows { + std::mutex mutex; + std::condition_variable changed; + std::map windows; + std::map embedded; + std::map seen; + std::int64_t counter = 0; + unsigned connections = 0; + bool abandoned = false; + + template + bool waitFor(Predicate predicate) { + std::unique_lock lock{mutex}; + return changed.wait_for(lock, std::chrono::seconds(20), [&] { return predicate() || abandoned; }) && !abandoned && predicate(); + } + +public: + void abandon() { + { + std::lock_guard lock{mutex}; + abandoned = true; + } + changed.notify_all(); + } + void setup(App& app) { + app.onUIStarted([this](App::UI) { + std::lock_guard lock{mutex}; + ++connections; + }); + app.cppFunction("windowReady", [this](App::UI ui, std::string name) { + lifecycleStage = LifecycleStage::bridgeConnected; + { + std::lock_guard lock{mutex}; + windows.insert_or_assign(name, ui); + embedded[name] = ui.isEmbeddedView(); + } + changed.notify_all(); + }); + app.cppFunction("bump", [this] { + std::vector all; + std::int64_t value; + { + std::lock_guard lock{mutex}; + value = ++counter; + for (auto& [name, ui] : windows) + all.push_back(ui); + } + for (auto& ui : all) { + try { + ui.jsFunction("windowTests.changed")(value); + } catch (...) { // a window that closed meanwhile + } + } + }); + app.cppFunction("seen", [this](std::string name, std::int64_t value) { + { + std::lock_guard lock{mutex}; + seen[name] = value; + } + changed.notify_all(); + }); + } + bool ready(const std::string& name) { + return waitFor([&] { return windows.contains(name); }); + } + bool isEmbedded(const std::string& name) { + std::lock_guard lock{mutex}; + return embedded[name]; + } + unsigned connectionCount() { + std::lock_guard lock{mutex}; + return connections; + } + App::UI window(const std::string& name) { + std::lock_guard lock{mutex}; + return windows.at(name); + } + void forget(const std::string& name) { + std::lock_guard lock{mutex}; + windows.erase(name); + } + bool saw(const std::string& name, std::int64_t value) { + return waitFor([&] { return seen.contains(name) && seen[name] == value; }); + } +}; + +// Runs `function` on the interface thread once started; the future gives the executor's outcome (ran, stopped, unavailable). +template +class OnInterfaceThread { + struct Receiver { + using receiver_concept = webfront::networking::ex::receiver_tag; + OnInterfaceThread* self; + auto get_env() const noexcept { + return webfront::networking::ex::prop{webfront::networking::ex::get_stop_token, webfront::networking::ex::never_stop_token{}}; + } + void set_value() && noexcept { + self->function(); + self->done.set_value(Outcome::ran); + } + void set_stopped() && noexcept { + self->done.set_value(Outcome::stopped); + } + void set_error(std::exception_ptr) && noexcept { + self->done.set_value(Outcome::unavailable); + } + }; + Function function; + std::promise done; + decltype(webfront::networking::ex::connect(std::declval().schedule())>(), + std::declval())) operation; + +public: + OnInterfaceThread(const webfront::frontend::UIExecutor& executor, Function work) + : function(std::move(work)), operation(webfront::networking::ex::connect(executor.schedule(), Receiver{this})) { } + std::future outcome() { + return done.get_future(); + } + void start() noexcept { + webfront::networking::ex::start(operation); + } +}; + +int checkSecondWindow() { + App app(webfront::WebFrontConfig{.documentRoot = std::filesystem::current_path()}); + lifecycleStage = LifecycleStage::startingInstrumented; + bool refusedBeforeShow = false; + try { + app.openSecondaryWindow(secondPage); + } catch (const std::logic_error&) { + refusedBeforeShow = true; + } + if (!refusedBeforeShow) + throw std::runtime_error("A second window was accepted before show()"); + if (app.requestClose(secondPage)) + throw std::runtime_error("A close request of a window was accepted before show()"); + SecondWindows windows; + windows.setup(app); + std::string failure; + std::thread host([&] { + try { + const auto check = [&](bool condition, const char* message) { + if (!condition) + throw std::runtime_error(message); + }; + if constexpr (App::supportsSecondaryWindow) { + // As soon as the interface loop runs, before the first page connected (WebView2 is still creating its + // environment then), a second window opens: the call waits for the first one instead of refusing (#646). + const auto executor = app.uiExecutor(); + for (int attempt = 0; attempt < 2000 && !executor.available(); ++attempt) + std::this_thread::sleep_for(std::chrono::milliseconds(5)); + app.openSecondaryWindow(earlyPage); + } + check(windows.ready("main"), "The first window did not connect"); + if constexpr (!App::supportsSecondaryWindow) { + bool refused = false; + try { + app.openSecondaryWindow(secondPage); + } catch (const std::logic_error&) { + refused = true; + } + check(refused, "A frontend without a second window did not refuse the call"); + } else { + check(windows.ready("early"), "The window opened as the first one started did not connect"); + check(app.requestClose(earlyPage), "The close request of the early window was refused"); + for (int attempt = 0; attempt < 200 && app.requestClose(earlyPage); ++attempt) + std::this_thread::sleep_for(std::chrono::milliseconds(25)); + check(!app.requestClose(earlyPage), "The early window did not close"); + windows.forget("early"); + windows.window("main").jsFunction("windowTests.setStorage")(std::string("from-main")); + // The round trip orders the fire-and-forget write before creating the second view. + check(windows.window("main").template jsFunction("windowTests.getStorage")().get() == "from-main", "The first window could not write storage"); + webfront::WindowOptions options; + options.title = "Second window"; + options.width = 640; + options.height = 480; + app.openSecondaryWindow(secondPage, options); + check(windows.ready("editor"), "The second window did not connect"); + check(windows.isEmbedded("main") && windows.isEmbedded("editor"), "A window of the application lacks the proof of an embedded view"); + check(windows.window("editor").template jsFunction("windowTests.getStorage")().get() == "from-main", "The second window does not share storage"); + // The same page again brings the window to the front: no third connection. + app.openSecondaryWindow(secondPage, options); + check(windows.window("editor").template jsFunction("windowTests.name")().get() == "editor", "The second window did not answer"); + check(windows.connectionCount() == 3, "Opening the same page again opened another window"); // main, early, editor + // A change made from one window is seen by both (shared cppFunction, pushed jsFunction). + windows.window("editor").jsFunction("windowTests.bump")(); + check(windows.saw("main", 1) && windows.saw("editor", 1), "A change made in one window did not reach both"); + // Closing the second window leaves the first usable. + check(app.requestClose(secondPage), "The close request of the second window was refused"); + for (int attempt = 0; attempt < 200 && app.requestClose(secondPage); ++attempt) + std::this_thread::sleep_for(std::chrono::milliseconds(25)); + check(!app.requestClose(secondPage), "The second window did not close"); + check(windows.window("main").template jsFunction("windowTests.name")().get() == "main", "The first window is not usable after the second closed"); + // Opened again, it shares the state again. + windows.forget("editor"); + app.openSecondaryWindow(secondPage, options); + check(windows.ready("editor"), "The second window did not reopen"); + windows.window("main").jsFunction("windowTests.bump")(); + check(windows.saw("editor", 2) && windows.saw("main", 2), "The reopened window does not share the state"); + // A request that the loop runs after the first window closed, in the same pass, is refused: the window it + // would build would be destroyed with the first one at once, and its caller told it exists (#646). Both + // operations are queued from one operation of the interface thread, so the next pass runs them in order. + enum class Late { pending, opened, refused, failed }; + std::atomic late{Late::pending}; + std::atomic closeAccepted{false}; + const auto executor = app.uiExecutor(); + OnInterfaceThread lateOpen(executor, [&]() noexcept { + try { + app.openSecondaryWindow("second-window.html?name=late"); + late = Late::opened; + } catch (const std::logic_error&) { + late = Late::refused; + } catch (...) { + late = Late::failed; + } + }); + OnInterfaceThread closeThenOpen(executor, [&]() noexcept { + closeAccepted = app.requestClose(); + lateOpen.start(); + }); + auto lateOutcome = lateOpen.outcome(); + auto closeOutcome = closeThenOpen.outcome(); + closeThenOpen.start(); + check(closeOutcome.wait_for(std::chrono::seconds(20)) == std::future_status::ready && closeOutcome.get() == Outcome::ran, + "The operation that closes the first window did not run"); + check(closeAccepted, "The close request of the first window was refused"); + check(lateOutcome.wait_for(std::chrono::seconds(20)) == std::future_status::ready, "The late request did not complete"); + const auto lateRan = lateOutcome.get() == Outcome::ran; + check(late != Late::failed, "A request made as the first window closed failed with an unexpected exception"); + // These frontends close the first window when the request runs, so the late request sees it closed; WebView2 + // posts WM_CLOSE and may legitimately open the window before the first one closes it. + if constexpr (std::same_as || std::same_as) + check(lateRan && late == Late::refused, "A second window was opened after the first one had closed"); + return; + } + check(app.requestClose(), "The close request of the first window was refused"); + } catch (const std::exception& error) { + failure = error.what(); + app.requestClose(); + } + }); + struct Join { + SecondWindows& windows; + std::thread& thread; + ~Join() { + windows.abandon(); + thread.join(); + } + }; + { + Join join{windows, host}; + app.show("second-window.html"); + lifecycleStage = LifecycleStage::windowClosed; + } + if (!failure.empty()) + throw std::runtime_error(failure); + if constexpr (App::supportsSecondaryWindow) { + if (app.requestClose(secondPage)) + throw std::runtime_error("The second window survived the first"); + bool refused = false; + try { + app.openSecondaryWindow(secondPage); + } catch (const std::logic_error&) { + refused = true; + } + if (!refused) + throw std::runtime_error("A second window was accepted after show() returned"); + } + return 0; +} + // The application on a thread of its own, for a frontend that allows it; the others must refuse with a diagnostic // instead of opening a window off the main thread. template @@ -762,6 +1038,7 @@ int run(std::string_view mode) { cases.emplace("native-window", checkNativeWindow); cases.emplace("second-open", checkSecondOpen); cases.emplace("host-close", checkHostClose); + cases.emplace("second-window", checkSecondWindow); cases.emplace("startup-time", checkStartupTime); cases.emplace("host-thread", +[] { return checkHostThread(); }); cases.emplace("view-association", checkViewAssociation); diff --git a/test/web/WKWebViewLifecycle.cpp b/test/web/WKWebViewLifecycle.cpp index 55bc0aa0..3d8f1465 100644 --- a/test/web/WKWebViewLifecycle.cpp +++ b/test/web/WKWebViewLifecycle.cpp @@ -253,6 +253,33 @@ void hiddenScheduling() { session.run(); } +// A secondary window of a hidden application stays hidden, also when its page is opened again (which brings a visible +// window to the front). +void hiddenSecondary() { + Object pool(send(type("NSAutoreleasePool"), "new")); + Object configuration(send(type("WKWebViewConfiguration"), "new")); + if (!send(send(configuration.get(), "preferences"), "respondsToSelector:", sel_registerName("setInactiveSchedulingPolicy:"))) + return; // hidden sessions require macOS 14 (see hidden-scheduling) + Session primary("http://127.0.0.1:0/", {.visible = false}); + primary.create(); + auto& windows = Windows::instance(); + windows.primary = &primary; + struct Clear { + Windows& windows; + ~Clear() { + windows.clear(); + } + } clear{windows}; + openSecondary("127.0.0.1", "0", "editor.html", {}); + const auto found = windows.secondary.find("editor.html"); + require(found != windows.secondary.end(), "The secondary window was not opened"); + require(!found->second->options.visible, "The secondary window does not follow the hidden first window"); + require(!send(found->second->window, "isVisible"), "The secondary window of a hidden application was shown"); + openSecondary("127.0.0.1", "0", "editor.html", {}); + require(windows.secondary.size() == 1, "Opening the same page again opened another window"); + require(!send(found->second->window, "isVisible"), "Opening the same page again showed a hidden window"); +} + void missingResponse() { Object pool(send(type("NSAutoreleasePool"), "new")); Session session("http://127.0.0.1:0/", {.visible = webfront::testdriver::visibleWindows}); @@ -663,6 +690,7 @@ int main(int argc, char** argv) { { "redirect-policy", redirectPolicy}, { "settings", settings}, { "hidden-scheduling", hiddenScheduling}, + { "hidden-secondary", hiddenSecondary}, {"translucent-background", translucentBackground}, {"navigation-diagnostic", navigationDiagnostic}, { "missing-response", missingResponse}, diff --git a/test/web/WebView2Lifecycle.cpp b/test/web/WebView2Lifecycle.cpp index 7eb58b84..58845a8d 100644 --- a/test/web/WebView2Lifecycle.cpp +++ b/test/web/WebView2Lifecycle.cpp @@ -549,6 +549,52 @@ int runtimeReadyBeforePageLoad() { return 0; } +// A secondary window keeps the startup delay the application configured (90 s in LifecycleOptions), not the 30 s default +// of the options its call builds (#646). +int secondaryStartupTimeout() { + App app(webfront::WebFrontConfig{.documentRoot = std::filesystem::current_path()}); + std::atomic showReturned{false}; + std::string failure; + std::thread host([&] { + try { + const auto executor = app.uiExecutor(); + for (int attempt = 0; attempt < 4000 && !executor.available(); ++attempt) + std::this_thread::sleep_for(std::chrono::milliseconds(5)); + constexpr std::string_view page = "second-window.html?name=editor"; + app.openSecondaryWindow(page); + std::chrono::milliseconds timeout{}; + webfront::frontend::invokeOnUIThread(executor, [&] { + auto& windows = webfront::frontend::detail::webview2::Windows::instance(); + const auto found = windows.secondary.find(std::string(page)); + if (found != windows.secondary.end()) + timeout = found->second->startupTimeout(); + }); + require(timeout == LifecycleOptions::get().startupTimeout, "The secondary window did not keep the configured startup timeout"); + } catch (const std::exception& error) { + failure = error.what(); + } + // Repeated until show() returns: a request made before the window exists reaches nothing. + while (!showReturned) { + app.requestClose(); + std::this_thread::sleep_for(std::chrono::milliseconds(50)); + } + }); + { + struct Join { + std::atomic& showReturned; + std::thread& host; + ~Join() { + showReturned = true; + host.join(); + } + } join{showReturned, host}; + app.show("second-window.html"); + } + if (!failure.empty()) + throw std::runtime_error(failure); + return 0; +} + int expectOpenFailure(std::string_view port, std::string_view diagnostic) { try { webfront::testdriver::TestFrontend::open(port, "index.html"); @@ -661,6 +707,7 @@ int run(std::string_view mode) { return startupCompletion(true); } }, {"late-navigation-failure", lateNavigationFailure}, + {"secondary-startup-timeout", secondaryStartupTimeout}, { "mta", rejectMta}, { "missing-runtime", [] { diff --git a/test/web/second-window.html b/test/web/second-window.html new file mode 100644 index 00000000..66532c51 --- /dev/null +++ b/test/web/second-window.html @@ -0,0 +1,16 @@ + + +Second window + +