feat(wayland): keep xdg_toplevel's activated and suspended states on the window

A consumer could not tell a window somebody is looking at from one that
merely exists. The compositor's word on it comes with every
xdg_toplevel configure — the `activated` state, and since version 6 of
xdg_wm_base `suspended`, "not ordinarily being repainted", for example
for a content covered by another window or outputs switched off for a
screen lock — and the window dropped the states array. A messenger
built on it took a conversation left open behind a lock screen or
another application for one that was being read: its texts were marked
read and never notified.

Window: `activated` and `suspended` hold the two states, and
onToplevelState fires after a configure changed either, with both
already set. They are batched as the size is: xdg_toplevel.configure
leaves them pending and the xdg_surface.configure that ends the batch
applies them (ApplyToplevelState) last, so the handler does nothing
with the window after its listeners. The constructor takes the first
configure before a listener can be added, so a consumer reads the two
once after it. Both are reported and the library combines nothing:
which of the two a lock screen or another window in front changes is
the compositor's choice, so a consumer that asks whether the user is
looking at the window wants `activated && !suspended`, and the consumer
notes say so. The members are the Wayland backend's; the Win32 and DOM
backends keep no such state.

Device: xdg_wm_base is bound at the version the compositor offers, up
to 6, where it was bound at 1: `suspended` does not exist below 6
(`activated` is version 1's). Every request the windows make is version
1's. Besides `suspended`, the higher versions bring the window state
values it passes over (the tiled ones, 2) and two events,
xdg_toplevel's configure_bounds (4) and wm_capabilities (5), which the
toplevel's listener takes and drops, since libwayland aborts a client
at an event whose handler is null.

Tests: ToplevelState feeds the two configure callbacks of a window
whose surfaces are proxies on a wl_display over a socketpair, as
TitleWayland makes them, and reads the bind off the wire: the states
pending until the surface's configure, the last toplevel configure of a
batch applied, one event for a batch that changes both, none for a
repeat or for other states, an empty array clearing both; an offer of
7, 6, 5 and 1 bound at 6, 6, 5 and 1; a handler in the xdg_wm_base,
xdg_surface and xdg_toplevel listeners for every event of the bundled
protocol.
This commit is contained in:
Jorijn van der Graaf 2026-11-17 00:49:53 +01:00
commit c006519fa0
Signed by: jorijnvdgraaf
GPG key ID: 2937E59CDCC1BCFB
7 changed files with 310 additions and 4 deletions

View file

@ -128,7 +128,7 @@ Heap-only: check `Device::rayTracingSupported`, or expect `std::runtime_error` f
### Input ### Input
- `Window` events, `Event<void>` unless noted: `onMouseMove` (then `currentMousePos`, `lastMousePos`, `mouseDelta`), `onMouseEnter` and `onMouseLeave` with `mouseInside` (native only: the DOM build declares the two events but never fires them, and has no `mouseInside`), `onMouseLeftClick`, `onMouseLeftHold`, `onMouseLeftRelease` and the right-button trio (`mouseLeftHeld`, `mouseRightHeld`), `onMouseScroll` (`Event<std::uint32_t>`: whole detents, reinterpret the payload as `int32`, positive is wheel down, every backend normalised to one per notch), `onRawKeyDown`, `onRawKeyHold`, `onRawKeyUp` (`Event<KeyCode>`, raw platform codes; `heldKeys`), `onTextInput` (`Event<const std::string_view>`, UTF-8; repeats are synthesised on Wayland), `onPreedit` and `onTextInputDelete` (input methods), `onTouchDown`, `onTouchMove`, `onTouchUp` (`Event<TouchPoint>`; the first finger also drives the pointer events), `onClose`, `onResize`, `onBeforeUpdate`, `onUpdate` (`Event<FrameTime>`: `now`, `delta`). On Wayland `lastInputTime` is the compositor's `time` of the pointer, touch or scroll event a listener is being invoked for (milliseconds from an undefined base, wrapping at 2^32, set before the event fires; an event the compositor sends without a time — an enter and the move that follows it, a leave, a touch cancel and its release — keeps the last one's): a consumer that dates gestures — a fling's velocity, a tap against a long press — reads it instead of its own clock at dispatch, since events queued while the loop was busy keep the times they happened at. A listener that dispatches Wayland events itself (it makes a `Window`, or calls `Clipboard::GetText`) has them set it too, for itself from there on and for the listeners of its event that come after it. The other backends have no such member. - `Window` events, `Event<void>` unless noted: `onMouseMove` (then `currentMousePos`, `lastMousePos`, `mouseDelta`), `onMouseEnter` and `onMouseLeave` with `mouseInside` (native only: the DOM build declares the two events but never fires them, and has no `mouseInside`), `onMouseLeftClick`, `onMouseLeftHold`, `onMouseLeftRelease` and the right-button trio (`mouseLeftHeld`, `mouseRightHeld`), `onMouseScroll` (`Event<std::uint32_t>`: whole detents, reinterpret the payload as `int32`, positive is wheel down, every backend normalised to one per notch), `onRawKeyDown`, `onRawKeyHold`, `onRawKeyUp` (`Event<KeyCode>`, raw platform codes; `heldKeys`), `onTextInput` (`Event<const std::string_view>`, UTF-8; repeats are synthesised on Wayland), `onPreedit` and `onTextInputDelete` (input methods), `onTouchDown`, `onTouchMove`, `onTouchUp` (`Event<TouchPoint>`; the first finger also drives the pointer events), `onClose`, `onResize`, `onBeforeUpdate`, `onUpdate` (`Event<FrameTime>`: `now`, `delta`). On Wayland `lastInputTime` is the compositor's `time` of the pointer, touch or scroll event a listener is being invoked for (milliseconds from an undefined base, wrapping at 2^32, set before the event fires; an event the compositor sends without a time — an enter and the move that follows it, a leave, a touch cancel and its release — keeps the last one's): a consumer that dates gestures — a fling's velocity, a tap against a long press — reads it instead of its own clock at dispatch, since events queued while the loop was busy keep the times they happened at. A listener that dispatches Wayland events itself (it makes a `Window`, or calls `Clipboard::GetText`) has them set it too, for itself from there on and for the listeners of its event that come after it. The other backends have no such member. On Wayland `activated` and `suspended` are what the compositor says of the window's place on the screen (xdg_toplevel's states: it counts as the active window; it is not ordinarily being repainted — covered by another window, say, or its outputs switched off for a screen lock — which a compositor with an xdg_wm_base older than version 6 never says), and `onToplevelState` fires after a configure changed either, with both already set. Which of the two a lock screen or another window in front changes is the compositor's choice, so the test for "the user is looking at this window" — is the message it shows read? — is `activated && !suspended`; by it a window that is visible but not the active one is not looked at. The constructor takes the first configure before a listener can be added: read the two once after it, then follow the event. Both are false until a configure sets them, which that first one need not do. The other backends have neither member.
- Keys: `Key(CrafterKeys::Space)` is `consteval` and folds to the platform's raw code (a Win32 scancode, a Linux keycode), so bindings stay portable in source and compare against `onRawKeyDown`'s `KeyCode` at runtime. Bindings serialised with `Input::BindingToString` are platform-specific. - Keys: `Key(CrafterKeys::Space)` is `consteval` and folds to the platform's raw code (a Win32 scancode, a Linux keycode), so bindings stay portable in source and compare against `onRawKeyDown`'s `KeyCode` at runtime. Bindings serialised with `Input::BindingToString` are platform-specific.
- `Input::Map`: `auto& jump = map.AddAction("Jump", Input::ActionType::Button);` (`Button`, `Axis1D`, `Vector2`), `jump.bindings = { Input::KeyBind{Key(CrafterKeys::Space)}, Input::GamepadButtonBind{id, Gamepad::Button::South} };` (also `MouseButtonBind`, `MouseScrollBind`, `MouseDeltaBind{scale}`, `GamepadAxisBind`, `GamepadStickBind{id, Gamepad::Stick::Left}`, `WASDBind{up, down, left, right}`), `map.Attach(window);`, and `map.Tick();` once per frame, after `Gamepad::Tick()`, which the loop runs before `onBeforeUpdate`. Every `Tick` recomputes the mouse delta and drains the scroll accumulator, and on Wayland `onBeforeUpdate` fires on every loop wake, so either tick from `onUpdate`, or tick in `onBeforeUpdate` and consume the delta and scroll actions in that same listener, as the Sponza example does. Read `action.pressed`, `value` or `vector2`, or subscribe to `onPerformed`, `onCanceled`, `onValueChanged`, `onVector2Changed`. `StartRebind(action, CaptureMask, callback)` captures the next input. - `Input::Map`: `auto& jump = map.AddAction("Jump", Input::ActionType::Button);` (`Button`, `Axis1D`, `Vector2`), `jump.bindings = { Input::KeyBind{Key(CrafterKeys::Space)}, Input::GamepadButtonBind{id, Gamepad::Button::South} };` (also `MouseButtonBind`, `MouseScrollBind`, `MouseDeltaBind{scale}`, `GamepadAxisBind`, `GamepadStickBind{id, Gamepad::Stick::Left}`, `WASDBind{up, down, left, right}`), `map.Attach(window);`, and `map.Tick();` once per frame, after `Gamepad::Tick()`, which the loop runs before `onBeforeUpdate`. Every `Tick` recomputes the mouse delta and drains the scroll accumulator, and on Wayland `onBeforeUpdate` fires on every loop wake, so either tick from `onUpdate`, or tick in `onBeforeUpdate` and consume the delta and scroll actions in that same listener, as the Sponza example does. Read `action.pressed`, `value` or `vector2`, or subscribe to `onPerformed`, `onCanceled`, `onValueChanged`, `onVector2Changed`. `StartRebind(action, CaptureMask, callback)` captures the next input.
- `Gamepad::connected`, `onConnected`, `onDisconnected`, per-device `buttons[]`, `axes[]` and events, `Rumble(dev, low, high, duration)`, `FindById(id)`; buttons are named by position (`South`, `East`, `West`, `North`). `Clipboard::SetText(text)` and `GetText()` (`std::optional<std::string>`). - `Gamepad::connected`, `onConnected`, `onDisconnected`, per-device `buttons[]`, `axes[]` and events, `Rumble(dev, low, high, duration)`, `FindById(id)`; buttons are named by position (`South`, `East`, `West`, `North`). `Clipboard::SetText(text)` and `GetText()` (`std::optional<std::string>`).

