From 959679fd8f5419cef82509217687947013417260 Mon Sep 17 00:00:00 2001 From: Ambroise Leclerc Date: Thu, 29 Oct 2026 22:33:17 +0100 Subject: [PATCH 1/2] Add NativeOrBrowserFrontend and nativeWebViewAvailable [#398] A native window when the platform engine is compiled in and a session exists, the system browser otherwise, with the reason printed once. Frontends may define closeServerAfterOpen() to override action at run time. The Life examples now use it instead of WEBFRONT_LIFE_NATIVE_WINDOW. --- README.md | 4 +- docs/CHANGELOG.md | 6 ++ docs/FRONTENDS.md | 18 ++++ examples/CMakeLists.txt | 17 +-- examples/life/LifeDeveloper.cpp | 2 - examples/life/LifeEmbedded.cpp | 2 - examples/life/LifeFrontend.hpp | 16 +-- include/webfront/WebFront.hpp | 4 +- include/webfront/frontend/Frontend.hpp | 107 +++++++++++++++++++ include/webfront/frontend/NativeWebView.hpp | 14 +++ test/cmake/native-autodetect/CMakeLists.txt | 4 - test/unit/WebFrontTests.cpp | 108 ++++++++++++++++++++ 12 files changed, 266 insertions(+), 36 deletions(-) diff --git a/README.md b/README.md index fab4f3f8..098f125e 100644 --- a/README.md +++ b/README.md @@ -243,7 +243,7 @@ app.show(); Recompilation is explicit. The resulting application runs offline without the project directory, developer callbacks or downloaded tool cache. The selected native engine's deployment requirements still apply; this is not an application installer. -The examples' [LifeFrontend.hpp](examples/life/LifeFrontend.hpp) selects the native engine or the default browser for both stages. +The examples' [LifeFrontend.hpp](examples/life/LifeFrontend.hpp) selects `NativeOrBrowserFrontend` for both stages: a native window when the engine is built and a session exists, the default browser otherwise. Your own application can select `webfront::NativeApp` or `webfront::NativeAppWithAssets` explicitly when it requires a native window. ## Use WebFront in your project @@ -281,6 +281,8 @@ int main() { } ``` +To get a native window when one can be opened and the system browser otherwise (for example over SSH, in a container or in CI, where no display exists), use `WebFrontWithFrontend`: no `#if` is needed, and the reason for a fallback is printed once. See [docs/FRONTENDS.md](docs/FRONTENDS.md). + Native engines are detected by default for consumer builds, whatever variables the parent project defines, and for standalone builds except with `ENABLE_TESTING=ON` or `ENABLE_FUZZING=ON`. The helper applies the native engine's target setup and defines `WEBFRONT_NATIVE_WINDOW` only when that engine is enabled; otherwise CMake prints installation advice and the application uses the default browser. On Windows, detection requires an MSVC-compatible compiler and downloads the pinned WebView2 SDK; the Evergreen runtime must be installed separately. Linux needs WebKitGTK 6.0 development files, and macOS needs Clang and macOS 13.3 or later. Explicit `WEBFRONT_EMBED_=ON|OFF` values take precedence; `WEBFRONT_AUTODETECT_NATIVE=OFF` disables detection. No option needs to be set before `add_subdirectory`/CPM for the default path. For explicit engine selection, `webfront_native_frontend_option(out)` and `webfront_setup_frontends_for_target(MyApp)` are also callable from the parent or other directories. The latter applies setup for all enabled engines; the native helper selects only the platform's native engine and never CEF. See [WKWebView](docs/WKWEBVIEW.md), [WebKitGTK](docs/WEBKITGTK.md) and the [frontend architecture](docs/adr/README.md). diff --git a/docs/CHANGELOG.md b/docs/CHANGELOG.md index f960393c..f5e53925 100644 --- a/docs/CHANGELOG.md +++ b/docs/CHANGELOG.md @@ -2,6 +2,12 @@ ## Unreleased +- Add `frontend::nativeWebViewAvailable` and `frontend::NativeOrBrowserFrontend` (#398): a native + window when the platform engine is compiled in and a session exists, the system browser otherwise, + with the reason printed once and available from `fallbackReason()`. An application needs neither a + `WEBFRONT_EMBED_*` macro nor a second application type. A frontend may define an optional + `static bool closeServerAfterOpen()` to override its `action` at run time. + - Accept ADR-019 for the delivered local automation contract, shared window and native grants, with consumer Jasmine coverage, the five-model qualification and the final PR #407 CI evidence. Record the remaining distribution publication gate and deferred remote/browser transports. diff --git a/docs/FRONTENDS.md b/docs/FRONTENDS.md index fe6aa8c1..ec0ce847 100644 --- a/docs/FRONTENDS.md +++ b/docs/FRONTENDS.md @@ -99,6 +99,24 @@ their own CTest timeouts. WKWebView adds native main-thread, Quit/closure, repeated-opening, initial HTTP failure, stalled-loading deadline and data-store/inspector/menu tests. See [WKWebView verification](WKWEBVIEW.md#unattended-verification). +## Native window with browser fallback + +`frontend::nativeWebViewAvailable` is `true` when this platform's native engine is compiled in. It says +nothing about the session. `frontend::NativeOrBrowserFrontend` decides at run time: its `initialize()` +tries the native engine and, if that throws (engine not compiled in, no `DISPLAY`/`WAYLAND_DISPLAY`, +missing runtime), it uses the system browser for the whole process and prints the reason once to +`std::cerr`. `fallbackReason()` returns that reason and `usesNativeWindow()` tells which path was taken +once the application is constructed. + +```cpp +using App = webfront::WebFrontWithFrontend; +``` + +A native window stops the server when it closes; the browser path leaves it running until Enter, as +`DefaultBrowserFrontend` does. Because `action` is `constexpr`, the frontend reports this through the +optional `closeServerAfterOpen()` hook, which `show()` consults after `open()` returns. +`NativeOrBrowserFrontendFor` composes any two frontends the same way. + ## Direct engine access Every frontend currently loads its page over HTTP and exchanges bridge messages over a WebSocket. [ADR-017](adr/ADR-017-acces-direct-aux-frontends.md) diff --git a/examples/CMakeLists.txt b/examples/CMakeLists.txt index bdd058f3..3a8ce401 100644 --- a/examples/CMakeLists.txt +++ b/examples/CMakeLists.txt @@ -1,14 +1,14 @@ # Only two examples: the minimal application and the successive Game of Life stages. include(Frontends) -# The Life examples use the native window when its engine is built and otherwise fall back to the system browser, -# which needs no dependency: a missing engine is explained here, never an error. +# The Life examples use NativeOrBrowserFrontend: the native window when its engine is built and a session exists, +# the system browser otherwise. A missing engine is explained here, never an error. webfront_native_frontend_option(WEBFRONT_LIFE_NATIVE_OPTION) set(WEBFRONT_LIFE_NATIVE_WINDOW OFF) if(WEBFRONT_LIFE_NATIVE_OPTION) if(${WEBFRONT_LIFE_NATIVE_OPTION}) set(WEBFRONT_LIFE_NATIVE_WINDOW ON) - endif() +endif() endif() if(NOT WEBFRONT_LIFE_NATIVE_WINDOW) webfront_native_window_advice(_life_advice) @@ -18,12 +18,6 @@ if(NOT WEBFRONT_LIFE_NATIVE_WINDOW) " ${_life_advice}\n" " CEF (-DWEBFRONT_EMBED_CEF=ON) makes CEFFrontend available to your own applications; the examples do not select it.") endif() -# Select the same frontend for the developer and embedded Life stages. -function(webfront_life_frontend target) - if(WEBFRONT_LIFE_NATIVE_WINDOW) - target_compile_definitions(${target} PRIVATE WEBFRONT_LIFE_NATIVE_WINDOW) - endif() -endfunction() add_executable(HelloWorld hello-world/HelloWorld.cpp) target_link_libraries(HelloWorld PRIVATE WebFront WebFront_warnings WebFront_options) @@ -36,21 +30,18 @@ target_link_libraries(WebFrontLifeConsole PRIVATE WebFront_warnings WebFront_opt add_executable(WebFrontLifeDeveloper life/LifeDeveloper.cpp) target_link_libraries(WebFrontLifeDeveloper PRIVATE WebFront WebFront_warnings WebFront_options) webfront_setup_frontends_for_target(WebFrontLifeDeveloper) -webfront_life_frontend(WebFrontLifeDeveloper) add_executable(WebFrontLifeReact life/react/LifeReact.cpp) target_link_libraries(WebFrontLifeReact PRIVATE WebFront WebFront_warnings WebFront_options) webfront_setup_frontends_for_target(WebFrontLifeReact) -webfront_life_frontend(WebFrontLifeReact) set(WEBFRONT_LIFE_ASSETS "" CACHE FILEPATH "LifeUI.hpp generated by wf embed (enables the offline Life example)") if(WEBFRONT_LIFE_ASSETS) if(NOT EXISTS "${WEBFRONT_LIFE_ASSETS}") message(FATAL_ERROR "WEBFRONT_LIFE_ASSETS must name an existing LifeUI.hpp generated by wf embed") - endif() +endif() add_executable(WebFrontLifeEmbedded life/LifeEmbedded.cpp) target_link_libraries(WebFrontLifeEmbedded PRIVATE WebFront WebFront_warnings WebFront_options) target_compile_definitions(WebFrontLifeEmbedded PRIVATE WEBFRONT_LIFE_ASSETS_HEADER="${WEBFRONT_LIFE_ASSETS}") webfront_setup_frontends_for_target(WebFrontLifeEmbedded) - webfront_life_frontend(WebFrontLifeEmbedded) endif() diff --git a/examples/life/LifeDeveloper.cpp b/examples/life/LifeDeveloper.cpp index e229fffa..c369f40f 100644 --- a/examples/life/LifeDeveloper.cpp +++ b/examples/life/LifeDeveloper.cpp @@ -15,8 +15,6 @@ int main(int argc, char** argv) { } try { webfront::demo::prepareLifeProject(options->project); - if constexpr (!webfront::demo::lifeNativeWindow) - std::cerr << webfront::demo::browserNotice << '\n'; webfront::demo::LifeApp app{options->project}; app.cppFunction("life.step", &webfront::demo::nextLife); if (!options->environment) diff --git a/examples/life/LifeEmbedded.cpp b/examples/life/LifeEmbedded.cpp index 3d217d0b..c1484f84 100644 --- a/examples/life/LifeEmbedded.cpp +++ b/examples/life/LifeEmbedded.cpp @@ -7,8 +7,6 @@ int main() { try { - if constexpr (!webfront::demo::lifeNativeWindow) - std::cerr << webfront::demo::browserNotice << '\n'; webfront::demo::LifeAppWithAssets app; app.cppFunction("life.step", &webfront::demo::nextLife); app.show(); diff --git a/examples/life/LifeFrontend.hpp b/examples/life/LifeFrontend.hpp index fe74e8a5..65909e45 100644 --- a/examples/life/LifeFrontend.hpp +++ b/examples/life/LifeFrontend.hpp @@ -5,23 +5,13 @@ namespace webfront::demo { -// examples/CMakeLists.txt defines WEBFRONT_LIFE_NATIVE_WINDOW when this platform's native engine is built. -// Otherwise the Life examples open the system browser, which needs no extra dependency. -#if defined(WEBFRONT_LIFE_NATIVE_WINDOW) -using LifeFrontend = frontend::NativeWebViewFrontend; -inline constexpr bool lifeNativeWindow = true; -#else -using LifeFrontend = frontend::DefaultBrowserFrontend; -inline constexpr bool lifeNativeWindow = false; -#endif +// A native window when this platform's engine is built and a session exists, the system browser otherwise +// (no engine, SSH, container, CI). The reason for a fallback is printed once by the frontend. +using LifeFrontend = frontend::NativeOrBrowserFrontend; using LifeApp = BasicDeveloperApp; template using LifeAppWithAssets = BasicWF, http::DefaultBuffersPolicy, LifeFrontend>; -inline constexpr const char* browserNotice = - "No native window engine was built: the default browser is opened instead. For a native window, install the " - "engine for your platform and run cmake again (see the README)."; - } // namespace webfront::demo diff --git a/include/webfront/WebFront.hpp b/include/webfront/WebFront.hpp index 50aff29f..cc363880 100644 --- a/include/webfront/WebFront.hpp +++ b/include/webfront/WebFront.hpp @@ -563,7 +563,9 @@ class BasicWF { Frontend::open(httpAddress, httpPort, htmlFilename); else Frontend::open(httpPort, htmlFilename); - if constexpr (Frontend::action == frontend::Action::closeServerAfterOpen) + if constexpr (requires { Frontend::closeServerAfterOpen(); }) + return Frontend::closeServerAfterOpen() ? WindowAction::closeWindow : WindowAction::none; + else if constexpr (Frontend::action == frontend::Action::closeServerAfterOpen) return WindowAction::closeWindow; else return WindowAction::none; diff --git a/include/webfront/frontend/Frontend.hpp b/include/webfront/frontend/Frontend.hpp index 6c014b26..dc228e23 100644 --- a/include/webfront/frontend/Frontend.hpp +++ b/include/webfront/frontend/Frontend.hpp @@ -12,6 +12,11 @@ #include #include +#include +#include +#include +#include +#include #include #include @@ -36,6 +41,7 @@ namespace webfront::frontend { * diagnostic naming its enabling CMake option. ContentPolicy rules and adapter capabilities * are documented in docs/CONTENT_POLICY.md. * An optional open(address, port, file, policy, window) overload also receives the application's WindowOptions. + * An optional static bool closeServerAfterOpen() overrides `action` at run time (NativeOrBrowserFrontend). * An optional open(address, port, file) overload receives the configured address; build URLs with * detail::applicationUrl() so all frontends preserve the same URI-reference semantics. */ @@ -95,6 +101,107 @@ struct CEFFrontend { } }; +namespace detail { + +#if defined(_WIN32) || defined(__APPLE__) || defined(__linux__) +using PlatformNativeFrontend = NativeWebViewFrontend; +#else +// No native engine exists on this platform: the fallback always takes the browser. +struct PlatformNativeFrontend { + static constexpr Action action{Action::closeServerAfterOpen}; + + static void initialize() { + throw std::runtime_error("no native web view exists for this platform"); + } + static void open(std::string_view, std::string_view) { + initialize(); + } +}; +#endif + +// Calls the richest open() the frontend offers, as BasicWF does. +template +void openWith(std::string_view address, std::string_view port, std::string_view file, const ContentPolicy& policy, const WindowOptions& window) { + if constexpr (requires { Frontend::open(address, port, file, policy, window); }) + Frontend::open(address, port, file, policy, window); + else if constexpr (requires { Frontend::open(address, port, file, policy); }) + Frontend::open(address, port, file, policy); + else if constexpr (requires { Frontend::open(address, port, file); }) + Frontend::open(address, port, file); + else + Frontend::open(port, file); +} + +} // namespace detail + +/** + * @brief A native window when one can be opened, the system browser otherwise. + * + * initialize() tries Native::initialize(); if it throws (engine not compiled in, no display, missing runtime), the + * frontend remembers the reason, prints it once to std::cerr and uses Browser for the whole process. The decision is + * per frontend type and made once, like every initialize(). Applications need neither a WEBFRONT_EMBED_* macro nor a + * second application type. + * + * `action` is that of the native window; the browser path is reported at run time through closeServerAfterOpen(), + * which the application consults after open() returns. + */ +template +struct NativeOrBrowserFrontendFor { + static constexpr Action action{Native::action}; + + /// Why the browser is used, or nullopt when the native window is. Meaningful after initialize(). + [[nodiscard]] static std::optional fallbackReason() { + return state().reason; + } + [[nodiscard]] static bool usesNativeWindow() { + return !state().reason.has_value(); + } + /// Whether the server stops once open() returns: true for a native window, false for the browser. + [[nodiscard]] static bool closeServerAfterOpen() { return usesNativeWindow() && Native::action == Action::closeServerAfterOpen; } + + static void initialize() { + auto& s = state(); + s.reason.reset(); + try { + Native::initialize(); + } catch (const std::exception& e) { + s.reason = e.what(); + } + if (s.reason) + std::cerr << "WebFront: opening the system browser instead of a native window: " << *s.reason << std::endl; + } + + static void open(std::string_view port, std::string_view file) { + if (usesNativeWindow()) + Native::open(port, file); + else + Browser::open(port, file); + } + static void open(std::string_view address, std::string_view port, std::string_view file) { + open(address, port, file, ContentPolicy{}, WindowOptions{}); + } + static void open(std::string_view address, std::string_view port, std::string_view file, const ContentPolicy& policy) { + open(address, port, file, policy, WindowOptions{}); + } + static void open(std::string_view address, std::string_view port, std::string_view file, const ContentPolicy& policy, const WindowOptions& window) { + if (usesNativeWindow()) + detail::openWith(address, port, file, policy, window); + else + detail::openWith(address, port, file, policy, window); + } + +private: + struct State { + std::optional reason; + }; + static State& state() { + static State instance; + return instance; + } +}; + +using NativeOrBrowserFrontend = NativeOrBrowserFrontendFor; + // WEBFRONT_EMBED_CEF only means "CEF is available"; it never changes which frontend // plain WebFront selects. Applications opt into CEF explicitly via WebFrontWithFrontend. using DefaultFrontend = DefaultBrowserFrontend; diff --git a/include/webfront/frontend/NativeWebView.hpp b/include/webfront/frontend/NativeWebView.hpp index 6bfb3f4a..3598937a 100644 --- a/include/webfront/frontend/NativeWebView.hpp +++ b/include/webfront/frontend/NativeWebView.hpp @@ -11,6 +11,20 @@ // Other platforms have no native alias; their applications can select another frontend. namespace webfront::frontend { +/** + * @brief True when this platform's native web view engine is compiled in (WEBFRONT_EMBED_WEBKITGTK on Linux, + * WEBFRONT_EMBED_WEBVIEW2 on Windows, WEBFRONT_EMBED_WKWEBVIEW on macOS). + * + * It says nothing about the session: a native window can still fail at run time, for instance without a display. + * NativeOrBrowserFrontend handles that case. + */ +#if (defined(_WIN32) && defined(WEBFRONT_EMBED_WEBVIEW2)) || (defined(__APPLE__) && defined(WEBFRONT_EMBED_WKWEBVIEW)) \ + || (defined(__linux__) && defined(WEBFRONT_EMBED_WEBKITGTK)) +inline constexpr bool nativeWebViewAvailable = true; +#else +inline constexpr bool nativeWebViewAvailable = false; +#endif + #if defined(_WIN32) /** @brief Opt-in Windows web view; availability and options are those of WebView2Frontend. */ using NativeWebViewFrontend = WebView2Frontend; diff --git a/test/cmake/native-autodetect/CMakeLists.txt b/test/cmake/native-autodetect/CMakeLists.txt index 96016bf4..d7483c09 100644 --- a/test/cmake/native-autodetect/CMakeLists.txt +++ b/test/cmake/native-autodetect/CMakeLists.txt @@ -19,8 +19,4 @@ if(TEST_EXAMPLES) function(webfront_setup_frontends_for_target target) endfunction() add_subdirectory("${ROOT}/examples" examples) - get_target_property(definitions WebFrontLifeDeveloper COMPILE_DEFINITIONS) - if("WEBFRONT_LIFE_NATIVE_WINDOW" IN_LIST definitions) - message(FATAL_ERROR "An unsupported platform must use the default browser") - endif() endif() diff --git a/test/unit/WebFrontTests.cpp b/test/unit/WebFrontTests.cpp index 96854b86..1e8afd76 100644 --- a/test/unit/WebFrontTests.cpp +++ b/test/unit/WebFrontTests.cpp @@ -11,9 +11,12 @@ #include #include #include +#include #include +#include #include #include +#include #include #include #include @@ -366,6 +369,111 @@ SCENARIO("The frontend contract: open() runs on the calling thread and a closing } } +struct FallbackNativeWindow { + static inline bool displayAvailable = true; + static inline int openCalls = 0; + static constexpr frontend::Action action{frontend::Action::closeServerAfterOpen}; + static void initialize() { + if (!displayAvailable) + throw std::runtime_error("cannot open a display; set DISPLAY or WAYLAND_DISPLAY"); + } + static void open(std::string_view, std::string_view) { ++openCalls; } +}; + +struct FallbackBrowser { + static inline int openCalls = 0; + static constexpr frontend::Action action{frontend::Action::keepServerRunning}; + static void initialize() {} + static void open(std::string_view, std::string_view) { ++openCalls; } +}; + +SCENARIO("Native window or browser, decided at run time") { + using Fallback = frontend::NativeOrBrowserFrontendFor; + STATIC_REQUIRE(frontend::FrontendType); + STATIC_REQUIRE(frontend::FrontendType); + STATIC_REQUIRE(std::is_same_v::FrontendProvider, frontend::NativeOrBrowserFrontend>); + + GIVEN("a native window that can open") { + FallbackNativeWindow::displayAvailable = true; + FallbackNativeWindow::openCalls = 0; + FallbackBrowser::openCalls = 0; + Fallback::initialize(); + THEN("the native window is used and closing it stops the server") { + REQUIRE(Fallback::usesNativeWindow()); + REQUIRE_FALSE(Fallback::fallbackReason().has_value()); + REQUIRE(Fallback::closeServerAfterOpen()); + Fallback::open("127.0.0.1", "9200", "index.html"); + REQUIRE(FallbackNativeWindow::openCalls == 1); + REQUIRE(FallbackBrowser::openCalls == 0); + } + } + GIVEN("a session without a display") { + FallbackNativeWindow::displayAvailable = false; + FallbackNativeWindow::openCalls = 0; + FallbackBrowser::openCalls = 0; + std::ostringstream captured; + auto* const previous = std::cerr.rdbuf(captured.rdbuf()); + Fallback::initialize(); + std::cerr.rdbuf(previous); + THEN("the browser is used, the reason is kept and printed, and the server keeps running") { + REQUIRE_FALSE(Fallback::usesNativeWindow()); + REQUIRE(Fallback::fallbackReason().value_or("").find("display") != std::string::npos); + REQUIRE(captured.str().find("opening the system browser instead of a native window") != std::string::npos); + REQUIRE_FALSE(Fallback::closeServerAfterOpen()); + Fallback::open("127.0.0.1", "9200", "index.html"); + REQUIRE(FallbackNativeWindow::openCalls == 0); + REQUIRE(FallbackBrowser::openCalls == 1); + } + THEN("an application falling back does not stop the server after open()") { + using App = BasicWFWithFrontend; + App app("9203"); + const auto previousStopCalls = WebFrontIoContextMock::stopCalls.load(); + app.show(); + REQUIRE(FallbackBrowser::openCalls == 1); + REQUIRE(WebFrontIoContextMock::stopCalls.load() == previousStopCalls); + } + } +#if defined(__linux__) && defined(WEBFRONT_EMBED_WEBKITGTK) + GIVEN("the real WebKitGTK engine and no DISPLAY or WAYLAND_DISPLAY") { + const char* const display = std::getenv("DISPLAY"); + const char* const wayland = std::getenv("WAYLAND_DISPLAY"); + const std::string savedDisplay = display ? display : ""; + const std::string savedWayland = wayland ? wayland : ""; + unsetenv("DISPLAY"); + unsetenv("WAYLAND_DISPLAY"); + std::ostringstream captured; + auto* const previous = std::cerr.rdbuf(captured.rdbuf()); + frontend::NativeOrBrowserFrontend::initialize(); + std::cerr.rdbuf(previous); + if (display) + setenv("DISPLAY", savedDisplay.c_str(), 1); + if (wayland) + setenv("WAYLAND_DISPLAY", savedWayland.c_str(), 1); + THEN("the frontend falls back to the browser and names the missing display") { + REQUIRE_FALSE(frontend::NativeOrBrowserFrontend::usesNativeWindow()); + REQUIRE(frontend::NativeOrBrowserFrontend::fallbackReason().value_or("").find("display") != std::string::npos); + } + } +#endif +} + +SCENARIO("The native engine availability is a constant") { + STATIC_REQUIRE(std::is_same_v); +#if defined(__linux__) && defined(WEBFRONT_EMBED_WEBKITGTK) + STATIC_REQUIRE(frontend::nativeWebViewAvailable); +#elif defined(__linux__) + STATIC_REQUIRE_FALSE(frontend::nativeWebViewAvailable); + THEN("without an engine the fallback frontend always uses the browser") { + std::ostringstream captured; + auto* const previous = std::cerr.rdbuf(captured.rdbuf()); + frontend::NativeOrBrowserFrontend::initialize(); + std::cerr.rdbuf(previous); + REQUIRE_FALSE(frontend::NativeOrBrowserFrontend::usesNativeWindow()); + REQUIRE(frontend::NativeOrBrowserFrontend::fallbackReason().value_or("").find("WEBFRONT_EMBED_WEBKITGTK") != std::string::npos); + } +#endif +} + SCENARIO("The frontend contract: a failing open() stops the server whatever its action") { GIVEN("a frontend that only launches an external program and fails to do so") { using App = BasicWFWithFrontend; From 1ddf5554fec4cfae30f3868db5aa9a3b263aed6f Mon Sep 17 00:00:00 2001 From: Ambroise Leclerc Date: Thu, 29 Oct 2026 22:55:45 +0100 Subject: [PATCH 2/2] Address review of NativeOrBrowserFrontend [#398] Initialize the browser frontend on fallback, avoid the constant comparison flagged by MSVC (C6326), run the real WebKitGTK no-display test in a child process, restore the CMake indentation, and document that only initialize() triggers the fallback. --- docs/FRONTENDS.md | 5 +-- examples/CMakeLists.txt | 4 +-- include/webfront/frontend/Frontend.hpp | 19 ++++++++--- test/unit/WebFrontTests.cpp | 44 ++++++++++++++++---------- 4 files changed, 47 insertions(+), 25 deletions(-) diff --git a/docs/FRONTENDS.md b/docs/FRONTENDS.md index ec0ce847..5f0c2c71 100644 --- a/docs/FRONTENDS.md +++ b/docs/FRONTENDS.md @@ -104,8 +104,9 @@ deadline and data-store/inspector/menu tests. See [WKWebView verification](WKWEB `frontend::nativeWebViewAvailable` is `true` when this platform's native engine is compiled in. It says nothing about the session. `frontend::NativeOrBrowserFrontend` decides at run time: its `initialize()` tries the native engine and, if that throws (engine not compiled in, no `DISPLAY`/`WAYLAND_DISPLAY`, -missing runtime), it uses the system browser for the whole process and prints the reason once to -`std::cerr`. `fallbackReason()` returns that reason and `usesNativeWindow()` tells which path was taken +missing runtime), it initializes the browser frontend and uses the system browser for the whole process and prints the reason once to +`std::cerr`. Only `initialize()` triggers the fallback: if the native `open()` throws, the exception +propagates as for any frontend. `fallbackReason()` returns that reason and `usesNativeWindow()` tells which path was taken once the application is constructed. ```cpp diff --git a/examples/CMakeLists.txt b/examples/CMakeLists.txt index 3a8ce401..f7f3314c 100644 --- a/examples/CMakeLists.txt +++ b/examples/CMakeLists.txt @@ -8,7 +8,7 @@ set(WEBFRONT_LIFE_NATIVE_WINDOW OFF) if(WEBFRONT_LIFE_NATIVE_OPTION) if(${WEBFRONT_LIFE_NATIVE_OPTION}) set(WEBFRONT_LIFE_NATIVE_WINDOW ON) -endif() + endif() endif() if(NOT WEBFRONT_LIFE_NATIVE_WINDOW) webfront_native_window_advice(_life_advice) @@ -39,7 +39,7 @@ set(WEBFRONT_LIFE_ASSETS "" CACHE FILEPATH "LifeUI.hpp generated by wf embed (en if(WEBFRONT_LIFE_ASSETS) if(NOT EXISTS "${WEBFRONT_LIFE_ASSETS}") message(FATAL_ERROR "WEBFRONT_LIFE_ASSETS must name an existing LifeUI.hpp generated by wf embed") -endif() + endif() add_executable(WebFrontLifeEmbedded life/LifeEmbedded.cpp) target_link_libraries(WebFrontLifeEmbedded PRIVATE WebFront WebFront_warnings WebFront_options) target_compile_definitions(WebFrontLifeEmbedded PRIVATE WEBFRONT_LIFE_ASSETS_HEADER="${WEBFRONT_LIFE_ASSETS}") diff --git a/include/webfront/frontend/Frontend.hpp b/include/webfront/frontend/Frontend.hpp index dc228e23..7ea6fab2 100644 --- a/include/webfront/frontend/Frontend.hpp +++ b/include/webfront/frontend/Frontend.hpp @@ -139,7 +139,9 @@ void openWith(std::string_view address, std::string_view port, std::string_view * * initialize() tries Native::initialize(); if it throws (engine not compiled in, no display, missing runtime), the * frontend remembers the reason, prints it once to std::cerr and uses Browser for the whole process. The decision is - * per frontend type and made once, like every initialize(). Applications need neither a WEBFRONT_EMBED_* macro nor a + * per frontend type and made once, like every initialize(). Only initialize() triggers the fallback: an exception + * from the native open() propagates, because a window that failed after it started cannot be told apart from one + * the user closed. Applications need neither a WEBFRONT_EMBED_* macro nor a * second application type. * * `action` is that of the native window; the browser path is reported at run time through closeServerAfterOpen(), @@ -157,8 +159,15 @@ struct NativeOrBrowserFrontendFor { return !state().reason.has_value(); } /// Whether the server stops once open() returns: true for a native window, false for the browser. - [[nodiscard]] static bool closeServerAfterOpen() { return usesNativeWindow() && Native::action == Action::closeServerAfterOpen; } + [[nodiscard]] static bool closeServerAfterOpen() { + if constexpr (Native::action == Action::closeServerAfterOpen) + return usesNativeWindow(); + else + return false; + } + // Called once per process by BasicWF (std::call_once). It resets the decision, so a direct caller must not + // race it with open(); the unit tests call it repeatedly on purpose. static void initialize() { auto& s = state(); s.reason.reset(); @@ -167,8 +176,10 @@ struct NativeOrBrowserFrontendFor { } catch (const std::exception& e) { s.reason = e.what(); } - if (s.reason) - std::cerr << "WebFront: opening the system browser instead of a native window: " << *s.reason << std::endl; + if (s.reason) { + std::cerr << "WebFront: opening the system browser instead of a native window: " << *s.reason << '\n'; + Browser::initialize(); + } } static void open(std::string_view port, std::string_view file) { diff --git a/test/unit/WebFrontTests.cpp b/test/unit/WebFrontTests.cpp index 1e8afd76..0756dfa1 100644 --- a/test/unit/WebFrontTests.cpp +++ b/test/unit/WebFrontTests.cpp @@ -25,6 +25,11 @@ #include #include +#if defined(__linux__) && defined(WEBFRONT_EMBED_WEBKITGTK) + #include + #include +#endif + using namespace webfront; SCENARIO("The public version matches the version detected by CMake", "[version]") { @@ -381,9 +386,10 @@ struct FallbackNativeWindow { }; struct FallbackBrowser { + static inline int initializeCalls = 0; static inline int openCalls = 0; static constexpr frontend::Action action{frontend::Action::keepServerRunning}; - static void initialize() {} + static void initialize() { ++initializeCalls; } static void open(std::string_view, std::string_view) { ++openCalls; } }; @@ -397,8 +403,10 @@ SCENARIO("Native window or browser, decided at run time") { FallbackNativeWindow::displayAvailable = true; FallbackNativeWindow::openCalls = 0; FallbackBrowser::openCalls = 0; + FallbackBrowser::initializeCalls = 0; Fallback::initialize(); THEN("the native window is used and closing it stops the server") { + REQUIRE(FallbackBrowser::initializeCalls == 0); REQUIRE(Fallback::usesNativeWindow()); REQUIRE_FALSE(Fallback::fallbackReason().has_value()); REQUIRE(Fallback::closeServerAfterOpen()); @@ -411,12 +419,14 @@ SCENARIO("Native window or browser, decided at run time") { FallbackNativeWindow::displayAvailable = false; FallbackNativeWindow::openCalls = 0; FallbackBrowser::openCalls = 0; + FallbackBrowser::initializeCalls = 0; std::ostringstream captured; auto* const previous = std::cerr.rdbuf(captured.rdbuf()); Fallback::initialize(); std::cerr.rdbuf(previous); THEN("the browser is used, the reason is kept and printed, and the server keeps running") { REQUIRE_FALSE(Fallback::usesNativeWindow()); + REQUIRE(FallbackBrowser::initializeCalls == 1); REQUIRE(Fallback::fallbackReason().value_or("").find("display") != std::string::npos); REQUIRE(captured.str().find("opening the system browser instead of a native window") != std::string::npos); REQUIRE_FALSE(Fallback::closeServerAfterOpen()); @@ -435,23 +445,23 @@ SCENARIO("Native window or browser, decided at run time") { } #if defined(__linux__) && defined(WEBFRONT_EMBED_WEBKITGTK) GIVEN("the real WebKitGTK engine and no DISPLAY or WAYLAND_DISPLAY") { - const char* const display = std::getenv("DISPLAY"); - const char* const wayland = std::getenv("WAYLAND_DISPLAY"); - const std::string savedDisplay = display ? display : ""; - const std::string savedWayland = wayland ? wayland : ""; - unsetenv("DISPLAY"); - unsetenv("WAYLAND_DISPLAY"); - std::ostringstream captured; - auto* const previous = std::cerr.rdbuf(captured.rdbuf()); - frontend::NativeOrBrowserFrontend::initialize(); - std::cerr.rdbuf(previous); - if (display) - setenv("DISPLAY", savedDisplay.c_str(), 1); - if (wayland) - setenv("WAYLAND_DISPLAY", savedWayland.c_str(), 1); + // A child process: GTK may already be initialized in this one, and the environment must stay untouched. + const pid_t child = fork(); + REQUIRE(child >= 0); + if (child == 0) { + unsetenv("DISPLAY"); + unsetenv("WAYLAND_DISPLAY"); + std::cerr.rdbuf(nullptr); + frontend::NativeOrBrowserFrontend::initialize(); + const bool fellBack = !frontend::NativeOrBrowserFrontend::usesNativeWindow() + && frontend::NativeOrBrowserFrontend::fallbackReason().value_or("").find("display") != std::string::npos; + _exit(fellBack ? 0 : 1); + } + int status = 0; + REQUIRE(waitpid(child, &status, 0) == child); THEN("the frontend falls back to the browser and names the missing display") { - REQUIRE_FALSE(frontend::NativeOrBrowserFrontend::usesNativeWindow()); - REQUIRE(frontend::NativeOrBrowserFrontend::fallbackReason().value_or("").find("display") != std::string::npos); + REQUIRE(WIFEXITED(status)); + REQUIRE(WEXITSTATUS(status) == 0); } } #endif