diff --git a/cmake/Frontends.cmake b/cmake/Frontends.cmake index a9bfed94..a323a75f 100644 --- a/cmake/Frontends.cmake +++ b/cmake/Frontends.cmake @@ -440,8 +440,9 @@ function(webfront_add_browser_tests target frontend assets_directory lifecycle_t 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 second-window) - # A closed secondary window disconnects at once, window after window (#702); WKWebView's page outlived its window. - if(frontend STREQUAL "WKWebView") + # A closed secondary window disconnects at once, window after window: WKWebView's page outlived its window (#702), + # and WebView2's page its controller (#708). + if(frontend MATCHES "^(WKWebView|WebView2)$") list(APPEND lifecycle_modes secondary-close) endif() # CEF neither supports nor checks a secondary thread: nothing to observe there (docs/HOST_INTEGRATION.md). diff --git a/docs/CHANGELOG.md b/docs/CHANGELOG.md index b365ba3a..aa988f23 100644 --- a/docs/CHANGELOG.md +++ b/docs/CHANGELOG.md @@ -52,6 +52,7 @@ these entries stays in the GitHub releases and the Git history. ### Fixed - A closed WKWebView secondary window, or one that another window covered, no longer leaves its page suspended and connected to the application: on macOS 14+ a secondary window is never suspended while inactive (#681, `docs/WKWEBVIEW.md`). - A closed WKWebView secondary window disconnects as soon as it is released, even while the system still holds its view: its page is closed explicitly instead of when the view's last reference goes, which kept the detached inspector window connected for more than thirty seconds (#702, `docs/WKWEBVIEW.md`). +- A closed WebView2 secondary window disconnects at once: its page navigates to `about:blank` before its controller closes, instead of ending whenever the renderer of the shared environment got to it, which once kept the detached inspector window connected for more than thirty seconds (#708, `docs/WEBVIEW2.md`). - A WKWebView page whose web content process ends says why: its memory or CPU limit, the application's request, or a crash of the WebKit engine, which `DeveloperBrowserIntegration-jasmine` met on the macOS runner while esbuild ran in its Worker, instead of only that the process terminated (#706, `docs/WKWEBVIEW.md`). - `webfront.session` names the native deadline that revoked a session (`revocation`: `operation-deadline` or `startup-deadline`, empty otherwise), and `Session::revokedBy()` gives it in C++: `AutomationMcpWatchdog` no longer fails when the window closes after the deadline, since its host recognised only a reason that the deadline never wrote (#709, `docs/AUTOMATION.md`). - An invalid content policy (an origin of `bridgeAllowedOrigins` or `navigationAllowedOrigins`, a `referrerPolicy`, a `htmlCacheControl`) throws `std::invalid_argument` before the server binds its port, as documented, instead of an "address already in use" error when that port is taken (#674). diff --git a/docs/FRONTENDS.md b/docs/FRONTENDS.md index 4ceb4392..4ca04a31 100644 --- a/docs/FRONTENDS.md +++ b/docs/FRONTENDS.md @@ -213,6 +213,7 @@ Registry order determines the initial cache default: the first enabled embedded - `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`. +- `secondary-close` (#702, #708; WKWebView and WebView2): a secondary window opened and closed five times in a row disconnects each time within 3 s, and the first window stays usable. - `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. diff --git a/docs/WEBVIEW2.md b/docs/WEBVIEW2.md index 9a0bc4be..a0b0f7e9 100644 --- a/docs/WEBVIEW2.md +++ b/docs/WEBVIEW2.md @@ -12,7 +12,7 @@ This page covers what is specific to WebView2. The rules shared by every fronten The **Microsoft Edge WebView2 Evergreen Runtime** must be installed separately. If it is absent, opening throws an actionable error before creating a window. App installers can redistribute Microsoft's small online Evergreen bootstrapper or the offline Evergreen standalone installer; see [Microsoft's runtime distribution guide](https://learn.microsoft.com/en-us/microsoft-edge/webview2/concepts/distribution). Fixed-version runtime packaging is outside this adapter's scope. -Follow the [shared main-thread contract](FRONTENDS.md#the-contract). WebView2 additionally needs STA-compatible COM; an existing MTA apartment is rejected. The adapter balances COM initialisation, owns the message loop, resizes the view with its window and applies `WM_DPICHANGED`'s suggested bounds. It handles JavaScript `window.close()` and releases its controller on shutdown. Closing is idempotent; a failed controller `Close()` is reported by `show()` without replacing an earlier error. Late callbacks after the session has ended can only release their own controller references. +Follow the [shared main-thread contract](FRONTENDS.md#the-contract). WebView2 additionally needs STA-compatible COM; an existing MTA apartment is rejected. The adapter balances COM initialisation, owns the message loop, resizes the view with its window and applies `WM_DPICHANGED`'s suggested bounds. It handles JavaScript `window.close()` and releases its controller on shutdown. Closing is idempotent; a failed controller `Close()` is reported by `show()` without replacing an earlier error. Late callbacks after the session has ended can only release their own controller references. A secondary window that closes is hidden and first navigates to `about:blank`, which ends its page and the page's connection; its controller closes when that navigation completes, or after one second (#708). Closing the controller alone ends the page only when its renderer gets to it, and the renderer of the shared environment may outlive the controller. Profiles default to `%LOCALAPPDATA%/WebFront//WebView2`, so the executable directory can be read-only. The FNV-64 executable-path hash is case-sensitive: paths differing only by case can select separate profiles. Instances of the same executable share that profile. It is persistent and is not automatically deleted; select another `userDataFolder` through the options below when isolation is needed. diff --git a/include/webfront/frontend/WebView2.hpp b/include/webfront/frontend/WebView2.hpp index 802090f3..dba3ea3d 100644 --- a/include/webfront/frontend/WebView2.hpp +++ b/include/webfront/frontend/WebView2.hpp @@ -301,8 +301,11 @@ class Session : public std::enable_shared_from_this { 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; + bool secondary = false; + std::function closedHook; + // Called once when a secondary window starts to end its page (#708): the registry takes it out of its table, so that + // its page can be opened again while it closes. + std::function closingHook; std::shared_ptr captureQueue = std::make_shared(); CaptureRegistration captureRegistration; @@ -317,7 +320,8 @@ class Session : public std::enable_shared_from_this { } void navigationStarting(ICoreWebView2NavigationStartingEventArgs* args) noexcept { - if (closed) + // The navigation of an unloading window is its own to about:blank, which no content policy lists. + if (closed || unloading) return; try { LPWSTR raw = nullptr; @@ -358,6 +362,7 @@ class Session : public std::enable_shared_from_this { void close() noexcept { stopStartupTimer(); stopPresentTimer(); + stopUnloadTimer(); if (closed) return; closed = true; @@ -518,7 +523,63 @@ class Session : public std::enable_shared_from_this { // (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 { + static constexpr UINT_PTR unloadTimerId = 0x5748; + // The wParam of the WM_CLOSE that finishUnload() posts: the page has ended, the window closes now. + static constexpr WPARAM unloadedClose = 0x5748; + // The longest wait for a closing secondary window's page to end, after which it closes all the same. + static constexpr UINT unloadMilliseconds = 1000; + bool unloading = false; + UINT_PTR unloadTimer = 0; + + /** + * A secondary window ends its page before its controller (#708). The controller's Close() releases the view, but + * the page, and with it its WebSocket, ends only when its renderer gets to it: the renderer of the shared environment + * may outlive the controller, and a closed inspector window then stayed connected for more than thirty seconds. + * Navigating to about:blank unloads the document, which closes its connections, at once. The window is hidden + * meanwhile; it closes when about:blank completes, or after unloadMilliseconds. False when the window closes at once: + * the first window (its process ends its pages), a window that failed or has no view, or a navigation refused. + */ + bool beginUnload() noexcept { + if (!secondary || closed || failure || !hasLiveController() || !view || !window) + return false; + try { + unloading = true; + ShowWindow(window, SW_HIDE); + unloadTimer = SetTimer(window, unloadTimerId, unloadMilliseconds, nullptr); + if (!unloadTimer) + throw std::runtime_error("WebView2: cannot start the unload delay"); + check(view->Navigate(L"about:blank"), "unloading the page of a closing window"); + trace("unloading"); + if (closingHook) { + auto hook = std::exchange(closingHook, {}); + try { + hook(); + } catch (...) { } + } + return true; + } catch (...) { + stopUnloadTimer(); + return false; // closed at once, as before + } + } + void finishUnload() noexcept { + stopUnloadTimer(); + if (window) + PostMessageW(window, WM_CLOSE, unloadedClose, 0); + } + void stopUnloadTimer() noexcept { + if (unloadTimer && window) + KillTimer(window, unloadTimer); + unloadTimer = 0; + } + bool showsBlankPage() const noexcept { + LPWSTR raw = nullptr; + if (!view || FAILED(view->get_Source(&raw)) || !raw) + return false; + const std::unique_ptr source(raw, CoTaskMemFree); + return std::wstring_view{source.get()} == L"about:blank"; + } + void stopPresentTimer() noexcept { if (presentTimer && window) KillTimer(window, presentTimer); presentTimer = 0; @@ -646,7 +707,7 @@ class Session : public std::enable_shared_from_this { } void processFailed(ICoreWebView2ProcessFailedEventArgs* args) noexcept { - if (closed) + if (closed || unloading) // the page is being ended on purpose: its process may go with it return; try { COREWEBVIEW2_PROCESS_FAILED_KIND kind{}; @@ -672,6 +733,12 @@ class Session : public std::enable_shared_from_this { } void navigationCompleted(ICoreWebView2NavigationCompletedEventArgs* args) noexcept { + if (!closed && unloading) { + // An earlier navigation that the unloading one cancelled also completes: only about:blank ends the window. + if (showsBlankPage()) + finishUnload(); + return; + } if (closed || !initialNavigationPending) return; try { @@ -739,7 +806,7 @@ class Session : public std::enable_shared_from_this { throw std::runtime_error("WebView2: cannot apply DPI window bounds"); } - bool handleWindowMessage(HWND handle, UINT message, LPARAM lParam) { + bool handleWindowMessage(HWND handle, UINT message, WPARAM wParam, LPARAM lParam) { switch (message) { case WM_DPICHANGED: applyDpiBounds(handle, lParam); @@ -763,6 +830,10 @@ class Session : public std::enable_shared_from_this { reapSecondaryWindows(); return true; case WM_CLOSE: + // A secondary window first ends its page (#708); the WM_CLOSE of finishUnload() then closes it. Any + // other WM_CLOSE meanwhile (the user, requestClose(), a failure) waits for that one. + if (unloading ? wParam != unloadedClose : beginUnload()) + return true; close(); DestroyWindow(handle); return true; @@ -787,6 +858,11 @@ class Session : public std::enable_shared_from_this { self->secondaryStartupTimedOut(); return 0; } + if (self && message == WM_TIMER && wParam == unloadTimerId && self->unloadTimer) { + self->trace("unload delay expired"); + self->finishUnload(); + return 0; + } if (self && message == WM_TIMER && wParam == presentTimerId && self->presentTimer) { self->trace("present delay expired"); self->presentWindow(); @@ -794,7 +870,7 @@ class Session : public std::enable_shared_from_this { } if (self) { try { - if (self->handleWindowMessage(handle, message, lParam)) + if (self->handleWindowMessage(handle, message, wParam, lParam)) return 0; } catch (...) { self->fail(); @@ -1039,7 +1115,9 @@ struct WindowHooks { 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 + // The same thread: the window is closed and retired when this returns, or, for a secondary window whose page + // ends first (#708), hidden and closed within Session::unloadMilliseconds. + SendMessageW(session.window, WM_CLOSE, 0, 0); return true; } }; diff --git a/include/webfront/frontend/WindowRegistry.hpp b/include/webfront/frontend/WindowRegistry.hpp index 6bca5ebe..ff30131f 100644 --- a/include/webfront/frontend/WindowRegistry.hpp +++ b/include/webfront/frontend/WindowRegistry.hpp @@ -15,6 +15,7 @@ #include "NativeWindow.hpp" #include "UIExecutor.hpp" +#include #include #include #include @@ -34,6 +35,9 @@ namespace webfront::frontend::detail { * * `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. + * A window that closes in two steps (WebView2 ends its page first, #708) also has a `std::function closingHook`, + * which it calls once when the first step starts: the window leaves the table at once, so that its page can be opened + * again, and stays alive until its closedHook. * * `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; @@ -45,24 +49,50 @@ namespace webfront::frontend::detail { */ template class WindowRegistry { + // Its hooks no longer reach the registry: the session is destroyed with it. + static void forget(Session& session) { + session.closedHook = nullptr; + if constexpr (requires { session.closingHook; }) + session.closingHook = nullptr; + } + public: /// The first window, `nullptr` when none runs. Session* primary = nullptr; std::map> secondary; std::vector> finished; // closed, destroyed by reap() + std::vector> closing; // out of the table, closing: kept until their closedHook 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()) + /// The session `which` started to close in two steps (its closingHook): it leaves the table, so that a new open() of + /// its page creates another window, and is kept until it closes. + void detach(const Session* which) { + for (auto entry = secondary.begin(); entry != secondary.end(); ++entry) + if (entry->second.get() == which) { + closing.push_back(std::move(entry->second)); + secondary.erase(entry); + return; + } + } + + /// The session `which`, showing `page`, closed (its closedHook): takes it out of the table, or out of the closing + /// windows, reports why it failed, and reaps it later. Found by identity: a window opened since for the same page stays. + void retire(const std::string& page, const Session* which) { + std::shared_ptr session; + if (const auto found = secondary.find(page); found != secondary.end() && found->second.get() == which) { + session = std::move(found->second); + secondary.erase(found); + } else if (const auto ending = std::ranges::find(closing, which, &std::shared_ptr::get); ending != closing.end()) { + session = std::move(*ending); + closing.erase(ending); + } else 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) { + if (session->failure) { try { - std::rethrow_exception(found->second->failure); + std::rethrow_exception(session->failure); } catch (const std::exception& error) { std::fprintf(stderr, "%.*s: the secondary window of '%s' closed: %s\n", @@ -72,8 +102,7 @@ class WindowRegistry { error.what()); } catch (...) { } } - finished.push_back(std::move(found->second)); - secondary.erase(found); + finished.push_back(std::move(session)); hooks.scheduleReap(*this); } @@ -91,10 +120,15 @@ class WindowRegistry { hooks.cancelReap(); auto windows = std::move(secondary); secondary.clear(); + auto ending = std::move(closing); + closing.clear(); for (auto& entry : windows) - entry.second->closedHook = nullptr; + forget(*entry.second); + for (auto& session : ending) + forget(*session); finished.clear(); windows.clear(); + ending.clear(); primary = nullptr; clearing = false; } @@ -126,9 +160,13 @@ class WindowRegistry { 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); + session->closedHook = [this, page, which = session.get()] { + retire(page, which); }; + if constexpr (requires { session->closingHook; }) + session->closingHook = [this, which = session.get()] { + detach(which); + }; 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. @@ -141,7 +179,8 @@ class WindowRegistry { return true; } - /// On the interface thread: asks the secondary window showing `page` to close, as its user would. False when there is none. + /// On the interface thread: asks the secondary window showing `page` to close, as its user would. False when there is + /// none (a window that closes in two steps is no longer there once the first step started). bool close(const std::string& page) { const auto found = secondary.find(page); if (found == secondary.end() || found->second->closed) diff --git a/test/cmake/CheckFrontendSelection.cmake b/test/cmake/CheckFrontendSelection.cmake index 72860055..0fca0982 100644 --- a/test/cmake/CheckFrontendSelection.cmake +++ b/test/cmake/CheckFrontendSelection.cmake @@ -437,7 +437,7 @@ foreach(case webkitgtk-display webkitgtk-linux cef-linux cef-macos cef-windows c continue() endif() if(case STREQUAL "webview2-windows") - set(expected_count 19) # with StartupTime-cold and -warm (#611) + set(expected_count 20) # with StartupTime-cold and -warm (#611), and secondary-close (#708) elseif(case STREQUAL "extension") set(expected_count 17) # an engine without STARTUP_TRACE has no start-up case elseif(case STREQUAL "cef-linux") diff --git a/test/unit/WindowRegistryTests.cpp b/test/unit/WindowRegistryTests.cpp index aea01815..326ee82d 100644 --- a/test/unit/WindowRegistryTests.cpp +++ b/test/unit/WindowRegistryTests.cpp @@ -21,6 +21,7 @@ #include #include #include +#include #include using namespace webfront::bdd; @@ -36,6 +37,7 @@ struct FakeSession { bool closed = false; std::exception_ptr failure; std::function closedHook; + std::function closingHook; // a window that closes in two steps (#708) bool inCallback = false; // true while its own closedHook runs bool closeOnStart = false; std::exception_ptr failOnStart; @@ -48,7 +50,7 @@ struct FakeSession { destroyProbe(); if (inCallback) events.push_back("destroyed in its own callback"); - if (closedHook) + if (closedHook || closingHook) events.push_back("hook still set " + page); } void start() { @@ -72,6 +74,7 @@ struct FakeHooks { static constexpr std::string_view name = "FakeFrontend"; int reapsScheduled = 0; bool canClose = true; + bool twoSteps = false; // close() only starts closing, as WebView2 ending its page template void scheduleReap(Registry&) { @@ -88,7 +91,11 @@ struct FakeHooks { events.push_back("close " + session.page); if (!canClose) return false; - session.close(); + if (twoSteps) { + if (session.closingHook) + std::exchange(session.closingHook, {})(); + } else + session.close(); return true; } }; @@ -173,6 +180,41 @@ const Scenario secondaryWindowRegistry{ }); }); + when("a window closes in two steps (#708)", [&] { + openPage(windows, "a.html"); + auto* const old = windows.secondary.at("a.html").get(); + windows.hooks.twoSteps = true; + require(windows.close("a.html")); + then("it leaves the table at once and is kept until it closes", [&] { + check(windows.secondary.empty()); + check(windows.closing.size() == 1); + check(!happened("destroy a.html")); + check(!windows.close("a.html")); + }); + andWhen("its page is opened again before it closed, then it closes", [&] { + openPage(windows, "a.html"); + auto* const fresh = windows.secondary.at("a.html").get(); + old->close(); + then("the new window stays, and only the old one is reaped", [&] { + check(std::ranges::count(events, "create a.html") == 2); + check(windows.secondary.size() == 1 && windows.secondary.at("a.html").get() == fresh); + check(windows.closing.empty() && windows.finished.size() == 1); + windows.reap(); + check(std::ranges::count(events, "destroy a.html") == 1); + check(!happened("destroyed in its own callback")); + }); + }); + andWhen("the first window ends before it closed", [&] { + events.clear(); + windows.clear(); + then("it is destroyed with its hooks cleared", [&] { + check(happened("destroy a.html")); + check(!happened("hook still set a.html")); + check(windows.closing.empty()); + }); + }); + }); + when("a window closes by itself while it starts", [&] { then("the caller learns why, and the page is not registered", [&] { checkThrows(