View file

@ -72,7 +72,7 @@ Tests are declared in `project.cpp`, not discovered, through the `LibraryTest(na
A test is an `int main()`: exit 0 passes, nonzero fails, 77 skips (for a missing capability, never for a failed check). Each runs in its own process, in parallel, with a 60 s default timeout, and the output of a failed, crashed or timed-out test is in `build/test-logs/<name>.log`; a later pass does not delete the log, so check its timestamp. What the tests need, in three groups: A test is an `int main()`: exit 0 passes, nonzero fails, 77 skips (for a missing capability, never for a failed check). Each runs in its own process, in parallel, with a 60 s default timeout, and the output of a failed, crashed or timed-out test is in `build/test-logs/<name>.log`; a later pass does not delete the log, so check its timestamp. What the tests need, in three groups:
- Pure logic, no GPU: they stage `Device`'s statics or feed synthetic data to the decision functions that were factored out for them (`Device::ResolveFeatures`, `ChooseDevice`, `CheckShaderCapabilities`, `GetMemoryType`, `PreferDirectDeviceWrite`, `PipelineCacheDataCompatible`, `AlignMappedFlushRange`, `BuildMipChainFinalBarriers`, `SwapchainStageUnion`, `BuildTlasWriteBarrier`, `UIRenderer::ClipFlags`, `Window::SwapchainMinImageCount`, `WorkaroundNvidiaAS::Patch`, `DescriptorHeapVulkan::ComputeLayout`, `FontAtlas::Packer`, the font and input-field helpers). `PushConstantRewrite` and `UIFusedShader` compile GLSL with glslang and check the SPIR-V with spirv-val at runtime, and `ExampleShaders` compiles every GLSL shader under `examples/` the way crafter-build would, the descriptor-set build included, so a shader contract change that breaks an example fails here without building the example; `FontAtlasDecode` reads `ui-shared.glsl` and `dom-webgpu.js` and holds their copies of the SDF encoding constants to `FontAtlas`'s; `MouseScroll`, `PointerEnterLeave` and `InputTime` drive the Wayland listener callbacks directly, and `TitleWayland` reads the requests a window sends off a `wl_display` connected to a socketpair. - Pure logic, no GPU: they stage `Device`'s statics or feed synthetic data to the decision functions that were factored out for them (`Device::ResolveFeatures`, `ChooseDevice`, `CheckShaderCapabilities`, `GetMemoryType`, `PreferDirectDeviceWrite`, `PipelineCacheDataCompatible`, `AlignMappedFlushRange`, `BuildMipChainFinalBarriers`, `SwapchainStageUnion`, `BuildTlasWriteBarrier`, `UIRenderer::ClipFlags`, `Window::SwapchainMinImageCount`, `WorkaroundNvidiaAS::Patch`, `DescriptorHeapVulkan::ComputeLayout`, `FontAtlas::Packer`, the font and input-field helpers). `PushConstantRewrite` and `UIFusedShader` compile GLSL with glslang and check the SPIR-V with spirv-val at runtime, and `ExampleShaders` compiles every GLSL shader under `examples/` the way crafter-build would, the descriptor-set build included, so a shader contract change that breaks an example fails here without building the example; `FontAtlasDecode` reads `ui-shared.glsl` and `dom-webgpu.js` and holds their copies of the SDF encoding constants to `FontAtlas`'s; `MouseScroll`, `PointerEnterLeave` and `InputTime` drive the Wayland listener callbacks directly, `TitleWayland` reads the requests a window sends off a `wl_display` connected to a socketpair, and `ToplevelState` does both: it feeds the `xdg_toplevel` and `xdg_surface` configure callbacks of a window whose surfaces are proxies on such a display, and reads the version `xdg_wm_base` is bound at off the wire.
- A headless device: `Device::Initialize()` and no `Window` (`HeapSlotReuse`, `DeferredDeletion`, `MeshLifetime`, `ImageStagingRelease`, `BLASBuildOptions`, the `TLAS*` tests, ...). Headless still means a Wayland display on Linux. Most of the RT ones check `Device::rayTracingSupported` and return 77 without it; `BLASBuildOptions`, `TLASInstanceDirtyTracking` and `MeshDecompressStagingRelease` do not, and crash on a GPU without ray tracing (`Device::RequireRayTracing` throws out of `main`). `DeviceSelection` skips with one GPU. - A headless device: `Device::Initialize()` and no `Window` (`HeapSlotReuse`, `DeferredDeletion`, `MeshLifetime`, `ImageStagingRelease`, `BLASBuildOptions`, the `TLAS*` tests, ...). Headless still means a Wayland display on Linux. Most of the RT ones check `Device::rayTracingSupported` and return 77 without it; `BLASBuildOptions`, `TLASInstanceDirtyTracking` and `MeshDecompressStagingRelease` do not, and crash on a GPU without ray tracing (`Device::RequireRayTracing` throws out of `main`). `DeviceSelection` skips with one GPU.
- A window and a live compositor: `FrameLoopSync`, `SetupCmdBufferReuse`, `UIFallbackParity`, `SwapchainTransferDst`, `WindowUpdateClock`, `HeapASRead`, `HeapDynamicIndexHit`, `RTPassPushData`, `WindowOptionalGlobals` (hides xdg-decoration, viewporter and fractional scale from the window in turn), `SwapchainImageCount` (every present mode, and swapchains with more images than frames in flight, in child processes on llvmpipe where the host's GPU never makes one), `TextAntialiasing` (text through `DispatchText` and `DispatchFused` against stb_truetype's own antialiased rasterizer, at 14 and 64 px and stretched, plus a glyph mirrored by its UVs and empty texels shrunk below 4 px), and `FeatureRequests` for its retry case. They render, read the frame back with `Window::CaptureNextFrame` (a PNG, decoded with a private `STB_IMAGE_STATIC` copy of stb_image) or a transfer pass of their own, and check pixels. - A window and a live compositor: `FrameLoopSync`, `SetupCmdBufferReuse`, `UIFallbackParity`, `SwapchainTransferDst`, `WindowUpdateClock`, `HeapASRead`, `HeapDynamicIndexHit`, `RTPassPushData`, `WindowOptionalGlobals` (hides xdg-decoration, viewporter and fractional scale from the window in turn), `SwapchainImageCount` (every present mode, and swapchains with more images than frames in flight, in child processes on llvmpipe where the host's GPU never makes one), `TextAntialiasing` (text through `DispatchText` and `DispatchFused` against stb_truetype's own antialiased rasterizer, at 14 and 64 px and stretched, plus a glyph mirrored by its UVs and empty texels shrunk below 4 px), and `FeatureRequests` for its retry case. They render, read the frame back with `Window::CaptureNextFrame` (a PNG, decoded with a private `STB_IMAGE_STATIC` copy of stb_image) or a transfer pass of their own, and check pixels.

View file

@ -318,7 +318,12 @@ void Device::handle_global(void *data, wl_registry *registry, std::uint32_t name
} else if (compositor == nullptr && strcmp(interface, wl_compositor_interface.name) == 0) { } else if (compositor == nullptr && strcmp(interface, wl_compositor_interface.name) == 0) {
compositor = reinterpret_cast<wl_compositor*>(wl_registry_bind(registry, name, &wl_compositor_interface, 3)); compositor = reinterpret_cast<wl_compositor*>(wl_registry_bind(registry, name, &wl_compositor_interface, 3));
} else if (strcmp(interface, xdg_wm_base_interface.name) == 0) { } else if (strcmp(interface, xdg_wm_base_interface.name) == 0) {
xdgWmBase = reinterpret_cast<xdg_wm_base*>(wl_registry_bind(registry, name, &xdg_wm_base_interface, 1)); // Up to version 6, for xdg_toplevel's `suspended` state
// (Window::suspended); `activated` is there from version 1. The
// requests the windows make are all version 1's. On the way come
// xdg_toplevel's configure_bounds (4) and wm_capabilities (5), which
// Window's listener takes and drops.
xdgWmBase = reinterpret_cast<xdg_wm_base*>(wl_registry_bind(registry, name, &xdg_wm_base_interface, std::min<std::uint32_t>(version, 6)));
xdg_wm_base_add_listener(xdgWmBase, &xdgWmBaseListener, nullptr); xdg_wm_base_add_listener(xdgWmBase, &xdgWmBaseListener, nullptr);
} else if (strcmp(interface, zxdg_decoration_manager_v1_interface.name) == 0) { } else if (strcmp(interface, zxdg_decoration_manager_v1_interface.name) == 0) {
manager = reinterpret_cast<zxdg_decoration_manager_v1*>(wl_registry_bind(registry, name, &zxdg_decoration_manager_v1_interface, 1)); manager = reinterpret_cast<zxdg_decoration_manager_v1*>(wl_registry_bind(registry, name, &zxdg_decoration_manager_v1_interface, 1));

View file

@ -1871,13 +1871,33 @@ void Window::wl_surface_frame_done(void* data, struct wl_callback *cb, uint32_t
} }
void Window::xdg_toplevel_configure(void* data, xdg_toplevel*, std::int32_t width, std::int32_t height, wl_array*){ void Window::xdg_toplevel_configure(void* data, xdg_toplevel*, std::int32_t width, std::int32_t height, wl_array* states){
// xdg-shell batches state — width/height are pending until the matching // xdg-shell batches state — width/height are pending until the matching
// xdg_surface.configure arrives. Width/height are in surface-local // xdg_surface.configure arrives. Width/height are in surface-local
// (logical DP) units; (0, 0) means "compositor has no preference". // (logical DP) units; (0, 0) means "compositor has no preference".
Window* window = reinterpret_cast<Window*>(data); Window* window = reinterpret_cast<Window*>(data);
window->pendingLogicalWidth = width; window->pendingLogicalWidth = width;
window->pendingLogicalHeight = height; window->pendingLogicalHeight = height;
// The states are batched with them. The array lists the ones that are
// set: one it leaves out is not.
window->pendingActivated = false;
window->pendingSuspended = false;
const std::uint32_t* state = static_cast<const std::uint32_t*>(states->data);
for (std::size_t i = 0; i < states->size / sizeof(std::uint32_t); ++i) {
if (state[i] == XDG_TOPLEVEL_STATE_ACTIVATED) window->pendingActivated = true;
else if (state[i] == XDG_TOPLEVEL_STATE_SUSPENDED) window->pendingSuspended = true;
}
}
void Window::xdg_toplevel_configure_bounds(void*, xdg_toplevel*, std::int32_t, std::int32_t) {}
void Window::xdg_toplevel_wm_capabilities(void*, xdg_toplevel*, wl_array*) {}
void Window::ApplyToplevelState() {
if (activated == pendingActivated && suspended == pendingSuspended) return;
activated = pendingActivated;
suspended = pendingSuspended;
onToplevelState.Invoke();
} }
void Window::xdg_toplevel_handle_close(void* data, xdg_toplevel*) { void Window::xdg_toplevel_handle_close(void* data, xdg_toplevel*) {
@ -1910,6 +1930,8 @@ void Window::xdg_surface_handle_configure(void* data, xdg_surface* xdg_surface,
} }
window->configured = true; window->configured = true;
// Last: the handler does nothing with the window after its listeners.
window->ApplyToplevelState();
} }
void Window::xdg_surface_handle_preferred_scale(void* data, wp_fractional_scale_v1*, std::uint32_t scale) { void Window::xdg_surface_handle_preferred_scale(void* data, wp_fractional_scale_v1*, std::uint32_t scale) {

View file

@ -305,6 +305,26 @@ export namespace Crafter {
}; };
std::vector<PollFd> pollFds; std::vector<PollFd> pollFds;
// What the compositor says of the window's place on the screen, as
// xdg_toplevel's states give it. `activated`: it counts as the
// active window (no promise of keyboard or pointer focus).
// `suspended`: it is not ordinarily being repainted — the
// protocol's examples are a content covered by another window and
// outputs switched off for a screen lock; the state came with
// version 6 of xdg_wm_base, so under a compositor with an older
// one it stays false. Which of the two a lock screen or another
// window in front changes is the compositor's own choice, so a
// consumer that asks whether the user is looking at the window
// (is the message it shows read?) wants `activated && !suspended`.
// Both are false until a configure sets them, which a new window's
// first one need not do. onToplevelState fires after a configure
// changed either, with both already set; the constructor takes the
// first configure before a listener can be added, so a consumer
// reads the two once after it.
bool activated = false;
bool suspended = false;
Event<void> onToplevelState;
float scale = 1.0f; float scale = 1.0f;
bool configured = false; bool configured = false;
// Pending size from the most recent xdg_toplevel.configure, in // Pending size from the most recent xdg_toplevel.configure, in
@ -312,6 +332,14 @@ export namespace Crafter {
// via Resize(); 0 means "compositor has no preference, keep current". // via Resize(); 0 means "compositor has no preference, keep current".
std::int32_t pendingLogicalWidth = 0; std::int32_t pendingLogicalWidth = 0;
std::int32_t pendingLogicalHeight = 0; std::int32_t pendingLogicalHeight = 0;
// The states of that configure, batched like its size:
// ApplyToplevelState makes them the window's at the
// xdg_surface.configure that ends the batch and fires
// onToplevelState when that changed one, as the handler's last
// step: it does nothing with the window after its listeners.
bool pendingActivated = false;
bool pendingSuspended = false;
void ApplyToplevelState();
xdg_toplevel* xdgToplevel = nullptr; xdg_toplevel* xdgToplevel = nullptr;
zxdg_toplevel_decoration_v1* decoration = nullptr; zxdg_toplevel_decoration_v1* decoration = nullptr;
wp_viewport* wpViewport = nullptr; wp_viewport* wpViewport = nullptr;
@ -340,10 +368,18 @@ export namespace Crafter {
static void xdg_toplevel_handle_close(void* data, xdg_toplevel*); static void xdg_toplevel_handle_close(void* data, xdg_toplevel*);
static void xdg_surface_handle_configure(void* data, xdg_surface* xdg_surface, std::uint32_t serial); static void xdg_surface_handle_configure(void* data, xdg_surface* xdg_surface, std::uint32_t serial);
static void xdg_toplevel_configure(void*, xdg_toplevel*, std::int32_t, std::int32_t, wl_array*); static void xdg_toplevel_configure(void*, xdg_toplevel*, std::int32_t, std::int32_t, wl_array*);
static void xdg_toplevel_configure_bounds(void*, xdg_toplevel*, std::int32_t, std::int32_t);
static void xdg_toplevel_wm_capabilities(void*, xdg_toplevel*, wl_array*);
constexpr static xdg_toplevel_listener xdg_toplevel_listener = { constexpr static xdg_toplevel_listener xdg_toplevel_listener = {
.configure = xdg_toplevel_configure, .configure = xdg_toplevel_configure,
.close = xdg_toplevel_handle_close, .close = xdg_toplevel_handle_close,
// Events of versions 4 and 5 of xdg_wm_base, which the bind for
// `suspended` brings with it. The window has no use for either,
// but libwayland aborts the client at an event whose handler is
// null.
.configure_bounds = xdg_toplevel_configure_bounds,
.wm_capabilities = xdg_toplevel_wm_capabilities,
}; };
constexpr static wl_callback_listener wl_callback_listener = { constexpr static wl_callback_listener wl_callback_listener = {
.done = wl_surface_frame_done, .done = wl_surface_frame_done,

View file

@ -463,6 +463,15 @@ extern "C" Configuration CrafterBuildProject(std::span<const std::string_view> a
// empty title, not a null string. No compositor. // empty title, not a null string. No compositor.
cfg.tests.push_back(LibraryTest("TitleWayland")); cfg.tests.push_back(LibraryTest("TitleWayland"));
// Window::activated and Window::suspended from xdg_toplevel's
// states, applied at the xdg_surface.configure that ends their
// batch; the version xdg_wm_base is bound at (the offer's, up
// to 6); a handler in the xdg_wm_base, xdg_surface and
// xdg_toplevel listeners for every event of the bundled
// protocol. Feeds the configure callbacks of a window whose
// surfaces are proxies on a socketpair display. No compositor.
cfg.tests.push_back(LibraryTest("ToplevelState"));
// Issue #40: multi-frame-in-flight frame pacing (per-frame fences // Issue #40: multi-frame-in-flight frame pacing (per-frame fences
// and acquire semaphores, per-image render-finished semaphores, no // and acquire semaphores, per-image render-finished semaphores, no
// steady-state wait-idle). Drives the // steady-state wait-idle). Drives the

View file

@ -0,0 +1,234 @@
//SPDX-License-Identifier: LGPL-3.0-only
//SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
// Window::activated and Window::suspended on the Wayland backend: the two
// xdg_toplevel states a consumer needs to tell whether the user is looking
// at its window. The compositor names the states that are set in each
// xdg_toplevel.configure and ends the batch with an xdg_surface.configure;
// the window dropped the array, so a consumer took a window behind a lock
// screen or another window for one that was seen (a messenger marks a text
// read there and never notifies of it).
//
// The surfaces are proxies on a wl_display connected to one end of a
// socketpair, as in TitleWayland, and the test calls the listener callbacks
// itself, so no compositor is needed. Asserts:
//
// - the states of a configure are pending until the xdg_surface.configure
// that ends its batch, and the last xdg_toplevel.configure of a batch is
// the one applied
// - onToplevelState finds both values set, and fires once for a batch
// that changes both
// - a batch that repeats the states, or changes other ones only
// (maximized, resizing, tiled), fires nothing
// - a state the array leaves out is not set
// - xdg_wm_base is bound at the version the compositor offers, up to 6
// (where `suspended` is) and never above the offer: a bind above it is
// a protocol error that ends the connection, so on a compositor with an
// older xdg_wm_base no window would open at all
// - the listeners of xdg_wm_base and of the xdg_surface and xdg_toplevel
// made from it have a handler for every event of the bundled protocol:
// the higher version brings xdg_toplevel's configure_bounds (4) and
// wm_capabilities (5), and libwayland aborts a client at an event whose
// handler is null
#include <wayland-client.h>
#include <sys/socket.h>
#include <unistd.h>
#include <cerrno>
#include <cstdlib>
#include <cstring>
#include "../../lib/xdg-shell-client-protocol.h"
import Crafter.Graphics;
import Crafter.Event;
import std;
using namespace Crafter;
namespace {
int failures = 0;
void Check(bool ok, std::string_view what) {
std::println("{} {}", ok ? "PASS" : "FAIL", what);
if (!ok) ++failures;
}
// What the display has written so far.
std::vector<std::uint8_t> Sent(wl_display* display, int peer) {
wl_display_flush(display);
std::vector<std::uint8_t> wire;
std::uint8_t chunk[4096];
for (ssize_t n; (n = recv(peer, chunk, sizeof(chunk), MSG_DONTWAIT)) > 0;) {
wire.insert(wire.end(), chunk, chunk + n);
}
return wire;
}
// The versions of the wl_registry.bind requests for `interface` in `wire`. A
// request is its object id, then its size and opcode in one word, then its
// arguments; bind's are the global's name, the interface as a string (its
// length with the NUL, then its bytes padded to a word), the version and
// the new object's id.
std::vector<std::uint32_t> BoundVersions(const std::vector<std::uint8_t>& wire, std::uint32_t registry, std::string_view interface) {
std::vector<std::uint32_t> versions;
for (std::size_t at = 0; at + 8 <= wire.size();) {
std::uint32_t header[2];
std::memcpy(header, wire.data() + at, sizeof(header));
const std::uint32_t size = header[1] >> 16;
if (size < 8 || at + size > wire.size()) break;
if (header[0] == registry && (header[1] & 0xFFFF) == WL_REGISTRY_BIND && size >= 16) {
std::uint32_t length;
std::memcpy(&length, wire.data() + at + 12, sizeof(length));
const std::size_t padded = (static_cast<std::size_t>(length) + 3) & ~static_cast<std::size_t>(3);
if (length > 0 && 16 + padded + 8 <= size
&& std::string_view(reinterpret_cast<const char*>(wire.data() + at + 16), length - 1) == interface) {
std::uint32_t version;
std::memcpy(&version, wire.data() + at + 16 + padded, sizeof(version));
versions.push_back(version);
}
}
at += size;
}
return versions;
}
// The compositor's two events of one batch: the toplevel's configure with
// the states that are set, then the surface's.
void Toplevel(Window& window, std::initializer_list<std::uint32_t> states) {
wl_array array;
wl_array_init(&array);
for (std::uint32_t state : states) {
*static_cast<std::uint32_t*>(wl_array_add(&array, sizeof(state))) = state;
}
Window::xdg_toplevel_configure(&window, window.xdgToplevel, 0, 0, &array);
wl_array_release(&array);
}
std::uint32_t serial = 0;
void Batch(Window& window, std::initializer_list<std::uint32_t> states) {
Toplevel(window, states);
Window::xdg_surface_handle_configure(&window, window.xdgSurface, ++serial);
}
// Whether `listener` has a handler for every event of `interface`. A
// listener is one function pointer per event, in the protocol's order.
template <class Listener>
bool HandlesEveryEvent(const Listener& listener, const wl_interface& interface) {
void (*handler)(void);
if (sizeof(Listener) != static_cast<std::size_t>(interface.event_count) * sizeof(handler)) return false;
const unsigned char* at = reinterpret_cast<const unsigned char*>(&listener);
for (int i = 0; i < interface.event_count; ++i, at += sizeof(handler)) {
std::memcpy(&handler, at, sizeof(handler));
if (handler == nullptr) return false;
}
return true;
}
// The window's two states, as a listener or the test found them.
struct Seen {
bool activated;
bool suspended;
bool operator==(const Seen&) const = default;
};
} // namespace
int main() {
int fds[2];
if (socketpair(AF_UNIX, SOCK_STREAM | SOCK_CLOEXEC, 0, fds) != 0) {
std::println("FAIL socketpair: {}", std::strerror(errno));
return EXIT_FAILURE;
}
// The display owns fds[0] from here.
wl_display* display = wl_display_connect_to_fd(fds[0]);
if (display == nullptr) {
std::println("FAIL wl_display_connect_to_fd: {}", std::strerror(errno));
return EXIT_FAILURE;
}
// libwayland makes whatever proxy it is asked to bind; nothing answers.
wl_registry* registry = wl_display_get_registry(display);
const std::uint32_t registryId = wl_proxy_get_id(reinterpret_cast<wl_proxy*>(registry));
{
// A default-constructed window, which ~Window can tear down without
// a device, holding proxies as its surfaces: the surface's configure
// acknowledges on the xdg_surface and, once the window is
// configured, commits the wl_surface.
Window window;
window.surface = static_cast<wl_surface*>(wl_registry_bind(registry, 1, &wl_surface_interface, 1));
window.xdgSurface = static_cast<xdg_surface*>(wl_registry_bind(registry, 2, &xdg_surface_interface, 1));
window.xdgToplevel = static_cast<xdg_toplevel*>(wl_registry_bind(registry, 3, &xdg_toplevel_interface, 1));
std::vector<Seen> seen;
EventListener<void> sub(&window.onToplevelState, [&] { seen.push_back({ window.activated, window.suspended }); });
const auto now = [&] { return Seen{ window.activated, window.suspended }; };
Check(now() == Seen{ false, false }, "a new window is neither activated nor suspended");
Toplevel(window, { XDG_TOPLEVEL_STATE_ACTIVATED });
Check(now() == Seen{ false, false } && seen.empty(), "a toplevel configure alone changes nothing: its states are pending");
Window::xdg_surface_handle_configure(&window, window.xdgSurface, ++serial);
Check(seen == std::vector<Seen>{ { true, false } }, "the surface configure applies them: activated, set before onToplevelState fires");
seen.clear();
Batch(window, { XDG_TOPLEVEL_STATE_ACTIVATED });
Batch(window, { XDG_TOPLEVEL_STATE_MAXIMIZED, XDG_TOPLEVEL_STATE_ACTIVATED, XDG_TOPLEVEL_STATE_RESIZING, XDG_TOPLEVEL_STATE_TILED_LEFT });
Check(seen.empty() && now() == Seen{ true, false }, "the same states again, and other states changing, fire nothing");
Batch(window, { XDG_TOPLEVEL_STATE_SUSPENDED });
Check(seen == std::vector<Seen>{ { false, true } }, "suspended in, activated left out: both changed, one event");
seen.clear();
Batch(window, { XDG_TOPLEVEL_STATE_SUSPENDED, XDG_TOPLEVEL_STATE_ACTIVATED });
Check(seen == std::vector<Seen>{ { true, true } }, "the two are independent: a window can be both");
seen.clear();
Batch(window, {});
Check(seen == std::vector<Seen>{ { false, false } }, "an empty array clears both");
seen.clear();
Toplevel(window, { XDG_TOPLEVEL_STATE_SUSPENDED });
Toplevel(window, { XDG_TOPLEVEL_STATE_ACTIVATED });
Window::xdg_surface_handle_configure(&window, window.xdgSurface, ++serial);
Check(seen == std::vector<Seen>{ { true, false } }, "two toplevel configures in one batch: the last one is applied");
Sent(display, fds[1]);
// ~Window destroys the three proxies.
}
// The bind. handle_global keeps the proxy in Device::xdgWmBase; each is
// destroyed here before the next.
std::vector<std::uint32_t> bound;
for (std::uint32_t offered : { 7u, 6u, 5u, 1u }) {
Device::handle_global(nullptr, registry, 4, xdg_wm_base_interface.name, offered);
for (std::uint32_t version : BoundVersions(Sent(display, fds[1]), registryId, xdg_wm_base_interface.name)) bound.push_back(version);
if (Device::xdgWmBase != nullptr) xdg_wm_base_destroy(Device::xdgWmBase);
Device::xdgWmBase = nullptr;
}
Check(bound == std::vector<std::uint32_t>{ 6, 6, 5, 1 }, "xdg_wm_base offered at 7, 6, 5 and 1 is bound at 6, 6, 5 and 1");
if (bound != std::vector<std::uint32_t>{ 6, 6, 5, 1 }) {
for (std::uint32_t version : bound) std::println(" bound at {}", version);
}
// What the bind brings must find a handler.
Check(HandlesEveryEvent(Device::xdgWmBaseListener, xdg_wm_base_interface)
&& HandlesEveryEvent(Window::xdg_surface_listener, xdg_surface_interface)
&& HandlesEveryEvent(Window::xdg_toplevel_listener, xdg_toplevel_interface),
"the listeners of xdg_wm_base, xdg_surface and xdg_toplevel handle every event of the bundled protocol");
const int error = wl_display_get_error(display);
Check(error == 0, "the display took every request");
if (error != 0) std::println(" the display failed: {}", std::strerror(error));
wl_registry_destroy(registry);
wl_display_disconnect(display);
close(fds[1]);
if (failures != 0) {
std::println("{} check(s) failed", failures);
return EXIT_FAILURE;
}
std::println("all checks passed");
return EXIT_SUCCESS;
}