Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions docs/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ these entries stays in the GitHub releases and the Git history.
## Unreleased

### Breaking
- `WebView2Options` is now `ViewOptions`, shared with WKWebView: `userDataFolder` moves after `launch`, so a positional initialization of `WebView2Options` stops compiling, and so does a designated one that writes `.userDataFolder` before `.contentPolicy`, `.window`, `.visible` or `.launch` (write it last) (#652, `docs/FRONTENDS.md`).
- `webfront/automation/Enable.hpp` no longer compiles with `WEBFRONT_DISTRIBUTION`: gate `enableAutomation` out of the distribution build, as the guide already advised (#632, ADR-025).
- `webfront-agent` is removed with its JSON CLI, MCP on stdio, `--serve`, `--attach`, `--list` and `--print-mcp-config`, as are `WEBFRONT_BUILD_AUTOMATION`, `WEBFRONT_AUTOMATION_FRONTEND` and `webfront_add_agent()`: connect the MCP client to the URL the application prints (#632, ADR-025, `docs/AUTOMATION.md`).
- `AutomationOptions::listen` becomes `directory` and may stay empty (a private directory named after the session is created), `Automation::endpoint()` becomes `directory()`, and the JSON-lines attachment channel (`ChannelServer`, `ChannelClient`) is gone (#632).
Expand Down Expand Up @@ -50,6 +51,9 @@ in a native pseudoterminal, and a faster, less flashy start of the native window
- Choose the colour of the WebKitGTK view under the page with `WindowOptions::background` (WebKitGTK; the other embedded frontends are listed here), and read the start-up milestones of a WebKitGTK view with `WEBFRONT_STARTUP_TRACE=1` (#611, `docs/WEBKITGTK.md`).

### Changed
- WebKitGTK takes a `startupTimeout` (30 s by default), and WebView2 refuses a secondary window once the first one closed, even for a page already open (#652).
- Open every native window from one `ViewOptions` (`WKWebViewOptions` and `WebView2Options` are aliases), whose test injections reach the secondary windows too (#652, `docs/FRONTENDS.md`).
- Write a native frontend from shared headers: `EmbeddedFrontend` (facade and every `open()` overload), `WindowRegistry`/`InterfaceSession`, `StartupTrace` and `Presentation`, tested on Linux with fake windows (#652, `docs/FRONTENDS.md`).
- Reveal the WKWebView window when the document has loaded or after one second (#611, `docs/WKWEBVIEW.md`).
- Reveal the WebView2 window after the first frame or one second (#611, `docs/WEBVIEW2.md`).
- Show the WebKitGTK window when the page reports its first frame, or when a one-second timer fires, even if the page has not painted, instead of at once; the embedded pages, the starter and the examples use the cheap `sans-serif` and `monospace` font stacks (#611, `docs/WEBKITGTK.md`).
Expand Down
10 changes: 10 additions & 0 deletions docs/FRONTENDS.md
Original file line number Diff line number Diff line change
Expand Up @@ -424,3 +424,13 @@ the native helper never selects CEF.
| `WEBFRONT_EMBED_WKWEBVIEW` | OFF | Link the system Cocoa and WebKit frameworks for WKWebViewFrontend (macOS 13.3+ only) |
| `WEBFRONT_EMBED_WEBKITGTK` | OFF | Enable the system WebKitGTK 6.0 embedded frontend (Linux only) |
| `WEBFRONT_EMBED_CEF` | OFF | Download and link CEF so CEFFrontend is available (Windows, Linux x86_64 and aarch64, and macOS only). Other platforms fail at configure time |

## Writing a native frontend

WebKitGTK, WKWebView, WebView2 and CEF share their toolkit-independent logic in `include/webfront/frontend/`; a new native frontend declares only the calls of its toolkit. The shared parts are tested on Linux with fake windows (`test/unit/WindowRegistryTests.cpp`).

- `EmbeddedFrontend.hpp`: `EmbeddedFrontend<Derived>` gives `uiExecutor()`, `nativeWindow()`, `requestClose()`, `initialize()`, `openSecondaryWindow()`, `closeSecondaryWindow()` and every overload of `open()`. The frontend declares `Host` (the tag of its executor and window hosts), `Options` (`ViewOptions`, which every native frontend takes: `startupTimeout`, `userDataFolder` (WebView2), `contentPolicy`, `window`, `visible`, `launch` and the test injections `chooseFiles`, `downloadDirectory`, `downloadFinished`, `answerScriptDialog`; a frontend ignores what its toolkit has no use for, and `WKWebViewOptions` and `WebView2Options` are aliases of it), `compiled`, `name` and `enable` (the message of a build without the engine), `secondaryWindows`, and the toolkit calls `openNative`, `closeNative`, `openSecondaryNative`, `closeSecondaryNative` (on the interface thread) and optionally `initializeNative`, `defaultOptions` and `waitsForFirstWindow`. Members that name the engine are instantiated only when `compiled` holds, so no `#if` surrounds them. A frontend without `initializeNative` throws from `initialize()` when it is not compiled; WebView2 declares an empty one, because its COM apartment belongs to each `open()`, and fails there.
- `WindowRegistry.hpp`: `WindowRegistry<Session, Hooks>` is the table of the secondary windows (open, bring to the front, close, retire a window that closed, reap it outside its own callback, clear when the first window ends) and `InterfaceSession<Registry>` is what an `open()` holds while its loop runs (attach, publish, then on every exit, also by exception: clear the secondary windows, withdraw the window, close the host). The hooks are `scheduleReap`, `cancelReap`, `present`, `close` and the `name` of the messages: an idle callback in WebKitGTK, a queued block in WKWebView, a message to the first window in WebView2.
- `StartupTrace.hpp`: `StartupTrace` (`WEBFRONT_STARTUP_TRACE=1`, with the one platform function that tells the age of the process) and `Presentation` (the window shows nearly transparent and becomes opaque once, at the page's first frame or after `Presentation::maximumDelayMs`; the frontend sets the opacity and runs the timer).

The startup delay (`startupTimeout`) is an option of WKWebView, WebView2 and WebKitGTK (30 s by default, the same message when it expires); CEF has none. WKWebView and WebKitGTK start the secondary windows with the first window's delay and test injections, as WebView2 does.
227 changes: 227 additions & 0 deletions include/webfront/frontend/EmbeddedFrontend.hpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,227 @@
// SPDX-License-Identifier: Apache-2.0 OR CECILL-B
/// @brief The static facade shared by the embedded frontends (#652): what a native frontend declares once, the base provides.
#pragma once

#include "../ContentPolicy.hpp"
#include "../ViewAssociation.hpp"
#include "Action.hpp"
#include "CloseRequest.hpp"
#include "NativeWindow.hpp"
#include "ScriptDialogs.hpp"
#include "UIExecutor.hpp"
#include "Window.hpp"

#include <chrono>
#include <filesystem>
#include <functional>
#include <limits>
#include <optional>
#include <stdexcept>
#include <string>
#include <string_view>
#include <vector>

namespace webfront::frontend {

namespace detail {
/// A startup deadline a toolkit timer can hold: positive and below 2^31 milliseconds. A negative or huge count would
/// otherwise wrap around when it becomes the unsigned argument of the timer.
[[nodiscard]] inline unsigned timerMilliseconds(std::chrono::milliseconds timeout, std::string_view frontend) {
if (timeout.count() < 1 || timeout.count() > std::numeric_limits<int>::max())
throw std::invalid_argument(std::string(frontend) + ": startupTimeout must be positive and at most " + std::to_string(std::numeric_limits<int>::max()) + " milliseconds");
return static_cast<unsigned>(timeout.count());
}
} // namespace detail

/// What an embedded frontend is asked when it opens a window, the same for the first window and the secondary ones. A
/// frontend honours the settings that its toolkit has (a field it has no use for is ignored) and its own startup deadline.
struct ViewOptions {
/// The initial navigation must succeed within this interval; no bridge connection is required. What ends the wait
/// depends on the engine: WKWebView, the end of the load; WebKitGTK, the commit of the navigation (resources still
/// loading are not waited for); WebView2, the creation of its browser, before the navigation starts.
std::chrono::milliseconds startupTimeout{30000};
ContentPolicy contentPolicy{};
WindowOptions window{};
/// WKWebView and WebView2: keep the native window hidden and avoid activating the application.
bool visible{true};
/// Test injections (WKWebView, WebKitGTK): answers `<input type="file">` without a dialog (an empty list cancels).
std::function<std::vector<std::string>()> chooseFiles{};
/// Test injection: a non-empty folder receives downloads without a save panel.
std::filesystem::path downloadDirectory{};
/// Test injection: called with the destination of each finished download.
std::function<void(const std::string&)> downloadFinished{};
/// Test injection: answers `alert`, `confirm` and `prompt` without a box (WKWebView, WebKitGTK, WebView2). WKWebView
/// does not handle `beforeunload` (its public WKUIDelegate has no method for it): a page that relies on it can lose
/// unsaved changes on navigation or close, and WebFront does not confirm it.
ScriptDialogHandler answerScriptDialog{};
/// Per-launch proof of this view (ADR-020): given to documents of the application's origin only, at the start of the
/// document, for WebFront.js to present in its handshake. Set by WebFront; empty gives the view no association.
ViewLaunch launch{};
/// WebView2 only: the profile folder; empty keeps the default. Last, so the members before it keep the order that
/// WKWebViewOptions had.
std::filesystem::path userDataFolder{};

/// A secondary window is built from the first one's: its visibility, its startup deadline and its test injections.
void inherit(const ViewOptions& first) {
visible = first.visible;
startupTimeout = first.startupTimeout;
chooseFiles = first.chooseFiles;
downloadDirectory = first.downloadDirectory;
downloadFinished = first.downloadFinished;
answerScriptDialog = first.answerScriptDialog;
}
};

/**
* @brief CRTP base of the embedded frontends: `uiExecutor()`, `nativeWindow()`, `requestClose()`, the second window, `initialize()`
* and every overload of `open()`, from the few members the frontend declares (docs/FRONTENDS.md):
*
* - `using Host = ...`: the type that names the process-wide hosts (UIExecutor.hpp, NativeWindow.hpp);
* - `static constexpr bool compiled`: the engine is part of this build; `static constexpr std::string_view name` and
* `enable` (what to configure) make the message of a frontend that is not;
* - `using Options`: the frontend's options (`contentPolicy`, `window` and `launch` at least; ViewOptions has them), and an
* optional `static Options defaultOptions()` for the ones a call starts from;
* - `static void openNative(address, port, file, const Options&)` and `closeNative(const NativeWindowHandle&)` (on the
* interface thread: the toolkit's own close request), and an optional `initializeNative()` (a frontend without one throws from initialize() when it is not compiled);
* - `static constexpr bool secondaryWindows`, and when true `openSecondaryNative(address, port, page, const Options&)` and
* `closeSecondaryNative(page) -> bool`, which run on the interface thread; `waitsForFirstWindow` (optional) tells that
* the call may come before the first window is ready (invokeOnUIThreadWhenReady).
*
* Members that name the engine are only instantiated when `compiled` holds, so they need no `#if` of their own.
*/
template <typename Derived>
struct EmbeddedFrontend {
static constexpr Action action{Action::closeServerAfterOpen};

/// The interface thread while open() runs the toolkit's loop (see UIExecutor.hpp).
[[nodiscard]] static UIExecutor uiExecutor() {
return uiExecutorHostOf<typename Derived::Host>().executor();
}
/// The window, readable on the interface thread while open() runs (see NativeWindow.hpp).
[[nodiscard]] static NativeWindow nativeWindow() {
return nativeWindowHostOf<typename Derived::Host>().window();
}

static void initialize() {
if constexpr (requires { Derived::initializeNative(); })
Derived::initializeNative();
else if constexpr (!Derived::compiled)
unavailable();
}

/// Asks the window to close, from any thread; false when no window is open (see CloseRequest.hpp).
static bool requestClose([[maybe_unused]] std::optional<UISession> session = std::nullopt) noexcept {
if constexpr (Derived::compiled)
return detail::requestWindowClose(uiExecutor(), nativeWindow(), [](const NativeWindowHandle& window) {
Derived::closeNative(window);
}, session);
else
return false;
}

/// Opens `page` in a second window beside the one open() runs, or brings the window already showing it to the front
/// (#616). Callable from any thread while open() runs; throws std::logic_error when no window is open.
static void openSecondaryWindow(std::string_view address, std::string_view port, std::string_view page, const ContentPolicy& policy,
const WindowOptions& window, const ViewLaunch& launch)
requires(Derived::secondaryWindows)
{
if constexpr (!Derived::compiled) {
unavailable();
} else {
auto options = secondaryOptionsOf(policy, window, launch);
try {
onUIThread([&] {
Derived::openSecondaryNative(address, port, page, options);
});
} catch (const UIExecutorUnavailable&) {
throw std::logic_error(std::string(Derived::name) + ": no window of the application is open; show() it before opening another");
}
}
}
/// Closes the secondary window showing `page`, from any thread; false when none is open.
static bool closeSecondaryWindow([[maybe_unused]] std::string_view page)
requires(Derived::secondaryWindows)
{
if constexpr (Derived::compiled) {
bool closed = false;
try {
invokeOnUIThread(uiExecutor(), [&] {
closed = Derived::closeSecondaryNative(page);
});
} catch (const UIExecutorUnavailable&) {
return false;
}
return closed;
} else {
return false;
}
}

static void open(std::string_view port, std::string_view file) {
open("127.0.0.1", port, file);
}
template <typename D = Derived> // dependent: the options type is only needed once the frontend is complete
static void open(std::string_view address, std::string_view port, std::string_view file, const typename D::Options& options = startingOptions()) {
if constexpr (Derived::compiled) {
// One rule for every frontend: a deadline no toolkit timer can hold is refused before any window exists.
if constexpr (requires { options.startupTimeout; })
(void)detail::timerMilliseconds(options.startupTimeout, Derived::name);
Derived::openNative(address, port, file, options);
} else
unavailable();
}
static void open(std::string_view address, std::string_view port, std::string_view file, const ContentPolicy& policy) {
open(address, port, file, optionsOf(policy));
}
static void open(std::string_view address, std::string_view port, std::string_view file, const ContentPolicy& policy, const WindowOptions& window) {
open(address, port, file, optionsOf(policy, &window));
}
static void open(std::string_view address, std::string_view port, std::string_view file, const ContentPolicy& policy, const WindowOptions& window,
const ViewLaunch& launch) {
open(address, port, file, optionsOf(policy, &window, &launch));
}

/// The options a call starts from: the frontend's configured ones, or the default ones.
template <typename D = Derived>
static typename D::Options startingOptions() {
if constexpr (requires { Derived::defaultOptions(); })
return Derived::defaultOptions();
else
return typename Derived::Options{};
}

private:
template <typename D = Derived>
static typename D::Options optionsOf(const ContentPolicy& policy, const WindowOptions* window = nullptr, const ViewLaunch* launch = nullptr) {
// The settings of the arguments the caller gave replace the configured ones; the others stay as configured.
auto options = startingOptions();
options.contentPolicy = policy;
if (window)
options.window = *window;
if (launch)
options.launch = *launch;
return options;
}
// A secondary window takes the first window's settings (ViewOptions::inherit, or the engine's own session), so it starts
// from default options: the application's provider is not asked, and its failure cannot stop a window that is only brought to the front.
template <typename D = Derived>
static typename D::Options secondaryOptionsOf(const ContentPolicy& policy, const WindowOptions& window, const ViewLaunch& launch) {
typename D::Options options{};
options.contentPolicy = policy;
options.window = window;
options.launch = launch;
return options;
}
template <typename Function>
static void onUIThread(Function&& function) {
if constexpr (requires { requires Derived::waitsForFirstWindow; })
invokeOnUIThreadWhenReady(uiExecutor(), function);
else
invokeOnUIThread(uiExecutor(), function);
}
[[noreturn]] static void unavailable() {
throw std::runtime_error(std::string(Derived::name) + " is unavailable. " + std::string(Derived::enable));
}
};

} // namespace webfront::frontend
Loading
Loading