diff --git a/.github/docker/linux-ci.Dockerfile b/.github/docker/linux-ci.Dockerfile index 5a80f0ba..ec4fa14e 100644 --- a/.github/docker/linux-ci.Dockerfile +++ b/.github/docker/linux-ci.Dockerfile @@ -1,16 +1,17 @@ -# Toolchain of the Linux desktop CI job (GCC 16, WebKitGTK, lcov, Xvfb), prebuilt so that a job downloads one image from +# Toolchain of the Linux desktop CI job (GCC 16, WebKitGTK, lcov, Xvfb, weston), prebuilt so that a job downloads one image from # ghcr.io instead of dozens of packages from an Ubuntu mirror. BuildAndTest.yml tags it with the hash of this file: # changing the file (for example to refresh the packages) is what rebuilds it. CMake is not part of it: the # setup-cmake action installs an exact, checksummed release. FROM ubuntu:26.04@sha256:c098726dd9b9733f3e885f8de0ef375206a311b0a317eadc40d347b1115fb944 LABEL org.opencontainers.image.source="https://github.com/ambroise-leclerc/WebFront" -LABEL org.opencontainers.image.description="WebFront CI: GCC 16, WebKitGTK 6, OpenSSL, lcov and Xvfb on Ubuntu 26.04" +LABEL org.opencontainers.image.description="WebFront CI: GCC 16, WebKitGTK 6, OpenSSL, lcov, Xvfb and weston on Ubuntu 26.04" ENV DEBIAN_FRONTEND=noninteractive # sudo: the composite actions of the repository call it, as they do on a hosted runner. build-essential: the CTest # fixtures configure sub-projects with CMake's default generator and compiler, which a hosted runner also provides. +# weston: the headless Wayland compositor of the WebKitGTKWayland-* tests. # libssl-dev: the signature verification of the updater tests (OpenSSL libcrypto). # file: CPackDeb needs it to list the dependencies of the package ApplicationPackageConfiguration builds. # libjson-xs-perl: a recommendation of lcov, which falls back to a pure-Perl parser about eight times slower without it. @@ -19,7 +20,7 @@ RUN apt-get update \ ca-certificates curl git sudo tar xz-utils build-essential \ ninja-build pkg-config python3 \ gcc-16 g++-16 libwebkitgtk-6.0-dev libssl-dev lcov libjson-xs-perl \ - xvfb xauth time file \ + xvfb xauth weston time file \ && rm -rf /var/lib/apt/lists/* # The workspace is mounted from the host runner and owned by another user: let git (and the tests that call it) read it. diff --git a/AGENTS.md b/AGENTS.md index 100e46d5..c8f0da84 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -25,7 +25,7 @@ The README introduces WebFront through the Game of Life walkthrough, demonstrati - `examples/`: the default build includes Hello World (`hello-world/`), the host loop (`host-loop/`: an application that keeps its own loop, `app.start()` or a host thread beside a native window; it ray-traces a Boing Ball on the CPU or with an optional CUDA unit, see `docs/HOST_LOOP_EXAMPLE.md`) and Game of Life (`life/`, with console, developer and embedded stages, plus the `life/react/` variant with a C++ panel inside React). The standalone [PTY example](docs/PTY.md) has its own CMake entry point. - `js/core/`: readable browser bridge, fallback and bootstrap loader compiled into `include/webfront/`, plus the embedding CMake modules; `js/developer/`: developer environment (its terminal and `wf`), the wf scripts that build it (`scripts/`), build and publication tools. The repository is itself a `wf` project (`js/developer/webfront.project.json` and its lock, selected with `--manifest-dir js/developer`): the environment builds itself, and its pure JavaScript specs (`test/developer/`) run with `wf test`. Production C++ remains header-only in `include/webfront/`. - `js/developer/starters/`: the sources of the `app` and `store` starters (`store` receives copies of `js/store/` when the environment is built) and `agent-guide.md`, the `AGENTS.md` that `wf create` puts beside a starter and that `webfront_write_agent_guide()` (`cmake/WebFrontAgentGuide.cmake`) writes in a consuming project. -- `js/services/`: optional `@webfront/services` package, the browser side of the system services (ADR-020; a skeleton so far), built like `@webfront/react` by `wf run services-package`; outside the core's embedded resource list. +- `js/services/`: optional `@webfront/services` package, the browser side of the system services (ADR-020; the window service so far, its C++ side in `include/webfront/services/window/`), built like `@webfront/react` by `wf run services-package`; outside the core's embedded resource list. - `js/pty/`: optional `@webfront/pty` adapter for native pseudoterminals. `wf run pty-package` assembles the archive used by the browser tests. See `docs/PTY.md`. - `js/store/`: optional `@webfront/store` package, the browser side of `webfront::store::Store` for any UI library (`docs/STORE.md`), built by `wf run store-package`. - `js/react/`: optional `@webfront/react` package (`createStore`, `useStore`, `Island`), declarations and package-local license. `wf run react-package` assembles it; tests verify the exact archive installed by the registry. It is outside the core's embedded resource list. diff --git a/cmake/Frontends.cmake b/cmake/Frontends.cmake index 1db4de08..80bf4fe7 100644 --- a/cmake/Frontends.cmake +++ b/cmake/Frontends.cmake @@ -441,6 +441,7 @@ 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) + list(APPEND lifecycle_modes window-services window-persistence) # 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)$") diff --git a/cmake/WebKitGTKSupport.cmake b/cmake/WebKitGTKSupport.cmake index 148dc370..fdf102ae 100644 --- a/cmake/WebKitGTKSupport.cmake +++ b/cmake/WebKitGTKSupport.cmake @@ -32,7 +32,7 @@ function(webfront_add_webkitgtk_tests) target_link_libraries(webkitgtk_lifecycle PRIVATE WebFront_test_hardening WebFront WebFront_warnings WebFront_options) add_dependencies(webtest webkitgtk_lifecycle) webfront_find_xvfb(display_runner) - foreach(mode sandbox-environment sandbox-recheck no-display worker-thread native-close repeated-show http-error pre-run-failure poll-failure profile-permissions window-title download download-user-dir choose-file cancel-choose close-with-dialog script-dialogs close-with-script-dialog first-frame present-timeout media-scoped) + foreach(mode sandbox-environment sandbox-recheck no-display worker-thread native-close repeated-show http-error pre-run-failure poll-failure profile-permissions window-title window-menu window-normal-position download download-user-dir choose-file cancel-choose close-with-dialog script-dialogs close-with-script-dialog first-frame present-timeout media-scoped) if(mode MATCHES "^(no-display|worker-thread|pre-run-failure|profile-permissions)$") add_test(NAME WebKitGTKAdapter-${mode} COMMAND webkitgtk_lifecycle ${mode}) elseif(display_runner) diff --git a/docs/CHANGELOG.md b/docs/CHANGELOG.md index 51868d51..4686d192 100644 --- a/docs/CHANGELOG.md +++ b/docs/CHANGELOG.md @@ -19,6 +19,8 @@ these entries stays in the GitHub releases and the Git history. - A type that converts to `std::string_view` without being a string is no longer written as text by `info()`, `fail()` and `checkEqual` (it appears as `{?}` without a `Printer`): specialize `webfront::bdd::isString` (or `Printer`) for it (#739, `docs/BDD.md`). ### Added +- Window control under every embedded frontend (`app.windowControl()`): position, size, states, application and context menus with shortcuts, and a notification icon, with `unsupported` where the toolkit cannot; `WindowOptions::rememberAs` reopens a window where it was (#764, `docs/FRONTENDS.md`). +- Optional window service for the page (`webfront::services::Window`, `windowService()` of `@webfront/services`), answering the embedded view only (#764, ADR-020). - A unit that only registers C++ functions or calls JavaScript can include the light `webfront/Bridge.hpp` and compiles in about a third of the time: pass it `webfront::bridgeFunctions(app)` or `webfront::bridgeUI(ui)` (#766, ADR-029). - Bundle npm packages that use `#` subpath imports (the `imports` of their `package.json`, naming their own files or a dependency), such as Svelte 5, once an environment with it is published (#767). - Start an interface without a UI library on a C++ state store with `wf create store`, once an environment with it is published (#767, `docs/STORE.md`). diff --git a/docs/FRONTENDS.md b/docs/FRONTENDS.md index 69d426c6..dc5f5477 100644 --- a/docs/FRONTENDS.md +++ b/docs/FRONTENDS.md @@ -66,10 +66,11 @@ on a command line or in a URL. ## Window title and size -`maximized`, `fullscreen`, `frameless`, `minimumWidth` and `minimumHeight` set the initial state, decoration and -smallest size of the window. **Only WebKitGTK and CEF apply them**; WebView2 and WKWebView ignore them, and a window -manager or compositor may not honour them. A frameless window has no close button: the page offers one. Persisted -geometry, menus and tray icons are not provided; use the [native window](#native-window). +`maximized`, `fullscreen`, `frameless`, `alwaysOnTop`, `minimumWidth` and `minimumHeight` set the initial state, +decoration and smallest size of the window. Every embedded frontend applies them; a window manager or compositor may not +honour them, and always-on-top is not available under Wayland. A frameless window has no close button: the page offers +one (under WKWebView the title bar becomes transparent and its buttons are hidden). The system browser ignores all of +this. `WebFrontConfig::window` (`webfront::WindowOptions`: `title`, `width`, `height`) sets the initial window of the embedded frontends (WebKitGTK, CEF, WebView2, WKWebView); the system browser ignores it. An empty title selects the @@ -81,6 +82,55 @@ frontend shows its window when the first document has loaded or after one second and WebView2 at their first frame), so that the window does not appear blank; CEF applies the colour to the browser and to its window, as an opaque colour whatever non-zero alpha is given (CEF accepts only 0x00 or 0xFF; `#rrggbb00` leaves its default), and `media` concerns WebKitGTK only. +## Window control, persistence and menus + +`WindowOptions::rememberAs` names the window: when it closes, an embedded frontend writes its position, size, maximized +and full screen state to `.window.json`, and the next window of that name opens there. The folder is +`$XDG_STATE_HOME/webfront` (or `~/.local/state/webfront`), `~/Library/Application Support/webfront` or +`%LOCALAPPDATA%\webfront`; `stateDirectory` replaces it. A position on a screen that is gone is not applied. Only the +application's first window is remembered. + +`app.windowControl()` gives C++ the window of the embedded view, on its [interface thread](#interface-thread-executor): +`placement`, `move`, `resize`, `setMaximized`, `setFullscreen`, `minimize`, `setAlwaysOnTop`, `setMinimumSize`, the +application menu (`setMenu`, with shortcuts such as `CmdOrCtrl+S`), a context menu (`showContextMenu`), a notification +icon (`setTray`) and `features()`, which tells beforehand what answers `unsupported`. Secondary windows are not +controlled. + +The page reaches the same operations when the application constructs the optional service before `show()`: + +```cpp +#include + +webfront::services::Window windowService(app); +``` + +The page side is `windowService()` of `@webfront/services`. Only the connection of the embedded view is served: any other +one is rejected with `window.notEmbedded` ([ADR-020](adr/ADR-020-services-systeme.md)). Every script the view admits can +use the service. + +| | WebKitGTK | WKWebView | WebView2 | CEF | +|---|---|---|---|---| +| position, always on top | X11 only; `unsupported` under Wayland | yes | yes | not under Wayland | +| size, maximize, full screen, minimize, minimum size | yes | yes | yes | yes | +| application menu and shortcuts | menu bar in the window | the macOS menu bar | menu bar; shortcuts while the page has the keyboard | `unsupported` | +| context menu | yes | yes | yes | yes | +| notification icon | `unsupported` (GTK 4 has none) | status item | notification area | `unsupported` | +| `activate("context", id)` (automation) | yes | `unsupported` | `unsupported` | yes | + +Under Wayland the system neither tells nor accepts where a window is: a placement has no position, and a remembered +window reopens with its size and state only (tested with a headless weston where it is installed, +`WebKitGTKWayland-*`). Nor does Wayland +tell a window that it is minimized: WebKitGTK reports `minimized` under X11 only. Positions and sizes are in the units of the toolkit (pixels of the outer window on Windows, +points of the frame on macOS) and are meant to be given back on the same machine. + +On Linux, maximizing, full screen and minimizing depend on a window manager; the automated tests, which run without one, +do not verify their effect. + +GTK 4 reports no window move, so WebKitGTK samples the position every 100 ms to know where a window was before the window +manager maximized or full-screened it; a sample counts once the next one agrees. A window moved and then maximized within +about 200 ms of that move therefore reopens at its previous normal position, never at a wrong one. CEF reports the +position as unsupported in a Wayland session (`XDG_SESSION_TYPE=wayland`), even though an X server may be reachable. + ## Content policy The [shared content policy](CONTENT_POLICY.md) defines bridge-origin authorization, embedded navigation, popup handling, DevTools and context-menu settings, including defaults and opt-outs. The system browser cannot expose embedded navigation/UI hooks; its bridge is protected by the same server check. diff --git a/docs/adr/ADR-007-frontends-explicites.md b/docs/adr/ADR-007-frontends-explicites.md index 7f5ed160..7be39273 100644 --- a/docs/adr/ADR-007-frontends-explicites.md +++ b/docs/adr/ADR-007-frontends-explicites.md @@ -19,6 +19,7 @@ | 1.12 | 2026-11-13 | Acceptée | Ambroise Leclerc | Intégration dans une application hôte : contrats facultatifs `launch()`, `requestClose()` et `requiresMainThread` ; `BasicWF::start()`, `BasicWF::requestClose()` et `webfront::UIThread` (#567). | Branche `567-host-integration` | | 1.13 | 2026-11-16 | Proposée | Ambroise Leclerc | Modes WebKitGTK développement par défaut et distribution exigeant le sandbox ; profil par exécutable généré pour le paquet applicatif, sans runtime (#596/#597). | Branche `596-jetson-native-launch` | | 1.14 | 2026-12-05 | Proposée | Ambroise Leclerc | État initial, décoration et taille minimale de la fenêtre dans `WindowOptions`, appliqués par WebKitGTK et CEF seulement ; géométrie persistée, menus et zone de notification restent à faire (#764). | Branche `764-window-options` | +| 1.15 | 2026-12-06 | Proposée | Ambroise Leclerc | Contrat facultatif `static WindowControlRef windowControl()` : la fenêtre d'un frontend intégré, contrôlée sur son thread d'interface, publiée pendant `open()`. Les options d'état de la version 1.14 sont appliquées par les quatre moteurs ; `alwaysOnTop`, `rememberAs` (géométrie persistée de la première fenêtre) et `stateDirectory` s'y ajoutent. Les limites par moteur sont dans `docs/FRONTENDS.md` ; les fenêtres secondaires ne sont ni mémorisées ni contrôlées (#764). | Branche `764-window-services` | ## État et chronologie diff --git a/docs/adr/ADR-020-services-systeme.md b/docs/adr/ADR-020-services-systeme.md index 03eb0dbc..3afb9b7a 100644 --- a/docs/adr/ADR-020-services-systeme.md +++ b/docs/adr/ADR-020-services-systeme.md @@ -15,6 +15,7 @@ | 1.8 | 2026-11-09 | Proposée, partiellement livrée | Ambroise Leclerc | Livraison de #461 (étape 4) : paquet `@webfront/services` (squelette : module de services vide et fonction de test), archive déterministe, registre de test et suite ; l'étape 4 est achevée. | [PR #503](https://github.com/ambroise-leclerc/WebFront/pull/503), [6eb8293](https://github.com/ambroise-leclerc/WebFront/commit/6eb82937896114ad98b72fd5ad0f38b4e18dbe73) | | 1.9 | 2026-11-09 | Proposée, partiellement livrée | Ambroise Leclerc | Livraison de #462 (étape 5) : exécuteur du thread d'interface (`frontend::UIExecutor`, sender `schedule()` : valeur sur le thread d'interface, arrêté si le jeton part ou si la boucle se ferme, erreur `UIExecutorUnavailable` sans boucle) publié par WKWebView, WebView2, WebKitGTK et CEF, et par `BrowserWithUILoopFrontend`, le navigateur système avec boucle minimale facultative (pompe de messages sur fenêtre de messages, run loop AppKit avec `NSApplication` en politique Accessory, boucle GLib), qui s'arrête par `requestStop()`. **Décision Linux** : le portail XDG passera par GDBus, c'est-à-dire `libgio-2.0` chargée à l'exécution comme GLib et WebKitGTK le sont déjà (aucune dépendance de construction, aucune bibliothèque D-Bus dédiée) ; sans GIO, le backend natif est indisponible. #463 est livré dans la version 1.10. | Branche `462-ui-thread-executor` | | 1.10 | 2026-11-09 | Proposée, partiellement livrée | Ambroise Leclerc | Livraison de #463 (étape 5, achevée) : accès typé à la fenêtre native (`frontend::NativeWindow`, `NativeWindowHost`) publié par WKWebView (`NSWindow*`), WebView2 (`HWND`), WebKitGTK (`GtkWindow*`) et CEF (`CefBrowser*`) ; `get()` ne répond que sur le thread d'interface (#462) et pendant la session (`notOpen`, `closed`, `wrongThread`, `unsupported`). `UI::nativeWindow()` ajoute la correspondance avec la connexion par l'association de #453 : toute connexion qui n'est pas la vue du frontend reçoit `notEmbedded`, donc le navigateur système reste sans parent. Identifiant de portail sous WebKitGTK : `x11:` lu à l'ouverture, `wayland:` exporté par `gdk_wayland_toplevel_export_handle` une fois la fenêtre prête (nouvelles tentatives pendant 5 s) ; vide tant qu'il est inconnu. Écart : la fenêtre reste publiée jusqu'à la fin de la boucle, y compris quand l'utilisateur vient de la fermer. La vérification manuelle d'un dialogue parenté sous chaque plateforme (`docs/FRONTENDS.md`) reste à exécuter avec le premier backend natif. | Branche `463-native-window-access` | +| 1.11 | 2026-12-06 | Proposée, partiellement livrée | Ambroise Leclerc | Premier service livré (#764) : **fenêtre** (`include/webfront/services/window/`, fonctions `webfront.services.window.*`, `windowService()` de `@webfront/services`), natif seulement et réservé à la vue du frontend intégré (`window.notEmbedded` sinon). Position, taille, états, premier plan, taille minimale, menus d'application et contextuels avec raccourcis, icône de notification ; `window.unsupported` là où la boîte à outils ne peut pas (position et premier plan sous Wayland, icône sous GTK 4 et CEF, barre de menus sous CEF). La page ne désigne aucun fichier : l'icône d'une barre système vient de C++ seulement. La persistance de la géométrie (`WindowOptions::rememberAs`) relève de l'ADR-007 1.15. Raccourcis globaux non livrés. | Branche `764-window-services` | ## État et chronologie diff --git a/docs/adr/README.md b/docs/adr/README.md index 2da82ce3..ec751679 100644 --- a/docs/adr/README.md +++ b/docs/adr/README.md @@ -49,7 +49,7 @@ verification evidence remain in [PROJECT_STATUS](../PROJECT_STATUS.md). | [ADR-004](ADR-004-appels-asynchrones-et-erreurs.md) | Asynchronous calls with deliberately asymmetric contracts | Accepted through 2.6; 2.7 proposed | 2022-02-06 | 2.7 — 2026-12-04 | | [ADR-005](ADR-005-evolution-reseau-asio-stdnet.md) | From standalone ASIO to stdnet: anticipating standard networking without blocking progress | Accepted through 3.1; 3.2 and 3.3 proposed | 2022-01-21 | 3.3 — 2026-12-05 | | [ADR-006](ADR-006-taches-structurees-et-arret.md) | Owning, cancelling and joining every task | Accepted | 2026-10-13 | 2.1 — 2026-10-25 | -| [ADR-007](ADR-007-frontends-explicites.md) | Explicit frontend selection and a shared lifecycle contract | Accepted through 1.12; 1.13 and 1.14 proposed | 2026-05-31 | 1.14 — 2026-12-05 | +| [ADR-007](ADR-007-frontends-explicites.md) | Explicit frontend selection and a shared lifecycle contract | Accepted through 1.12; 1.13 to 1.15 proposed | 2026-05-31 | 1.15 — 2026-12-06 | | [ADR-008](ADR-008-contenu-de-confiance-et-origines.md) | Restricting bridge origins without promising a sandbox | Accepted through 1.0; 1.1 to 1.4 proposed | 2026-10-18 | 1.4 — 2026-12-05 | | [ADR-009](ADR-009-modules-et-assets-reproductibles.md) | Serving modules locally and regenerating assets reproducibly | Accepted | 2023-03-16 | 2.5 — 2026-10-25 | | [ADR-010](ADR-010-composants-et-outils-optionnels.md) | Extending WebFront through optional components and development tools | Accepted through 1.8; 1.9 and 1.10 proposed | 2026-10-14 | 1.10 — 2026-12-05 | @@ -62,7 +62,7 @@ verification evidence remain in [PROJECT_STATUS](../PROJECT_STATUS.md). | [ADR-017](ADR-017-acces-direct-aux-frontends.md) | Direct access to embedded frontends, with HTML kept normative | Proposed | 2026-10-24 | 1.1 — 2026-10-25 | | [ADR-018](ADR-018-acces-au-dom.md) | DOM access from C++ through a bounded mutation stream, without contesting the DOM of UI libraries | Proposed, partially superseded, partially delivered | 2026-10-26 | 1.7 — 2026-12-05 | | [ADR-019](ADR-019-developpement-automatisable-et-agents.md) | Automating the developer environment through shared operations and an optional local MCP adapter | Accepted (1.2); amendment 1.5 by ADR-025 proposed | 2026-10-28 | 1.5 — 2026-11-21 | -| [ADR-020](ADR-020-services-systeme.md) | System services (files, clipboard, shell, notifications…) through optional C++ portals with per-connection backends, granting handles rather than paths | Proposed | 2026-10-31 | 1.8 — 2026-11-09 | +| [ADR-020](ADR-020-services-systeme.md) | System services (files, clipboard, shell, notifications…) through optional C++ portals with per-connection backends, granting handles rather than paths | Proposed | 2026-10-31 | 1.11 — 2026-12-06 | | [ADR-021](ADR-021-publication-de-l-environnement-developpeur.md) | Simplifying the publication of the developer environment: automate the release, keep pinned hashes, no dedicated server | Accepted (domain delivered; phase 1 to implement) | 2026-11-02 | 1.0 — 2026-11-02 | | [ADR-022](ADR-022-profils-et-niveaux-de-support.md) | Compiler profiles, GCC 13 S2 minimum, exit clause and LTS build tools | Accepted | 2026-11-11 | 1.1 — 2026-11-11 | | [ADR-023](ADR-023-espace-de-noms-des-commandes-du-terminal.md) | Terminal command names: `wf` stays the prefix of project commands, read-only file commands (`ls`, `cat`, `tree`, `mounts`), file command names reserved ahead, dependency graph with `wf list --tree`, `wf why`, `wf info` | Accepted | 2026-11-14 | 1.0 — 2026-11-14 | diff --git a/include/webfront/WebFront.hpp b/include/webfront/WebFront.hpp index 4e455276..f51f3697 100644 --- a/include/webfront/WebFront.hpp +++ b/include/webfront/WebFront.hpp @@ -17,6 +17,7 @@ #include "details/SpaceState.hpp" #include "dom/Document.hpp" #include "frontend/Frontend.hpp" +#include "frontend/WindowControl.hpp" #include "http/HTTPServer.hpp" #include "Introspection.hpp" #include "JsFunction.hpp" @@ -1050,6 +1051,17 @@ class BasicWF { return {}; } + /// Control of the window of the frontend (position, state, menus, tray; docs/FRONTENDS.md), usable on its interface + /// thread. `unsupported` for a frontend without one. + [[nodiscard]] frontend::WindowControlRef windowControl() const { + if constexpr (requires { + { Frontend::windowControl() } -> std::same_as; + }) + return Frontend::windowControl(); + else + return {}; + } + /// Adds a handler for each browser that connects from now on, called after the onUIStarted /// handler and the earlier subscribers. It stays registered while the returned subscription /// lives; components use this so they never replace the application's handler. diff --git a/include/webfront/frontend/CEF.hpp b/include/webfront/frontend/CEF.hpp index 4bf075bf..74b6acb1 100644 --- a/include/webfront/frontend/CEF.hpp +++ b/include/webfront/frontend/CEF.hpp @@ -88,6 +88,7 @@ class CEFSubprocessExit : public std::exception { // CEF defines macros such as NO_UNIQUE_ADDRESS and ALWAYS_INLINE that break stdexec's preprocessor // machinery when it is included afterwards: pull every stdnet and stdexec header WebFront uses in first. #include "../networking/SenderHeaders.hpp" + #include "CEFWindow.hpp" #include "cef_app.h" #include "cef_browser.h" @@ -376,6 +377,14 @@ class SimpleCEFWindowDelegate : public CefWindowDelegate { // Set window properties for a clean application window window->SetTitle(windowOptions.title); window->CenterWindow(CefSize(windowOptions.width, windowOptions.height)); + if (control) { + control->attach(window); + control->setView(browserView); + if (restored && restored->x && restored->y && CefWindowControl::positionable() && frontend::reachable(*restored, CefWindowControl::screens())) + static_cast(control->move(*restored->x, *restored->y)); + if (windowOptions.alwaysOnTop) + static_cast(control->setAlwaysOnTop(true)); + } if (const auto color = frontend::detail::parseBackground(windowOptions.background)) window->SetBackgroundColor(backgroundColor(*color)); // The window is shown when the first document has loaded, or after one second if it has not (#611): the page @@ -391,7 +400,14 @@ class SimpleCEFWindowDelegate : public CefWindowDelegate { CefPostDelayedTask(TID_UI, new PresentTask(self, window), presentDelayMilliseconds); } + void OnWindowBoundsChanged(CefRefPtr /*window*/, const CefRect& /*bounds*/) override { + if (control) + control->boundsChanged(); + } + void OnWindowDestroyed(CefRefPtr /*window*/) override { + if (control) + control->release(); browserView = nullptr; if (setReveal) setReveal(nullptr); @@ -422,6 +438,17 @@ class SimpleCEFWindowDelegate : public CefWindowDelegate { return windowOptions.maximized ? CEF_SHOW_STATE_MAXIMIZED : CEF_SHOW_STATE_NORMAL; } + /// The control to attach to the window once created, and the placement kept by an earlier session. + void SetControl(CefWindowControl* windowControl, std::optional saved) { + control = windowControl; + restored = saved; + } + + void SetMinimumSize(int width, int height) { + windowOptions.minimumWidth = width; + windowOptions.minimumHeight = height; + } + void SetBrowserView(CefRefPtr view) { browserView = view; } @@ -464,6 +491,8 @@ class SimpleCEFWindowDelegate : public CefWindowDelegate { CefRefPtr browserView; std::function)> setReveal; WindowOptions windowOptions; + CefWindowControl* control = nullptr; // outlives the window: openWindow() owns it + std::optional restored; bool presented = false; #ifdef __clang__ @@ -994,13 +1023,14 @@ class DrainTask : public CefTask { #endif }; -inline void openWindow(std::string url, - webfront::detail::BoundContentPolicy contentPolicy, - CefRefPtr client = nullptr, - const std::filesystem::path& profile = {}, - WindowOptions windowSettings = {}, - bool preserveSignalHandlers = false, - const ViewLaunch& launch = {}) { +inline void openWindow(std::string url, + webfront::detail::BoundContentPolicy contentPolicy, + CefRefPtr client = nullptr, + const std::filesystem::path& profile = {}, + WindowOptions windowSettings = {}, + bool preserveSignalHandlers = false, + const ViewLaunch& launch = {}, + std::function(const Menu&)> answerContextMenu = {}) { // One window per process. Refuse a second open() first, before CefInitialize (which succeeds again when the context // exists) and before any view: its browser would reach OnAfterCreated and replace the published window of the running // one, before host.attach() could refuse it, and the first connection's dialogs would be parented to the new window. @@ -1079,8 +1109,31 @@ inline void openWindow(std::string url, CefRefPtr browser_view = CefBrowserView::CreateBrowserView(client, url, browser_settings, extraInfo, nullptr, nullptr); // Create a window delegate for controlling the window appearance - CefRefPtr window_delegate(new SimpleCEFWindowDelegate(frontend::detail::resolveWindow(std::move(windowSettings)))); + const auto saved = frontend::loadPlacement(windowSettings); + const auto resolvedWindow = frontend::detail::resolveWindow(frontend::restoredOptions(std::move(windowSettings), saved)); + CefRefPtr window_delegate(new SimpleCEFWindowDelegate(resolvedWindow)); window_delegate->SetBrowserView(browser_view); + CefWindowControl windowControl([delegate = window_delegate.get()](int width, int height) { + delegate->SetMinimumSize(width, height); + }); + windowControl.answerContextMenu = std::move(answerContextMenu); + window_delegate->SetControl(&windowControl, saved); + // The delegate outlives this function while CEF holds it: whatever leaves the function (an exception included) must + // first take the window and view references out of the control and the control out of the delegate. + struct Detach { + CefWindowControl& control; + SimpleCEFWindowDelegate& delegate; + bool done{false}; + void run() noexcept { + if (std::exchange(done, true)) + return; + control.release(); + delegate.SetControl(nullptr, std::nullopt); + } + ~Detach() { + run(); + } + } detach{windowControl, *window_delegate}; window_delegate->SetRevealHook([client](std::function reveal) { client->onInitialLoad = std::move(reveal); }); @@ -1095,6 +1148,7 @@ inline void openWindow(std::string url, CefPostTask(TID_UI, new DrainTask); }); { + frontend::PublishedWindowControl published(frontend::windowControlHostOf(), windowControl); struct Closing { frontend::UIExecutorHost& host; ~Closing() { @@ -1105,6 +1159,12 @@ inline void openWindow(std::string url, CefRunMessageLoop(); } + if (!resolvedWindow.rememberAs.empty()) + if (const auto placement = windowControl.lastPlacement()) + frontend::savePlacement(resolvedWindow, *placement); + // The window and view references are released before CEF ends. + detach.run(); + // Shutdown CEF CefShutdown(); if (!client->navigationFailure.empty()) @@ -1119,19 +1179,21 @@ inline void closeBrowser(void* browser) { static_cast(browser)->GetHost()->CloseBrowser(true); } -inline void open(std::string_view address, - std::string_view port, - std::string_view file, - const ContentPolicy& policy = {}, - const WindowOptions& window = {}, - const ViewLaunch& launch = {}) { +inline void open(std::string_view address, + std::string_view port, + std::string_view file, + const ContentPolicy& policy = {}, + const WindowOptions& window = {}, + const ViewLaunch& launch = {}, + std::function(const Menu&)> answerContextMenu = {}) { detail::openWindow(frontend::detail::applicationUrl(address, port, file, launch.origin), webfront::detail::BoundContentPolicy{frontend::detail::applicationUrl(address, port, "", launch.origin), policy}, nullptr, {}, window, false, - launch); + launch, + std::move(answerContextMenu)); } } // namespace webfront::cef @@ -1152,9 +1214,10 @@ inline void initialize() { inline void open(std::string_view /*address*/, std::string_view /*port*/, std::string_view /*file*/, - const ContentPolicy& = {}, - const WindowOptions& = {}, - const ViewLaunch& = {}) { + const ContentPolicy& = {}, + const WindowOptions& = {}, + const ViewLaunch& = {}, + std::function(const Menu&)> = {}) { throw std::runtime_error("webfront::frontend::CEFFrontend requires CEF support, but this build was configured with " "WEBFRONT_EMBED_CEF=OFF. Reconfigure with -DWEBFRONT_EMBED_CEF=ON to use the embedded CEF frontend."); } diff --git a/include/webfront/frontend/CEFWindow.hpp b/include/webfront/frontend/CEFWindow.hpp new file mode 100644 index 00000000..b9efc24a --- /dev/null +++ b/include/webfront/frontend/CEFWindow.hpp @@ -0,0 +1,352 @@ +// SPDX-License-Identifier: Apache-2.0 OR CECILL-B +// Author: Ambroise Leclerc +// Created: 2026-12-06 +// +// WebFront — frontend +// Role: WindowControl of a CEF Views window: placement, state and context menu; no application menu nor tray. +// Thread: ui-loop | Alloc: unrestricted +// LLM: included by CEF.hpp only with WEBFRONT_EMBED_CEF; every call on CEF's UI thread, release() before CefShutdown + +#pragma once + +#include "WindowControl.hpp" + +#if defined(WEBFRONT_EMBED_CEF) + + #include "cef_menu_model.h" + #include "cef_menu_model_delegate.h" + #include "cef_task.h" + #include "views/cef_display.h" + #include "views/cef_window.h" + + #if defined(__linux__) + #include "internal/cef_types_linux.h" + #endif + + #include + #include + #include + +namespace webfront::cef { + +using frontend::WindowPlacement; + +/// One context menu: its ids, what was chosen, and the answer it owes once. +class CefContextMenu : public CefMenuModelDelegate { +public: + static constexpr int firstCommand = 28500; // MENU_ID_USER_FIRST and beyond are the application's + + CefContextMenu(const Menu& menu, frontend::WindowControl::Closed whenClosed) : closed(std::move(whenClosed)) { + model = CefMenuModel::CreateMenuModel(this); + build(model, frontend::withInheritedState(menu)); + } + + CefRefPtr nativeModel() const { + return model; + } + /// Records the choice of `id`, false when the menu has no such enabled item. + bool choose(std::string_view id) { + if (!closed) + return false; // already answered: the menu is gone + for (std::size_t i = 0; i < ids.size(); ++i) + if (ids[i] == id && enabled[i]) { + choice = ids[i]; + return true; + } + return false; + } + /// Runs the handler, once. + void answer() noexcept { + if (const auto handler = std::exchange(closed, {})) { + try { + handler(choice); + } catch (...) { + try { + log::error("CEF: a menu handler failed"); + } catch (...) { } + } + } + model = nullptr; // the model holds its delegate + } + + void ExecuteCommand(CefRefPtr, int command, cef_event_flags_t) override { + const auto index = static_cast(command - firstCommand); + if (command >= firstCommand && index < ids.size()) + choice = ids[index]; + } + void MenuClosed(CefRefPtr) override { + // The command of the chosen item may be executed after the menu is told closed: answer from the next task. + CefPostTask(TID_UI, new Answer(this)); + } + +private: + class Answer : public CefTask { + public: + explicit Answer(CefRefPtr owner) : menu(std::move(owner)) { } + void Execute() override { + menu->answer(); + } + + private: + CefRefPtr menu; + IMPLEMENT_REFCOUNTING(Answer); + }; + + void build(CefRefPtr target, const Menu& menu) { + for (const auto& item : menu) { + if (item.separator) { + target->AddSeparator(); + continue; + } + const int command = firstCommand + static_cast(ids.size()); + if (!item.items.empty()) { + // A submenu takes a command of its own, which no handler answers. + ids.emplace_back(); + enabled.push_back(false); + const auto child = target->AddSubMenu(command, item.label); + build(child, item.items); + } else { + ids.push_back(item.id); + enabled.push_back(item.enabled); + if (item.checkable) { + target->AddCheckItem(command, item.label); + target->SetChecked(command, item.checked); + } else + target->AddItem(command, item.label); + } + target->SetEnabled(command, item.enabled); + } + } + + CefRefPtr model; + std::vector ids; + std::vector enabled; + std::optional choice; + frontend::WindowControl::Closed closed; + IMPLEMENT_REFCOUNTING(CefContextMenu); +}; + +/** + * @brief The window of the CEF frontend. Position and always-on-top are unsupported where Chromium does not use X11 on + * Linux (Wayland). The Views toolkit offers neither an application menu bar of its own nor a notification icon. + */ +class CefWindowControl : public frontend::WindowControl { +public: + explicit CefWindowControl(std::function onMinimumSize = {}) : minimumSizeChanged(std::move(onMinimumSize)) { } + + /// The window exists: from now on the control answers for it. + void attach(CefRefPtr created) { + window = std::move(created); + boundsChanged(); + } + /// The view of the page, whose top left corner places the context menus. + void setView(CefRefPtr pageView) { + view = std::move(pageView); + } + /// The window moved, was resized or changed state: keeps what another session restores. + void boundsChanged() { + if (!window) + return; + const auto now = current(); + if (now.minimized) + return; // a minimized window does not say that it was maximized: keep what was known + remembered.maximized = now.maximized; + remembered.fullscreen = now.fullscreen; + if (!now.maximized && !now.fullscreen && now.width > 0 && now.height > 0) { + remembered.x = now.x; + remembered.y = now.y; + remembered.width = now.width; + remembered.height = now.height; + } + } + /// The last placement worth restoring; known after the window is gone. + [[nodiscard]] std::optional lastPlacement() const { + if (remembered.width <= 0) + return std::nullopt; + return remembered; + } + void release() noexcept { + if (pending) { + pending->answer(); + pending = nullptr; + } + window = nullptr; + view = nullptr; + } + + static std::vector screens() { + std::vector> displays; + CefDisplay::GetAllDisplays(displays); + std::vector areas; + for (const auto& display : displays) { + const auto area = display->GetWorkArea(); + areas.push_back({area.x, area.y, area.width, area.height}); + } + return areas; + } + + /// Whether the system lets a program place its windows. + static bool positionable() { + #if defined(__linux__) + // cef_get_xdisplay() is also set on a Wayland desktop (XWayland), where Chromium cannot place its windows. + const char* session = std::getenv("XDG_SESSION_TYPE"); + return cef_get_xdisplay() != nullptr && !frontend::waylandSession(session ? session : ""); + #else + return true; + #endif + } + + [[nodiscard]] frontend::WindowFeatures features() override { + const bool placed = positionable(); + return {.position = placed, + .size = true, + .maximize = true, + .fullscreen = true, + .minimize = true, + .alwaysOnTop = placed, + .minimumSize = true, + .menu = false, + .contextMenu = true, + .tray = false}; + } + [[nodiscard]] std::expected placement() override { + if (!window) + return std::unexpected(frontend::WindowFailure::closed); + return current(); + } + [[nodiscard]] std::expected restorablePlacement() override { + auto result = placement(); + if (result && (result->maximized || result->fullscreen || result->minimized) && remembered.width > 0) { + result->x = remembered.x; + result->y = remembered.y; + result->width = remembered.width; + result->height = remembered.height; + result->minimized = false; + } + return result; + } + + frontend::WindowStatus move(int x, int y) override { + if (!window) + return closed(); + if (!positionable()) + return unsupported(); + window->SetPosition(CefPoint(x, y)); + return {}; + } + frontend::WindowStatus resize(int width, int height) override { + if (width <= 0 || height <= 0) + return std::unexpected(frontend::WindowFailure::invalid); + if (!window) + return closed(); + window->SetSize(CefSize(width, height)); + return {}; + } + frontend::WindowStatus setMaximized(bool on) override { + if (!window) + return closed(); + if (on) + window->Maximize(); + else if (window->IsMaximized()) + window->Restore(); + return {}; + } + frontend::WindowStatus setFullscreen(bool on) override { + if (!window) + return closed(); + window->SetFullscreen(on); + return {}; + } + frontend::WindowStatus minimize() override { + if (!window) + return closed(); + window->Minimize(); + return {}; + } + frontend::WindowStatus setAlwaysOnTop(bool on) override { + if (!window) + return closed(); + if (!positionable()) + return unsupported(); + window->SetAlwaysOnTop(on); + return {}; + } + frontend::WindowStatus setMinimumSize(int width, int height) override { + if (width < 0 || height < 0) + return std::unexpected(frontend::WindowFailure::invalid); + if (!window) + return closed(); + if (minimumSizeChanged) + minimumSizeChanged(width, height); + window->InvalidateLayout(); + return {}; + } + frontend::WindowStatus activate(frontend::MenuSource source, std::string_view id) override { + if (source != frontend::MenuSource::context) + return unsupported(); + if (!window) + return closed(); + if (!pending || !pending->choose(id)) + return std::unexpected(frontend::WindowFailure::invalid); + const auto menu = std::exchange(pending, nullptr); + window->CancelMenu(); + CefPostTask(TID_UI, new Dismiss(menu)); // should the toolkit not tell a menu it never showed that it closed + return {}; + } + +protected: + frontend::WindowStatus popUp(const Menu& menu, int x, int y, Closed done) override { + if (!window || !view) + return closed(); + CefPoint at(x, y); + if (!view->ConvertPointToScreen(at)) + return std::unexpected(frontend::WindowFailure::failed); + if (pending) { + window->CancelMenu(); + pending->answer(); + } + pending = new CefContextMenu(menu, std::move(done)); + window->ShowMenu(pending->nativeModel(), at, CEF_MENU_ANCHOR_TOPLEFT); + return {}; + } + +private: + class Dismiss : public CefTask { + public: + explicit Dismiss(CefRefPtr dismissed) : menu(std::move(dismissed)) { } + void Execute() override { + menu->answer(); + } + + private: + CefRefPtr menu; + IMPLEMENT_REFCOUNTING(Dismiss); + }; + + static frontend::WindowStatus closed() { + return std::unexpected(frontend::WindowFailure::closed); + } + [[nodiscard]] WindowPlacement current() { + const auto bounds = window->GetBounds(); + WindowPlacement result; + if (positionable()) { + result.x = bounds.x; + result.y = bounds.y; + } + result.width = bounds.width; + result.height = bounds.height; + result.maximized = window->IsMaximized(); + result.fullscreen = window->IsFullscreen(); + result.minimized = window->IsMinimized(); + return result; + } + + CefRefPtr window; + CefRefPtr view; + CefRefPtr pending; + WindowPlacement remembered{}; + std::function minimumSizeChanged; +}; + +} // namespace webfront::cef +#endif diff --git a/include/webfront/frontend/EmbeddedFrontend.hpp b/include/webfront/frontend/EmbeddedFrontend.hpp index 61119350..07e8b6cf 100644 --- a/include/webfront/frontend/EmbeddedFrontend.hpp +++ b/include/webfront/frontend/EmbeddedFrontend.hpp @@ -19,6 +19,7 @@ #include "ScriptDialogs.hpp" #include "UIExecutor.hpp" #include "Window.hpp" +#include "WindowControl.hpp" #include #include @@ -64,6 +65,8 @@ struct ViewOptions { /// 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{}; + /// Test injection: chooses in a native context menu (the id, or nothing to dismiss it) instead of showing it. + std::function(const Menu&)> answerContextMenu{}; /// 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{}; @@ -79,6 +82,7 @@ struct ViewOptions { downloadDirectory = first.downloadDirectory; downloadFinished = first.downloadFinished; answerScriptDialog = first.answerScriptDialog; + answerContextMenu = first.answerContextMenu; } }; @@ -116,6 +120,12 @@ struct EmbeddedFrontend { return nativeWindowHostOf().window(); } + /// Control of the window (position, state, menus, tray), usable on the interface thread while open() runs + /// (see WindowControl.hpp). + [[nodiscard]] static WindowControlRef windowControl() { + return windowControlHostOf().control(); + } + static void initialize() { if constexpr (requires { Derived::initializeNative(); }) Derived::initializeNative(); diff --git a/include/webfront/frontend/Frontend.hpp b/include/webfront/frontend/Frontend.hpp index 39eeba47..ab3cb164 100644 --- a/include/webfront/frontend/Frontend.hpp +++ b/include/webfront/frontend/Frontend.hpp @@ -254,7 +254,7 @@ struct CEFFrontend : EmbeddedFrontend { } } static void openNative(std::string_view address, std::string_view port, std::string_view file, const Options& options) { - cef::open(address, port, file, options.contentPolicy, options.window, options.launch); + cef::open(address, port, file, options.contentPolicy, options.window, options.launch, options.answerContextMenu); } static void closeNative([[maybe_unused]] const NativeWindowHandle& window) { #ifdef WEBFRONT_EMBED_CEF diff --git a/include/webfront/frontend/WKWebView.hpp b/include/webfront/frontend/WKWebView.hpp index 90f4c72a..f188d074 100644 --- a/include/webfront/frontend/WKWebView.hpp +++ b/include/webfront/frontend/WKWebView.hpp @@ -49,6 +49,8 @@ using WKWebViewOptions = ViewOptions; } // namespace webfront::frontend #if defined(WEBFRONT_EMBED_WKWEBVIEW) && defined(__APPLE__) + #include "WKWebViewWindow.hpp" + #include #include #include @@ -330,10 +332,13 @@ struct Session { std::exception_ptr failure; std::shared_ptr captureTarget = std::make_shared(); CaptureRegistration captureRegistration; + /// The control of the window (position, state, menus, status item), created with it. + std::unique_ptr control; ~Session() { *alive = nullptr; - endSheets(); // Each open panel answers "cancel" now, while the view still exists to receive it. + control.reset(); // while the window and the main menu are still those of this session + endSheets(); // Each open panel answers "cancel" now, while the view still exists to receive it. abandonDownloads(); captureRegistration = {}; abandonCaptures(*captureTarget); @@ -430,9 +435,21 @@ struct Session { } } + /// Keeps the placement of the application's own window for its next one, while the window is still on screen. + void keepPlacement() noexcept { + if (secondary || !control || options.window.rememberAs.empty()) + return; + try { + if (const auto placement = control->restorablePlacement()) + savePlacement(options.window, *placement); + } catch (...) { } + } + void close() noexcept { if (secondary && closed) return; // the primary window repeats its stop request: the loop may have started since the first call + if (!closed) + keepPlacement(); closed = true; if (secondary) { if (window) @@ -560,7 +577,8 @@ struct Session { } // Deliver script-created popup attempts to the delegates, which always cancel unmanaged views. send(send(configuration.get(), "preferences"), "setJavaScriptCanOpenWindowsAutomatically:", static_cast(true)); - const auto windowOptions = frontend::detail::resolveWindow(options.window); + const auto saved = secondary ? std::nullopt : loadPlacement(options.window); + const auto windowOptions = frontend::detail::resolveWindow(restoredOptions(options.window, saved)); const CGRect bounds{ { 0, 0}, {static_cast(windowOptions.width), static_cast(windowOptions.height)} @@ -610,12 +628,29 @@ struct Session { send(window, "setContentView:", view); send(window, "makeFirstResponder:", view); send(window, "center"); + control = std::make_unique(window, view, delegate); + control->answerContextMenu = options.answerContextMenu; + if (windowOptions.frameless) + control->removeTitleBar(); + static_cast(control->setMinimumSize(windowOptions.minimumWidth, windowOptions.minimumHeight)); + // The size given at creation is that of the content; a kept placement is that of the frame. + if (saved) { + static_cast(control->resize(saved->width, saved->height)); + if (reachable(*saved, cocoawindow::CocoaWindowControl::screens())) + static_cast(control->move(*saved->x, *saved->y)); + } + if (windowOptions.alwaysOnTop) + static_cast(control->setAlwaysOnTop(true)); trace("view created"); if (options.visible) { // Nearly transparent, not hidden: an occluded window would suspend the page's animation frames. send(window, "setAlphaValue:", 0.01); send(window, "makeKeyAndOrderFront:", static_cast(nullptr)); send(app, "activateIgnoringOtherApps:", static_cast(true)); + if (windowOptions.fullscreen) + static_cast(control->setFullscreen(true)); + else if (windowOptions.maximized) + static_cast(control->setMaximized(true)); } } @@ -1042,7 +1077,19 @@ inline void contentProcessTerminatedWithReason(id self, SEL, id, long reason) { s->fail("web content process terminated: " + contentTerminationReason(reason)); } +inline void menuChosen(id self, SEL, id sender) { + if (auto s = session(self); s && s->control) + s->control->menuChosen(sender); +} +inline void windowFrameChanged(id self, SEL, id) { + if (auto s = session(self); s && s->control) + s->control->frameChanged(); +} + inline void addApplicationMethods(Class cls) { + addMethod(cls, "webfrontMenu:", menuChosen, "v@:@"); + addMethod(cls, "windowDidMove:", windowFrameChanged, "v@:@"); + addMethod(cls, "windowDidResize:", windowFrameChanged, "v@:@"); addMethod(cls, "windowWillClose:", sessionClosed, "v@:@"); addMethod(cls, "webViewDidClose:", sessionClosed, "v@:@"); addMethod(cls, "webfrontQuit:", sessionClosed, "v@:@"); @@ -1181,7 +1228,7 @@ inline void addNavigationMethods(Class cls) { } inline Class delegateClass() { - static Class cls = registerClass("WebFrontWKDelegate_v1", reinterpret_cast(type("NSObject")), [](Class result) { + static Class cls = registerClass("WebFrontWKDelegate_v2", reinterpret_cast(type("NSObject")), [](Class result) { addApplicationMethods(result); addNavigationMethods(result); }); @@ -1286,6 +1333,7 @@ inline void open(std::string_view address, std::string_view port, std::string_vi Object pool(send(type("NSAutoreleasePool"), "new")); Session window(applicationUrl(address, port, file, options.launch.origin), options); window.create(); + PublishedWindowControl publishedControl(windowControlHostOf(), *window.control); window.start(); // The AppKit loop drains the main queue: a wake is a block on it. Closing completes pending operations stopped, // also when run() throws or returns at once because the window already closed. The window is published once the diff --git a/include/webfront/frontend/WKWebViewWindow.hpp b/include/webfront/frontend/WKWebViewWindow.hpp new file mode 100644 index 00000000..1f9f65d1 --- /dev/null +++ b/include/webfront/frontend/WKWebViewWindow.hpp @@ -0,0 +1,471 @@ +// SPDX-License-Identifier: Apache-2.0 OR CECILL-B +// Author: Ambroise Leclerc +// Created: 2026-12-06 +// +// WebFront — frontend +// Role: WindowControl of an NSWindow through the Objective-C runtime: placement, state, menus and status item. +// Thread: ui-loop | Alloc: unrestricted +// LLM: used by WKWebView.hpp; main thread only, release() before the window is released + +#pragma once + +#include "WindowControl.hpp" + +#if defined(__APPLE__) + + #include + #include + #include + #include + #include + #include + + #include + #include + #include + +namespace webfront::frontend::detail::cocoawindow { + +template +Result msg(id object, const char* selector, Args... args) { + return reinterpret_cast(objc_msgSend)(object, sel_registerName(selector), args...); +} + +/// A CGRect result: Intel returns a structure of this size through objc_msgSend_stret. +inline CGRect rectOf(id object, const char* selector) { + #if defined(__x86_64__) + CGRect result{}; + reinterpret_cast(objc_msgSend_stret)(&result, object, sel_registerName(selector)); + return result; + #else + return msg(object, selector); + #endif +} + +inline id classNamed(const char* name) { + return reinterpret_cast(objc_getClass(name)); +} + +/// A retained NSString. +inline id string(std::string_view value) { + return msg(msg(classNamed("NSString"), "alloc"), "initWithBytes:length:encoding:", value.data(), value.size(), 4UL); +} + +struct Owned { + id value; + explicit Owned(id owned) : value(owned) { } + Owned(const Owned&) = delete; + Owned& operator=(const Owned&) = delete; + ~Owned() { + msg(value, "release"); + } +}; + +/// The key equivalent of a parsed shortcut, in UTF-8. +inline std::string keyEquivalent(const Shortcut& shortcut) { + const auto& key = shortcut.key; + if (key == "enter") + return "\r"; + if (key == "escape") + return "\x1b"; + if (key == "delete") + return "\x08"; + if (key == "tab") + return "\t"; + if (key == "space") + return " "; + if (key == "plus") + return "+"; + // The function keys of AppKit (NSUpArrowFunctionKey 0xF700 and on), as three bytes of UTF-8. + unsigned code = 0; + if (key == "up") + code = 0xF700; + else if (key == "down") + code = 0xF701; + else if (key == "left") + code = 0xF702; + else if (key == "right") + code = 0xF703; + else if (key.size() > 1 && key[0] == 'f') + code = 0xF704u + static_cast(std::atoi(key.c_str() + 1) - 1); + if (code == 0) + return key; + return {static_cast(0xE0 | (code >> 12)), static_cast(0x80 | ((code >> 6) & 0x3F)), static_cast(0x80 | (code & 0x3F))}; +} + +class CocoaWindowControl : public WindowControl { + static constexpr long applicationBase = 1000; + static constexpr long trayBase = 2000; + static constexpr long contextBase = 3000; + + id window; + id view; + id target; // the session's delegate, which answers webfrontMenu: + + std::vector menuIds, trayIds, contextIds; + std::vector menuItems; // the entries added to the main menu, retained + std::vector menuLeaves, trayLeaves; + Selected menuSelected, traySelected; + std::optional contextChoice; + id statusItem = nullptr; + WindowPlacement normal{}; // the geometry when neither zoomed, full screen nor miniaturized + + static WindowStatus closed() { + return std::unexpected(WindowFailure::closed); + } + static id application() { + return msg(classNamed("NSApplication"), "sharedApplication"); + } + /// The height of the primary screen: AppKit counts from its bottom left corner. + static CGFloat primaryHeight() { + const auto screens = msg(classNamed("NSScreen"), "screens"); + return msg(screens, "count") ? rectOf(msg(screens, "objectAtIndex:", 0UL), "frame").size.height : 0; + } + static CGRect flipped(CGRect rect) { + rect.origin.y = primaryHeight() - rect.origin.y - rect.size.height; + return rect; + } + + [[nodiscard]] bool isFullscreen() const { + return (msg(window, "styleMask") & (1UL << 14)) != 0; + } + [[nodiscard]] bool isZoomed() const { + return !isFullscreen() && msg(window, "isZoomed"); + } + [[nodiscard]] WindowPlacement current() const { + const auto frame = flipped(rectOf(window, "frame")); + WindowPlacement result; + result.x = static_cast(std::lround(frame.origin.x)); + result.y = static_cast(std::lround(frame.origin.y)); + result.width = static_cast(std::lround(frame.size.width)); + result.height = static_cast(std::lround(frame.size.height)); + result.fullscreen = isFullscreen(); + result.maximized = isZoomed(); + result.minimized = msg(window, "isMiniaturized"); + return result; + } + + /// Fills an NSMenu; the tag of a leaf is `base` plus its position among the leaves. + void build(id nativeMenu, const Menu& menu, long base, std::vector& ids, std::vector* leaves) { + msg(nativeMenu, "setAutoenablesItems:", static_cast(false)); + for (const auto& item : menu) { + if (item.separator) { + msg(nativeMenu, "addItem:", msg(classNamed("NSMenuItem"), "separatorItem")); + continue; + } + const Owned label(string(item.label)); + const auto shortcut = parseShortcut(item.shortcut); + const Owned key(string(shortcut ? keyEquivalent(*shortcut) : std::string{})); + const bool leaf = item.items.empty(); + const Owned entry(msg(msg(classNamed("NSMenuItem"), "alloc"), + "initWithTitle:action:keyEquivalent:", + label.value, + leaf ? sel_registerName("webfrontMenu:") : static_cast(nullptr), + key.value)); + msg(entry.value, "setEnabled:", static_cast(item.enabled)); + if (leaf) { + if (shortcut) { + const auto mask = (shortcut->shift ? 1UL << 17 : 0) | (shortcut->control ? 1UL << 18 : 0) | (shortcut->alt ? 1UL << 19 : 0) + | (shortcut->meta ? 1UL << 20 : 0); + msg(entry.value, "setKeyEquivalentModifierMask:", static_cast(mask)); + } + msg(entry.value, "setTarget:", target); + msg(entry.value, "setTag:", base + static_cast(ids.size())); + msg(entry.value, "setState:", item.checked ? 1L : 0L); + ids.push_back(item.id); + if (leaves) + leaves->push_back(entry.value); // owned by its menu + } else { + const Owned submenu(msg(msg(classNamed("NSMenu"), "alloc"), "initWithTitle:", label.value)); + build(submenu.value, item.items, base, ids, leaves); + msg(entry.value, "setSubmenu:", submenu.value); + } + msg(nativeMenu, "addItem:", entry.value); + } + } + + void removeMenu() { + const auto main = msg(application(), "mainMenu"); + for (const auto item : menuItems) { + if (main && msg(main, "indexOfItem:", item) >= 0) + msg(main, "removeItem:", item); + msg(item, "release"); + } + menuItems.clear(); + menuLeaves.clear(); + menuIds.clear(); + menuSelected = {}; + } + void removeTray() { + if (statusItem) { + msg(msg(classNamed("NSStatusBar"), "systemStatusBar"), "removeStatusItem:", statusItem); + msg(statusItem, "release"); + statusItem = nullptr; + } + trayLeaves.clear(); + trayIds.clear(); + traySelected = {}; + } + + static void choose(const std::vector& ids, const Selected& selected, long index) noexcept { + if (index < 0 || static_cast(index) >= ids.size() || !selected) + return; + try { + // Copies: the handler may replace the menu it comes from. + const auto id = ids[static_cast(index)]; + const auto handler = selected; + handler(id); + } catch (...) { + try { + log::error("WKWebView: a menu handler failed"); + } catch (...) { } + } + } + +public: + CocoaWindowControl(id nsWindow, id webView, id menuTarget) : window(nsWindow), view(webView), target(menuTarget) { + normal = current(); + } + ~CocoaWindowControl() override { + release(); + } + + /// Removes the menus and the status item; the control then answers `closed`. + void release() noexcept { + if (!window) + return; + try { + removeTray(); + removeMenu(); + } catch (...) { } + window = nullptr; + } + + /// The action of every menu item, sent to the session's delegate. + void menuChosen(id sender) noexcept { + const auto tag = msg(sender, "tag"); + if (tag >= contextBase) { + const auto index = static_cast(tag - contextBase); + if (index < contextIds.size()) + contextChoice = contextIds[index]; + } else if (tag >= trayBase) + choose(trayIds, traySelected, tag - trayBase); + else + choose(menuIds, menuSelected, tag - applicationBase); + } + + /// Called by the delegate after the window moved or was resized. + void frameChanged() noexcept { + if (!window) + return; + const auto now = current(); + if (!now.maximized && !now.fullscreen && !now.minimized) + normal = now; + } + + /// Frameless: the content covers the title bar, whose buttons are hidden. The window stays able to take the keyboard. + void removeTitleBar() { + msg(window, "setStyleMask:", msg(window, "styleMask") | (1UL << 15)); // full size content view + msg(window, "setTitlebarAppearsTransparent:", static_cast(true)); + msg(window, "setTitleVisibility:", 1L); + for (unsigned long button = 0; button < 3; ++button) // close, miniaturize, zoom + msg(msg(window, "standardWindowButton:", button), "setHidden:", static_cast(true)); + } + + static std::vector screens() { + std::vector areas; + const auto all = msg(classNamed("NSScreen"), "screens"); + for (unsigned long i = 0; i < msg(all, "count"); ++i) { + const auto area = flipped(rectOf(msg(all, "objectAtIndex:", i), "visibleFrame")); + areas.push_back( + {static_cast(area.origin.x), static_cast(area.origin.y), static_cast(area.size.width), static_cast(area.size.height)}); + } + return areas; + } + + [[nodiscard]] WindowFeatures features() override { + return {.position = true, + .size = true, + .maximize = true, + .fullscreen = true, + .minimize = true, + .alwaysOnTop = true, + .minimumSize = true, + .menu = true, + .contextMenu = true, + .tray = true}; + } + [[nodiscard]] std::expected placement() override { + if (!window) + return std::unexpected(WindowFailure::closed); + return current(); + } + [[nodiscard]] std::expected restorablePlacement() override { + auto result = placement(); + if (result && (result->maximized || result->fullscreen || result->minimized)) { + result->x = normal.x; + result->y = normal.y; + result->width = normal.width; + result->height = normal.height; + result->minimized = false; + } + return result; + } + + WindowStatus move(int x, int y) override { + if (!window) + return closed(); + const auto height = rectOf(window, "frame").size.height; + const CGPoint origin{static_cast(x), primaryHeight() - static_cast(y) - height}; + msg(window, "setFrameOrigin:", origin); + frameChanged(); + return {}; + } + WindowStatus resize(int width, int height) override { + if (width <= 0 || height <= 0) + return std::unexpected(WindowFailure::invalid); + if (!window) + return closed(); + auto frame = rectOf(window, "frame"); + frame.origin.y += frame.size.height - static_cast(height); // the top left corner stays + frame.size = {static_cast(width), static_cast(height)}; + msg(window, "setFrame:display:", frame, static_cast(true)); + frameChanged(); + return {}; + } + WindowStatus setMaximized(bool on) override { + if (!window) + return closed(); + if (on != isZoomed()) + msg(window, "zoom:", static_cast(nullptr)); + return {}; + } + WindowStatus setFullscreen(bool on) override { + if (!window) + return closed(); + msg(window, "setCollectionBehavior:", msg(window, "collectionBehavior") | (1UL << 7)); // full screen primary + if (on != isFullscreen()) + msg(window, "toggleFullScreen:", static_cast(nullptr)); + return {}; + } + WindowStatus minimize() override { + if (!window) + return closed(); + msg(window, "miniaturize:", static_cast(nullptr)); + return {}; + } + WindowStatus setAlwaysOnTop(bool on) override { + if (!window) + return closed(); + msg(window, "setLevel:", on ? 3L : 0L); // NSFloatingWindowLevel, NSNormalWindowLevel + return {}; + } + WindowStatus setMinimumSize(int width, int height) override { + if (width < 0 || height < 0) + return std::unexpected(WindowFailure::invalid); + if (!window) + return closed(); + msg(window, "setMinSize:", CGSize{static_cast(width), static_cast(height)}); + return {}; + } + + WindowStatus setMenu(const Menu& menu, Selected selected) override { + if (!validMenu(menu)) + return std::unexpected(WindowFailure::invalid); + if (!window) + return closed(); + // What can be refused is checked before the old menu is taken away. + const auto main = msg(application(), "mainMenu"); + if (!menu.empty() && !main) + return std::unexpected(WindowFailure::failed); + removeMenu(); + if (menu.empty()) + return {}; + menuSelected = std::move(selected); + // Built into a menu of its own, then moved after the Application and Edit menus of the frontend. + const Owned built(msg(classNamed("NSMenu"), "new")); + build(built.value, withInheritedState(menu), applicationBase, menuIds, &menuLeaves); + while (msg(built.value, "numberOfItems") > 0) { + const auto item = msg(msg(built.value, "itemAtIndex:", 0L), "retain"); + msg(built.value, "removeItemAtIndex:", 0L); + msg(main, "addItem:", item); + menuItems.push_back(item); + } + return {}; + } + + WindowStatus setTray(const std::optional& tray, Selected selected) override { + if (!window) + return closed(); + if (tray && !validMenu(tray->menu)) + return std::unexpected(WindowFailure::invalid); + if (!tray) { + removeTray(); + return {}; + } + // The icon is read before the old tray is taken away: an unreadable one leaves it in place. + id image = nullptr; + if (!tray->icon.empty()) { + const Owned path(string(tray->icon.string())); + image = msg(msg(classNamed("NSImage"), "alloc"), "initWithContentsOfFile:", path.value); + if (!image) + return std::unexpected(WindowFailure::invalid); + msg(image, "setSize:", CGSize{18, 18}); + } + removeTray(); + statusItem = msg(msg(msg(classNamed("NSStatusBar"), "systemStatusBar"), "statusItemWithLength:", static_cast(-1)), "retain"); + const auto button = msg(statusItem, "button"); + const Owned title(string(tray->title.empty() && !image ? std::string("\xE2\x97\x8F") : tray->title)); + const Owned tooltip(string(tray->tooltip)); + msg(button, "setTitle:", title.value); + msg(button, "setToolTip:", tooltip.value); + if (image) { + msg(button, "setImage:", image); + msg(image, "release"); + } + if (!tray->menu.empty()) { + const Owned nativeMenu(msg(classNamed("NSMenu"), "new")); + build(nativeMenu.value, withInheritedState(tray->menu), trayBase, trayIds, &trayLeaves); + msg(statusItem, "setMenu:", nativeMenu.value); + } + traySelected = std::move(selected); + return {}; + } + + WindowStatus activate(MenuSource source, std::string_view item) override { + if (source == MenuSource::context) + return unsupported(); // popUpMenuPositioningItem: blocks until the user chooses + if (!window) + return closed(); + const bool fromTray = source == MenuSource::tray; + const auto& ids = fromTray ? trayIds : menuIds; + const auto& leaves = fromTray ? trayLeaves : menuLeaves; + const auto found = std::ranges::find(ids, item); + if (found == ids.end()) + return std::unexpected(WindowFailure::invalid); + const auto entry = leaves[static_cast(found - ids.begin())]; + const auto menu = msg(entry, "menu"); + // A top level item was moved to the main menu: its menu is that one. + if (menu) + msg(menu, "performActionForItemAtIndex:", msg(menu, "indexOfItem:", entry)); + return {}; + } + +protected: + WindowStatus popUp(const Menu& menu, int x, int y, Closed done) override { + if (!window) + return closed(); + contextIds.clear(); + contextChoice.reset(); + const Owned nativeMenu(msg(classNamed("NSMenu"), "new")); + build(nativeMenu.value, withInheritedState(menu), contextBase, contextIds, nullptr); + // WKWebView is flipped: its coordinates are those of the page. + const CGPoint at{static_cast(x), static_cast(y)}; + msg(nativeMenu.value, "popUpMenuPositioningItem:atLocation:inView:", static_cast(nullptr), at, view); + done(std::exchange(contextChoice, std::nullopt)); + return {}; + } +}; + +} // namespace webfront::frontend::detail::cocoawindow +#endif diff --git a/include/webfront/frontend/WebKitGTK.hpp b/include/webfront/frontend/WebKitGTK.hpp index 419a40b0..23ce676a 100644 --- a/include/webfront/frontend/WebKitGTK.hpp +++ b/include/webfront/frontend/WebKitGTK.hpp @@ -25,7 +25,9 @@ #include "UIExecutor.hpp" #include "Url.hpp" #include "WebKitGTKPolicy.hpp" +#include "WebKitGTKWindow.hpp" #include "Window.hpp" +#include "WindowControl.hpp" #include "WindowRegistry.hpp" #include @@ -94,6 +96,9 @@ class Api { const char* (*windowGetTitle)(Object) = symbol("gtk_window_get_title"); void (*windowSize)(Object, int, int) = symbol("gtk_window_set_default_size"); void (*windowChild)(Object, Object) = symbol("gtk_window_set_child"); + Object (*boxNew)(int, int) = symbol("gtk_box_new"); + void (*boxAppend)(Object, Object) = symbol("gtk_box_append"); + void (*widgetVexpand)(Object, int) = symbol("gtk_widget_set_vexpand"); void (*windowMaximize)(Object) = symbol("gtk_window_maximize"); void (*windowFullscreen)(Object) = symbol("gtk_window_fullscreen"); void (*windowDecorated)(Object, int) = symbol("gtk_window_set_decorated"); @@ -375,6 +380,7 @@ struct Session : FailureState { Api& a = api(); Api::Object loop = a.loopNew(nullptr, 0); Api::Object window = nullptr; + Api::Object content = nullptr; // the vertical box of the window: the menu bar, then the view Api::Object view = nullptr; Api::Object network = nullptr; webfront::detail::BoundContentPolicy policy; @@ -418,8 +424,12 @@ struct Session : FailureState { unsigned portalTimer = 0; // retries the Wayland export until the toplevel can be exported int portalAttempts = 0; std::uint64_t portalGeneration = 0; // the publication this session's identifier belongs to - unsigned long windowHandler = 0; - std::vector viewHandlers; + /// The control of the window (position, state, menus), and the placement saved by an earlier session. + std::unique_ptr control; + std::optional savedPlacement; + bool mapped = false; + unsigned long windowHandler = 0; + std::vector viewHandlers; /// Profile files of the GStreamer opt-out (`WindowOptions::media == false`); empty otherwise. std::filesystem::path mediaPlugins, mediaRegistry; unsigned long messageHandler = 0; // on the content manager, not on the view @@ -432,6 +442,7 @@ struct Session : FailureState { Session(const Session&) = delete; Session& operator=(const Session&) = delete; ~Session() { + control.reset(); // before the widgets it uses if (portalTimer) a.sourceRemove(std::exchange(portalTimer, 0)); stopNavigationTimer(); @@ -486,9 +497,33 @@ struct Session : FailureState { a.windowDestroy(std::exchange(window, nullptr)); } + /// Keeps the placement of the application's own window for its next one, while the window is still on screen. + void keepPlacement() noexcept { + if (secondary || !mapped || !control || windowOptions.rememberAs.empty()) + return; + try { + if (const auto placement = control->restorablePlacement()) + savePlacement(windowOptions, *placement); + } catch (...) { } + } + /// What needs a mapped window: the saved position, if it is still on a screen, and the level of the window. + void placeWindow() { + mapped = true; + std::optional> restored; + if (savedPlacement && reachable(*savedPlacement, control->screens())) { + static_cast(control->move(*savedPlacement->x, *savedPlacement->y)); + restored = std::pair{*savedPlacement->x, *savedPlacement->y}; + } + control->trackPosition(restored); + if (windowOptions.alwaysOnTop) + static_cast(control->setAlwaysOnTop(true)); + } + void close() noexcept { const bool first = !closed; - closed = true; + if (first) + keepPlacement(); + 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 @@ -557,10 +592,18 @@ struct Session : FailureState { } view = a.refSink(a.objectNew(a.viewType(), "web-context", context, "network-session", network, nullptr)); a.unref(context); + if (!secondary) { + savedPlacement = loadPlacement(windowOptions); + windowOptions = restoredOptions(std::move(windowOptions), savedPlacement); + } window = a.windowNew(); a.windowTitle(window, windowOptions.title.c_str()); a.windowSize(window, windowOptions.width, windowOptions.height); - a.windowChild(window, view); + content = a.boxNew(1 /*GTK_ORIENTATION_VERTICAL*/, 0); + a.widgetVexpand(view, 1); + a.boxAppend(content, view); + a.windowChild(window, content); + control = std::make_unique(window, content, view); if (windowOptions.minimumWidth > 0 || windowOptions.minimumHeight > 0) // -1: no minimum on that side a.widgetSizeRequest(window, windowOptions.minimumWidth > 0 ? windowOptions.minimumWidth : -1, @@ -596,7 +639,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); - if (!secondary) // the portal identifier is that of the application's own window + placeWindow(); + 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. @@ -1000,10 +1044,11 @@ struct OpenOptions { ViewLaunch launch{}; std::chrono::milliseconds startupTimeout{30000}; // the initial document must load within this interval // The test injections of ViewOptions, for the first window and for the secondary ones. - std::function()> chooseFiles{}; - std::filesystem::path downloadDirectory{}; - std::function downloadFinished{}; - ScriptDialogHandler answerScriptDialog{}; + std::function()> chooseFiles{}; + std::filesystem::path downloadDirectory{}; + std::function downloadFinished{}; + ScriptDialogHandler answerScriptDialog{}; + std::function(const Menu&)> answerContextMenu{}; }; /// The options a frontend receives, as the session of a window takes them. @@ -1015,7 +1060,8 @@ inline OpenOptions openOptionsOf(const ViewOptions& view) { .chooseFiles = view.chooseFiles, .downloadDirectory = view.downloadDirectory, .downloadFinished = view.downloadFinished, - .answerScriptDialog = view.answerScriptDialog}; + .answerScriptDialog = view.answerScriptDialog, + .answerContextMenu = view.answerContextMenu}; } /// What the registry of the secondary windows (WindowRegistry.hpp) asks of GTK: reaping is an idle callback. @@ -1101,6 +1147,8 @@ open(std::string_view address, std::string_view port, std::string_view file, con session.downloadFinished = options.downloadFinished; session.answerScriptDialog = options.answerScriptDialog; session.create(mode); + session.control->answerContextMenu = options.answerContextMenu; + PublishedWindowControl publishedControl(windowControlHostOf(), *session.control); if (options.configure) options.configure(session); // g_idle_add_full is thread-safe and wakes the main context the loop of run() iterates. GTK realizes the window at diff --git a/include/webfront/frontend/WebKitGTKWindow.hpp b/include/webfront/frontend/WebKitGTKWindow.hpp new file mode 100644 index 00000000..91fb650a --- /dev/null +++ b/include/webfront/frontend/WebKitGTKWindow.hpp @@ -0,0 +1,691 @@ +// SPDX-License-Identifier: Apache-2.0 OR CECILL-B +// Author: Ambroise Leclerc +// Created: 2026-12-06 +// +// WebFront — frontend +// Role: WindowControl of the WebKitGTK window: GTK 4 state and menus, Xlib for what GTK 4 no longer does (position, above). +// Thread: ui-loop | Alloc: unrestricted +// LLM: used by WebKitGTK.hpp only; Wayland has no position nor always-on-top, and GTK 4 has no notification area + +#pragma once + +#include "WindowControl.hpp" + +#if defined(WEBFRONT_EMBED_WEBKITGTK) && defined(__linux__) + + #include + #include + #include + #include + #include + #include + #include + + #include + +namespace webfront::frontend::detail::webkitgtk { + +// As in WebKitGTK.hpp, only the stable C ABI crosses this boundary: no GTK nor X11 header. +class WindowApi { + void* module = dlopen("libwebkitgtk-6.0.so.4", RTLD_NOW | RTLD_LOCAL); + void* x11 = dlopen("libX11.so.6", RTLD_NOW | RTLD_LOCAL); + + template + Function symbol(const char* name) { + const auto result = module ? reinterpret_cast(dlsym(module, name)) : nullptr; + if (!result) + throw std::runtime_error(std::string("WebKitGTK: missing runtime symbol ") + name); + return result; + } + template + Function optionalSymbol(const char* name) { + return module ? reinterpret_cast(dlsym(module, name)) : nullptr; + } + template + Function xSymbol(const char* name) { + return x11 ? reinterpret_cast(dlsym(x11, name)) : nullptr; + } + +public: + using Object = void*; + using Callback = void (*)(); + struct Rectangle { + int x, y, width, height; + }; + + void (*defaultSize)(Object, int*, int*) = symbol("gtk_window_get_default_size"); + void (*setDefaultSize)(Object, int, int) = symbol("gtk_window_set_default_size"); + int (*isMaximized)(Object) = symbol("gtk_window_is_maximized"); + int (*isFullscreen)(Object) = symbol("gtk_window_is_fullscreen"); + void (*maximize)(Object) = symbol("gtk_window_maximize"); + void (*unmaximize)(Object) = symbol("gtk_window_unmaximize"); + void (*fullscreen)(Object) = symbol("gtk_window_fullscreen"); + void (*unfullscreen)(Object) = symbol("gtk_window_unfullscreen"); + void (*minimize)(Object) = symbol("gtk_window_minimize"); + void (*sizeRequest)(Object, int, int) = symbol("gtk_widget_set_size_request"); + int (*width)(Object) = symbol("gtk_widget_get_width"); + int (*height)(Object) = symbol("gtk_widget_get_height"); + Object (*nativeSurface)(Object) = symbol("gtk_native_get_surface"); + int (*instanceIsA)(Object, std::uintptr_t) = symbol("g_type_check_instance_is_a"); + Object (*surfaceDisplay)(Object) = symbol("gdk_surface_get_display"); + std::uintptr_t (*x11SurfaceType)() = optionalSymbol("gdk_x11_surface_get_type"); + unsigned long (*x11Xid)(Object) = optionalSymbol("gdk_x11_surface_get_xid"); + Object (*x11Display)(Object) = optionalSymbol("gdk_x11_display_get_xdisplay"); + // Menus. + Object (*menuNew)() = symbol("g_menu_new"); + void (*menuAppend)(Object, const char*, const char*) = symbol("g_menu_append"); + void (*menuSection)(Object, const char*, Object) = symbol("g_menu_append_section"); + void (*menuSubmenu)(Object, const char*, Object) = symbol("g_menu_append_submenu"); + Object (*groupNew)() = symbol("g_simple_action_group_new"); + Object (*actionNew)(const char*, Object) = symbol("g_simple_action_new"); + Object (*statefulActionNew)(const char*, Object, Object) = symbol("g_simple_action_new_stateful"); + Object (*variantBoolean)(int) = symbol("g_variant_new_boolean"); + void (*actionEnabled)(Object, int) = symbol("g_simple_action_set_enabled"); + void (*addAction)(Object, Object) = symbol("g_action_map_add_action"); + void (*activateAction)(Object, const char*, Object) = symbol("g_action_group_activate_action"); + void (*insertGroup)(Object, const char*, Object) = symbol("gtk_widget_insert_action_group"); + Object (*menuBarNew)(Object) = symbol("gtk_popover_menu_bar_new_from_model"); + Object (*popoverNew)(Object) = symbol("gtk_popover_menu_new_from_model"); + void (*popoverArrow)(Object, int) = symbol("gtk_popover_set_has_arrow"); + void (*popoverPointing)(Object, const Rectangle*) = symbol("gtk_popover_set_pointing_to"); + void (*popoverPopup)(Object) = symbol("gtk_popover_popup"); + void (*popoverPopdown)(Object) = symbol("gtk_popover_popdown"); + void (*setParent)(Object, Object) = symbol("gtk_widget_set_parent"); + void (*unparent)(Object) = symbol("gtk_widget_unparent"); + int (*translate)(Object, Object, double, double, double*, double*) = symbol("gtk_widget_translate_coordinates"); + void (*boxPrepend)(Object, Object) = symbol("gtk_box_prepend"); + void (*boxRemove)(Object, Object) = symbol("gtk_box_remove"); + Object (*firstChild)(Object) = symbol("gtk_widget_get_first_child"); + Object (*nextSibling)(Object) = symbol("gtk_widget_get_next_sibling"); + void (*setSensitive)(Object, int) = symbol("gtk_widget_set_sensitive"); + int (*getSensitive)(Object) = symbol("gtk_widget_get_sensitive"); + unsigned (*toplevelState)(Object) = symbol("gdk_toplevel_get_state"); + Object (*shortcutControllerNew)() = symbol("gtk_shortcut_controller_new"); + void (*propagationPhase)(Object, int) = symbol("gtk_event_controller_set_propagation_phase"); + Object (*triggerParse)(const char*) = symbol("gtk_shortcut_trigger_parse_string"); + Object (*namedAction)(const char*) = symbol("gtk_named_action_new"); + Object (*shortcutNew)(Object, Object) = symbol("gtk_shortcut_new"); + void (*addShortcut)(Object, Object) = symbol("gtk_shortcut_controller_add_shortcut"); + void (*addController)(Object, Object) = symbol("gtk_widget_add_controller"); + void (*removeController)(Object, Object) = symbol("gtk_widget_remove_controller"); + unsigned long (*connect)(Object, const char*, Callback, Object, void (*)(void*, void*), int) = symbol("g_signal_connect_data"); + void (*unref)(Object) = symbol("g_object_unref"); + unsigned (*idleAdd)(int, int (*)(void*), void*, void (*)(void*)) = symbol("g_idle_add_full"); + int (*sourceRemove)(unsigned) = symbol("g_source_remove"); + unsigned (*timeoutAdd)(int, unsigned, int (*)(void*), void*, void (*)(void*)) = symbol("g_timeout_add_full"); + Object (*displayMonitors)(Object) = symbol("gdk_display_get_monitors"); + unsigned (*itemCount)(Object) = symbol("g_list_model_get_n_items"); + Object (*itemAt)(Object, unsigned) = symbol("g_list_model_get_item"); + void (*monitorGeometry)(Object, Rectangle*) = symbol("gdk_monitor_get_geometry"); + int (*monitorScale)(Object) = symbol("gdk_monitor_get_scale_factor"); + // Xlib, absent on a Wayland-only system. + int (*xMove)(Object, unsigned long, int, int) = xSymbol("XMoveWindow"); + int (*xFlush)(Object) = xSymbol("XFlush"); + int (*xSync)(Object, int) = xSymbol("XSync"); + int (*xDefaultScreen)(Object) = xSymbol("XDefaultScreen"); + unsigned long (*xRoot)(Object) = xSymbol("XDefaultRootWindow"); + int (*xScreenWidth)(Object, int) = xSymbol("XDisplayWidth"); + int (*xScreenHeight)(Object, int) = xSymbol("XDisplayHeight"); + int (*xTranslate)(Object, unsigned long, unsigned long, int, int, int*, int*, unsigned long*) = xSymbol("XTranslateCoordinates"); + unsigned long (*xAtom)(Object, const char*, int) = xSymbol("XInternAtom"); + int (*xProperty)(Object, + unsigned long, + unsigned long, + long, + long, + int, + unsigned long, + unsigned long*, + int*, + unsigned long*, + unsigned long*, + unsigned char**) = xSymbol("XGetWindowProperty"); + int (*xFree)(void*) = xSymbol("XFree"); + int (*xSendEvent)(Object, unsigned long, int, long, void*) = xSymbol("XSendEvent"); + + [[nodiscard]] bool hasX11() const { + return x11SurfaceType && x11Xid && x11Display && xMove && xFlush && xTranslate && xRoot && xAtom && xProperty && xFree && xSendEvent && xDefaultScreen + && xScreenWidth && xScreenHeight && xSync; + } +}; + +inline WindowApi& windowApi() { + static WindowApi instance; + return instance; +} + +/// The GTK name of the key of a shortcut, and the accelerator string gtk_shortcut_trigger_parse_string reads. +[[nodiscard]] inline std::string gtkAccelerator(const Shortcut& shortcut) { + std::string result; + if (shortcut.control) + result += ""; + if (shortcut.alt) + result += ""; + if (shortcut.shift) + result += ""; + if (shortcut.meta) + result += ""; + static constexpr std::pair names[] = { + { "enter", "Return"}, + {"escape", "Escape"}, + {"delete", "Delete"}, + { "space", "space"}, + { "tab", "Tab"}, + { "up", "Up"}, + { "down", "Down"}, + { "left", "Left"}, + { "right", "Right"}, + { "plus", "plus"}, + { ",", "comma"}, + { ".", "period"}, + { "-", "minus"}, + { "=", "equal"}, + { "/", "slash"}, + { "\\", "backslash"}, + { ";", "semicolon"}, + { "'", "apostrophe"}, + { "`", "grave"}, + { "[", "bracketleft"}, + { "]", "bracketright"}, + { "<", "less"}, + { ">", "greater"}, + { "?", "question"}, + { "!", "exclam"} + }; + for (const auto& [key, name] : names) + if (shortcut.key == key) + return result + std::string(name); + if (shortcut.key.size() > 1 && shortcut.key[0] == 'f') + return result + "F" + shortcut.key.substr(1); + return result + shortcut.key; +} + +/// The control of one window. `window` is the GtkWindow, `box` the vertical GtkBox that holds `view`. +class GtkWindowControl : public WindowControl { + using Object = WindowApi::Object; + + struct Choice { + static inline std::size_t live = 0; // interface thread only + std::function chosen; + Choice() { + ++live; + } + Choice(const Choice&) = delete; + Choice& operator=(const Choice&) = delete; + ~Choice() { + --live; + } + }; + struct Popup { + GtkWindowControl* owner; + Object popover = nullptr; + Object group = nullptr; + std::vector ids; + std::optional chosen; + Closed closed; + unsigned source = 0; + }; + + WindowApi& a = windowApi(); + Object window; + Object box; + Object view; + Object menuBar = nullptr; + Object group = nullptr; + Object shortcuts = nullptr; + unsigned greyed = 0; // names the actions that stand for disabled submenus + std::vector menuIds; + Selected menuSelected; + std::unique_ptr popup; + // Where the window was when last neither maximized nor full screen. GTK 4 tells of no move, so it is sampled; a sample + // counts once the next one agrees, as a window manager may move a window before it says that it is maximized. + std::optional> normalPosition; + std::optional> candidatePosition; + unsigned tracker = 0; + + [[nodiscard]] std::optional> positionIfNormal() { + const auto now = placement(); + if (!now || now->maximized || now->fullscreen || now->minimized || !now->x || !now->y) + return std::nullopt; + return std::pair{*now->x, *now->y}; + } + /// Before this program changes the state of the window: its position is known to be the normal one. + void rememberPosition() { + if (const auto position = positionIfNormal()) + normalPosition = candidatePosition = position; + } + static int onSample(void* data) noexcept { + auto* self = static_cast(data); + try { + const auto position = self->positionIfNormal(); + if (position && position == self->candidatePosition) + self->normalPosition = position; + self->candidatePosition = position; + } catch (...) { } + return 1; + } + + struct X11 { + Object display; + unsigned long window; + }; + + /// The X window, or why there is none: not realized yet, or a display that is not X11. + [[nodiscard]] std::expected x11() const { + const auto surface = a.nativeSurface(window); + if (!surface) + return std::unexpected(WindowFailure::notOpen); + if (!a.hasX11() || !a.instanceIsA(surface, a.x11SurfaceType())) + return std::unexpected(WindowFailure::unsupported); + return X11{a.x11Display(a.surfaceDisplay(surface)), a.x11Xid(surface)}; + } + + /// The left and top of the decoration a window manager drew around the window (_NET_FRAME_EXTENTS), 0 without one. + [[nodiscard]] std::pair frameExtents(const X11& target) const { + const auto property = a.xAtom(target.display, "_NET_FRAME_EXTENTS", 0); + unsigned long type = 0, count = 0, after = 0; + int format = 0; + unsigned char* data = nullptr; + std::pair result{0, 0}; + if (a.xProperty(target.display, target.window, property, 0, 4, 0, 6 /*XA_CARDINAL*/, &type, &format, &count, &after, &data) == 0 && data) { + if (format == 32 && count == 4) { + const auto* values = reinterpret_cast(data); + result = {static_cast(values[0]), static_cast(values[2])}; + } + a.xFree(data); + } + return result; + } + + // The signal connection owns its Choice: it goes with the action, that is with the menu or popup it was built for. + static void releaseChoice(void* choice, void*) noexcept { + delete static_cast(choice); + } + static void onActivate(Object, Object, Choice* choice) noexcept { + try { + choice->chosen(); + } catch (...) { + try { + log::error("WebKitGTK: a menu handler failed"); + } catch (...) { } + } + } + + /// Builds the GMenu of `menu`, adding one action per leaf to `actions`, named "i". + Object buildModel(const Menu& menu, + Object actions, + const std::string& prefix, + std::vector& ids, + std::vector>& accelerators, + const std::function(std::string)>& handler, + bool topLevelOfBar = false) { + const auto model = a.menuNew(); + auto section = a.menuNew(); + const auto flush = [&] { + a.menuSection(model, nullptr, section); + a.unref(section); + }; + for (const auto& item : menu) { + if (item.separator) { + flush(); + section = a.menuNew(); + } else if (!item.items.empty()) { + const auto child = buildModel(item.items, actions, prefix, ids, accelerators, handler); + if (item.enabled) + a.menuSubmenu(section, item.label.c_str(), child); + else { + // A submenu cannot be greyed: an item of a disabled action takes its place. (The top level of a menu + // bar must stay submenus: setMenu() makes those insensitive.) + if (topLevelOfBar) + a.menuSubmenu(section, item.label.c_str(), child); + else { + const auto name = "d" + std::to_string(greyed++); + const auto action = a.actionNew(name.c_str(), nullptr); + a.actionEnabled(action, 0); + a.addAction(actions, action); + a.unref(action); + a.menuAppend(section, item.label.c_str(), (prefix + "." + name).c_str()); + } + } + a.unref(child); + } else { + const auto name = "i" + std::to_string(ids.size()); + const auto action = item.checkable ? a.statefulActionNew(name.c_str(), nullptr, a.variantBoolean(item.checked ? 1 : 0)) + : a.actionNew(name.c_str(), nullptr); + a.actionEnabled(action, item.enabled ? 1 : 0); + auto choice = std::make_unique(); + choice->chosen = handler(item.id); + a.connect(action, "activate", reinterpret_cast(onActivate), choice.release(), releaseChoice, 0); + a.addAction(actions, action); + a.unref(action); + ids.push_back(item.id); + const auto detailed = prefix + "." + name; + a.menuAppend(section, item.label.c_str(), detailed.c_str()); + if (const auto shortcut = parseShortcut(item.shortcut)) + accelerators.emplace_back(gtkAccelerator(*shortcut), detailed); + } + } + flush(); + return model; + } + + void removeMenu() { + if (shortcuts) + a.removeController(window, std::exchange(shortcuts, nullptr)); + if (menuBar) + a.boxRemove(box, std::exchange(menuBar, nullptr)); + if (group) { + a.insertGroup(window, "wf", nullptr); + a.unref(std::exchange(group, nullptr)); + } + menuIds.clear(); + menuSelected = {}; + greyed = 0; + } + + void finishPopup() { + if (!popup) + return; + auto done = std::move(popup); + if (done->source) + a.sourceRemove(done->source); + a.insertGroup(done->popover, "wfc", nullptr); + a.unparent(done->popover); + a.unref(done->group); + try { + if (done->closed) + done->closed(done->chosen); + } catch (...) { + try { + log::error("WebKitGTK: a context menu handler failed"); + } catch (...) { } + } + } + static int onPopupClosedLater(void* data) noexcept { + auto* self = static_cast(data); + self->popup->source = 0; + self->finishPopup(); + return 0; + } + // "closed" can come before the action of the chosen item: the answer is given from an idle callback. + static void onPopupClosed(Object, GtkWindowControl* self) noexcept { + if (self->popup && !self->popup->source) + self->popup->source = self->a.idleAdd(200, onPopupClosedLater, self, nullptr); + } + +public: + GtkWindowControl(Object gtkWindow, Object gtkBox, Object webView) : window(gtkWindow), box(gtkBox), view(webView) { } + ~GtkWindowControl() override { + if (tracker) + a.sourceRemove(tracker); + finishPopup(); + removeMenu(); + } + + /// Once the window is mapped: follows its normal position. `known` is where it was put, should it open maximized. + void trackPosition(std::optional> known) { + normalPosition = known; + if (!tracker && x11()) + tracker = a.timeoutAdd(0, 100, onSample, this, nullptr); + } + + /// For tests: the menu items the toolkit still holds a handler for, in the whole process. + [[nodiscard]] static std::size_t liveChoices() noexcept { + return Choice::live; + } + /// For tests: which titles of the menu bar can be opened. + [[nodiscard]] std::vector barSensitivity() const { + std::vector result; + for (auto title = menuBar ? a.firstChild(menuBar) : nullptr; title; title = a.nextSibling(title)) + result.push_back(a.getSensitive(title) != 0); + return result; + } + + [[nodiscard]] WindowFeatures features() override { + const bool onX11 = x11().has_value(); + return {.position = onX11, + .size = true, + .maximize = true, + .fullscreen = true, + .minimize = true, + .alwaysOnTop = onX11, + .minimumSize = true, + .menu = true, + .contextMenu = true, + .tray = false}; // GTK 4 has no status icon + } + + [[nodiscard]] std::expected placement() override { + WindowPlacement result; + result.maximized = a.isMaximized(window) != 0; + result.fullscreen = a.isFullscreen(window) != 0; + // GDK_TOPLEVEL_STATE_MINIMIZED, which only X11 reports: no Wayland protocol tells a window that it is minimized. + if (const auto surface = a.nativeSurface(window)) + result.minimized = (a.toplevelState(surface) & 1u) != 0; + a.defaultSize(window, &result.width, &result.height); + if (result.maximized || result.fullscreen) { + result.width = a.width(window); + result.height = a.height(window); + } + const auto target = x11(); + if (!target && target.error() == WindowFailure::notOpen) + return std::unexpected(WindowFailure::notOpen); + if (target) { + int x = 0, y = 0; + unsigned long child = 0; + if (a.xTranslate(target->display, target->window, a.xRoot(target->display), 0, 0, &x, &y, &child)) { + const auto [left, top] = frameExtents(*target); + result.x = x - left; + result.y = y - top; + } + } + return result; + } + + [[nodiscard]] std::expected restorablePlacement() override { + auto result = placement(); + if (result) + result->minimized = false; // a window does not open minimized + if (result && (result->maximized || result->fullscreen)) { + a.defaultSize(window, &result->width, &result->height); // GTK keeps the size from before + result->x = result->y = std::nullopt; + if (normalPosition && x11()) { + result->x = normalPosition->first; + result->y = normalPosition->second; + } + } + return result; + } + + /// The monitors of the X display, each in the pixels a window position is given in (GDK divides them by the scale of the + /// monitor); the whole X screen when GDK lists none. Empty without an X display. + [[nodiscard]] std::vector screens() const { + const auto target = x11(); + if (!target) + return {}; + std::vector areas; + if (const auto monitors = a.displayMonitors(a.surfaceDisplay(a.nativeSurface(window)))) { + for (unsigned i = 0, count = a.itemCount(monitors); i < count; ++i) { + const auto monitor = a.itemAt(monitors, i); + if (!monitor) + continue; + WindowApi::Rectangle geometry{}; + a.monitorGeometry(monitor, &geometry); + const auto scale = std::max(1, a.monitorScale(monitor)); + areas.push_back({geometry.x * scale, geometry.y * scale, geometry.width * scale, geometry.height * scale}); + a.unref(monitor); + } + } + if (areas.empty()) { + const auto screen = a.xDefaultScreen(target->display); + areas.push_back({0, 0, a.xScreenWidth(target->display, screen), a.xScreenHeight(target->display, screen)}); + } + return areas; + } + + WindowStatus move(int x, int y) override { + const auto target = x11(); + if (!target) + return std::unexpected(target.error()); + a.xMove(target->display, target->window, x, y); + a.xSync(target->display, 0); + return {}; + } + WindowStatus resize(int newWidth, int newHeight) override { + if (newWidth <= 0 || newHeight <= 0) + return std::unexpected(WindowFailure::invalid); + a.setDefaultSize(window, newWidth, newHeight); + return {}; + } + WindowStatus setMaximized(bool on) override { + rememberPosition(); + (on ? a.maximize : a.unmaximize)(window); + return {}; + } + WindowStatus setFullscreen(bool on) override { + rememberPosition(); + (on ? a.fullscreen : a.unfullscreen)(window); + return {}; + } + WindowStatus minimize() override { + a.minimize(window); + return {}; + } + WindowStatus setAlwaysOnTop(bool on) override { + const auto target = x11(); + if (!target) + return std::unexpected(target.error()); + // The EWMH request a window manager honours; the layout of XClientMessageEvent, padded to the size of XEvent. + union { + struct { + int type; + unsigned long serial; + int sendEvent; + Object display; + unsigned long window; + unsigned long messageType; + int format; + long data[5]; + } message; + long padding[24]; + } event; + std::memset(&event, 0, sizeof event); + event.message.type = 33; // ClientMessage + event.message.window = target->window; + event.message.messageType = a.xAtom(target->display, "_NET_WM_STATE", 0); + event.message.format = 32; + event.message.data[0] = on ? 1 : 0; + event.message.data[1] = static_cast(a.xAtom(target->display, "_NET_WM_STATE_ABOVE", 0)); + event.message.data[3] = 1; // a normal application + constexpr long mask = (1L << 19) | (1L << 20); // SubstructureNotifyMask | SubstructureRedirectMask + const auto sent = a.xSendEvent(target->display, a.xRoot(target->display), 0, mask, &event); + a.xFlush(target->display); + if (!sent) + return std::unexpected(WindowFailure::failed); + return {}; + } + WindowStatus setMinimumSize(int minimumWidth, int minimumHeight) override { + if (minimumWidth < 0 || minimumHeight < 0) + return std::unexpected(WindowFailure::invalid); + a.sizeRequest(window, minimumWidth > 0 ? minimumWidth : -1, minimumHeight > 0 ? minimumHeight : -1); + return {}; + } + + WindowStatus setMenu(const Menu& menu, Selected selected) override { + if (!validMenu(menu)) + return std::unexpected(WindowFailure::invalid); + finishPopup(); + removeMenu(); + if (menu.empty()) + return {}; + menuSelected = std::move(selected); + group = a.groupNew(); + std::vector> accelerators; + const auto inherited = withInheritedState(menu); + const auto model = buildModel( + inherited, + group, + "wf", + menuIds, + accelerators, + [this](std::string id) { + return std::function([this, id = std::move(id)] { + if (const auto handler = menuSelected) + handler(id); + }); + }, + true); + a.insertGroup(window, "wf", group); + menuBar = a.menuBarNew(model); + a.unref(model); + a.boxPrepend(box, menuBar); + auto title = a.firstChild(menuBar); + for (const auto& item : inherited) { + if (item.separator || item.items.empty() || !title) + continue; + a.setSensitive(title, item.enabled ? 1 : 0); + title = a.nextSibling(title); + } + shortcuts = a.shortcutControllerNew(); + a.propagationPhase(shortcuts, 1); // GTK_PHASE_CAPTURE: before the page sees the key + for (const auto& [accelerator, action] : accelerators) + if (const auto trigger = a.triggerParse(accelerator.c_str())) + a.addShortcut(shortcuts, a.shortcutNew(trigger, a.namedAction(action.c_str()))); + a.addController(window, shortcuts); + return {}; + } + + WindowStatus activate(MenuSource source, std::string_view id) override { + if (source == MenuSource::tray) + return unsupported(); + const bool context = source == MenuSource::context; + const auto& ids = context ? (popup ? popup->ids : std::vector{}) : menuIds; + const auto found = std::ranges::find(ids, id); + if (found == ids.end()) + return std::unexpected(WindowFailure::invalid); + const auto name = "i" + std::to_string(found - ids.begin()); + a.activateAction(context ? popup->group : group, name.c_str(), nullptr); + if (context && popup) + a.popoverPopdown(popup->popover); + return {}; + } + + /// Whether a context menu is shown, and dismisses it (tests). + bool dismissContextMenu() { + if (!popup) + return false; + a.popoverPopdown(popup->popover); + return true; + } + +protected: + WindowStatus popUp(const Menu& menu, int x, int y, Closed closed) override { + finishPopup(); + popup = std::make_unique(); + popup->owner = this; + popup->closed = std::move(closed); + popup->group = a.groupNew(); + std::vector> accelerators; + const auto model = buildModel(withInheritedState(menu), popup->group, "wfc", popup->ids, accelerators, [this](std::string id) { + return std::function([this, id = std::move(id)] { + if (popup) + popup->chosen = id; + }); + }); + popup->popover = a.popoverNew(model); + a.unref(model); + a.insertGroup(popup->popover, "wfc", popup->group); + a.setParent(popup->popover, box); + a.popoverArrow(popup->popover, 0); + double left = x, top = y; + a.translate(view, box, x, y, &left, &top); + const WindowApi::Rectangle at{static_cast(left), static_cast(top), 1, 1}; + a.popoverPointing(popup->popover, &at); + a.connect(popup->popover, "closed", reinterpret_cast(onPopupClosed), this, nullptr, 0); + a.popoverPopup(popup->popover); + return {}; + } +}; + +} // namespace webfront::frontend::detail::webkitgtk +#endif diff --git a/include/webfront/frontend/WebView2.hpp b/include/webfront/frontend/WebView2.hpp index 9f19eaad..cb3a0bcb 100644 --- a/include/webfront/frontend/WebView2.hpp +++ b/include/webfront/frontend/WebView2.hpp @@ -43,6 +43,7 @@ using WebView2Options = ViewOptions; #if defined(WEBFRONT_EMBED_WEBVIEW2) && defined(_WIN32) #include "../system/WindowsCompat.hpp" + #include "WebView2Window.hpp" #include #include @@ -308,6 +309,10 @@ class Session : public std::enable_shared_from_this { std::function closingHook; std::shared_ptr captureQueue = std::make_shared(); CaptureRegistration captureRegistration; + /// The control of the window (position, state, menus, tray), created with it. + std::unique_ptr control; + /// Test injection: chooses in a context menu instead of showing it. Set before createWindow(). + std::function(const Menu&)> answerContextMenu; ~Session() { close(); @@ -365,7 +370,10 @@ class Session : public std::enable_shared_from_this { stopUnloadTimer(); if (closed) return; - closed = true; + keepPlacement(); + closed = true; + if (control) + control->release(); // after `closed`: removing the menu resizes the window captureRegistration = {}; for (const auto& job : captureQueue->close()) answer(*job, std::unexpected("the window is closed")); @@ -387,6 +395,16 @@ class Session : public std::enable_shared_from_this { } } + /// Keeps the placement of the application's own window for its next one, while the window still exists. + void keepPlacement() noexcept { + if (secondary || !window || !control || windowOptions.rememberAs.empty()) + return; + try { + if (const auto placement = control->restorablePlacement()) + savePlacement(windowOptions, *placement); + } catch (...) { } + } + void fail() noexcept { stopStartupTimer(); if (!failure) @@ -435,6 +453,11 @@ class Session : public std::enable_shared_from_this { void createWindow(bool visible = true, WindowOptions settings = {}) { windowOptions = frontend::detail::resolveWindow(std::move(settings)); visibleWindow = visible; + std::optional saved; + if (!secondary) { + saved = loadPlacement(windowOptions); + windowOptions = restoredOptions(std::move(windowOptions), saved); + } trace("session creation"); className = L"WebFront.WebView2." + std::to_wstring(reinterpret_cast(this)); WNDCLASSW windowClass{}; @@ -454,20 +477,32 @@ class Session : public std::enable_shared_from_this { if (!RegisterClassW(&windowClass)) throw std::runtime_error("WebView2: cannot register window class"); registered = true; - window = CreateWindowExW(visible ? WS_EX_LAYERED : 0, - className.c_str(), - utf16(windowOptions.title).c_str(), - WS_OVERLAPPEDWINDOW, - CW_USEDEFAULT, - CW_USEDEFAULT, - windowOptions.width, - windowOptions.height, - nullptr, - nullptr, - windowClass.hInstance, - this); + window = CreateWindowExW(visible ? WS_EX_LAYERED : 0, + className.c_str(), + utf16(windowOptions.title).c_str(), + windowOptions.frameless ? static_cast(WS_POPUP | WS_SYSMENU | WS_MINIMIZEBOX) : static_cast(WS_OVERLAPPEDWINDOW), + windowOptions.frameless ? 100 : CW_USEDEFAULT, + windowOptions.frameless ? 100 : CW_USEDEFAULT, + windowOptions.width, + windowOptions.height, + nullptr, + nullptr, + windowClass.hInstance, + this); if (!window) throw std::runtime_error("WebView2: cannot create window"); + control = std::make_unique(window, [this] { + resize(); + }); + control->answerContextMenu = answerContextMenu; + static_cast(control->setMinimumSize(windowOptions.minimumWidth, windowOptions.minimumHeight)); + if (windowOptions.width < windowOptions.minimumWidth || windowOptions.height < windowOptions.minimumHeight) + static_cast( + control->resize((std::max)(windowOptions.width, windowOptions.minimumWidth), (std::max)(windowOptions.height, windowOptions.minimumHeight))); + if (saved && reachable(*saved, win32::WindowControlWin32::screens())) + static_cast(control->move(*saved->x, *saved->y)); + if (windowOptions.alwaysOnTop) + static_cast(control->setAlwaysOnTop(true)); // Bounds initialization errors and an unresponsive runtime must not leave an empty window forever. // 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. @@ -483,7 +518,9 @@ class Session : public std::enable_shared_from_this { presentTimer = SetTimer(window, presentTimerId, 1000, nullptr); if (!presentTimer) throw std::runtime_error("WebView2: cannot start presentation timer"); - ShowWindow(window, SW_SHOW); + ShowWindow(window, windowOptions.maximized && !windowOptions.fullscreen ? SW_SHOWMAXIMIZED : SW_SHOW); + if (windowOptions.fullscreen) + static_cast(control->setFullscreen(true)); } } @@ -824,6 +861,9 @@ class Session : public std::enable_shared_from_this { } bool handleWindowMessage(HWND handle, UINT message, WPARAM wParam, LPARAM lParam) { + LRESULT handled = 0; + if (control && control->handleMessage(message, wParam, lParam, handled)) + return true; switch (message) { case WM_DPICHANGED: applyDpiBounds(handle, lParam); @@ -914,9 +954,32 @@ class Session : public std::enable_shared_from_this { trace("view requested"); } + void acceleratorKeyPressed(ICoreWebView2AcceleratorKeyPressedEventArgs* args) noexcept { + try { + COREWEBVIEW2_KEY_EVENT_KIND kind{}; + UINT key = 0; + check(args->get_KeyEventKind(&kind), "reading a key event"); + check(args->get_VirtualKey(&key), "reading a key"); + if ((kind == COREWEBVIEW2_KEY_EVENT_KIND_KEY_DOWN || kind == COREWEBVIEW2_KEY_EVENT_KIND_SYSTEM_KEY_DOWN) && control && control->handleKey(key)) + check(args->put_Handled(TRUE), "handling a shortcut"); + } catch (...) { + fail(); + } + } + void registerLifecycleHandlers() { auto weak = weak_from_this(); EventRegistrationToken token{}; + check( + controller->add_AcceleratorKeyPressed( + Microsoft::WRL::Callback([weak](ICoreWebView2Controller*, + ICoreWebView2AcceleratorKeyPressedEventArgs* args) -> HRESULT { + if (const auto self = weak.lock()) + self->acceleratorKeyPressed(args); + return S_OK; + }).Get(), + &token), + "registering the shortcut handler"); check( view->add_ProcessFailed( Microsoft::WRL::Callback([weak](ICoreWebView2*, ICoreWebView2ProcessFailedEventArgs* args) -> HRESULT { @@ -1208,11 +1271,13 @@ inline void open(std::string_view address, session->viewLaunch = options.launch; session->url = utf16(frontend::detail::applicationUrl(address, port, file, options.launch.origin)); session->answerScriptDialog = options.answerScriptDialog; + session->answerContextMenu = options.answerContextMenu; if (prepare) prepare(*session); const auto profile = options.userDataFolder.empty() ? userDataFolder() : std::filesystem::absolute(options.userDataFolder); std::filesystem::create_directories(profile); session->createWindow(options.visible, options.window); + PublishedWindowControl publishedControl(windowControlHostOf(), *session->control); session->start(profile); // The wake posts to the window, which the pump of run() dispatches. A post that fails (a full message queue) throws: // the host then fails the operations that relied on that notification instead of leaving them waiting. The session diff --git a/include/webfront/frontend/WebView2Window.hpp b/include/webfront/frontend/WebView2Window.hpp new file mode 100644 index 00000000..d17e3b85 --- /dev/null +++ b/include/webfront/frontend/WebView2Window.hpp @@ -0,0 +1,535 @@ +// SPDX-License-Identifier: Apache-2.0 OR CECILL-B +// Author: Ambroise Leclerc +// Created: 2026-12-06 +// +// WebFront — frontend +// Role: WindowControl of a Win32 window: placement, full screen, menu bar, context menu, accelerators and notification icon. +// Thread: ui-loop | Alloc: unrestricted +// LLM: used by WebView2.hpp; every call happens on the interface thread, release() before the window is destroyed + +#pragma once + +#include "WindowControl.hpp" + +#if defined(_WIN32) + + #include "../system/WindowsCompat.hpp" + + #include + #include + #include + #include + #include + #include + + #include + #include + +namespace webfront::frontend::detail::win32 { + +/// The message the notification icon sends to the window. +inline constexpr UINT trayMessage = WM_APP + 0x4C5; + +inline std::wstring wide(std::string_view text) { + if (text.empty()) + return {}; + const auto size = static_cast(text.size()); + const auto length = MultiByteToWideChar(CP_UTF8, 0, text.data(), size, nullptr, 0); + std::wstring result(static_cast(length > 0 ? length : 0), L'\0'); + if (length > 0) + MultiByteToWideChar(CP_UTF8, 0, text.data(), size, result.data(), length); + return result; +} + +/// The virtual key of a parsed shortcut, 0 when the keyboard has none. +inline UINT virtualKey(const Shortcut& shortcut) { + const auto& key = shortcut.key; + if (key.size() == 1) { + const auto scan = VkKeyScanW(static_cast(key[0])); + return scan == -1 ? 0u : static_cast(scan & 0xFF); + } + static constexpr std::pair names[] = { + { "enter", VK_RETURN}, + {"escape", VK_ESCAPE}, + {"delete", VK_DELETE}, + { "space", VK_SPACE}, + { "tab", VK_TAB}, + { "up", VK_UP}, + { "down", VK_DOWN}, + { "left", VK_LEFT}, + { "right", VK_RIGHT}, + { "plus", VK_OEM_PLUS} + }; + for (const auto& [name, code] : names) + if (key == name) + return code; + if (key.size() > 1 && key[0] == 'f') + return static_cast(VK_F1 + std::atoi(key.c_str() + 1) - 1); + return 0; +} + +class WindowControlWin32 : public WindowControl { + static constexpr UINT applicationBase = 1000; + static constexpr UINT trayBase = 2000; + static constexpr UINT contextBase = 3000; + static constexpr UINT trayId = 1; + + struct Accelerator { + Shortcut shortcut; + UINT key; + std::string id; + }; + + HWND window; + std::function relayout; + HMENU menuBar = nullptr; + std::vector menuIds; + std::vector accelerators; + Selected menuSelected; + HMENU trayMenu = nullptr; + HICON trayIcon = nullptr; + bool trayShown = false; + bool ownsTrayIcon = false; + std::vector trayIds; + Selected traySelected; + bool full = false; + LONG_PTR savedStyle = 0; + WINDOWPLACEMENT savedWindowPlacement{}; + int minimumWidth = 0, minimumHeight = 0; + + [[nodiscard]] bool alive() const { + return window && IsWindow(window); + } + static WindowStatus closed() { + return std::unexpected(WindowFailure::closed); + } + static WindowStatus status(BOOL done) { + if (!done) + return std::unexpected(WindowFailure::failed); + return {}; + } + + static HMENU build(const Menu& menu, HMENU target, UINT base, std::vector& ids, std::vector* keys) { + for (const auto& item : menu) { + if (item.separator) { + AppendMenuW(target, MF_SEPARATOR, 0, nullptr); + continue; + } + std::wstring label; + for (const auto character : wide(item.label)) { + label += character; + if (character == L'&') + label += L'&'; // not a mnemonic + } + UINT flags = MF_STRING; + if (!item.enabled) + flags |= MF_GRAYED; + if (!item.items.empty()) { + const auto child = build(item.items, CreatePopupMenu(), base, ids, keys); + AppendMenuW(target, flags | MF_POPUP, reinterpret_cast(child), label.c_str()); + continue; + } + if (item.checked) + flags |= MF_CHECKED; + if (const auto shortcut = parseShortcut(item.shortcut)) { + label += L'\t' + wide(item.shortcut); + if (keys && item.enabled) + keys->push_back({*shortcut, virtualKey(*shortcut), item.id}); + } + AppendMenuW(target, flags, base + static_cast(ids.size()), label.c_str()); + ids.push_back(item.id); + } + return target; + } + + static void choose(const std::vector& ids, const Selected& selected, std::size_t index) noexcept { + if (index >= ids.size() || !selected) + return; + try { + // Copies: the handler may replace the menu it comes from. + const auto id = ids[index]; + const auto handler = selected; + handler(id); + } catch (...) { + try { + log::error("WebView2: a menu handler failed"); + } catch (...) { } + } + } + + void removeMenu() { + if (menuBar) { + if (alive() && GetMenu(window) == menuBar) + SetMenu(window, nullptr); + DestroyMenu(std::exchange(menuBar, nullptr)); + } + menuIds.clear(); + accelerators.clear(); + menuSelected = {}; + } + + NOTIFYICONDATAW trayData() const { + NOTIFYICONDATAW data{}; + data.cbSize = sizeof(data); + data.hWnd = window; + data.uID = trayId; + return data; + } + + void removeTray() { + if (std::exchange(trayShown, false)) { + auto data = trayData(); + Shell_NotifyIconW(NIM_DELETE, &data); + } + if (trayMenu) + DestroyMenu(std::exchange(trayMenu, nullptr)); + if (trayIcon && ownsTrayIcon) + DestroyIcon(trayIcon); + trayIcon = nullptr; + ownsTrayIcon = false; + trayIds.clear(); + traySelected = {}; + } + + void showTrayMenu() { + if (!trayMenu) + return; + POINT at{}; + GetCursorPos(&at); + SetForegroundWindow(window); // without it the menu does not close when the user clicks elsewhere + const auto chosen = TrackPopupMenu(trayMenu, TPM_RETURNCMD | TPM_NONOTIFY | TPM_RIGHTBUTTON, at.x, at.y, 0, window, nullptr); + if (chosen >= static_cast(trayBase)) + choose(trayIds, traySelected, static_cast(chosen) - trayBase); + } + + RECT outerRect() const { + RECT bounds{}; + GetWindowRect(window, &bounds); + return bounds; + } + +public: + WindowControlWin32(HWND handle, std::function onClientAreaChanged) : window(handle), relayout(std::move(onClientAreaChanged)) { } + ~WindowControlWin32() override { + release(); + } + + /// Removes the menu and the notification icon; the control then answers `closed`. + void release() noexcept { + try { + removeTray(); + removeMenu(); + } catch (...) { } + window = nullptr; + relayout = {}; + } + + /// The messages of the window that are the control's; true when handled, with `result` as the procedure's answer. + bool handleMessage(UINT message, WPARAM wParam, LPARAM lParam, LRESULT& result) { + result = 0; + if (message == WM_COMMAND && lParam == 0 && HIWORD(wParam) == 0) { + const UINT id = LOWORD(wParam); + if (id >= applicationBase && id < trayBase) + choose(menuIds, menuSelected, id - applicationBase); + else if (id >= trayBase && id < contextBase) + choose(trayIds, traySelected, id - trayBase); + else + return false; + return true; + } + if (message == trayMessage && wParam == trayId) { + const auto event = static_cast(lParam); + if (event == WM_LBUTTONUP || event == WM_RBUTTONUP) + showTrayMenu(); + return true; + } + if (message == WM_GETMINMAXINFO && (minimumWidth > 0 || minimumHeight > 0)) { + auto& limits = *reinterpret_cast(lParam); + if (minimumWidth > 0) + limits.ptMinTrackSize.x = minimumWidth; + if (minimumHeight > 0) + limits.ptMinTrackSize.y = minimumHeight; + return true; + } + return false; + } + + /// A key pressed in the page: true when it is a shortcut of the application menu, which then has been chosen. + bool handleKey(UINT key) { + const auto down = [](int code) { + return (GetKeyState(code) & 0x8000) != 0; + }; + for (const auto& accelerator : accelerators) { + const auto& shortcut = accelerator.shortcut; + if (accelerator.key == key && down(VK_CONTROL) == shortcut.control && down(VK_MENU) == shortcut.alt && down(VK_SHIFT) == shortcut.shift + && (down(VK_LWIN) || down(VK_RWIN)) == shortcut.meta) { + const auto found = std::ranges::find(menuIds, accelerator.id); + if (found != menuIds.end()) + choose(menuIds, menuSelected, static_cast(found - menuIds.begin())); + return true; + } + } + return false; + } + + /// The work areas of the monitors. + static std::vector screens() { + std::vector areas; + EnumDisplayMonitors( + nullptr, + nullptr, + [](HMONITOR monitor, HDC, LPRECT, LPARAM data) -> BOOL { + MONITORINFO info{}; + info.cbSize = sizeof(info); + if (GetMonitorInfoW(monitor, &info)) { + const auto& work = info.rcWork; + reinterpret_cast*>(data)->push_back({static_cast(work.left), + static_cast(work.top), + static_cast(work.right - work.left), + static_cast(work.bottom - work.top)}); + } + return TRUE; + }, + reinterpret_cast(&areas)); + return areas; + } + + [[nodiscard]] WindowFeatures features() override { + return {.position = true, + .size = true, + .maximize = true, + .fullscreen = true, + .minimize = true, + .alwaysOnTop = true, + .minimumSize = true, + .menu = true, + .contextMenu = true, + .tray = true}; + } + + [[nodiscard]] std::expected placement() override { + if (!alive()) + return std::unexpected(WindowFailure::closed); + const auto bounds = outerRect(); + WindowPlacement result; + result.x = static_cast(bounds.left); + result.y = static_cast(bounds.top); + result.width = static_cast(bounds.right - bounds.left); + result.height = static_cast(bounds.bottom - bounds.top); + result.maximized = IsZoomed(window) != FALSE; + result.fullscreen = full; + result.minimized = IsIconic(window) != FALSE; + return result; + } + + [[nodiscard]] std::expected restorablePlacement() override { + auto result = placement(); + if (!result || (!result->maximized && !result->minimized && !result->fullscreen)) + return result; + WINDOWPLACEMENT state{}; + state.length = sizeof(state); + if (full) + state = savedWindowPlacement; + else if (!GetWindowPlacement(window, &state)) + return std::unexpected(WindowFailure::failed); + // rcNormalPosition is in workspace coordinates: shifted by what the taskbar takes at the left or top. + MONITORINFO monitor{}; + monitor.cbSize = sizeof(monitor); + GetMonitorInfoW(MonitorFromRect(&state.rcNormalPosition, MONITOR_DEFAULTTONEAREST), &monitor); + const auto& normal = state.rcNormalPosition; + result->x = static_cast(normal.left + monitor.rcWork.left - monitor.rcMonitor.left); + result->y = static_cast(normal.top + monitor.rcWork.top - monitor.rcMonitor.top); + result->width = static_cast(normal.right - normal.left); + result->height = static_cast(normal.bottom - normal.top); + result->maximized = result->maximized || state.showCmd == SW_SHOWMAXIMIZED || (state.flags & WPF_RESTORETOMAXIMIZED) != 0; + result->minimized = false; + return result; + } + + WindowStatus move(int x, int y) override { + if (!alive()) + return closed(); + return status(SetWindowPos(window, nullptr, x, y, 0, 0, SWP_NOSIZE | SWP_NOZORDER | SWP_NOACTIVATE)); + } + WindowStatus resize(int width, int height) override { + if (width <= 0 || height <= 0) + return std::unexpected(WindowFailure::invalid); + if (!alive()) + return closed(); + return status(SetWindowPos(window, nullptr, 0, 0, width, height, SWP_NOMOVE | SWP_NOZORDER | SWP_NOACTIVATE)); + } + WindowStatus setMaximized(bool on) override { + if (!alive()) + return closed(); + if (on != (IsZoomed(window) != FALSE)) + ShowWindow(window, on ? SW_MAXIMIZE : SW_RESTORE); + return {}; + } + WindowStatus minimize() override { + if (!alive()) + return closed(); + ShowWindow(window, SW_MINIMIZE); + return {}; + } + WindowStatus setFullscreen(bool on) override { + if (!alive()) + return closed(); + if (on == full) + return {}; + if (on) { + savedWindowPlacement.length = sizeof(savedWindowPlacement); + MONITORINFO monitor{}; + monitor.cbSize = sizeof(monitor); + if (!GetWindowPlacement(window, &savedWindowPlacement) || !GetMonitorInfoW(MonitorFromWindow(window, MONITOR_DEFAULTTONEAREST), &monitor)) + return std::unexpected(WindowFailure::failed); + full = true; + savedStyle = GetWindowLongPtrW(window, GWL_STYLE); + SetMenu(window, nullptr); + SetWindowLongPtrW(window, GWL_STYLE, savedStyle & ~static_cast(WS_OVERLAPPEDWINDOW)); + const auto& area = monitor.rcMonitor; + SetWindowPos(window, HWND_TOP, area.left, area.top, area.right - area.left, area.bottom - area.top, SWP_NOOWNERZORDER | SWP_FRAMECHANGED); + } else { + full = false; + SetWindowLongPtrW(window, GWL_STYLE, savedStyle); + if (menuBar) + SetMenu(window, menuBar); + SetWindowPlacement(window, &savedWindowPlacement); + SetWindowPos(window, nullptr, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE | SWP_NOZORDER | SWP_NOOWNERZORDER | SWP_FRAMECHANGED); + } + if (relayout) + relayout(); + return {}; + } + WindowStatus setAlwaysOnTop(bool on) override { + if (!alive()) + return closed(); + return status(SetWindowPos(window, on ? HWND_TOPMOST : HWND_NOTOPMOST, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE | SWP_NOACTIVATE)); + } + WindowStatus setMinimumSize(int width, int height) override { + if (width < 0 || height < 0) + return std::unexpected(WindowFailure::invalid); + minimumWidth = width; + minimumHeight = height; + return {}; + } + + WindowStatus setMenu(const Menu& menu, Selected selected) override { + if (!validMenu(menu)) + return std::unexpected(WindowFailure::invalid); + if (!alive()) + return closed(); + if (menu.empty()) { + removeMenu(); + } else { + // The new bar is complete before the old one goes: a refusal leaves the old menu in place. + std::vector ids; + std::vector keys; + const auto bar = build(withInheritedState(menu), CreateMenu(), applicationBase, ids, &keys); + if (!full && !SetMenu(window, bar)) { + DestroyMenu(bar); + return std::unexpected(WindowFailure::failed); + } + if (const auto old = std::exchange(menuBar, bar)) + DestroyMenu(old); // already detached by SetMenu, or never attached while full screen + menuIds = std::move(ids); + accelerators = std::move(keys); + menuSelected = std::move(selected); + } + DrawMenuBar(window); + if (relayout) + relayout(); + return {}; + } + + WindowStatus setTray(const std::optional& tray, Selected selected) override { + if (!alive()) + return closed(); + if (tray && !validMenu(tray->menu)) + return std::unexpected(WindowFailure::invalid); + if (!tray) { + removeTray(); + return {}; + } + // Everything the new tray needs is made before the old one is touched: a refusal leaves the old tray in place. + HICON icon = nullptr; + bool ownsIcon = false; + if (!tray->icon.empty()) { + icon = static_cast(LoadImageW(nullptr, tray->icon.c_str(), IMAGE_ICON, 0, 0, LR_LOADFROMFILE | LR_DEFAULTSIZE)); + if (!icon) + return std::unexpected(WindowFailure::invalid); + ownsIcon = true; + } else + icon = LoadIconW(nullptr, MAKEINTRESOURCEW(32512)); // IDI_APPLICATION, shared: never destroyed + std::vector ids; + HMENU menu = nullptr; + if (!tray->menu.empty()) + menu = build(withInheritedState(tray->menu), CreatePopupMenu(), trayBase, ids, nullptr); + auto data = trayData(); + data.uFlags = NIF_MESSAGE | NIF_ICON | NIF_TIP; + data.uCallbackMessage = trayMessage; + data.hIcon = icon; + const auto tip = wide(tray->tooltip.empty() ? tray->title : tray->tooltip); + wcsncpy_s(data.szTip, tip.c_str(), _TRUNCATE); + if (!Shell_NotifyIconW(trayShown ? NIM_MODIFY : NIM_ADD, &data)) { + if (menu) + DestroyMenu(menu); + if (ownsIcon) + DestroyIcon(icon); + return std::unexpected(WindowFailure::failed); + } + if (trayMenu) + DestroyMenu(trayMenu); + if (trayIcon && ownsTrayIcon) + DestroyIcon(trayIcon); + trayMenu = menu; + trayIcon = icon; + ownsTrayIcon = ownsIcon; + trayIds = std::move(ids); + traySelected = std::move(selected); + trayShown = true; + return {}; + } + + WindowStatus activate(MenuSource source, std::string_view id) override { + if (source == MenuSource::context) + return unsupported(); // TrackPopupMenu blocks until the user chooses + if (!alive()) + return closed(); + const bool fromTray = source == MenuSource::tray; + const auto& ids = fromTray ? trayIds : menuIds; + const auto menu = fromTray ? trayMenu : menuBar; + const auto found = std::ranges::find(ids, id); + if (found == ids.end()) + return std::unexpected(WindowFailure::invalid); + const auto command = (fromTray ? trayBase : applicationBase) + static_cast(found - ids.begin()); + const auto state = GetMenuState(menu, command, MF_BYCOMMAND); + if (state != static_cast(-1) && (state & MF_GRAYED) == 0) + SendMessageW(window, WM_COMMAND, command, 0); + return {}; + } + +protected: + WindowStatus popUp(const Menu& menu, int x, int y, Closed done) override { + if (!alive()) + return closed(); + std::vector ids; + const auto popup = build(withInheritedState(menu), CreatePopupMenu(), contextBase, ids, nullptr); + const auto context = GetDC(window); + const int dpi = context ? GetDeviceCaps(context, LOGPIXELSX) : 96; + if (context) + ReleaseDC(window, context); + POINT at{MulDiv(x, dpi, 96), MulDiv(y, dpi, 96)}; + ClientToScreen(window, &at); + SetForegroundWindow(window); + const auto chosen = TrackPopupMenu(popup, TPM_RETURNCMD | TPM_NONOTIFY | TPM_RIGHTBUTTON, at.x, at.y, 0, window, nullptr); + DestroyMenu(popup); + std::optional id; + if (chosen >= static_cast(contextBase) && static_cast(chosen) - contextBase < ids.size()) + id = ids[static_cast(chosen) - contextBase]; + done(std::move(id)); + return {}; + } +}; + +} // namespace webfront::frontend::detail::win32 +#endif diff --git a/include/webfront/frontend/Window.hpp b/include/webfront/frontend/Window.hpp index 023269eb..5b51b8ee 100644 --- a/include/webfront/frontend/Window.hpp +++ b/include/webfront/frontend/Window.hpp @@ -16,6 +16,7 @@ #include #include #include +#include #if defined(_WIN32) #include "../system/WindowsCompat.hpp" @@ -47,16 +48,36 @@ struct WindowOptions { /// nothing is initialized. A page that does touch media in that case terminates its web process (WebKitGTK cannot create /// its media elements), so the default stays true. Frontends other than WebKitGTK ignore it. bool media{true}; - /// Initial state and decoration of the window. WebKitGTK and CEF apply them; WebView2 and WKWebView ignore them. The + /// Initial state and decoration of the window, applied by every embedded frontend. The /// window manager or compositor has the last word (it may refuse to maximize, or draw its own decoration). bool maximized{false}; bool fullscreen{false}; ///< Takes precedence over maximized. bool frameless{false}; ///< No title bar nor borders: the page then offers its own way to close. - /// The smallest size the user may give the window; 0 leaves it to the toolkit. WebKitGTK and CEF only. + /// The smallest size the user may give the window; 0 leaves it to the toolkit. int minimumWidth{0}; int minimumHeight{0}; + /// Keeps the window above the others, where the system allows it (not under Wayland). + bool alwaysOnTop{false}; + /// Name under which the first window's position, size and state are kept when it closes and applied when it opens again; + /// empty (the default) keeps nothing. Letters, digits, `.`, `_` and `-`, not starting with a dot (placementFile()). + std::string rememberAs{}; + /// Folder of that file; empty selects the user's state folder of the platform. + std::filesystem::path stateDirectory{}; }; +/// @brief One entry of a native menu (WindowControl.hpp). A submenu has `items` and no `id`. +struct MenuItem { + std::string id{}; + std::string label{}; + std::string shortcut{}; ///< "Ctrl+S", "CmdOrCtrl+Shift+O", "F5"; see parseShortcut(). + bool enabled{true}; + bool checkable{false}; + bool checked{false}; + bool separator{false}; + std::vector items{}; +}; +using Menu = std::vector; + namespace frontend::detail { inline std::string executableName() { diff --git a/include/webfront/frontend/WindowControl.hpp b/include/webfront/frontend/WindowControl.hpp new file mode 100644 index 00000000..1908b426 --- /dev/null +++ b/include/webfront/frontend/WindowControl.hpp @@ -0,0 +1,605 @@ +// SPDX-License-Identifier: Apache-2.0 OR CECILL-B +// Author: Ambroise Leclerc +// Created: 2026-12-06 +// +// WebFront — frontend +// Role: Control of an embedded window (geometry, state, menus, tray) as each toolkit allows it, and its persisted placement (ADR-020). +// Thread: ui-loop | Alloc: unrestricted +// LLM: public contract; call a WindowControl on the interface thread only, and treat `unsupported` as a normal answer + +#pragma once + +#include "../tooling/Logger.hpp" +#include "../utils/Json.hpp" +#include "UIExecutor.hpp" +#include "Window.hpp" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace webfront::frontend { + +/// @brief Why an operation on the window did nothing. +enum class WindowFailure { + unsupported, ///< The toolkit, the display server or the window mode cannot do it. + notEmbedded, ///< The caller is not the view of the window (window service). + notOpen, ///< No window yet. + closed, ///< The window is gone. + wrongThread, ///< Not called on the interface thread. + invalid, ///< Arguments refused: a menu or a shortcut that cannot be built, a size that is not positive. + failed, ///< The system refused. +}; + +[[nodiscard]] constexpr std::string_view describe(WindowFailure failure) noexcept { + switch (failure) { + case WindowFailure::unsupported: + return "unsupported"; + case WindowFailure::notEmbedded: + return "notEmbedded"; + case WindowFailure::notOpen: + return "notOpen"; + case WindowFailure::closed: + return "closed"; + case WindowFailure::wrongThread: + return "wrongThread"; + case WindowFailure::invalid: + return "invalid"; + case WindowFailure::failed: + return "failed"; + } + return "failed"; +} + +using WindowStatus = std::expected; + +/// @brief Where the window is and in which state. The units are those of the toolkit and round-trip on the same machine: +/// pixels of the outer window on Windows, points of the window's frame (origin at the top left of the primary screen) on +/// macOS, device pixels of the position and GTK's logical size under X11. +struct WindowPlacement { + /// Absent when the system does not tell where a window is (Wayland). + std::optional x{}; + std::optional y{}; + int width{0}; + int height{0}; + bool maximized{false}; + bool fullscreen{false}; + bool minimized{false}; + + [[nodiscard]] bool operator==(const WindowPlacement&) const = default; +}; + +/// @brief What this window can do; an operation whose flag is false answers `unsupported`. +struct WindowFeatures { + bool position{false}; + bool size{false}; + bool maximize{false}; + bool fullscreen{false}; + bool minimize{false}; + bool alwaysOnTop{false}; + bool minimumSize{false}; + bool menu{false}; + bool contextMenu{false}; + bool tray{false}; + + [[nodiscard]] std::vector names() const { + std::vector result; + const auto add = [&](bool present, const char* name) { + if (present) + result.emplace_back(name); + }; + add(position, "position"); + add(size, "size"); + add(maximize, "maximize"); + add(fullscreen, "fullscreen"); + add(minimize, "minimize"); + add(alwaysOnTop, "alwaysOnTop"); + add(minimumSize, "minimumSize"); + add(menu, "menu"); + add(contextMenu, "contextMenu"); + add(tray, "tray"); + return result; + } +}; + +// Declared in Window.hpp, which ViewOptions needs. +using webfront::Menu; +using webfront::MenuItem; + +/// @brief Where a selection comes from. +enum class MenuSource { application, context, tray }; + +/// @brief An icon in the notification area. The icon file is chosen by C++ only (a page never names a path). +struct Tray { + std::string title{}; ///< Shown instead of an icon on macOS; Windows has no title. + std::string tooltip{}; + std::filesystem::path icon{}; ///< `.ico` on Windows, any image NSImage reads on macOS; empty keeps a default. + Menu menu{}; +}; + +/// @brief A keyboard shortcut of a menu item, e.g. "Ctrl+Shift+S", "CmdOrCtrl+Q" or "F5". +struct Shortcut { + bool control{false}; + bool alt{false}; + bool shift{false}; + bool meta{false}; + std::string key{}; ///< A lowercase letter, a digit, a punctuation character, "f1" to "f12" or a name (see parseShortcut). + + [[nodiscard]] bool operator==(const Shortcut&) const = default; +}; + +/// @brief Reads a shortcut: modifiers (Ctrl, Alt, Shift, Meta, CmdOrCtrl) then a key, joined with "+". A key that types +/// text needs a modifier other than Shift. Named keys: Enter, Escape, Delete, Space, Tab, Up, Down, Left, Right, Plus. +[[nodiscard]] inline std::optional parseShortcut(std::string_view text) { +#if defined(__APPLE__) + constexpr bool apple = true; +#else + constexpr bool apple = false; +#endif + Shortcut result; + while (!text.empty()) { + const auto plus = text.find('+'); + std::string token(text.substr(0, plus)); + std::ranges::transform(token, token.begin(), [](unsigned char c) { + return static_cast(std::tolower(c)); + }); + const bool last = plus == std::string_view::npos; + text.remove_prefix(last ? text.size() : plus + 1); + if (!last) { + if (text.empty()) + return std::nullopt; + if (token == "ctrl" || token == "control") + result.control = true; + else if (token == "alt" || token == "option") + result.alt = true; + else if (token == "shift") + result.shift = true; + else if (token == "meta" || token == "cmd" || token == "super") + result.meta = true; + else if (token == "cmdorctrl") + (apple ? result.meta : result.control) = true; + else + return std::nullopt; + continue; + } + bool function = false; + if (token.size() > 1 && token[0] == 'f') { + int number = 0; + const auto end = token.data() + token.size(); + const auto parsed = std::from_chars(token.data() + 1, end, number); + function = parsed.ec == std::errc{} && parsed.ptr == end && number >= 1 && number <= 12; + } + static constexpr std::string_view names[] = {"enter", "escape", "delete", "space", "tab", "up", "down", "left", "right", "plus"}; + const bool named = std::ranges::find(names, token) != std::end(names); + const bool character = token.size() == 1 && token[0] > ' ' && token[0] < 127; + if (!function && !named && !character) + return std::nullopt; + if (!function && !result.control && !result.alt && !result.meta) + return std::nullopt; + result.key = std::move(token); + } + if (result.key.empty()) + return std::nullopt; + return result; +} + +namespace detail { +inline constexpr std::size_t maximumMenuItems = 512; +inline constexpr std::size_t maximumMenuDepth = 4; + +inline bool validMenuLevel(const Menu& menu, std::set& ids, std::size_t& count, std::size_t depth) { + if (depth > maximumMenuDepth) + return false; + for (const auto& item : menu) { + if (++count > maximumMenuItems) + return false; + if (item.separator) + continue; + if (item.label.empty()) + return false; + if (!item.items.empty()) { + if (!item.shortcut.empty() || !validMenuLevel(item.items, ids, count, depth + 1)) + return false; + continue; + } + if (item.id.empty() || !ids.insert(item.id).second) + return false; + if (!item.shortcut.empty() && !parseShortcut(item.shortcut)) + return false; + } + return true; +} +} // namespace detail + +/// @brief Whether every native toolkit can be given this menu: labels, unique ids for the items that can be chosen, shortcuts +/// that parse, at most 512 items and 4 levels. +[[nodiscard]] inline bool validMenu(const Menu& menu) { + std::set ids; + std::size_t count = 0; + return detail::validMenuLevel(menu, ids, count, 1); +} + +/// @brief The menu with everything under a disabled submenu disabled too: no toolkit keeps the items (and their shortcuts) +/// of a greyed submenu from being chosen by itself. +[[nodiscard]] inline Menu withInheritedState(Menu menu, bool enabled = true) { + for (auto& item : menu) { + item.enabled = item.enabled && enabled; + item.items = withInheritedState(std::move(item.items), item.enabled); + } + return menu; +} + +/// @brief The items that can be chosen, in the order a native menu is built: their position is the native identifier. +[[nodiscard]] inline std::vector menuLeaves(const Menu& menu) { + std::vector leaves; + const auto visit = [&leaves](const auto& self, const Menu& level) -> void { + for (const auto& item : level) { + if (item.separator) + continue; + if (item.items.empty()) + leaves.push_back(&item); + else + self(self, item.items); + } + }; + visit(visit, menu); + return leaves; +} + +/** + * @brief The window of an embedded frontend, as its toolkit lets it be controlled. Every member is called on the interface + * thread (UIExecutor). What a toolkit cannot do answers `unsupported`; features() tells it beforehand. + */ +class WindowControl { +public: + using Selected = std::function; + using Closed = std::function)>; + + WindowControl() = default; + WindowControl(const WindowControl&) = delete; + WindowControl& operator=(const WindowControl&) = delete; + virtual ~WindowControl() = default; + + [[nodiscard]] virtual WindowFeatures features() = 0; + [[nodiscard]] virtual std::expected placement() = 0; + /// The placement to restore in another session: the geometry of the window when it is neither maximized nor full screen, + /// with the flags of its state. + [[nodiscard]] virtual std::expected restorablePlacement() { + return placement(); + } + virtual WindowStatus move(int, int) { + return unsupported(); + } + virtual WindowStatus resize(int, int) { + return unsupported(); + } + virtual WindowStatus setMaximized(bool) { + return unsupported(); + } + virtual WindowStatus setFullscreen(bool) { + return unsupported(); + } + virtual WindowStatus minimize() { + return unsupported(); + } + virtual WindowStatus setAlwaysOnTop(bool) { + return unsupported(); + } + /// 0 leaves that side to the toolkit. + virtual WindowStatus setMinimumSize(int, int) { + return unsupported(); + } + /// Replaces the application menu; an empty menu removes it. `selected` runs on the interface thread. + virtual WindowStatus setMenu(const Menu&, Selected) { + return unsupported(); + } + /// Replaces the notification area icon; nothing removes it. `selected` runs on the interface thread. + virtual WindowStatus setTray(const std::optional&, Selected) { + return unsupported(); + } + /// Chooses an item of the application or tray menu as the user would, through the native menu (automation and tests). + virtual WindowStatus activate(MenuSource, std::string_view) { + return unsupported(); + } + /// Shows a context menu at a point of the page (CSS pixels from its top left corner). `closed` runs once on the interface + /// thread with the chosen id, or nothing when the menu was dismissed; it may run before this returns. + WindowStatus showContextMenu(const Menu& menu, int x, int y, Closed closed) { + if (menu.empty() || !validMenu(menu)) + return std::unexpected(WindowFailure::invalid); + if (answerContextMenu) { + closed(answerContextMenu(menu)); + return {}; + } + return popUp(menu, x, y, std::move(closed)); + } + + /// Test injection (ViewOptions::answerContextMenu): chooses in a context menu instead of showing it. + std::function(const Menu&)> answerContextMenu{}; + +protected: + virtual WindowStatus popUp(const Menu&, int, int, Closed) { + return unsupported(); + } + static WindowStatus unsupported() { + return std::unexpected(WindowFailure::unsupported); + } +}; + +namespace detail { +class WindowControlShared { +public: + void publish(WindowControl& value) { + std::lock_guard lock(mutex); + control = &value; + published = true; + } + void retract() noexcept { + std::lock_guard lock(mutex); + control = nullptr; + } + [[nodiscard]] std::expected get(const UIExecutor& executor) const { + WindowControl* value = nullptr; + { + std::lock_guard lock(mutex); + if (!control) + return std::unexpected(published ? WindowFailure::closed : WindowFailure::notOpen); + value = control; + } + if (!executor.onUIThread()) + return std::unexpected(WindowFailure::wrongThread); + return value; + } + +private: + mutable std::mutex mutex; + WindowControl* control{nullptr}; + bool published{false}; +}; +} // namespace detail + +/// @brief Handle to the WindowControl of a frontend, as NativeWindow is to its window: cheap to copy, answers only on the +/// interface thread while the window exists. A default-constructed one is `unsupported`. +class WindowControlRef { + std::weak_ptr shared; + UIExecutor executor; + +public: + WindowControlRef() = default; + WindowControlRef(std::weak_ptr value, UIExecutor uiExecutor) : shared(std::move(value)), executor(std::move(uiExecutor)) { } + + /// Valid inside the interface-thread operation that asked for it; never keep it. + [[nodiscard]] std::expected get() const { + const auto state = shared.lock(); + if (!state) + return std::unexpected(WindowFailure::unsupported); + return state->get(executor); + } +}; + +/// @brief The frontend's side: publishes the control of the window it created and retracts it before it dies. +class WindowControlHost { + std::shared_ptr shared{std::make_shared()}; + UIExecutor executor; + +public: + explicit WindowControlHost(UIExecutor uiExecutor) : executor(std::move(uiExecutor)) { } + [[nodiscard]] WindowControlRef control() const { + return WindowControlRef{shared, executor}; + } + void publish(WindowControl& value) { + shared->publish(value); + } + void retract() noexcept { + shared->retract(); + } +}; + +template +[[nodiscard]] WindowControlHost& windowControlHostOf() { + static WindowControlHost host{uiExecutorHostOf().executor()}; + return host; +} + +/// @brief Publishes a control for the time of a scope. +class PublishedWindowControl { + WindowControlHost& host; + +public: + PublishedWindowControl(WindowControlHost& value, WindowControl& control) : host(value) { + host.publish(control); + } + PublishedWindowControl(const PublishedWindowControl&) = delete; + PublishedWindowControl& operator=(const PublishedWindowControl&) = delete; + ~PublishedWindowControl() { + host.retract(); + } +}; + +// --- Persisted placement ----------------------------------------------------------------------------------------------- + +/// @brief Where the placement of a window with `WindowOptions::rememberAs` is kept; nothing without that name, with a name +/// that is not made of letters, digits, `.`, `_` and `-` (or starts with a dot), or without a folder to keep it in. +[[nodiscard]] inline std::optional placementFile(const WindowOptions& options) { + const auto& name = options.rememberAs; + if (name.empty() || name.size() > 128 || name.front() == '.' || !std::ranges::all_of(name, [](unsigned char c) { + return std::isalnum(c) || c == '.' || c == '_' || c == '-'; + })) + return std::nullopt; + auto directory = options.stateDirectory; + if (directory.empty()) { +#if defined(_WIN32) + std::wstring buffer(32768, L'\0'); // the longest value Windows keeps; too large for the stack + const auto length = GetEnvironmentVariableW(L"LOCALAPPDATA", buffer.data(), static_cast(buffer.size())); + if (length > 0 && length < buffer.size()) { + buffer.resize(length); + directory = std::filesystem::path(buffer) / "webfront"; + } +#elif defined(__APPLE__) + if (const auto* home = std::getenv("HOME"); home && *home) + directory = std::filesystem::path(home) / "Library" / "Application Support" / "webfront"; +#else + if (const auto* state = std::getenv("XDG_STATE_HOME"); state && std::filesystem::path(state).is_absolute()) + directory = std::filesystem::path(state) / "webfront"; + else if (const auto* home = std::getenv("HOME"); home && *home) + directory = std::filesystem::path(home) / ".local" / "state" / "webfront"; +#endif + } + if (directory.empty()) + return std::nullopt; + return directory / (name + ".window.json"); +} + +[[nodiscard]] inline std::string encodePlacement(const WindowPlacement& placement) { + std::string text = "{"; + const auto number = [&text](const char* key, int value) { + text += std::string("\"") + key + "\":" + std::to_string(value) + ","; + }; + if (placement.x && placement.y) { + number("x", *placement.x); + number("y", *placement.y); + } + number("width", placement.width); + number("height", placement.height); + number("maximized", placement.maximized ? 1 : 0); + number("fullscreen", placement.fullscreen ? 1 : 0); + text.back() = '}'; + return text; +} + +/// Nothing for a text that is not a placement with a plausible size. +[[nodiscard]] inline std::optional decodePlacement(std::string_view text) { + try { + WindowPlacement placement; + json::Reader reader(text); + reader.object([&](const std::string& key) { + const auto raw = reader.rawValue(); + int value = 0; + const auto parsed = std::from_chars(raw.data(), raw.data() + raw.size(), value); + if (parsed.ec != std::errc{} || parsed.ptr != raw.data() + raw.size() || value < -1000000 || value > 1000000) + return; + if (key == "x") + placement.x = value; + else if (key == "y") + placement.y = value; + else if (key == "width") + placement.width = value; + else if (key == "height") + placement.height = value; + else if (key == "maximized") + placement.maximized = value != 0; + else if (key == "fullscreen") + placement.fullscreen = value != 0; + }); + reader.end(); + if (placement.width <= 0 || placement.height <= 0) + return std::nullopt; + if (!placement.x || !placement.y) + placement.x = placement.y = std::nullopt; + return placement; + } catch (const std::exception&) { + return std::nullopt; + } +} + +[[nodiscard]] inline std::optional loadPlacement(const WindowOptions& options) { + try { + const auto file = placementFile(options); + if (!file) + return std::nullopt; + std::ifstream input(*file, std::ios::binary); + if (!input) + return std::nullopt; + std::string text(4096, '\0'); + input.read(text.data(), static_cast(text.size())); + text.resize(static_cast(input.gcount())); + return decodePlacement(text); + } catch (const std::exception&) { + return std::nullopt; + } +} + +/// Keeps the placement for the next session; a failure is logged, never thrown (the window is closing). +inline void savePlacement(const WindowOptions& options, const WindowPlacement& placement) noexcept { + try { + const auto file = placementFile(options); + if (!file || placement.width <= 0 || placement.height <= 0) + return; + auto kept = placement; + // A maximized or full screen window does not tell where it was before: the last position kept stays. + if (!kept.x && (kept.maximized || kept.fullscreen)) + if (const auto previous = loadPlacement(options)) { + kept.x = previous->x; + kept.y = previous->y; + } + std::filesystem::create_directories(file->parent_path()); + auto temporary = *file; + temporary += ".tmp"; + { + std::ofstream output(temporary, std::ios::binary | std::ios::trunc); + output << encodePlacement(kept); + if (!output.flush()) + throw std::runtime_error("cannot write the window placement"); + } + std::filesystem::rename(temporary, *file); + } catch (const std::exception& error) { + try { + log::warn("WebFront: the window placement was not saved: {}", error.what()); + } catch (...) { } + } +} + +/// The options of a window created with a saved placement: its size and state replace those asked for. The position is not +/// an option: the frontend applies it to the created window, when it is still on a screen (see reachable()). +[[nodiscard]] inline WindowOptions restoredOptions(WindowOptions options, const std::optional& saved) { + if (saved) { + options.width = saved->width; + options.height = saved->height; + options.maximized = saved->maximized; + options.fullscreen = saved->fullscreen; + } + return options; +} + +/// Whether a Linux session is a Wayland one, as Chromium decides when it picks its platform (XDG_SESSION_TYPE): there a +/// program can neither place nor read the position of its windows, even though an X server (XWayland) may be reachable. +[[nodiscard]] inline bool waylandSession(std::string_view sessionType) noexcept { + return sessionType == "wayland"; +} + +/// A screen, or the part of it windows may use. +struct ScreenArea { + int x{0}; + int y{0}; + int width{0}; + int height{0}; +}; + +/// Whether enough of a window at that position would be on one of the screens for the user to take hold of its title: +/// a placement saved with a screen that is gone is not applied. +[[nodiscard]] inline bool reachable(const WindowPlacement& placement, std::span screens) { + if (!placement.x || !placement.y) + return false; + constexpr int grip = 48; + return std::ranges::any_of(screens, [&](const ScreenArea& screen) { + const auto visible = std::min(*placement.x + placement.width, screen.x + screen.width) - std::max(*placement.x, screen.x); + return visible >= std::min(grip, placement.width) && *placement.y >= screen.y - grip / 2 && *placement.y <= screen.y + screen.height - grip; + }); +} + +} // namespace webfront::frontend diff --git a/include/webfront/services/window/WindowService.hpp b/include/webfront/services/window/WindowService.hpp new file mode 100644 index 00000000..7b8eb971 --- /dev/null +++ b/include/webfront/services/window/WindowService.hpp @@ -0,0 +1,204 @@ +// SPDX-License-Identifier: Apache-2.0 OR CECILL-B +// Author: Ambroise Leclerc +// Created: 2026-12-06 +// +// WebFront — services/window +// Role: Optional window service (ADR-020): the page of the embedded view controls its window through `webfront.services.window.*`. +// Thread: thread-safe | Alloc: unrestricted +// LLM: optional service; see docs/FRONTENDS.md, every function refuses a connection that is not the embedded view + +#pragma once + +#include "../../Task.hpp" +#include "../../WebFront.hpp" + +#include +#include +#include +#include +#include +#include +#include + +namespace webfront::services { + +/** + * @brief Gives the page of the embedded view control of its window. Construct it once per application, before show(); the + * application must outlive its connections as for any cppFunction. The page side is `windowService()` of + * `@webfront/services`. + * + * Every function answers only the connection of the embedded view (UI::isEmbeddedView()): another connection is rejected + * with the code `window.notEmbedded` and nothing happens. What the toolkit cannot do is rejected with + * `window.unsupported`; the other codes are `window.`. A page names no file: a tray set by a page + * has no icon of its own (set one from C++ with frontend::WindowControl::setTray). + */ +template +class Window { + using UI = typename App::UI; + +public: + /// One menu item as the bridge carries it: depth (0 for the first level), id, label, shortcut and flags + /// (1 disabled, 2 checkable, 4 checked, 8 separator). The items of a submenu follow it, one level deeper. + using Entry = std::tuple; + using Entries = std::vector; + /// hasPosition, x, y, width, height, maximized, fullscreen, minimized. + using Placement = std::tuple; + + /// The JavaScript function that receives the selections: (source, id, number). `number` is the request of a context menu, or the generation (given by the page with setMenu or setTray) of the menu a selection was made in. `source` is "application", "context" + /// or "tray"; `id` is empty for a dismissed context menu. + static constexpr const char* eventFunction = "webfrontWindowEvents"; + + explicit Window(App& app) : application(app) { + add>("features", [](frontend::WindowControl& window) { + return window.features().names(); + }); + add("placement", [](frontend::WindowControl& window) { + const auto value = checked(window.placement()); + return Placement{value.x && value.y, + value.x.value_or(0), + value.y.value_or(0), + value.width, + value.height, + value.maximized, + value.fullscreen, + value.minimized}; + }); + add("move", [](frontend::WindowControl& window, std::int32_t x, std::int32_t y) { + check(window.move(x, y)); + }); + add("resize", [](frontend::WindowControl& window, std::int32_t width, std::int32_t height) { + check(window.resize(width, height)); + }); + add("maximize", [](frontend::WindowControl& window, bool on) { + check(window.setMaximized(on)); + }); + add("fullscreen", [](frontend::WindowControl& window, bool on) { + check(window.setFullscreen(on)); + }); + add("minimize", [](frontend::WindowControl& window) { + check(window.minimize()); + }); + add("alwaysOnTop", [](frontend::WindowControl& window, bool on) { + check(window.setAlwaysOnTop(on)); + }); + add("minimumSize", [](frontend::WindowControl& window, std::int32_t width, std::int32_t height) { + check(window.setMinimumSize(width, height)); + }); + addForCaller("setMenu", [](frontend::WindowControl& window, UI caller, const Entries& entries, std::int32_t generation) { + check(window.setMenu(menuOf(entries), notify(caller, "application", generation))); + }); + addForCaller( + "setTray", + [](frontend::WindowControl& window, UI caller, const std::string& title, const std::string& tooltip, const Entries& entries, std::int32_t generation) { + check(window.setTray(frontend::Tray{.title = title, .tooltip = tooltip, .menu = menuOf(entries)}, notify(caller, "tray", generation))); + }); + add("removeTray", [](frontend::WindowControl& window) { + check(window.setTray(std::nullopt, {})); + }); + addForCaller( + "contextMenu", + [](frontend::WindowControl& window, UI caller, const Entries& entries, std::int32_t x, std::int32_t y, std::int32_t request) { + check(window.showContextMenu(menuOf(entries), x, y, [caller, request](std::optional id) { + caller.jsFunction(eventFunction)("context", id.value_or(std::string{}), request); + })); + }); + add("activate", [](frontend::WindowControl& window, const std::string& source, const std::string& id) { + using Source = frontend::MenuSource; + if (source != "application" && source != "context" && source != "tray") + fail(frontend::WindowFailure::invalid); + check(window.activate(source == "tray" ? Source::tray : source == "context" ? Source::context : Source::application, id)); + }); + } + + /// The menu of a flat list of entries; throws the `window.invalid` error for depths that do not form a tree. + [[nodiscard]] static frontend::Menu menuOf(const Entries& entries) { + frontend::Menu menu; + std::size_t next = 0; + read(entries, next, 0, menu); + if (next != entries.size() || !frontend::validMenu(menu)) + fail(frontend::WindowFailure::invalid); + return menu; + } + +private: + App& application; + + static void read(const Entries& entries, std::size_t& next, std::int32_t depth, frontend::Menu& menu) { + while (next < entries.size() && std::get<0>(entries[next]) == depth) { + const auto& [level, id, label, shortcut, flags] = entries[next++]; + frontend::MenuItem item{.id = id, + .label = label, + .shortcut = shortcut, + .enabled = (flags & 1) == 0, + .checkable = (flags & 2) != 0, + .checked = (flags & 4) != 0, + .separator = (flags & 8) != 0}; + if (depth < static_cast(frontend::detail::maximumMenuDepth)) + read(entries, next, depth + 1, item.items); + menu.push_back(std::move(item)); + } + } + + [[noreturn]] static void fail(frontend::WindowFailure failure) { + const auto name = std::string(frontend::describe(failure)); + throw BridgeError("window." + name, "The window service failed: " + name); + } + static void check(const frontend::WindowStatus& status) { + if (!status) + fail(status.error()); + } + template + static Value checked(std::expected result) { + if (!result) + fail(result.error()); + return *std::move(result); + } + + static frontend::WindowControl::Selected notify(UI caller, std::string source, std::int32_t generation) { + return [caller, source = std::move(source), generation](const std::string& id) { + caller.jsFunction(eventFunction)(source, id, generation); + }; + } + + static void requireView(const UI& caller) { + if (!caller.isEmbeddedView()) + fail(frontend::WindowFailure::notEmbedded); + } + + /// Runs `operation` on the interface thread with the window's control. + template + static ResultTask onInterfaceThread(frontend::UIExecutor executor, frontend::WindowControlRef reference, Operation operation) { + auto work = [reference = std::move(reference), operation = std::move(operation)]() mutable { + const auto control = reference.get(); + if (!control) + fail(control.error()); + return operation(**control); + }; + if (!executor.available()) + fail(frontend::WindowFailure::unsupported); + if constexpr (std::is_void_v) + co_await (executor.schedule() | networking::ex::then(std::move(work))); + else + co_return co_await (executor.schedule() | networking::ex::then(std::move(work))); + } + + template + void addForCaller(const char* name, Function function) { + application.cppFunction(std::string("webfront.services.window.") + name, [&app = application, function](UI caller, Args... arguments) { + requireView(caller); + return onInterfaceThread(app.uiExecutor(), + app.windowControl(), + [function, caller, ... values = std::move(arguments)](frontend::WindowControl& window) { + return function(window, caller, values...); + }); + }); + } + template + void add(const char* name, Function function) { + addForCaller(name, [function](frontend::WindowControl& window, const UI&, const Args&... values) { + return function(window, values...); + }); + } +}; + +} // namespace webfront::services diff --git a/js/services/README.md b/js/services/README.md index 61b05990..2a5f9ff0 100644 --- a/js/services/README.md +++ b/js/services/README.md @@ -5,8 +5,30 @@ Browser side of the optional WebFront system services (see ADR-020). It is insta to the core's embedded resources. The C++ counterparts will live under `include/webfront/services/` as the services are delivered. -This release is a skeleton: `services` is empty and `selfTest()` returns the package name, which -proves the delivery chain. From the repository's wf project, run `wf run services-package` after +`selfTest()` returns the package name, which proves the delivery chain. One service is delivered, the +window of the embedded view. The application registers its C++ side before `show()`: + +```cpp +#include + +webfront::services::Window windowService(app); +``` + +and the page uses it: + +```js +import {windowService} from '@webfront/services'; + +const view = windowService(); +if ((await view.features()).includes('menu')) + await view.setMenu([{label: 'File', items: [{id: 'save', label: 'Save', shortcut: 'CmdOrCtrl+S'}]}], id => save()); +const chosen = await view.contextMenu([{id: 'copy', label: 'Copy'}], event.clientX, event.clientY); +``` + +A page opened in another browser is rejected with `window.notEmbedded`, and what a toolkit cannot do with +`window.unsupported`; `docs/FRONTENDS.md` of WebFront lists the limits of each engine. + +From the repository's wf project, run `wf run services-package` after `wf install` to generate `build-services-package/webfront-services-0.1.0.tgz` and its SHA-512. This prepares an npm archive; it does **not** publish it. Install it from a registry carrying that archive with `wf install @webfront/services@0.1.0`. The repository's test registry packages diff --git a/js/services/index.d.ts b/js/services/index.d.ts index 4cc988e1..25b9d82f 100644 --- a/js/services/index.d.ts +++ b/js/services/index.d.ts @@ -1,4 +1,49 @@ -/** The services of this package, by name: none yet. */ -export declare const services: Readonly>; +export interface MenuItem { + /** Names the item for the handler; unique in its menu, required unless it is a separator or has `items`. */ + id?: string; + label?: string; + /** For example "Ctrl+S", "CmdOrCtrl+Shift+Q" or "F5". */ + shortcut?: string; + enabled?: boolean; + checkable?: boolean; + checked?: boolean; + separator?: boolean; + items?: readonly MenuItem[]; +} +export interface WindowPlacement { + /** Absent where the system does not tell the position of a window (Wayland). */ + x?: number; + y?: number; + width: number; + height: number; + maximized: boolean; + fullscreen: boolean; + minimized: boolean; +} +export type WindowFeature = + | 'position' | 'size' | 'maximize' | 'fullscreen' | 'minimize' | 'alwaysOnTop' | 'minimumSize' | 'menu' | 'contextMenu' | 'tray'; +export type MenuSource = 'application' | 'context' | 'tray'; +/** Every call rejects with a `window.*` error code: `window.unsupported`, `window.notEmbedded`, `window.invalid`... */ +export interface WindowService { + features(): Promise; + placement(): Promise; + move(x: number, y: number): Promise; + resize(width: number, height: number): Promise; + maximize(on?: boolean): Promise; + fullscreen(on?: boolean): Promise; + minimize(): Promise; + setAlwaysOnTop(on?: boolean): Promise; + setMinimumSize(width: number, height: number): Promise; + /** Replaces the application menu; an empty one removes it. */ + setMenu(items: readonly MenuItem[], onSelect?: (id: string) => void): Promise; + setTray(tray: {title?: string; tooltip?: string; menu?: readonly MenuItem[]}, onSelect?: (id: string) => void): Promise; + removeTray(): Promise; + contextMenu(items: readonly MenuItem[], x: number, y: number): Promise; + activate(source: MenuSource, id: string): Promise; + dispose(): void; +} +export declare function windowService(options?: {bridge?: unknown; target?: object}): WindowService; +/** The services of this package, by name. */ +export declare const services: Readonly<{window: typeof windowService}>; /** Proves that the package was installed, resolved and bundled: returns its own name. */ export declare function selfTest(): '@webfront/services'; diff --git a/js/services/index.mjs b/js/services/index.mjs index ca2303d2..64f3b734 100644 --- a/js/services/index.mjs +++ b/js/services/index.mjs @@ -1,9 +1,126 @@ // Browser side of the optional WebFront system services (ADR-020). The package is installed with wf and bundled into -// the application; none of it belongs to the core's embedded resources. The services themselves (files, dialogs...) -// are added here as their C++ counterparts are delivered: the skeleton only proves the delivery chain. +// the application; none of it belongs to the core's embedded resources. Each service has its C++ counterpart under +// include/webfront/services/, which the application registers; the other services are added here as they are delivered. -/** The services of this package, by name: none yet. */ -export const services = Object.freeze({}); +const windowPrefix = 'webfront.services.window.'; +const windowEvents = 'webfrontWindowEvents'; // the function C++ calls, one per page + +// A menu tree as the flat list of [depth, id, label, shortcut, flags] the bridge carries. +function menuEntries(items, depth = 0, entries = []) { + if (!Array.isArray(items)) throw new TypeError('A menu is an array of items'); + for (const item of items) { + const flags = (item.enabled === false ? 1 : 0) | (item.checkable || item.checked ? 2 : 0) + | (item.checked ? 4 : 0) | (item.separator ? 8 : 0); + entries.push([depth, String(item.id ?? ''), String(item.label ?? ''), String(item.shortcut ?? ''), flags]); + if (item.items !== undefined) menuEntries(item.items, depth + 1, entries); + } + return entries; +} + +/** + * The window of the embedded view, served by webfront::services::Window. A page opened in another browser is rejected with + * the code `window.notEmbedded`; what the toolkit cannot do, with `window.unsupported`. One instance per page. + */ +export function windowService({bridge = globalThis.webFront, target = globalThis} = {}) { + if (!bridge) throw new TypeError('The WebFront bridge is not loaded'); + if (target[windowEvents]) throw new Error('The window service is already in use in this page'); + const call = (name, ...values) => bridge.cppFunction(windowPrefix + name)(...values); + const list = entries => bridge.list ? bridge.list(entries) : entries; + // The handlers of each menu source, by generation. A generation is the number of the setMenu/setTray call that made the + // menu; C++ gives it back with every selection, so a selection reaches the handler of the menu it was made in, whatever + // calls are still unanswered. States of a generation: pending (sent, not answered), installed (its call was accepted: + // the newest of them is the menu on the screen) or gone (refused, or superseded by a newer accepted call; its late + // selections are dropped). + const generations = {application: new Map(), tray: new Map()}; + let disposed = false; + const live = () => { + if (disposed) throw new Error('The window service is disposed'); + }; + const pending = new Map(); + // Numbered across the instances of a page: a late answer for a disposed one must not settle a call of the next. + const nextRequest = () => (target.webfrontWindowRequests = ((target.webfrontWindowRequests ?? 0) % 0x7fffffff) + 1); + const receive = (source, id, number) => { + if (source === 'context') { + const settle = pending.get(number); + pending.delete(number); + settle?.(id === '' ? null : id); + return; + } + generations[source]?.get(number)?.(id); + }; + target[windowEvents] = receive; + + // The generation is registered before the call, which a selection may precede the answer of. A refused call forgets its + // own generation only; an accepted one supersedes every older generation of its source. + const install = async (source, handler, send) => { + live(); + const known = generations[source], generation = nextRequest(); + known.set(generation, handler ?? (() => {})); + try { + await send(generation); + } catch (error) { + known.delete(generation); + throw error; + } + for (const older of [...known.keys()]) if (older < generation) known.delete(older); + }; + + // Every call of the page goes through the live check: after dispose() it rejects instead of reaching the window. + const guarded = (...parts) => { + try { + live(); + } catch (error) { + return Promise.reject(error); + } + return call(...parts); + }; + + return Object.freeze({ + features: async () => [...await guarded('features')], + async placement() { + const [positioned, x, y, width, height, maximized, fullscreen, minimized] = await guarded('placement'); + return {...(positioned ? {x, y} : {}), width, height, maximized, fullscreen, minimized}; + }, + move: (x, y) => guarded('move', x, y), + resize: (width, height) => guarded('resize', width, height), + maximize: (on = true) => guarded('maximize', on), + fullscreen: (on = true) => guarded('fullscreen', on), + minimize: () => guarded('minimize'), + setAlwaysOnTop: (on = true) => guarded('alwaysOnTop', on), + setMinimumSize: (width, height) => guarded('minimumSize', width, height), + setMenu: (items, onSelect) => install('application', onSelect, generation => call('setMenu', list(menuEntries(items)), generation)), + setTray: ({title = '', tooltip = '', menu = []}, onSelect) => + install('tray', onSelect, generation => call('setTray', title, tooltip, list(menuEntries(menu)), generation)), + removeTray: () => install('tray', null, () => call('removeTray')), + /** Resolves with the id of the chosen item, or null when the menu was dismissed. */ + contextMenu(items, x, y) { + const number = nextRequest(); + return new Promise((resolve, reject) => { + live(); + pending.set(number, resolve); + Promise.resolve() + // Disposed before it was sent: already answered, and no menu must appear. + .then(() => disposed ? null : call('contextMenu', list(menuEntries(items)), Math.round(x), Math.round(y), number)) + .catch(error => { + pending.delete(number); + reject(error); + }); + }); + }, + /** Chooses an item of a native menu ('application', 'context' or 'tray') as the user would. */ + activate: (source, id) => guarded('activate', source, id), + dispose() { + disposed = true; + for (const settle of pending.values()) settle(null); + pending.clear(); + for (const known of Object.values(generations)) known.clear(); + if (target[windowEvents] === receive) delete target[windowEvents]; + }, + }); +} + +/** The services of this package, by name. */ +export const services = Object.freeze({window: windowService}); /** Proves that the package was installed, resolved and bundled: returns its own name. */ export function selfTest() { diff --git a/test/cmake/CheckFrontendGenerators.cmake b/test/cmake/CheckFrontendGenerators.cmake index a280f20c..7f76898f 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 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}") + if(NOT count EQUAL 19) + message(FATAL_ERROR "${generator}: expected Jasmine, seventeen 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 0fca0982..447b5394 100644 --- a/test/cmake/CheckFrontendSelection.cmake +++ b/test/cmake/CheckFrontendSelection.cmake @@ -437,15 +437,15 @@ foreach(case webkitgtk-display webkitgtk-linux cef-linux cef-macos cef-windows c continue() endif() if(case STREQUAL "webview2-windows") - set(expected_count 20) # with StartupTime-cold and -warm (#611), and secondary-close (#708) + set(expected_count 22) # 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 + set(expected_count 19) # an engine without STARTUP_TRACE has no start-up case elseif(case STREQUAL "cef-linux") - set(expected_count 15) # no host-thread case: CEF has no secondary-thread path to observe + set(expected_count 17) # no host-thread case: CEF has no secondary-thread path to observe elseif(case STREQUAL "wkwebview-macos") - set(expected_count 19) # with secondary-close (#702) + set(expected_count 21) # with secondary-close (#702) else() - set(expected_count 18) + set(expected_count 20) endif() if(NOT count EQUAL expected_count) list(APPEND failures "${case}: expected ${expected_count} tests, got ${count}") diff --git a/test/cmake/WebKitGTKTestEnvironment.cmake b/test/cmake/WebKitGTKTestEnvironment.cmake index 9bbf7877..6b27cb32 100644 --- a/test/cmake/WebKitGTKTestEnvironment.cmake +++ b/test/cmake/WebKitGTKTestEnvironment.cmake @@ -21,8 +21,9 @@ function(webfront_configure_webkitgtk_test name) "GDK_BACKEND=x11" "GSK_RENDERER=cairo" "LIBGL_ALWAYS_SOFTWARE=1") # XTest controls the display's global pointer. Parallel windows on the suite's shared display can cover the # file input or steal a press/release; the port lock does not protect against tests using ephemeral ports. + # window-menu also types keys, and stands for a window manager on the root window of its display. # WithDisplay.sh then starts a private Xvfb even when RunTestSuite enabled display sharing for the suite. - if(name MATCHES "^WebKitGTKAdapter-(choose-file|cancel-choose|close-with-dialog)$") + if(name MATCHES "^WebKitGTKAdapter-(choose-file|cancel-choose|close-with-dialog|window-menu)$") set_property(TEST ${name} APPEND PROPERTY ENVIRONMENT "WEBFRONT_TEST_SHARED_DISPLAY=0") endif() endfunction() diff --git a/test/cmake/frontends/CMakeLists.txt b/test/cmake/frontends/CMakeLists.txt index 2e87ff70..c7c36060 100644 --- a/test/cmake/frontends/CMakeLists.txt +++ b/test/cmake/frontends/CMakeLists.txt @@ -3,7 +3,7 @@ project(FrontendWiring NONE) enable_testing() if(CASE STREQUAL "webkitgtk-display") include("${ROOT}/test/cmake/WebKitGTKTestEnvironment.cmake") - foreach(mode choose-file cancel-choose close-with-dialog download script-dialogs) + foreach(mode choose-file cancel-choose close-with-dialog download script-dialogs window-menu) set(name WebKitGTKAdapter-${mode}) add_test(NAME ${name} COMMAND "${CMAKE_COMMAND}" -E true) set_property(TEST ${name} PROPERTY ENVIRONMENT "KEEP_EXISTING=1") @@ -12,7 +12,7 @@ if(CASE STREQUAL "webkitgtk-display") if(NOT "KEEP_EXISTING=1" IN_LIST environment OR NOT "GDK_BACKEND=x11" IN_LIST environment) message(FATAL_ERROR "${name} lost its existing or engine environment") endif() - if(mode MATCHES "^(choose-file|cancel-choose|close-with-dialog)$") + if(mode MATCHES "^(choose-file|cancel-choose|close-with-dialog|window-menu)$") if(NOT "WEBFRONT_TEST_SHARED_DISPLAY=0" IN_LIST environment) message(FATAL_ERROR "${name} must isolate its global XTest pointer from parallel windows") endif() @@ -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 18 OR NOT "WebFrontWebKitGTKIntegration" IN_LIST ARGN) + if(NOT shared_count EQUAL 20 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/tools/WithWeston.sh b/test/tools/WithWeston.sh new file mode 100755 index 00000000..4b54df0e --- /dev/null +++ b/test/tools/WithWeston.sh @@ -0,0 +1,28 @@ +#!/usr/bin/env bash +# Runs a command as a Wayland client of a headless weston of its own: WithWeston.sh [arguments...] +set -euo pipefail +weston=$1 +shift +runtime=$(mktemp -d) # mode 700, as Wayland requires +compositor= +cleanup() { + if [[ -n $compositor ]]; then + kill "$compositor" 2>/dev/null || true + wait "$compositor" 2>/dev/null || true + fi + rm -rf "$runtime" +} +trap cleanup EXIT +export XDG_RUNTIME_DIR=$runtime +"$weston" --backend=headless --socket=webfront-test --idle-time=0 >"$runtime/weston.log" 2>&1 & +compositor=$! +for ((attempt = 0; attempt < 100; ++attempt)); do + [[ -S $runtime/webfront-test ]] && break + kill -0 "$compositor" 2>/dev/null || break + sleep 0.1 +done +if [[ ! -S $runtime/webfront-test ]]; then + cat "$runtime/weston.log" >&2 + exit 1 +fi +env -u DISPLAY WAYLAND_DISPLAY=webfront-test GDK_BACKEND=wayland "$@" diff --git a/test/unit/CMakeLists.txt b/test/unit/CMakeLists.txt index 8026024f..fe4e3a08 100644 --- a/test/unit/CMakeLists.txt +++ b/test/unit/CMakeLists.txt @@ -82,7 +82,7 @@ list(APPEND TESTS_LIST FileSystemTests.cpp NativeFSTests.cpp DownloadsTests.cpp list(APPEND TESTS_LIST DefaultFSTests.cpp StdnetShutdownTests.cpp ProfileLeaseTests.cpp SafePathTests.cpp UISubscribersTests.cpp) list(APPEND TESTS_LIST ReadBindingTests.cpp ViewAssociationTests.cpp WatchTests.cpp WatchTreeTests.cpp WatchContainersTests.cpp WatchPassTests.cpp WatchWriteTests.cpp IntrospectionTests.cpp BridgeStateTests.cpp BroadcastTests.cpp SpaceTests.cpp WebFrontTests.cpp WebLinkTests.cpp CEFPathsTests.cpp CEFMacrosTests.cpp) list(APPEND TESTS_LIST DeveloperTests.cpp WfDriverTests.cpp AutomationTests.cpp AutomationChannelTests.cpp AutomationDiscoveryTests.cpp AutomationMcpHttpTests.cpp AutomationStateTests.cpp JasmineConsumerTests.cpp HostTests.cpp LifeTests.cpp HostLoopTests.cpp StructuredShutdownTests.cpp JsFunctionSenderTests.cpp ApplicationTaskTests.cpp DeferredCallTests.cpp BridgeLightTests.cpp BridgeLightPage.cpp) -list(APPEND TESTS_LIST Main.cpp ScenarioIsolation.cpp FrontendUrlTests.cpp ApplicationUrlTests.cpp FrontendContractTests.cpp UIExecutorTests.cpp NativeWindowTests.cpp WindowRegistryTests.cpp CommandsTests.cpp EmbeddedCoreAssetsTests.cpp) +list(APPEND TESTS_LIST Main.cpp ScenarioIsolation.cpp FrontendUrlTests.cpp ApplicationUrlTests.cpp FrontendContractTests.cpp UIExecutorTests.cpp NativeWindowTests.cpp WindowRegistryTests.cpp WindowControlTests.cpp CommandsTests.cpp EmbeddedCoreAssetsTests.cpp) if(WEBFRONT_USE_MDDLOG) list(APPEND TESTS_LIST MddlogLoggerTests.cpp MddlogTransportTests.cpp) endif() diff --git a/test/unit/WindowControlTests.cpp b/test/unit/WindowControlTests.cpp new file mode 100644 index 00000000..20771aa7 --- /dev/null +++ b/test/unit/WindowControlTests.cpp @@ -0,0 +1,191 @@ +// SPDX-License-Identifier: Apache-2.0 OR CECILL-B +// Author: Ambroise Leclerc +// Created: 2026-12-06 +// +// WebFront — test/unit +// Role: Shortcuts, menus, kept placements and the publication of a WindowControl, without a window. +// Thread: thread-safe | Alloc: unrestricted +// LLM: the engines' behaviour is tested in test/web (window-services, window-persistence, window-menu) + +#include "TemporaryDirectory.hpp" +#include +#include +#include + +#include +#include +#include + +using namespace webfront::bdd; +using namespace webfront::frontend; +using webfront::WindowOptions; + +namespace { +struct BareWindow : WindowControl { + WindowFeatures features() override { + return {}; + } + std::expected placement() override { + return WindowPlacement{.width = 10, .height = 10}; + } +}; +} // namespace + +const Scenario shortcuts{"menu shortcuts", {"window-control"}, [] { + require(parseShortcut("Ctrl+Shift+S") == Shortcut{.control = true, .shift = true, .key = "s"}); + require(parseShortcut("alt+F4") == Shortcut{.alt = true, .key = "f4"}); + require(parseShortcut("F5") == Shortcut{.key = "f5"}); + require(parseShortcut("Meta+Enter") == Shortcut{.meta = true, .key = "enter"}); + require(parseShortcut("CmdOrCtrl+Q").has_value()); + for (const auto* refused : {"", "s", "Shift+S", "Ctrl+", "Ctrl+F13", "Hyper+S", "Ctrl+Save", "Enter"}) + check(!parseShortcut(refused)); + }}; + +const Scenario menus{"menus every toolkit can build", {"window-control"}, [] { + require(validMenu({ + {.label = "File", .items = {{.id = "save", .label = "Save", .shortcut = "Ctrl+S"}, {.separator = true}}} + })); + check(!validMenu({ + {.id = "a", .label = "A"}, + {.id = "a", .label = "Twice"} + })); + check(!validMenu({{.label = "No id"}})); + check(!validMenu({{.id = "a"}})); + check(!validMenu({ + {.id = "a", .label = "A", .shortcut = "S"} + })); + webfront::Menu deep{ + {.id = "leaf", .label = "Leaf"} + }; + for (int level = 0; level < 4; ++level) + deep = { + {.label = "Level", .items = deep} + }; + check(!validMenu(deep)); + }}; + +const Scenario disabledSubmenus{"what is under a disabled submenu is disabled", {"window-control"}, [] { + const auto menu = withInheritedState({ + {.label = "Off", .enabled = false, .items = {{.label = "Sub", .items = {{.id = "a", .label = "A"}}}}}, + {.label = "On", .items = {{.id = "b", .label = "B"}}} + }); + check(!menu[0].items[0].enabled); + check(!menu[0].items[0].items[0].enabled); + check(menu[1].items[0].enabled); + }}; + +const Scenario serviceMenus{"the flat menu of the window service", {"window-control"}, [] { + using Service = webfront::services::Window; + const auto menu = Service::menuOf({ + {0, "", "File", "", 0}, + {1, "save", "Save", "Ctrl+S", 1}, + {1, "wrap", "Wrap", "", 6}, + {0, "help", "Help", "", 0} + }); + requireEqual(menu.size(), 2u); + requireEqual(menu[0].items.size(), 2u); + check(!menu[0].items[0].enabled); + check(menu[0].items[1].checkable && menu[0].items[1].checked); + for (const auto& entries : { + Service::Entries{{1, "a", "A", "", 0}}, + Service::Entries{{0, "a", "A", "", 0}, {2, "b", "B", "", 0}} + }) { + bool refused = false; + try { + static_cast(Service::menuOf(entries)); + } catch (const webfront::BridgeError&) { + refused = true; + } + check(refused); + } + }}; + +const Scenario keptPlacement{"the kept placement of a window", {"window-control"}, [] { + webfront::test::TemporaryDirectory directory; + WindowOptions options{.rememberAs = "main", .stateDirectory = directory.path()}; + check(!loadPlacement(options)); + savePlacement(options, {.x = -20, .y = 40, .width = 640, .height = 480}); + const auto saved = loadPlacement(options); + require(saved.has_value()); + check(*saved == WindowPlacement{.x = -20, .y = 40, .width = 640, .height = 480}); + + // A maximized window that tells no position keeps the former one. + savePlacement(options, {.width = 600, .height = 400, .maximized = true}); + require(loadPlacement(options) == WindowPlacement{.x = -20, .y = 40, .width = 600, .height = 400, .maximized = true}); + const auto restored = restoredOptions(options, loadPlacement(options)); + check(restored.width == 600 && restored.height == 400 && restored.maximized); + + for (const auto* name : {"", "../escape", ".hidden", "a/b"}) { + options.rememberAs = name; + check(!placementFile(options)); + } + for (const auto* text : {"", "{}", "[1]", "{\"width\":-1,\"height\":5}", "{\"width\":10,"}) + check(!decodePlacement(text)); + }}; + +const Scenario reachablePlacement{"a placement on a screen that is gone is not applied", {"window-control"}, [] { + const std::array screens{ + ScreenArea{0, 0, 1920, 1080} + }; + check(reachable({.x = 100, .y = 100, .width = 800, .height = 600}, screens)); + check(!reachable({.x = 2500, .y = 100, .width = 800, .height = 600}, screens)); + check(!reachable({.x = 100, .y = -400, .width = 800, .height = 600}, screens)); + check(!reachable({.width = 800, .height = 600}, screens)); + }}; + +const Scenario reachableOnSeveralMonitors{"a placement follows the monitors, not their bounding box", {"window-control"}, [] { + // A monitor left of the primary one (negative origin) and a smaller one above-right, with a gap. + const std::array screens{ + ScreenArea{-1280, 0, 1280, 1024}, + ScreenArea{ 0, 0, 1920, 1080}, + ScreenArea{ 2200, -300, 800, 600} + }; + check(reachable({.x = -1200, .y = 50, .width = 800, .height = 600}, screens)); + check(reachable({.x = 2300, .y = -200, .width = 600, .height = 400}, screens)); + // In the gap between the second and third monitors, and under the third one. + check(!reachable({.x = 1960, .y = 100, .width = 200, .height = 200}, screens)); + check(!reachable({.x = 2300, .y = 500, .width = 600, .height = 400}, screens)); + // Left of every monitor, and no monitor at all. + check(!reachable({.x = -2000, .y = 100, .width = 400, .height = 300}, screens)); + check(!reachable({.x = 100, .y = 100, .width = 400, .height = 300}, std::span{})); + }}; + +const Scenario waylandSessions{"a Wayland session is recognized from its type", {"window-control"}, [] { + check(waylandSession("wayland")); + check(!waylandSession("x11")); + check(!waylandSession("")); + }}; + +const Scenario controlDefaults{"what a toolkit does not do is unsupported", {"window-control"}, [] { + BareWindow window; + check(window.move(1, 1).error() == WindowFailure::unsupported); + check(window.setMenu({}, {}).error() == WindowFailure::unsupported); + check(window + .showContextMenu( + { + {.id = "a", .label = "A"} + }, + 0, + 0, + [](auto) { }) + .error() + == WindowFailure::unsupported); + check(window.showContextMenu({}, 0, 0, [](auto) { }).error() == WindowFailure::invalid); + std::string chosen; + window.answerContextMenu = [](const webfront::Menu& menu) { + return std::optional{menu.back().id}; + }; + require(window + .showContextMenu( + { + {.id = "a", .label = "A"} + }, + 0, + 0, + [&](auto id) { + chosen = id.value_or(""); + }) + .has_value()); + checkEqual(chosen, std::string("a")); + check(WindowControlRef{}.get().error() == WindowFailure::unsupported); + }}; diff --git a/test/web/CMakeLists.txt b/test/web/CMakeLists.txt index 1af29c8f..fb5a88d1 100644 --- a/test/web/CMakeLists.txt +++ b/test/web/CMakeLists.txt @@ -306,6 +306,21 @@ if(_browser_tests_available) ARGUMENTS --project "${_suite_project}" --registry-dir "${_registry}" --timeout ${_suite_timeout} -- test --timeout ${_suite_timeout}) webfront_use_own_profile(${WEBFRONT_FRONTEND_${WEBFRONT_WEBTEST_FRONTEND}_TEST_NAME} jasmine) + # The window cases again as a Wayland client, where a window has no position (#764): with a headless weston of their + # own, only where weston is installed (the Linux CI image). + if(WEBFRONT_WEBTEST_FRONTEND STREQUAL "WebKitGTK" AND TEST WebKitGTKLifecycle-window-services) + find_program(WEBFRONT_WESTON_EXECUTABLE weston) + if(WEBFRONT_WESTON_EXECUTABLE) + foreach(_mode window-services window-persistence) + add_test(NAME WebKitGTKWayland-${_mode} COMMAND "${PROJECT_SOURCE_DIR}/test/tools/WithWeston.sh" + "${WEBFRONT_WESTON_EXECUTABLE}" "$" ${_mode}) + webfront_set_browser_test_properties(WebKitGTKWayland-${_mode} "${CMAKE_CURRENT_SOURCE_DIR}" + "${WEBFRONT_FRONTEND_WebKitGTK_TEST_TIMEOUT}") + webfront_configure_webkitgtk_test(WebKitGTKWayland-${_mode}) + set_property(TEST WebKitGTKWayland-${_mode} APPEND PROPERTY ENVIRONMENT WEBFRONT_TEST_WAYLAND=1) + endforeach() + endif() + endif() if(WEBFRONT_WEBTEST_FRONTEND STREQUAL "CEF" AND CMAKE_SYSTEM_NAME STREQUAL "Linux") webfront_find_xvfb(_tls_xvfb) set(_tls_fixture "${CMAKE_CURRENT_SOURCE_DIR}/fixtures/tls") diff --git a/test/web/FrontendLifecycle.cpp b/test/web/FrontendLifecycle.cpp index acad65ee..497c8f85 100644 --- a/test/web/FrontendLifecycle.cpp +++ b/test/web/FrontendLifecycle.cpp @@ -8,6 +8,7 @@ // LLM: real-browser test; a stage is selected through the bridge by the specs #include "../driver/TestFrontend.hpp" +#include #include #include #include @@ -20,6 +21,7 @@ #include #include #include +#include #include #include #include @@ -1220,6 +1222,149 @@ int checkStartupTime() { return 0; } +// The frontend with the test injection of context menus: where the native menu blocks until the user chooses, the choice is +// made for them. +inline std::atomic contextMenuAnswered = false; +template +struct ContextAnswering : Base { + static auto startingOptions() + requires requires { Base::startingOptions(); } + { + auto options = Base::startingOptions(); +#if defined(_WIN32) || defined(__APPLE__) + options.answerContextMenu = [](const webfront::frontend::Menu& menu) { + contextMenuAnswered = true; + return std::optional{menu.back().id}; + }; +#endif + return options; + } +}; +using WindowApp = webfront::BasicWFWithFrontend>>; + +// Shows `page` with the window service and returns what the page reports before the host closes the window. +std::string windowReport(webfront::WebFrontConfig config, std::string_view page) { + WindowApp app(std::move(config)); + webfront::services::Window service(app); + std::mutex mutex; + std::string report; + std::atomic reported = false; + app.cppFunction("windowReport", [&](std::string text) { + { + std::scoped_lock lock{mutex}; + report = std::move(text); + } + reported = true; + }); + app.cppFunction("contextAnswered", [] { + return contextMenuAnswered.load(); + }); + lifecycleStage = LifecycleStage::startingInstrumented; + std::atomic done = false; + std::thread closer([&] { + while (!reported && !done) + std::this_thread::sleep_for(std::chrono::milliseconds(10)); + // requestClose() answers false until the window is published: repeat it until show() has returned. + while (!done) { + app.requestClose(); + std::this_thread::sleep_for(std::chrono::milliseconds(100)); + } + }); + struct Join { + std::atomic& done; + std::thread& thread; + ~Join() { + done = true; + thread.join(); + } + } join{done, closer}; + app.show(page); + std::scoped_lock lock{mutex}; + return report; +} + +// A variable that only the Linux cases set (MSVC refuses getenv, and none of them runs there). +std::string linuxTestVariable([[maybe_unused]] const char* name) { +#if defined(__linux__) + if (const auto* value = std::getenv(name)) + return value; +#endif + return {}; +} + +// The page of the view drives geometry, state, menus and the tray, and what the toolkit cannot do is `unsupported`; a +// connection that is not the view changes nothing (ADR-020). +int checkWindowServices() { + const auto report = windowReport({.documentRoot = std::filesystem::current_path()}, "window-services.html"); + std::cout << "window-services: " << report << std::endl; + if (!report.starts_with("ok:")) + throw std::runtime_error("The window services scenario failed: " + report); + // Wayland neither tells nor accepts where a window is: the page is told so (it then checked the `unsupported` errors). + if (!linuxTestVariable("WEBFRONT_TEST_WAYLAND").empty() && (report.contains("position") || report.contains("alwaysOnTop"))) + throw std::runtime_error("A position or an always-on-top is announced under Wayland: " + report); + return 0; +} + +// An application reopens its window at the position and size of its previous session; where the system does not tell the +// position (Wayland), the size only. CEF cannot be initialized twice in a process: there, the first session is that of +// another one (`window-persistence-first`). +webfront::WebFrontConfig persistenceConfig(const std::filesystem::path& directory) { + webfront::WebFrontConfig config{.documentRoot = std::filesystem::current_path()}; + config.window = {.width = 800, .height = 600, .rememberAs = "lifecycle", .stateDirectory = directory}; + return config; +} + +std::string firstPlacement(const std::filesystem::path& directory) { + const auto first = windowReport(persistenceConfig(directory), "window-persistence.html?save"); + std::cout << "window-persistence: saved " << first << std::endl; + if (!first.ends_with(" 700x500")) + throw std::runtime_error("The window could not be resized: " + first); + if (!linuxTestVariable("WEBFRONT_TEST_WAYLAND").empty() && !first.starts_with("unknown ")) + throw std::runtime_error("A position is told under Wayland: " + first); + const auto saved = webfront::frontend::loadPlacement(persistenceConfig(directory).window); + if (!saved || saved->width != 700 || saved->height != 500) + throw std::runtime_error("The placement of the first session was not saved"); + return first; +} + +int saveFirstPlacement() { + const auto directory = linuxTestVariable("WEBFRONT_TEST_WINDOW_STATE"); + if (directory.empty()) + throw std::runtime_error("window-persistence-first is run by window-persistence"); + const auto first = firstPlacement(directory); + std::ofstream(std::filesystem::path(directory) / "first.txt") << first; + return 0; +} + +int checkWindowPersistence() { + const auto directory = std::filesystem::temp_directory_path() + / ("webfront-window-" + std::to_string(std::chrono::steady_clock::now().time_since_epoch().count())); + std::filesystem::create_directories(directory); + struct Remove { + std::filesystem::path path; + ~Remove() { + std::error_code ignored; + std::filesystem::remove_all(path, ignored); + } + } remove{directory}; + std::string first; +#if defined(WEBFRONT_EMBED_CEF) && defined(__linux__) + if constexpr (std::is_same_v) { + const auto self = std::filesystem::read_symlink("/proc/self/exe").string(); + ::setenv("WEBFRONT_TEST_WINDOW_STATE", directory.c_str(), 1); + if (std::system(("\"" + self + "\" window-persistence-first").c_str()) != 0) + throw std::runtime_error("The first session failed"); + std::getline(std::ifstream(directory / "first.txt"), first); + } else +#endif + first = firstPlacement(directory); + const auto second = windowReport(persistenceConfig(directory), "window-persistence.html"); + std::cout << "window-persistence: reopened " << second << std::endl; + if (second != first) + throw std::runtime_error("The window did not reopen where it was: " + first + " then " + second); + return 0; +} + int run(std::string_view mode) { std::map cases; cases.emplace( @@ -1255,6 +1400,9 @@ int run(std::string_view mode) { cases.emplace("navigation-failure", expectNavigationFailure); cases.emplace("ui-executor", checkUIExecutor); cases.emplace("native-window", checkNativeWindow); + cases.emplace("window-services", checkWindowServices); + cases.emplace("window-persistence", checkWindowPersistence); + cases.emplace("window-persistence-first", saveFirstPlacement); cases.emplace("second-open", checkSecondOpen); cases.emplace("host-close", checkHostClose); cases.emplace("second-window", checkSecondWindow); diff --git a/test/web/WebKitGTKLifecycle.cpp b/test/web/WebKitGTKLifecycle.cpp index 55df716c..91a59367 100644 --- a/test/web/WebKitGTKLifecycle.cpp +++ b/test/web/WebKitGTKLifecycle.cpp @@ -505,6 +505,221 @@ void closeWithScriptDialog() { throw std::runtime_error("The script dialog was not opened"); } +/// The window's menu, driven as a user does: its shortcut by a real key press (XTest), a context menu dismissed without a +/// choice, and the always-on-top request a window manager receives. +void windowMenu() { + std::vector selected; + std::vector> contextAnswers; + const FakeClick pointer; + if (!pointer.available()) + throw std::runtime_error("XTest is unavailable: run the scenario under Xvfb with libXtst"); + using FakeKey = int (*)(void*, unsigned, int, unsigned long); + using Keycode = unsigned char (*)(void*, unsigned long); + using Select = int (*)(void*, unsigned long, long); + using Pending = int (*)(void*); + using Next = int (*)(void*, void*); + using Open = void* (*)(const char*); + using Close = int (*)(void*); + const auto key = reinterpret_cast(dlsym(pointer.xtest, "XTestFakeKeyEvent")); + const auto keycode = reinterpret_cast(dlsym(pointer.x11, "XKeysymToKeycode")); + const auto select = reinterpret_cast