From 4e8b69514c306cb150573cebab27d657c5a40f7f Mon Sep 17 00:00:00 2001 From: Ambroise Leclerc <6860842+ambroise-leclerc@users.noreply.github.com> Date: Sun, 6 Dec 2026 01:33:17 +0100 Subject: [PATCH 01/24] Add window services with persisted placement, menus and a page-facing service under WebKitGTK (#764) --- cmake/Frontends.cmake | 1 + cmake/WebKitGTKSupport.cmake | 2 +- include/webfront/WebFront.hpp | 12 + .../webfront/frontend/EmbeddedFrontend.hpp | 10 + include/webfront/frontend/WebKitGTK.hpp | 64 +- include/webfront/frontend/WebKitGTKWindow.hpp | 564 +++++++++++++++++ include/webfront/frontend/Window.hpp | 25 +- include/webfront/frontend/WindowControl.hpp | 587 ++++++++++++++++++ .../services/window/WindowService.hpp | 204 ++++++ test/web/FrontendLifecycle.cpp | 102 +++ test/web/WebKitGTKLifecycle.cpp | 103 +++ test/web/window-persistence.html | 31 + test/web/window-services.html | 105 ++++ 13 files changed, 1797 insertions(+), 13 deletions(-) create mode 100644 include/webfront/frontend/WebKitGTKWindow.hpp create mode 100644 include/webfront/frontend/WindowControl.hpp create mode 100644 include/webfront/services/window/WindowService.hpp create mode 100644 test/web/window-persistence.html create mode 100644 test/web/window-services.html 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..b54592f4 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 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/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/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/WebKitGTK.hpp b/include/webfront/frontend/WebKitGTK.hpp index 419a40b0..1630d5b4 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,29 @@ 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; + if (savedPlacement && reachable(*savedPlacement, control->screens())) + static_cast(control->move(*savedPlacement->x, *savedPlacement->y)); + 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 +588,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 +635,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 +1040,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 +1056,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 +1143,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..94d4d00d --- /dev/null +++ b/include/webfront/frontend/WebKitGTKWindow.hpp @@ -0,0 +1,564 @@ +// 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 (*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"); + // 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 { + std::function chosen; + }; + 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; + std::vector menuIds; + std::vector> choices; + Selected menuSelected; + std::unique_ptr popup; + + 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; + } + + static void releaseChoice(void*, void*) noexcept { } + 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) { + 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); + a.menuSubmenu(section, item.label.c_str(), child); + 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.get(), releaseChoice, 0); + a.addAction(actions, action); + a.unref(action); + choices.push_back(std::move(choice)); + 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 = {}; + } + + 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 { + finishPopup(); + removeMenu(); + } + + [[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; + 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->maximized || result->fullscreen)) { + a.defaultSize(window, &result->width, &result->height); // GTK keeps the size from before + result->x = result->y = std::nullopt; + } + return result; + } + + /// The screens of the X display, as one area; empty without one. + [[nodiscard]] std::vector screens() const { + const auto target = x11(); + if (!target) + return {}; + const auto screen = a.xDefaultScreen(target->display); + return { + {0, 0, a.xScreenWidth(target->display, screen), a.xScreenHeight(target->display, screen)} + }; + } + + 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 { + (on ? a.maximize : a.unmaximize)(window); + return {}; + } + WindowStatus setFullscreen(bool on) override { + (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(); + choices.clear(); + if (menu.empty()) + return {}; + menuSelected = std::move(selected); + group = a.groupNew(); + std::vector> accelerators; + const auto model = buildModel(menu, group, "wf", menuIds, accelerators, [this](std::string id) { + return std::function([this, id = std::move(id)] { + if (const auto handler = menuSelected) + handler(id); + }); + }); + a.insertGroup(window, "wf", group); + menuBar = a.menuBarNew(model); + a.unref(model); + a.boxPrepend(box, menuBar); + 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(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/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..eb69d2e5 --- /dev/null +++ b/include/webfront/frontend/WindowControl.hpp @@ -0,0 +1,587 @@ +// 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 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) + wchar_t buffer[32768]; + const auto length = GetEnvironmentVariableW(L"LOCALAPPDATA", buffer, static_cast(std::size(buffer))); + if (length > 0 && length < std::size(buffer)) + 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; +} + +/// 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..06cc30e7 --- /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, request). `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) { + check(window.setMenu(menuOf(entries), notify(caller, "application"))); + }); + addForCaller( + "setTray", + [](frontend::WindowControl& window, UI caller, const std::string& title, const std::string& tooltip, const Entries& entries) { + check(window.setTray(frontend::Tray{.title = title, .tooltip = tooltip, .menu = menuOf(entries)}, notify(caller, "tray"))); + }); + 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) { + return [caller, source = std::move(source)](const std::string& id) { + caller.jsFunction(eventFunction)(source, id, std::int32_t{0}); + }; + } + + 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/test/web/FrontendLifecycle.cpp b/test/web/FrontendLifecycle.cpp index acad65ee..81cf6628 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 @@ -1220,6 +1221,105 @@ 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; +} + +// 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); + 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. +int checkWindowPersistence() { + const auto directory = std::filesystem::temp_directory_path() + / ("webfront-window-" + std::to_string(std::chrono::steady_clock::now().time_since_epoch().count())); + struct Remove { + std::filesystem::path path; + ~Remove() { + std::error_code ignored; + std::filesystem::remove_all(path, ignored); + } + } remove{directory}; + webfront::WebFrontConfig config{.documentRoot = std::filesystem::current_path()}; + config.window = {.width = 800, .height = 600, .rememberAs = "lifecycle", .stateDirectory = directory}; + const auto first = windowReport(config, "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); + const auto saved = webfront::frontend::loadPlacement(config.window); + if (!saved || saved->width != 700 || saved->height != 500) + throw std::runtime_error("The placement of the first session was not saved"); + const auto second = windowReport(config, "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 +1355,8 @@ 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("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..e80d39d2 100644 --- a/test/web/WebKitGTKLifecycle.cpp +++ b/test/web/WebKitGTKLifecycle.cpp @@ -505,6 +505,108 @@ 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(dlsym(pointer.x11, "XSelectInput")); - const auto pending = reinterpret_cast(dlsym(pointer.x11, "XPending")); - const auto next = reinterpret_cast(dlsym(pointer.x11, "XNextEvent")); - const auto closeX = reinterpret_cast(dlsym(pointer.x11, "XCloseDisplay")); - const auto openX = reinterpret_cast(dlsym(pointer.x11, "XOpenDisplay")); - int tick = 0; - int waiting = 0; - bool above = false; - bool hidden = false; - bool minimized = false; - void* manager = nullptr; + const auto key = reinterpret_cast(dlsym(pointer.xtest, "XTestFakeKeyEvent")); + const auto keycode = reinterpret_cast(dlsym(pointer.x11, "XKeysymToKeycode")); + const auto select = reinterpret_cast