fix(wayland): the surface takes a new size with the first frame drawn at it, and a configure's rebuild waits for Render

At a resize RebuildSwapchain sent wp_viewport.set_destination for the
new size at once, and the configure listener, which had called it,
acknowledged the configure and committed the surface. The destination
is the surface's size, and it is state the next wl_surface.commit
applies whatever buffer is attached then. That commit was the
listener's, or the one a consumer makes to ask for a frame callback,
and it put the old frame at the new size, where it stayed until the
consumer's next frame brought a buffer of that size (#199). The
acknowledgement named that commit as the answer to the configure. And
the rebuild ran inside libwayland's dispatch: the consumer's loop stood
still in it, each new size before a frame cost a swapchain, and a
Vulkan error there was thrown from inside the dispatch, where the `try`
a consumer has around Update() does not cover it (#200).

Window: the configure listener keeps a new size (deferredLogicalWidth
and Height, surface-local) and, where a frame is owed, the serial
(unackedConfigure), and makes no Vulkan call. Render() takes what waits
at its two boundaries (RebuildIfDeferred) and makes the swapchain again
where that calls for one: first thing, for what came since the last
frame, and after its present, as before, for what its listeners and the
present asked for, and now for a size configured while they ran. Right
before its present a frame sends what the surface is to take with its
buffer (SendFrameSurfaceState): the destination, when the surface's
size is not the one last sent (sentLogicalWidth and Height), and the
acknowledgement of the configure it answers, the last one when several
came. The present's commit then applies them together with the buffer.
The constructor sends no destination: the window's first frame does.

The surface's size is state of the window for that, beside the buffers'
(logicalWidth and Height; logicalConfigured says which of the two sizes
the window was given). TakeDeferredSize makes a configured size the
surface's, unchanged, and works the pixels out of it with the scale of
that moment. MatchSizesToScale does the same before every swapchain is
made, and for a window the application sized (the constructor's size,
Resize) works the surface's size out of the pixels, which is what
RebuildSwapchain and the constructor did when they sent the
destination. The destination is that state as it is and not ceil(width
/ scale) at the present, because the scale is the compositor's to
change in any dispatch: between a configure and the frame that takes
it, and in the middle of a frame, when a listener reads the clipboard
or makes a window. And a size and a scale that change together can come
to the pixels the swapchain has: then no swapchain is made, and the
frame still brings the surface its size with the acknowledgement.

With that the destination of a configured size is the size itself,
where it was worked back from the pixels and could come out larger
(392x796 at 2.85 came back as 393x797), and a configure at the size the
surface has leaves a window the compositor sized alone while the scale
stays what it was, where it could make the window grow again (#201). A
window the application sized, configured at the size its surface has,
takes the pixels for that size once where its own do not come to it
(320x240 at 1.75, shown at 183x138, becomes 321x242), and is then left
alone in the same way. That much of #201 comes with this change, since
the state it asks for is the one this needs. The buffers' size is still
rounded up, where the protocol rounds half away from zero: the rest of
#201.

A swapchain RebuildSwapchain made for another reason after the scale
changed (a present mode, a present that found the swapchain out of
date) applied the new scale by working the destination out again from
the pixels. It still does for a window the application sized. A window
the compositor sized keeps the surface's size and takes the pixels for
it. The acquire's OUT_OF_DATE path repeated four of RebuildSwapchain's
lines and sent no destination: it calls RebuildSwapchain now, and so
settles the two sizes as the other rebuilds do.

Of a Resize and a configured size the one asked for last is taken, as
when the listener resized on the spot: a configure with a size clears a
Resize that waits for its frame's present, also when its size is the
one the window has, and Resize clears a configured size that waits.

A configure that asks for nothing new while nothing is owed is
acknowledged in the listener, as before. One that comes while a size
waits, or while the surface does not show the window as it is (a
swapchain still to be made, one that has presented no frame yet, a size
not sent yet), waits for that frame. One for the size the window has,
when nothing else is owed, is acknowledged at once and takes the wait
away with it, as an acknowledgement of a serial older than the last is
a protocol error. A frame being recorded when a size comes does not
acknowledge it while that size waits; when a Resize later in the frame
takes the size's place, that frame does. The listener still commits,
which applies whatever else is pending on the surface, such as a
request for a frame callback that StartUpdate made after a frame.

For consumers: onResize for a compositor's resize fires from inside
Render(), before the onUpdate of the frame that brings the size, with
the queue idle and no frame being recorded, as Resize fires it; until
that frame the window keeps its old size on screen. A window that draws
on demand took onResize as its cue to ask for a frame, and gets
onFrameOwed for it: the Wayland backend's alone, fired from the
configure after onToplevelState, and only for a window that is still
there after that event's listeners, whenever the configure leaves a
frame owed. A size the surface does not have yet that comes to the
pixels the window has (the scale changed with it) fires onFrameOwed and
no onResize. Resize and SetPresentMode outside a frame rebuild at once
as they did, and there too the surface takes the new size with the next
frame. A rebuild that throws stays pending, since RebuildSwapchain
clears swapchainRebuildPending only once the swapchain is made, and the
next Render() tries it again. The README, the consumer notes and the
guide's gotchas say so, and the bug-prover lens section lists the
pending surface state and the scale among the re-entry contexts.

Examples: InputSystem and the native mains of VulkanTriangle, RTVolume
and Sponza drew one frame and then only ran the event loop, so nothing
would have answered a compositor's resize of their windows. They call
StartUpdate after that frame, as the examples that draw every frame do.

Not changed: a scale that changes by itself still reaches the buffers
and the surface only with the next swapchain or the next configured
size (#165); the first configure's size (#166); and Win32's WM_SIZE,
which still rebuilds from the window procedure. A window under
StartUpdate on the compositor's clock still draws from its frame
callback, so for it the rebuild, like every frame's Vulkan call, stays
inside libwayland's dispatch; one on its own clock is updated by
StartSync's loop after the dispatch, as before. #200 is answered for a
consumer that calls Update() itself. A present that fails after
SendFrameSurfaceState leaves what that sent pending for the surface's
next commit, whoever makes it.

Tests: ConfigureResize feeds the configure callbacks of a window whose
surfaces are proxies on a wl_display over a socketpair, as
ToplevelState does, with a made-up swapchain handle and no device,
steps the two ends of a frame, and reads the requests off the wire: a
configure for a new size sends one bare commit; the frame sends the
destination and the acknowledgement before its present, once; several
configures before a frame cost one of each, of the last serial; a
configure for nothing new, or back to the window's size, is
acknowledged in the listener, and the serial that waited never is; a
frame being recorded when a size comes does not acknowledge it while
the size waits, and does once a Resize has taken its place; the
window's first frame and the first at any new size of the surface bring
the destination, and a configure before it waits, and so does one for
the size a rebuild that threw is still pending for, and one that comes
after a present that found the swapchain out of date, whose surface
state is not sent a second time; without a viewport the acknowledgement
still waits. The destination is the configured size when the scale
changes before the frame, when it changes between the frame's start and
its present, and when the size and the scale together come to the
swapchain's pixels, in either order of the two events, which makes no
swapchain; with the numbers of #201's trace, 392x796 at 2.85, it is
that size, and three more configures at it change nothing. A swapchain
made after the scale changed keeps a configured window's surface size
and an application-sized window's pixels. Of a Resize and a configured
size the later one is taken, also when it is the size the window has.
onFrameOwed fires after onToplevelState and not for a window its
listener destroyed; every acknowledgement names a later serial than the
one before.

ResizeViewport runs a window against the compositor with WAYLAND_DEBUG
set and stderr in a file, and replays the log, which has the driver's
attach and commit too: at every commit the destination in effect
belongs to the buffer in effect, to within a surface-local pixel, and
every acknowledgement of a configure that asked for a size, once the
surface has a buffer, is committed with a buffer of that size in effect
and with that size itself as the destination, through a Resize with a
commit before the next frame, a size the compositor configures (the
window asks to be maximized), and one it configures while the frame
loop of StartUpdate runs (the window asks to be restored), which that
loop takes and answers by itself. Where the compositor configures no
other size at that request, the step is a SKIP, and the test holds the
log to it: no configure for another size came. `ResizeViewport
--keyboard` is the manual probe for a phone: it asks for text input and
takes it back three times (SetTextInput), which is what brings a
phone's on-screen keyboard up and down, and holds the resizes that
makes to the same checks.
This commit is contained in:
Jorijn van der Graaf 2026-11-19 04:47:00 +01:00
commit 89111e0d65
Signed by: jorijnvdgraaf
GPG key ID: 2937E59CDCC1BCFB
14 changed files with 2059 additions and 71 deletions

View file

@ -27,8 +27,15 @@ The execution contexts to enumerate, beside the charter's:
queue (freed `framesInFlight` frames later) or after a wait for the GPU;
a freed descriptor slot is handed out again at once; a swapchain rebuild
asked for from a listener mid-frame (`Resize`, `SetPresentMode`) waits
for that frame's present, and `onResize` runs after it; a static owner
is destroyed after the driver is gone. Within one dispatch, Vulkan
for that frame's present, and `onResize` runs after it; on Wayland a
size the compositor configures, once the window has a swapchain, waits
for a frame boundary of `Render()`: the start of the next one, before
its fence wait and acquire, or the end of the one whose listeners
dispatched it, after its present. The swapchain is made again there,
and `onResize` fires, only where the size changes the pixels, which a
size and a scale that change together need not; a rebuild that threw
waits for the next `Render()`; a static owner is destroyed after
the driver is gone. Within one dispatch, Vulkan
orders nothing between workgroups.
- Re-entry from the platform. The Wayland listeners run inside
`wl_display_dispatch`, `wl_display_dispatch_pending` and
@ -37,7 +44,15 @@ The execution contexts to enumerate, beside the charter's:
window procedure from the message loop and also synchronously from
inside `CreateWindowEx`, `SendMessage` and `DefWindowProc`. The DOM's
listeners in `dom-env.js` call the `__crafterDom_*` exports. A listener
can resize, close or destroy the window it was called for.
can resize, close or destroy the window it was called for. What a
Wayland surface takes with a buffer (the viewport's destination, a
configure's acknowledgement) is pending until the next
`wl_surface.commit`, whoever makes it: the configure listener, a
consumer asking for a frame callback, the driver inside
`vkQueuePresentKHR`, which may commit more than once per present. The
compositor's preferred scale (`Window::scale`) changes in any dispatch:
between a configure and the frame that takes its size, and in the
middle of a frame.
Windows.Gaming.Input reports gamepad connects and disconnects on threads
of its own, queued under a lock until the event loop takes them.
- Shared state: `Device`'s statics are process-wide; `Device::frameCounter`

View file

@ -31,6 +31,7 @@ window.StartSync(); // the event loop
- Include `vulkan/vulkan.h` yourself, before the imports (the examples wrap it in `#ifndef CRAFTER_GRAPHICS_WINDOW_DOM`): the library includes it only in its own global module fragments, and neither Vulkan's types nor its macros (`VK_TRUE`, the `VK_*` flags) cross an `import`. On the DOM build `Device::Initialize()` takes no arguments and `DeviceFeatures` does not exist, which is why the dual-target examples keep a separate DOM `main`.
- `StartSync` runs the platform loop until `open` is false (`onClose` fires first). Each pass of the loop dispatches platform events into the `Window` events, runs `Gamepad::Tick()` and `onBeforeUpdate`, and runs `Update()` for a window that is due. On Wayland a window on the compositor's clock updates from its frame callback during that event dispatch, before the pass's `onBeforeUpdate`, and the loop wakes for every event, so `onBeforeUpdate` fires several times per frame; on Win32 and in the browser `onBeforeUpdate` precedes the same pass's `Update`. `updateInterval`, set before `StartUpdate`, makes a window update every so often whether visible or not; pair it with `SetPresentMode(PresentMode::Mailbox)` so a present never waits for the display. `AddPollFd(fd, callback)` (Wayland) wakes the loop for a socket or an eventfd.
- `Update()` computes `mouseDelta` and calls `Render()`, which waits for the fence of its frame slot (three frames in flight, `Window::numFrames`; the slot is `window.currentFrame`), acquires a swapchain image (`window.currentImage`; the swapchain has as many images as its present mode needs, not necessarily three), writes it into this window's swapchain slots of the heap, reclaims deferred deletions, begins `drawCmdBuffers[currentFrame]`, binds the heap (or the descriptor set), fires `onUpdate(FrameTime)`, records every pass in `passes` in order with a barrier on the swapchain image between them, transitions the image to present, submits and presents. Per-frame GPU work of your own (a TLAS rebuild, a physics dispatch) is recorded from `onUpdate` into `window.drawCmdBuffers[window.currentFrame]`; the heaps are bound by then and the passes come after. A `Resize` or `SetPresentMode` from a listener of the frame (an input action ticked in `onUpdate`, say) takes effect after its present. `onResize` fires after a swapchain rebuild (a new size or present mode); the swapchain slots follow by themselves, and anything else that holds the old images or is sized after the window is made again there.
- On Wayland the compositor resizes a window with a configure (a maximize, a tile, a drag of its border, a phone's on-screen keyboard coming or going), and the window answers it with a frame, not in the configure's listener, which only keeps the size. The next `Render()` starts by making the swapchain again at it and firing `onResize`, before the frame's `onUpdate`, with the queue idle and no frame being recorded, as `Resize` fires it; and the frame it then presents brings, with the present's commit, the first buffer of the new size together with the surface's new size and the configure's acknowledgement. (A size configured while a frame is being recorded is taken at the end of that `Render()`, after its present, and the frame after it brings it.) So `onResize` for such a resize comes from inside `Render()`: for a consumer that calls `Update()` itself, a `try` around it covers the rebuild's Vulkan calls, while a window under `StartUpdate` draws where its frames always do: from its frame callback, inside the event dispatch, when it is on the compositor's clock, and from `StartSync`'s loop, after the dispatch, when it is on its own (`updateInterval`). Until that frame's present the window keeps its old size on screen, and then changes size with the buffer drawn for the new one, where it used to change at the configure and show the last frame scaled until the next. The exception is a present that fails: what the frame sent ahead of it stays pending for the surface's next commit. A window that updates from `StartUpdate` needs nothing: its next `Update()`, from the frame callback or from its clock, is that frame. On the compositor's clock that counts on the frame callbacks going on while a configure waits for its answer, as KWin's do. A window that draws on demand (it calls `Update()` itself when something changed) must ask for a frame when `onFrameOwed` fires, as it does from `onResize`: `onFrameOwed` (Wayland only, `Event<void>`) fires from the configure, after `onToplevelState`, whenever the configure leaves a frame owed, and nothing has been rebuilt by then. The listener marks the window as wanting a frame and lets its loop draw it; it does not call `Update()` itself, because the event fires wherever the events are dispatched, and that may be inside a frame being recorded (a listener of that frame made a `Window` or called `Clipboard::GetText`), which `onResize` never is. Without that frame the configure is never answered and the window never takes the new size. A window that has stopped updating (`StopUpdate`) is in the same position. `Resize` and `SetPresentMode` called outside a frame still rebuild at once and fire `onResize` from the call; the surface takes the new size with the next frame there too. A rebuild that throws is tried again by the next `Render()`. A Wayland window has two sizes: `width` and `height`, the pixels of its buffers, and `logicalWidth` and `logicalHeight`, the surface's size in surface-local units, which is what a configure gives and what the compositor lays the window out by; `scale` is the compositor's preferred scale (1 where it has no `wp_fractional_scale_v1` or no `wp_viewporter`), and the two sizes are worked out from one another with it only when a size is taken and when a swapchain is made, so between those moments `scale` may be newer than they are. A size the compositor configured is the surface's size unchanged, with `width` and `height` the pixels it came to then, rounded up (the size in the first configure, the one the constructor waits for, is the exception: it is not taken, #166); a size the application gave (the constructor's, `Resize`) is in pixels, and the surface's size is what they came to. Of a `Resize` and a configured size the one asked for last is taken. Where a configured size comes to the pixels the window has (an output's scale changed under a window that fills it), the frame brings the surface its new size, nothing is rebuilt and `onResize` does not fire; `onFrameOwed` does. A scale that changes by itself is not acted on until the next swapchain or configured size (#165).
- A `RenderPass` is `Record(cmd, frameIdx, window)` plus `SwapchainStage()`, which must return the stage that touches the swapchain image (`COMPUTE_SHADER`, `RAY_TRACING_SHADER` or `TRANSFER`): the frame's barriers take their stage and access masks from it. `frameIdx` is the frame slot, `window.currentFrame`, not the image: the frame's image is `window.images[window.currentImage]`. The image stays in `VK_IMAGE_LAYOUT_GENERAL` through the whole pass list, with `STORAGE | TRANSFER_SRC` usage and `TRANSFER_DST` where the surface allows it (`window.swapchainUsage`). Nothing clears it: draw a background quad, or clear from a transfer pass where `TRANSFER_DST` is there.
- `window.width` and `height` are physical pixels, as is `currentMousePos`. `CaptureNextFrame(path)` saves the next frame as a PNG. `SetTitle`, `SetAppId`, `SetCursorImage`, `SetDefaultCursor`; `SetTextInput(active, x, y, w, h, purpose)` tells the compositor's input method a text field has focus, which opens an on-screen keyboard on a phone.
- Several windows can exist (on Wayland `Device::windows` lists them; the other backends keep no list), and may share a heap, each writing only its own swapchain slots, but they share one frame clock: one rendering window is the assumption behind the deletion queue, the staging rings and the font atlas's evictions. Without a `Window`, nothing advances `Device::frameCounter`: a program that draws text without one steps it itself after each frame's work, or its full atlas never frees a cell and new glyphs stay blank.
@ -128,7 +129,7 @@ Heap-only: check `Device::rayTracingSupported`, or expect `std::runtime_error` f
### 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. 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.
- `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. `onFrameOwed`, Wayland's too, is the cue of a resize for a window that draws on demand: see "A program, and what the loop does".
- 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.
- `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,9 +72,9 @@ 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:
- 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.
- 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. `ConfigureResize` does the same for a configure's size: with a made-up swapchain handle it steps the two ends of a frame (`TakeDeferredSize` and `MatchSizesToScale`, `SendFrameSurfaceState`) and reads which commit gets the viewport's destination and the acknowledgement, and what the destination is when the scale changes in between.
- 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), `ResizeViewport` (a `Resize` and a configured size, got by maximizing its window for a moment, against the connection itself: it runs with `WAYLAND_DEBUG` set and stderr in a file and replays the log, which has the driver's attach and commit too), and `FeatureRequests` for its retry case. `UIFallbackParity`, `SwapchainTransferDst`, `HeapASRead`, `HeapDynamicIndexHit`, `RTPassPushData` and `TextAntialiasing` read the frame back with `Window::CaptureNextFrame` (a PNG, decoded with a private `STB_IMAGE_STATIC` copy of stb_image), `SwapchainImageCount` with a transfer pass of its own, and check pixels. The others read no frame back: they check what the frame loop, the device and the window report (their counts and members, the validation layer's count, the connection's protocol errors), and `ResizeViewport` the connection's log.
Conventions the existing tests follow:
@ -146,6 +146,7 @@ These were decided deliberately. Do not undo them without the maintainer's say-s
- Buffer slot indices: `AllocateBufferSlots` returns an index relative to the heap's buffer region, while GLSL `descriptor_heap` SSBO arrays index in buffer-descriptor units from heap byte 0. `BufferSlot` converts to `bufferStartElement + raw`; raw code (the RT examples) passes `heap.bufferStartElement` as a `uint16_t` spec constant, which needs `shaderInt16`. In descriptor-set mode `bufferStartElement` is 0. Image and sampler slots are used as they are. A wrong index reads zeros, which looks like "every item field is zero".
- `UIRenderer::RegisterBuffer` refuses a buffer created without `VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT`. Freed slots are handed out again at once, so a slot may only be freed when no frame in flight reads it (after `vkQueueWaitIdle`, or at a scene switch). In descriptor-set mode a slot write destroys the previous view immediately.
- The swapchain image stays in `VK_IMAGE_LAYOUT_GENERAL` across the pass list and is never cleared; `Window::clearColor` is unused. `swapchainUsage` says whether `TRANSFER_DST` was available. `onResize` fires after a swapchain rebuild; slots listed with `AddSwapchainSlot` follow by themselves, and anything else holding the old images is made again there. A rebuild asked for during a frame (`Resize` or `SetPresentMode` from a listener) waits for that frame's present, since the rest of the frame indexes the swapchain it acquired from. `RenderPass::Record`'s `frameIdx` is the frame slot, not the image.
- On Wayland the configure listener only keeps a size (`deferredLogicalWidth`) and a serial (`unackedConfigure`): `Render()` rebuilds at its boundaries (`RebuildIfDeferred`), so a compositor's resize, where it changes the pixels, fires `onResize` from inside it, and a rebuild that throws stays pending for the next one. The window has two sizes, `width` x `height` (the buffers' pixels) and `logicalWidth` x `logicalHeight` (the surface's size: a configured size unchanged, `logicalConfigured`, or what the application's pixels come to), and `scale` ties them only where one is worked out from the other: when a configured size is taken and before every swapchain (`MatchSizesToScale`). Nothing works the surface's size back from `width / scale` at another moment: the scale changes in any dispatch, in the middle of a frame too (a listener that dispatches events), and for a configured size the two roundings land above it wherever the size times the scale is not a whole number (#201: 392x796 at 2.85 came back as 393x797). Of a `Resize` and a configured size the one asked for last waits, each clearing the other's. What the surface takes with a buffer goes out in `SendFrameSurfaceState`, right before the present: the viewport's destination when the surface's size is not the one last sent (`sentLogicalWidth`), which is sent nowhere else, and the acknowledgement of a configure that waits for a frame (one that asks for nothing new while nothing is owed is acknowledged in the listener). Both are state the next `wl_surface.commit` applies, and commits that are no frame's happen all the time: the listener's own, a consumer's request for a frame callback, and the second commit the NVIDIA driver makes in a FIFO present where the compositor has `wp_fifo_v1` (seen on `615.78.08` under KWin 6.8.0). So a destination sent at the rebuild is applied to the old buffer, which is then shown scaled (#199), and an acknowledgement sent in the listener for a new size names that frame as the answer. A change that touches the surface's size (the scale of #165, the buffers' rounding of #201) keeps to that. The cue for a window that draws on demand is `onFrameOwed`.
- `Device::frameCounter` is one clock for every window, so the deletion queue and the staging rings assume one rendering window. The font atlas evicts on it too, on both backends: without a `Window` advancing it nothing is ever evicted, and a full atlas leaves new glyphs blank, so a headless test steps it itself (`FontAtlasEviction`).
- `ImageVulkan::Create`'s default `consumerStage` is the RT stage, corrected to compute on a device without ray tracing; the font atlas passes compute explicitly. `VulkanTransition`'s `GENERAL` mapping does the same.
- `UIRenderer::ShapeText` and `FontAtlas` key their caches on the `Font*`: call `UIRenderer::InvalidateFont`, which clears both, before destroying a `Font`, or a new one at the same address aliases stale runs and glyphs. The atlas also keeps the `Font*` of a glyph waiting for a cell until the next frame's first call, where it rasterises from it.

View file

@ -106,7 +106,24 @@ shaded through an intersection shader with an any-hit cut-out.
window rewrites with the acquired image every frame, so nothing is
rewritten after a resize, and two windows can share a heap. A `Resize`
or `SetPresentMode` from a listener of the frame being recorded takes
effect after that frame's present.
effect after that frame's present. On Wayland a size the compositor
configures, once the window is made, is taken at a frame boundary of
`Render()`, as a rule the start of the next one. Where it changes the
pixels, the swapchain is made again there and `onResize` fires, and
the frame presented after it brings, with the present's commit, its
buffer together with the surface's new size (the viewport's
destination) and the configure's acknowledgement. The surface so
changes size with the first buffer drawn for the new one, where it
used to change at the configure and show the last frame scaled until
the next (#199); only a present that fails leaves that state for the
surface's next commit. And a Vulkan error at the resize comes out of
`Render()`. The surface's size is the configured one, unchanged
(`window.logicalWidth`, `logicalHeight`, in surface-local units);
`width` and `height` are the pixels it came to when it was taken or a
swapchain was last made, at the scale of that moment, and
`window.scale` may be a newer one (#165). A window that draws on
demand learns of the resize from `onFrameOwed`, which fires at the
configure.
- **Device** *(Vulkan only)* — single-instance bring-up targeting
`VK_EXT_descriptor_heap`; pipelines are created with
`VK_PIPELINE_CREATE_2_DESCRIPTOR_HEAP_BIT_EXT` so there are no

View file

@ -237,6 +237,9 @@ int main() {
std::println("─── Ready. Focus the window and try the controls. ───");
window.Render();
// The window draws nothing, but its frames keep coming: on Wayland a
// frame is what answers the compositor when it resizes the window.
window.StartUpdate();
window.StartSync();
std::println("Done.");

View file

@ -205,6 +205,10 @@ int main() {
window.passes.push_back(&rtPass);
window.Render();
// The scene is still, but its frames keep coming: a frame is what shows
// it at a new size, and on Wayland what answers the compositor when it
// resizes the window.
window.StartUpdate();
window.StartSync();
return 0;
}

View file

@ -259,6 +259,10 @@ int main() {
window.passes.push_back(&rtPass);
window.Render();
// The scene is still, but its frames keep coming: a frame is what shows
// it at a new size, and on Wayland what answers the compositor when it
// resizes the window.
window.StartUpdate();
window.StartSync();
return 0;
}

View file

@ -174,6 +174,10 @@ int main() {
// as push data. Nothing here (or in raygen.glsl) changes. See README.md
// ("Native status") and interfaces/Crafter.Graphics-ShaderVulkan.cppm.
window.Render();
// The scene is still, but its frames keep coming: a frame is what shows
// it at a new size, and on Wayland what answers the compositor when it
// resizes the window.
window.StartUpdate();
window.StartSync();
}
#else

View file

@ -383,7 +383,8 @@ Window::Window(std::uint32_t width, std::uint32_t height) : width(width), height
// the buffer at width/scale x height/scale, so without a viewporter there
// is no fractional scale either: scale stays 1, the surface is as large as
// its buffer, and the compositor scales it up on a HiDPI output. A scale
// that changes after this is applied only by the next resize (#165).
// that changes after this is applied only by the next swapchain, or by
// the next size the compositor configures (#165).
if (Device::fractionalScaleManager != nullptr && Device::wpViewporter != nullptr) {
wp_scale = wp_fractional_scale_manager_v1_get_fractional_scale(Device::fractionalScaleManager, surface);
wp_fractional_scale_v1_add_listener(wp_scale, &wp_fractional_scale_v1_listener, this);
@ -401,10 +402,15 @@ Window::Window(std::uint32_t width, std::uint32_t height) : width(width), height
zxdg_toplevel_decoration_v1_set_mode(decoration, ZXDG_TOPLEVEL_DECORATION_V1_MODE_SERVER_SIDE);
}
// The viewport's destination is not set here: it is the size the surface
// takes with a buffer, so the window's first frame brings it
// (SendFrameSurfaceState). What it is to be is settled now, from the
// constructor's size in pixels and the scale the compositor has named so
// far, as it used to be sent from here.
if (Device::wpViewporter != nullptr) {
wpViewport = wp_viewporter_get_viewport(Device::wpViewporter, surface);
wp_viewport_set_destination(wpViewport, std::ceil(width/scale), std::ceil(height/scale));
}
MatchSizesToScale();
wl_surface_commit(surface);
#endif
@ -743,9 +749,19 @@ void Window::PointerScroll(double detents) {
}
void Window::Resize(std::uint32_t newWidth, std::uint32_t newHeight) {
// Skip degenerate resizes. Win32 minimised windows give (0, 0); Wayland
// sometimes echoes the current size in a configure.
// Skip degenerate resizes: Win32 minimised windows give (0, 0). A
// Wayland configure does not come through here: its size waits for the
// next Render() (xdg_surface_handle_configure).
if (newWidth == 0 || newHeight == 0) return;
#ifdef CRAFTER_GRAPHICS_WINDOW_WAYLAND
// The last size asked for wins, whoever asked. A size the compositor
// configured that still waits for its frame gives way to this later
// one, the size the window has included, as it did when the configure's
// listener resized on the spot and this call came after it. The
// configure's serial goes on waiting for a frame.
deferredLogicalWidth = 0;
deferredLogicalHeight = 0;
#endif
// A listener of the frame being recorded asked: the rest of that frame
// still draws into an image of the current swapchain at the current
// size, so the size changes once the frame has been presented. The last
@ -768,28 +784,110 @@ void Window::Resize(std::uint32_t newWidth, std::uint32_t newHeight) {
width = newWidth;
height = newHeight;
#ifdef CRAFTER_GRAPHICS_WINDOW_WAYLAND
// The application's size, in pixels: the surface's follows from it.
logicalConfigured = false;
#endif
RebuildSwapchain();
}
void Window::RebuildSwapchain() {
// Configure handlers and WM_SIZE run between frames, and a frame that
// asked waited for its present, but frames may still be in flight: none
// may still use the old swapchain.
// Pending from here until the swapchain is made, whoever called: a
// rebuild that throws below is then tried again by the next Render().
swapchainRebuildPending = true;
// WM_SIZE and a Resize or SetPresentMode from outside a frame run
// between frames, and what a frame or a configure asked for waited for a
// frame boundary (RebuildIfDeferred), but frames may still be in flight:
// none may still use the old swapchain.
Device::CheckVkResult(vkQueueWaitIdle(Device::queue));
// The queue is idle, so every deferred resource is now safe to free
// regardless of its retire frame (issue #101).
Device::DrainDeletions();
#ifdef CRAFTER_GRAPHICS_WINDOW_WAYLAND
if (wpViewport) {
wp_viewport_set_destination(wpViewport,
static_cast<int>(std::ceil(width / scale)),
static_cast<int>(std::ceil(height / scale)));
// The buffers' size and the surface's, from the scale of this moment.
// The surface itself is told nothing here. Its size is the viewport's
// destination, which the next commit applies whatever buffer is attached
// then: sent now, the old frame would be shown scaled to the new size
// until the first new one (#199). SendFrameSurfaceState sends it with
// that frame.
MatchSizesToScale();
#endif
RecreateSwapchainAndImages();
// Made, so nothing waits. Cleared only here: a rebuild that threw above
// still waits, and the next Render() tries it again instead of drawing
// into a swapchain whose views CreateSwapchain has already destroyed.
// And before the listeners, which may render, or ask for another.
swapchainRebuildPending = false;
onResize.Invoke();
}
#ifdef CRAFTER_GRAPHICS_WINDOW_WAYLAND
namespace {
// The pixels a surface-local length takes at `scale`, as a size the
// compositor configured becomes the swapchain's. Rounded up, in float,
// where fractional-scale-v1 rounds half away from zero: that much of
// #201 is as it was.
std::uint32_t ScaledPixels(std::int32_t logical, float scale) {
return static_cast<std::uint32_t>(std::ceil(logical * scale));
}
// The other way: the surface-local length `pixels` come to at `scale`,
// for a window the application sized.
std::int32_t SurfaceLength(std::uint32_t pixels, float scale) {
return static_cast<std::int32_t>(std::ceil(pixels / scale));
}
}
void Window::MatchSizesToScale() {
if (logicalConfigured) {
width = ScaledPixels(logicalWidth, scale);
height = ScaledPixels(logicalHeight, scale);
} else {
logicalWidth = SurfaceLength(width, scale);
logicalHeight = SurfaceLength(height, scale);
}
}
#endif
bool Window::TakeDeferredSize() {
const std::uint32_t widthBefore = width;
const std::uint32_t heightBefore = height;
if (deferredWidth != 0) {
width = deferredWidth;
height = deferredHeight;
deferredWidth = 0;
deferredHeight = 0;
#ifdef CRAFTER_GRAPHICS_WINDOW_WAYLAND
// The application's size, in pixels: the surface's follows from it
// at the rebuild. Asking for the size the window has changes
// nothing, as in Resize.
if (width != widthBefore || height != heightBefore) logicalConfigured = false;
#endif
}
#ifdef CRAFTER_GRAPHICS_WINDOW_WAYLAND
// The compositor's size, when that is what waits (Resize and the
// configure's listener each clear the other's): the surface's size from
// here on, unchanged, and the pixels for it at the scale of this moment.
// Those may be the pixels the swapchain has, where the scale changed
// with the size. Then nothing is rebuilt, and the frame still brings the
// surface its new size.
if (deferredLogicalWidth != 0) {
logicalWidth = deferredLogicalWidth;
logicalHeight = deferredLogicalHeight;
logicalConfigured = true;
deferredLogicalWidth = 0;
deferredLogicalHeight = 0;
MatchSizesToScale();
}
#endif
return width != widthBefore || height != heightBefore;
}
RecreateSwapchainAndImages();
onResize.Invoke();
void Window::RebuildIfDeferred() {
// The sizes are taken before the rebuild, so an onResize listener that
// renders finds none waiting.
if (TakeDeferredSize() || swapchainRebuildPending) RebuildSwapchain();
}
void Window::RecreateSwapchainAndImages() {
@ -1297,6 +1395,15 @@ namespace {
}
void Window::Render() {
// A rebuild that waited for a frame boundary and came since the last
// one: on Wayland the size the compositor configured, which its listener
// only keeps (#199, #200), and a rebuild that threw. Here, not in that
// listener, a consumer that calls Update() itself has its `try` around
// it cover the Vulkan calls, and configures that came since the last
// frame cost one rebuild between them. onResize fires from it, with the
// queue idle and no frame being recorded, as it does from Resize.
RebuildIfDeferred();
// This frame's slot among the numFrames in flight. Its command buffer,
// descriptor-heap copy and acquire semaphore were last used numFrames
// frames ago: wait for that submission's fence before touching any of
@ -1317,10 +1424,7 @@ void Window::Render() {
VkResult acquire = vkAcquireNextImageKHR(Device::device, swapChain, UINT64_MAX,
imageAcquired, (VkFence)nullptr, &currentImage);
if (acquire == VK_ERROR_OUT_OF_DATE_KHR) {
Device::CheckVkResult(vkQueueWaitIdle(Device::queue));
Device::DrainDeletions();
RecreateSwapchainAndImages();
onResize.Invoke();
RebuildSwapchain();
acquire = vkAcquireNextImageKHR(Device::device, swapChain, UINT64_MAX,
imageAcquired, (VkFence)nullptr, &currentImage);
}
@ -1489,6 +1593,16 @@ void Window::Render() {
presentInfo.pWaitSemaphores = &renderFinishedSemaphores[currentImage];
#ifdef CRAFTER_GRAPHICS_WINDOW_WAYLAND
// The present attaches this frame's buffer and commits the surface. What
// the surface is to take with that buffer goes right before it, so that
// one commit applies all of it: the surface's size, where this frame is
// the first drawn for it, and the acknowledgement of the configure the
// frame answers (#199). Nothing between here and the present commits the
// surface.
SendFrameSurfaceState();
#endif
VkResult result = vkQueuePresentKHR(Device::queue, &presentInfo);
// The frame is handed over: a swapchain rebuild may go ahead now.
recording = false;
@ -1498,6 +1612,19 @@ void Window::Render() {
} else {
Device::CheckVkResult(result);
}
#ifdef CRAFTER_GRAPHICS_WINDOW_WAYLAND
// The surface shows this swapchain from here, unless the present found
// it out of date and queued nothing. What SendFrameSurfaceState sent is
// with the compositor all the same then, pending until the surface's
// next commit. That is the first frame of the swapchain made below,
// unless a commit that is no frame's comes before it (the configure
// listener's, a consumer's request for a frame callback), which would
// show the last buffer at the new size after all: nothing sent can be
// taken back, and the present is where the driver commits.
if (result != VK_ERROR_OUT_OF_DATE_KHR) {
presentedGeneration = swapchainGeneration;
}
#endif
// No vkQueueWaitIdle in the steady-state path: per-frame fences now gate
// command-buffer reuse, so the CPU is free to acquire/record frame N+1
// while the GPU is still executing frame N.
@ -1515,23 +1642,12 @@ void Window::Render() {
}
// The rebuild the frame held back: the present's, or a Resize or
// SetPresentMode from one of its listeners. RebuildSwapchain drains the
// queue (the only other wait-idles are Resize's and SetPresentMode's own
// and the acquire's OUT_OF_DATE path) and fires onResize before the next
// SetPresentMode from one of its listeners, or on Wayland a size
// configured while they ran (a listener that dispatches events).
// RebuildSwapchain drains the queue and fires onResize before the next
// frame; the wait also leaves every per-frame fence signaled, so the next
// Render()'s fence wait passes through.
bool rebuild = swapchainRebuildPending;
if (deferredWidth != 0) {
rebuild = rebuild || deferredWidth != width || deferredHeight != height;
width = deferredWidth;
height = deferredHeight;
deferredWidth = 0;
deferredHeight = 0;
}
if (rebuild) {
swapchainRebuildPending = false;
RebuildSwapchain();
}
RebuildIfDeferred();
}
#ifdef CRAFTER_TIMING
@ -1908,30 +2024,97 @@ void Window::xdg_toplevel_handle_close(void* data, xdg_toplevel*) {
void Window::xdg_surface_handle_configure(void* data, xdg_surface* xdg_surface, std::uint32_t serial) {
Window* window = reinterpret_cast<Window*>(data);
// The compositor configures our surface, acknowledge the configure event
xdg_surface_ack_configure(xdg_surface, serial);
if (window->configured) {
// Subsequent configure: if the toplevel asked for a new size
// (non-zero, different from current), drive the resize end-to-end.
// (0, 0) means "compositor has no preference, keep current size".
// The swapchain may not exist yet on the very first frame between
// the constructor's wait loop and CreateSwapchain — the Resize
// guard against equal sizes already covers that path.
if (window->pendingLogicalWidth > 0 && window->pendingLogicalHeight > 0 &&
window->swapChain != VK_NULL_HANDLE) {
std::uint32_t newWidth = static_cast<std::uint32_t>(
std::ceil(window->pendingLogicalWidth * window->scale));
std::uint32_t newHeight = static_cast<std::uint32_t>(
std::ceil(window->pendingLogicalHeight * window->scale));
window->Resize(newWidth, newHeight);
// The size this batch asks for. The listener only keeps it: the next
// Render() makes the swapchain again (RebuildIfDeferred) and answers the
// configure with its frame. Rebuilt here, a Vulkan error would be thrown
// through libwayland's dispatch (#200), the consumer's loop would stand
// still in it for the rebuild, and each of several configures before a
// frame would cost one. (0, 0) means the compositor has no preference,
// and a size that waited goes on waiting. Before the swapchain exists a
// configure's size is not taken (the first configure's, #166).
const bool hasSwapchain = window->configured && window->swapChain != VK_NULL_HANDLE;
if (hasSwapchain && window->pendingLogicalWidth > 0 && window->pendingLogicalHeight > 0) {
// The last size asked for wins, whoever asked: a Resize from a
// listener of the frame being recorded, which waits for that frame's
// present, gives way to this later one, as it did when this listener
// called Resize itself.
window->deferredWidth = 0;
window->deferredHeight = 0;
// The size the window has means that nothing waits any more,
// whatever did. It has it when the surface's size is this one and
// the buffers are the pixels for it at the scale of now: a scale
// that changed since they were made has the frame make them again,
// and a size that only comes to the same pixels as the one before
// (the scale changed with it) is still another size for the surface.
const bool current = window->pendingLogicalWidth == window->logicalWidth
&& window->pendingLogicalHeight == window->logicalHeight
&& ScaledPixels(window->pendingLogicalWidth, window->scale) == window->width
&& ScaledPixels(window->pendingLogicalHeight, window->scale) == window->height;
window->deferredLogicalWidth = current ? 0 : window->pendingLogicalWidth;
window->deferredLogicalHeight = current ? 0 : window->pendingLogicalHeight;
// And the size is the compositor's from here, also where the
// application's pixels had come to it.
if (current) window->logicalConfigured = true;
}
// An acknowledgement says that the next commit answers the configure.
// While a frame is owed, that commit is the frame's and not the one
// below or a consumer's request for a frame callback, which show the old
// frame: the serial waits for it, the last one when several come
// (SendFrameSurfaceState). A frame is owed while a size waits, and while
// the surface does not show the window as it is: a swapchain still to
// be made (a rebuild that threw, after which width and height are ahead
// of it), one no frame has been presented from yet, a size the surface
// has not been sent. Otherwise what the surface shows answers the
// configure already, and this acknowledgement takes with it any serial
// that waited: one older than the last acknowledged is a protocol error.
const bool sizeUnsent = window->wpViewport != nullptr
&& (window->logicalWidth != window->sentLogicalWidth || window->logicalHeight != window->sentLogicalHeight);
const bool frameOwed = window->deferredLogicalWidth != 0
|| (hasSwapchain && (window->swapchainRebuildPending || window->presentedGeneration != window->swapchainGeneration || sizeUnsent));
if (frameOwed) {
window->unackedConfigure = serial;
} else {
window->unackedConfigure.reset();
xdg_surface_ack_configure(xdg_surface, serial);
}
// Not the answer to a configure that waits, and it brings the surface no
// new size, since the viewport's destination comes with the frame too
// (#199). It applies what else is pending: a frame callback StartUpdate
// asked for, which is what starts its loop.
if (window->configured) {
wl_surface_commit(window->surface);
}
window->configured = true;
// Last: the handler does nothing with the window after its listeners.
// The events last, since a listener may destroy the window: the second
// fires only for one that is still there, and nothing of the window is
// used after it.
window->ApplyToplevelState();
if (frameOwed && std::ranges::contains(Device::windows, window)) {
window->onFrameOwed.Invoke();
}
}
void Window::SendFrameSurfaceState() {
// The surface's size, when this frame is the first to be drawn for it
// (the window's first frame among them). It is the size that was settled
// when the buffers' was, and not worked out from the scale of this
// moment: a listener of this frame may have dispatched a new one since.
// A swapchain made again for the size the surface has sends nothing.
if (wpViewport != nullptr && (logicalWidth != sentLogicalWidth || logicalHeight != sentLogicalHeight)) {
wp_viewport_set_destination(wpViewport, logicalWidth, logicalHeight);
sentLogicalWidth = logicalWidth;
sentLogicalHeight = logicalHeight;
}
// A frame recorded before a size came does not honour it: that
// configure, and any after it, waits for the frame at that size.
if (unackedConfigure && deferredLogicalWidth == 0) {
xdg_surface_ack_configure(xdgSurface, *unackedConfigure);
unackedConfigure.reset();
}
}
void Window::xdg_surface_handle_preferred_scale(void* data, wp_fractional_scale_v1*, std::uint32_t scale) {

View file

@ -84,7 +84,10 @@ export namespace Crafter {
// the old images have been destroyed: anything that holds one of
// them, or is sized after the window, is made again here. The heap
// slots that name the swapchain image follow by themselves (see
// DescriptorHeapVulkan::AddSwapchainSlot).
// DescriptorHeapVulkan::AddSwapchainSlot). On Wayland a size the
// compositor configures is taken by the next Render(), so for that
// resize this fires from there, before the frame's onUpdate, and
// not from the configure's listener (see onFrameOwed).
Event<void> onResize;
bool open = true;
bool updating = false;
@ -228,7 +231,14 @@ export namespace Crafter {
void SetTextInput(bool active, std::int32_t x = 0, std::int32_t y = 0, std::int32_t width = 0, std::int32_t height = 0, TextInputPurpose purpose = TextInputPurpose::Normal);
// Like SetPresentMode, a resize asked for while a frame is being
// recorded takes effect once that frame has been presented, width and
// height included, which the rest of the frame still draws at.
// height included, which the rest of the frame still draws at. On
// Wayland the surface takes the new size with the first frame drawn
// at it, not here: until that frame is presented the compositor
// shows the last one at the size it was drawn at. And there the
// last size asked for is the one the window takes, whoever asked: a
// size the compositor configured that still waits for its frame
// gives way to this call, and a size this call left waiting gives
// way to a configure that comes after it.
void Resize(std::uint32_t width, std::uint32_t height);
void Render();
void Update();
@ -325,21 +335,113 @@ export namespace Crafter {
bool suspended = false;
Event<void> onToplevelState;
// Fires after a configure that leaves the window owing the
// compositor a frame: it asked for a size the window does not have,
// or it came while the surface does not show the window as it is
// yet (a swapchain waits for its first frame). Nothing has been
// rebuilt by then. The next Render() makes the swapchain again at
// the new size, fires onResize, and presents a frame whose commit
// carries that buffer, the surface's new size and the configure's
// acknowledgement, so the surface changes size with the first
// buffer drawn for the new one and not before (#199), and a Vulkan
// error at the resize comes out of Render(), not out of the
// configure's listener (#200). Until that frame the compositor
// waits: the window keeps its old size on screen. A window that
// updates from StartUpdate draws it at its next frame callback, or
// on its clock. One that draws on demand asks for a frame here, as
// it does from onResize: this is where it learns of the resize,
// since onResize comes with the frame, and does not come at all
// where the new size takes the pixels the swapchain has (the scale
// changed with it). Fires for every such configure, also when a
// frame was owed already, and after onToplevelState, with the
// configure's states set. And it fires from the event dispatch
// wherever that runs, which may be inside a frame that is being
// recorded (a listener of that frame made a window or read the
// clipboard): a listener notes that a frame is wanted and leaves
// the drawing to its loop, since Update() must not be called from
// inside a frame.
Event<void> onFrameOwed;
float scale = 1.0f;
bool configured = false;
// Pending size from the most recent xdg_toplevel.configure, in
// surface-local (logical DP) units. Applied on xdg_surface.configure
// via Resize(); 0 means "compositor has no preference, keep current".
// surface-local (logical DP) units, until the xdg_surface.configure
// that ends its batch; 0 means "compositor has no preference, keep
// current".
std::int32_t pendingLogicalWidth = 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.
// onToplevelState when that changed one.
bool pendingActivated = false;
bool pendingSuspended = false;
void ApplyToplevelState();
// The surface's size, in surface-local units: what the viewport's
// destination is, or becomes with the next frame
// (SendFrameSurfaceState). It is state of its own beside width and
// height, the size of the buffers, and not worked back from them
// when it is sent: the scale may have changed since they were
// worked out, and for a size the compositor configured the two
// roundings, there and back, land above it wherever the size times
// the scale is not a whole number (#201). logicalConfigured says
// which of the two sizes the window was given. True: a configure
// gave this one, and it is that size unchanged, with width and
// height the pixels it came to when they were last worked out
// (MatchSizesToScale). False: the application gave width and height
// (the constructor's size, a Resize), and this is what they came
// to. Without a viewport the scale stays 1 and the two sizes are
// the same numbers.
std::int32_t logicalWidth = 0;
std::int32_t logicalHeight = 0;
bool logicalConfigured = false;
// Before a swapchain is made: works the size the window was not
// given out of the one it was, with the scale of that moment. A
// window the compositor sized keeps logicalWidth x logicalHeight
// and takes the pixels for it, one the application sized keeps its
// pixels and takes the surface-local size they come to. So the
// next swapchain applies a scale that changed, whatever it is made
// for (the time until then is #165), without moving a configured
// window off the size the compositor gave it. No Vulkan call.
void MatchSizesToScale();
// The destination last sent to the viewport, 0 before the first.
// Where logicalWidth x logicalHeight differs from it, the surface
// is still to take its size, with the next frame.
std::int32_t sentLogicalWidth = 0;
std::int32_t sentLogicalHeight = 0;
// The size the last configure asked for, in surface-local units,
// while the window does not have it; 0 when none waits. The
// listener only keeps it, and TakeDeferredSize makes it the
// window's when Render() takes it, with the pixels it comes to at
// the scale of that moment. A configure for the size the window
// has clears it, and so does a Resize, which is then the later
// word; a configure without a size leaves it.
std::int32_t deferredLogicalWidth = 0;
std::int32_t deferredLogicalHeight = 0;
// The configure waiting for the frame that honours it, the last one
// when several came: acknowledging it says that the next commit
// answers it, and the commits before that frame's still show the
// old size (the listener's own, a consumer's request for a frame
// callback). SendFrameSurfaceState acknowledges it once no size
// waits any more. A configure that asks for nothing new while
// nothing is owed is acknowledged in the listener.
std::optional<std::uint32_t> unackedConfigure;
// The swapchainGeneration of the swapchain the last presented frame
// was drawn into: while it is not the current one, the surface
// still shows a buffer of the swapchain before (or nothing yet),
// and a configure that comes then waits for the current one's
// first frame.
std::uint64_t presentedGeneration = 0;
// Before a frame's present: the requests whose state that present's
// commit applies together with the frame's buffer. The viewport's
// destination, when the surface's size is not the one last sent (a
// new size, the window's first frame): logicalWidth x
// logicalHeight as they are, whatever the scale is by now. Set any
// earlier, the next commit would scale the buffer still attached
// to it (#199). And the acknowledgement of unackedConfigure, unless
// a size still waits, which a frame recorded before it came does
// not honour. Sends nothing else and does not commit.
void SendFrameSurfaceState();
xdg_toplevel* xdgToplevel = nullptr;
zxdg_toplevel_decoration_v1* decoration = nullptr;
wp_viewport* wpViewport = nullptr;
@ -423,10 +525,29 @@ export namespace Crafter {
// Render() transitions each on its first acquire (imageInitialised).
// Does NOT fire onResize — callers do that.
void RecreateSwapchainAndImages();
// What Resize and SetPresentMode do once no frame is being recorded:
// waits for the queue, frees the deletion queue, makes the swapchain
// again at width x height and fires onResize.
// Makes the swapchain again at width x height, where no frame is
// being recorded: waits for the queue, frees the deletion queue,
// makes it and fires onResize. On Wayland it first settles the two
// sizes with the scale of that moment (MatchSizesToScale), so width
// and height may change in here for a window the compositor sized.
// It keeps swapchainRebuildPending set from its first step until
// the swapchain is made.
void RebuildSwapchain();
// Makes the size that waits for a frame boundary the window's: the
// last Resize a listener of a frame asked for (deferredWidth) or,
// on Wayland, the size the compositor configured
// (deferredLogicalWidth). Only one of the two waits, the one asked
// for last. True when width or height changed, so that the
// swapchain has to be made again. A configured size may leave them
// as they are, where the scale changed with it: then only the
// surface's size changes, which the next frame sends. No Vulkan
// call: Render() rebuilds.
bool TakeDeferredSize();
// At a frame boundary, where no frame is being recorded: the rebuild
// that waits, if one does. Render() runs it first thing, for what
// came between frames (a configure's size), and again after its
// present, for what its own listeners and its present asked for.
void RebuildIfDeferred();
// Saves the frame the next Render() draws to a PNG at `path`, for
// visual regression tests and screenshots: that Render copies the
@ -463,8 +584,13 @@ export namespace Crafter {
// True from a frame's acquire to its present: images[currentImage]
// and the frame's heap copy are this frame's, and a swapchain rebuild
// (Resize, SetPresentMode) waits for the present. What is waiting:
// a new present mode, or a present that found the swapchain out of
// date; and the last size a resize asked for, 0 when none did.
// a swapchain still to be made, for a new size or present mode, a
// present that found it out of date, or a rebuild that threw, which
// the next Render() tries again (RebuildSwapchain clears the flag
// once the swapchain is made); and the last size a Resize asked
// for, 0 when none did. On Wayland a size the compositor configured
// waits in deferredLogicalWidth, whenever it comes, and takes the
// place of one that waits here, as a later Resize takes its place.
bool recording = false;
bool swapchainRebuildPending = false;
std::uint32_t deferredWidth = 0;

View file

@ -472,6 +472,20 @@ extern "C" Configuration CrafterBuildProject(std::span<const std::string_view> a
// surfaces are proxies on a socketpair display. No compositor.
cfg.tests.push_back(LibraryTest("ToplevelState"));
// Issue #199: a size the compositor configures waits for the
// next frame, which makes the swapchain again and sends the
// viewport's destination and the configure's acknowledgement
// before its present, so that they are applied by the commit
// that brings the first buffer of the new size and not by one
// before it. Feeds the configure callbacks of a window whose
// surfaces are proxies on a socketpair display, as
// ToplevelState does, steps the two ends of a frame
// (TakeDeferredSize, SendFrameSurfaceState) and reads the
// requests off the wire, through changes of the scale and
// through Resize too: the destination is the configured size
// itself. No compositor, no GPU.
cfg.tests.push_back(LibraryTest("ConfigureResize"));
// Issue #40: multi-frame-in-flight frame pacing (per-frame fences
// and acquire semaphores, per-image render-finished semaphores, no
// steady-state wait-idle). Drives the
@ -596,6 +610,21 @@ extern "C" Configuration CrafterBuildProject(std::span<const std::string_view> a
// Needs the Wayland backend and a real compositor.
cfg.tests.push_back(LibraryTest("WindowOptionalGlobals"));
// Issue #199, on a live connection: at every commit of the
// window's surface the viewport's destination in effect is the
// size of the buffer in effect, and every acknowledgement of a
// configure that asked for a size is committed with a buffer of
// that size in effect and that size itself as the destination
// (#201), through a Resize with a commit before the next frame
// and through the sizes the compositor configures. Runs with
// WAYLAND_DEBUG set and stderr in a file
// and replays the log, which has the driver's attach and commit
// too. Maximizes its window for a moment to be configured a
// size. `ResizeViewport --keyboard` is the manual probe for a
// phone, whose on-screen keyboard resizes the window. Needs the
// Wayland backend and a real compositor.
cfg.tests.push_back(LibraryTest("ResizeViewport"));
// RTPass pushes the application's push data and traces at an
// explicit size: clears the frame, traces a quadrant with a hit
// colour that changes every frame, and checks the read-back.

View file

@ -0,0 +1,859 @@
//SPDX-License-Identifier: LGPL-3.0-only
//SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
// Issue #199: a size the compositor configures is answered by the frame drawn
// at it. The configure listener used to make the swapchain again on the spot,
// acknowledge the configure, send the viewport's destination for the new size
// and commit the surface. The destination is the surface's size, and that
// commit applied it to the buffer still attached: the old frame was shown
// scaled to the new size until the consumer's next frame brought a buffer of
// that size. The acknowledgement had named the old frame as the answer to
// the configure, and the rebuild's Vulkan calls ran, and threw, inside
// libwayland's dispatch (#200).
//
// Now the listener keeps the size and the serial, and Render() does the rest
// at its boundaries: RebuildIfDeferred takes the size (TakeDeferredSize) and
// makes the swapchain again, and SendFrameSurfaceState sends the destination
// and the acknowledgement right before the present, whose commit applies
// them with the frame's buffer. The surface's size is state of the window
// for that (logicalWidth, logicalHeight): a size the compositor configured
// is sent as the destination unchanged, and is not worked back from the
// pixels and a scale that may have changed since. This test drives those
// pieces without a swapchain: the window is default-constructed with a
// made-up swapchain handle, its surfaces are proxies on a wl_display
// connected to one end of a socketpair, as in ToplevelState, and the test
// calls the listener callbacks itself and reads the requests off the other
// end. `Begin` and `Present` below stand for the two ends of Render();
// ResizeViewport runs the real one against a compositor. Asserts:
//
// - a configure for a new size sends one bare commit: no destination, no
// acknowledgement, and no Vulkan call (there is no device here, and the
// old listener's rebuild would have crashed on it). The size and the
// serial wait, the window's size stays the swapchain's, and onFrameOwed
// fires
// - the frame takes the size and sends the destination and the
// acknowledgement before its present, once
// - several configures before a frame cost one rebuild and one
// acknowledgement, of the last serial, and a configure without a size
// among them waits with the others
// - a configure that asks for nothing new while nothing is owed is
// acknowledged in the listener, before its commit, and fires nothing
// - a configure back to the size the window has takes the wait away: it
// is acknowledged at once, and the serial that waited never is, which
// would be a protocol error after a later one
// - a frame being recorded when a size comes does not acknowledge it
// - a window's first frame brings the destination (the constructor sends
// none), and so does the first frame at any new size; a configure that
// comes before that frame waits for it
// - a configure for the size a rebuild that threw is still pending for
// waits for the frame as well, and so does one that comes after a
// present that found the swapchain out of date, whose surface state is
// not sent a second time
// - without a viewport the acknowledgement still waits for the frame
// - the size is turned into pixels with the scale of the moment the frame
// takes it, and the destination is the configured size whatever the
// scale does: when it changes before the frame, between the frame's
// start and its present (a listener that dispatches events), and when
// the new size at the new scale comes to the pixels the swapchain has,
// in either order of the two events. That last frame makes no swapchain
// and still brings the surface its size
// - on a fractional scale the destination is the configured size and not a
// pixel more, and a window configured at the size it has is left alone
// (the numbers of #201's phone trace)
// - a swapchain made for another reason after the scale changed: a window
// the compositor sized keeps the surface's size and takes the pixels for
// it, one the application sized keeps its pixels and the surface takes
// the size they come to
// - of a Resize from a listener of the frame and a configured size, the
// one asked for last is taken, also when it is the size the window has
// - onFrameOwed fires after onToplevelState, with the states set, and not
// at all for a window an onToplevelState listener destroyed
// - every acknowledgement names a later serial than the one before
//
// No compositor and no GPU. Needs the Wayland backend, hence Linux only.
#include <wayland-client.h>
#include <sys/socket.h>
#include <unistd.h>
#include <cerrno>
#include <cstdlib>
#include <cstring>
#include "../../lib/xdg-shell-client-protocol.h"
#include "../../lib/viewporter.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;
}
using Requests = std::vector<std::string>;
// `got` against `expected`, printing what came when they differ.
void Expect(const Requests& got, const Requests& expected, std::string_view what) {
Check(got == expected, what);
if (got != expected) {
std::println(" sent: {}", got);
std::println(" expected: {}", expected);
}
}
Requests Sorted(Requests requests) {
std::ranges::sort(requests);
return requests;
}
// Every acknowledgement the test read off the wire, in order.
std::vector<std::uint32_t> acknowledged;
// A compositor's serials: one counter, never reused.
std::uint32_t lastSerial = 100;
// A window as its constructor leaves it: the first configure taken, a
// swapchain made, no frame presented yet. The swapchain is a handle nothing
// dereferences and a generation; the surface, the xdg_surface, the toplevel
// and the viewport are proxies nothing answers.
struct Fixture {
wl_display* display;
int peer;
std::optional<Window> holder;
std::uint32_t surfaceId = 0;
std::uint32_t xdgSurfaceId = 0;
std::uint32_t viewportId = 0;
int owed = 0;
std::optional<EventListener<void>> owedSub;
Fixture(wl_display* display, wl_registry* registry, int peer, float scale, std::uint32_t width, std::uint32_t height, bool viewport = true)
: display(display), peer(peer) {
Window& window = holder.emplace();
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));
if (viewport) {
window.wpViewport = static_cast<wp_viewport*>(wl_registry_bind(registry, 4, &wp_viewport_interface, 1));
viewportId = wl_proxy_get_id(reinterpret_cast<wl_proxy*>(window.wpViewport));
}
surfaceId = wl_proxy_get_id(reinterpret_cast<wl_proxy*>(window.surface));
xdgSurfaceId = wl_proxy_get_id(reinterpret_cast<wl_proxy*>(window.xdgSurface));
window.scale = scale;
window.width = width;
window.height = height;
// The configure the constructor waits for, before there is a swapchain.
Configure(0, 0);
// The surface's size, from the constructor's pixels.
window.MatchSizesToScale();
window.swapChain = reinterpret_cast<decltype(window.swapChain)>(static_cast<std::uintptr_t>(0x1));
window.swapchainGeneration = 1;
// Where the constructor lists it, and where the handler looks for a
// window that outlived its listeners.
Device::windows.push_back(&window);
owedSub.emplace(&window.onFrameOwed, [this] { ++owed; });
Sent();
}
~Fixture() {
// ~Window destroys the proxies; without a device it leaves the
// swapchain handle alone.
holder.reset();
Sent();
}
Window& window() { return *holder; }
// The compositor's two events of one batch. Returns the serial.
std::uint32_t Configure(std::int32_t width, std::int32_t height, std::initializer_list<std::uint32_t> states = {}) {
Window& window = *holder;
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;
}
// The handles before the calls: the second may destroy the window.
xdg_surface* const surface = window.xdgSurface;
Window::xdg_toplevel_configure(&window, window.xdgToplevel, width, height, &array);
wl_array_release(&array);
const std::uint32_t serial = ++lastSerial;
Window::xdg_surface_handle_configure(&window, surface, serial);
return serial;
}
// What RebuildSwapchain does besides its Vulkan calls: the window's two
// sizes from the scale of the moment, and a swapchain, which
// CreateSwapchain numbers, after which none waits to be made.
void Rebuild() {
Window& window = *holder;
window.MatchSizesToScale();
++window.swapchainGeneration;
window.swapchainRebuildPending = false;
}
// The start of Render(), which is RebuildIfDeferred: the size that waits
// becomes the window's, and new pixels, or a rebuild that waited, make a
// new swapchain. True when one was made.
bool Begin() {
Window& window = *holder;
if (!window.TakeDeferredSize() && !window.swapchainRebuildPending) return false;
Rebuild();
return true;
}
// The end of Render(): the surface state for the frame, then the
// present, after which the surface shows this swapchain.
void Present() {
Window& window = *holder;
window.SendFrameSurfaceState();
window.presentedGeneration = window.swapchainGeneration;
}
// A whole frame.
void Frame() {
Begin();
Present();
}
// What the window has sent to its surface, its xdg_surface and its
// viewport since the last call, in order: "commit", "ack <serial>",
// "destination <w>x<h>". A request is its object id, then its size and
// opcode in one word, then its arguments.
Requests Sent() {
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);
}
Requests requests;
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;
const std::uint32_t opcode = header[1] & 0xFFFF;
if (size < 8 || at + size > wire.size()) break;
const auto argument = [&](std::size_t index) {
std::int32_t value = 0;
if (8 + 4 * (index + 1) <= size) std::memcpy(&value, wire.data() + at + 8 + 4 * index, sizeof(value));
return value;
};
if (header[0] == surfaceId && opcode == WL_SURFACE_COMMIT) {
requests.push_back("commit");
} else if (header[0] == xdgSurfaceId && opcode == XDG_SURFACE_ACK_CONFIGURE) {
requests.push_back(std::format("ack {}", static_cast<std::uint32_t>(argument(0))));
acknowledged.push_back(static_cast<std::uint32_t>(argument(0)));
} else if (viewportId != 0 && header[0] == viewportId && opcode == WP_VIEWPORT_SET_DESTINATION) {
requests.push_back(std::format("destination {}x{}", argument(0), argument(1)));
}
at += size;
}
return requests;
}
};
bool NothingWaits(const Window& window) {
return window.deferredLogicalWidth == 0 && window.deferredLogicalHeight == 0 && !window.unackedConfigure
&& window.presentedGeneration == window.swapchainGeneration
&& window.sentLogicalWidth == window.logicalWidth && window.sentLogicalHeight == window.logicalHeight;
}
// The scale as the compositor names it, in 120ths.
void Scale(Window& window, std::uint32_t scale120) {
Window::xdg_surface_handle_preferred_scale(&window, nullptr, scale120);
}
} // 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 auto fixture = [&](float scale, std::uint32_t width, std::uint32_t height, bool viewport = true) {
return Fixture(display, registry, fds[1], scale, width, height, viewport);
};
// The window's first frame: the constructor sends no destination, the
// frame does. Every fixture after this one has it behind it.
{
Fixture f = fixture(2.0f, 640, 480);
f.Present();
Expect(f.Sent(), { "destination 320x240" }, "a window's first frame brings the viewport's destination");
Check(NothingWaits(f.window()), "after it nothing is owed");
f.Frame();
Expect(f.Sent(), {}, "the frames after it send nothing");
}
// A new size, and the frame that answers it.
{
Fixture f = fixture(2.0f, 640, 480);
f.Frame();
f.Sent();
Window& window = f.window();
const std::uint32_t serial = f.Configure(400, 300);
Expect(f.Sent(), { "commit" },
"a configure for a new size: one bare commit, with neither the surface's new size nor an acknowledgement");
Check(window.width == 640 && window.height == 480,
std::format("the window's size is still the swapchain's ({}x{})", window.width, window.height));
Check(window.deferredLogicalWidth == 400 && window.deferredLogicalHeight == 300 && window.unackedConfigure == serial,
"the size and the serial wait for a frame");
Check(f.owed == 1, std::format("onFrameOwed fired once ({})", f.owed));
Check(f.Begin(), "the next frame takes the size");
Check(window.width == 800 && window.height == 600 && window.deferredLogicalWidth == 0 && window.deferredLogicalHeight == 0,
std::format("the window has it in pixels ({}x{} at scale 2), and no size waits", window.width, window.height));
Expect(f.Sent(), {}, "taking it sends nothing");
f.Present();
Expect(Sorted(f.Sent()), Sorted({ std::format("ack {}", serial), "destination 400x300" }),
"before its present the frame sends the destination and the acknowledgement, and does not commit");
Check(NothingWaits(window), "after the frame nothing is owed");
f.Frame();
Expect(f.Sent(), {}, "the frames after it send neither again");
Check(f.owed == 1, "onFrameOwed fired for the configure only");
}
// Several configures before a frame.
{
Fixture f = fixture(1.0f, 320, 240);
f.Frame();
f.Sent();
Window& window = f.window();
f.Configure(400, 300);
f.Configure(500, 350);
const std::uint32_t last = f.Configure(0, 0, { XDG_TOPLEVEL_STATE_ACTIVATED });
Expect(f.Sent(), { "commit", "commit", "commit" }, "three configures before a frame: three bare commits");
Check(window.deferredLogicalWidth == 500 && window.deferredLogicalHeight == 350,
"the last size asked for waits, through a configure without a size");
Check(window.unackedConfigure == last, "the last serial waits, the one without a size");
Check(f.owed == 3, std::format("onFrameOwed fired for each ({})", f.owed));
Check(f.Begin() && window.width == 500 && window.height == 350, "one frame takes the last size");
f.Present();
Expect(Sorted(f.Sent()), Sorted({ std::format("ack {}", last), "destination 500x350" }),
"and sends one destination and one acknowledgement, of the last serial");
Check(NothingWaits(window), "after the frame nothing is owed");
}
// Nothing new while nothing is owed: answered in the listener, as before.
{
Fixture f = fixture(2.0f, 640, 480);
f.Frame();
f.Sent();
Window& window = f.window();
const std::uint32_t none = f.Configure(0, 0, { XDG_TOPLEVEL_STATE_ACTIVATED });
Expect(f.Sent(), { std::format("ack {}", none), "commit" },
"a configure without a size while nothing is owed: acknowledged in the listener, before its commit");
const std::uint32_t same = f.Configure(320, 240);
Expect(f.Sent(), { std::format("ack {}", same), "commit" },
"a configure for the size the window has: the same");
Check(NothingWaits(window) && f.owed == 0, "neither leaves a frame owed or fires onFrameOwed");
Check(!f.Begin(), "and the next frame makes no swapchain");
f.Present();
Expect(f.Sent(), {}, "nor sends anything");
}
// The compositor goes back to the size the window has before a frame.
{
Fixture f = fixture(1.0f, 320, 240);
f.Frame();
f.Sent();
Window& window = f.window();
const std::uint32_t first = f.Configure(400, 300);
f.Sent();
const std::uint32_t back = f.Configure(320, 240);
Expect(f.Sent(), { std::format("ack {}", back), "commit" },
"a configure back to the window's size: acknowledged at once, as the surface shows that size");
Check(NothingWaits(window), "the size and the serial that waited are gone");
Check(!f.Begin(), "the next frame makes no swapchain");
f.Present();
Expect(f.Sent(), {}, std::format("and never acknowledges {}, the serial before the one acknowledged", first));
}
// A size that comes while a frame is being recorded.
{
Fixture f = fixture(1.0f, 320, 240);
f.Frame();
f.Sent();
Window& window = f.window();
f.Begin();
const std::uint32_t serial = f.Configure(400, 300);
f.Present();
Expect(f.Sent(), { "commit" },
"a frame being recorded when a size comes: its present sends neither a destination nor an acknowledgement");
Check(window.unackedConfigure == serial && window.deferredLogicalWidth == 400, "the size and the serial wait on");
Check(f.Begin() && window.width == 400 && window.height == 300, "the frame after it takes the size");
f.Present();
Expect(Sorted(f.Sent()), Sorted({ std::format("ack {}", serial), "destination 400x300" }), "and answers the configure");
}
// A configure before the window's first frame.
{
Fixture f = fixture(2.0f, 640, 480);
const std::uint32_t serial = f.Configure(0, 0, { XDG_TOPLEVEL_STATE_ACTIVATED });
Expect(f.Sent(), { "commit" }, "a configure before the window's first frame: not acknowledged in the listener");
Check(f.owed == 1, "onFrameOwed fired for it");
f.Present();
Expect(Sorted(f.Sent()), Sorted({ std::format("ack {}", serial), "destination 320x240" }),
"the first frame brings the destination and the acknowledgement");
}
// A swapchain made between frames, as Resize makes one outside a frame:
// its first frame brings the destination, and a configure before that
// frame waits for it.
{
Fixture f = fixture(2.0f, 640, 480);
f.Frame();
f.Sent();
Window& window = f.window();
window.width = 800;
window.height = 500;
window.logicalConfigured = false;
f.Rebuild();
Expect(f.Sent(), {}, "a swapchain made at a new size sends the surface nothing");
const std::uint32_t serial = f.Configure(0, 0);
Expect(f.Sent(), { "commit" }, "a configure while a new swapchain waits for its first frame: not acknowledged in the listener");
Check(!f.Begin(), "no size waits for the frame");
f.Present();
Expect(Sorted(f.Sent()), Sorted({ std::format("ack {}", serial), "destination 400x250" }),
"the swapchain's first frame brings its destination and the acknowledgement");
// The same size again, as SetPresentMode makes a swapchain: the
// surface has its size, and a configure still waits for a buffer of
// the swapchain there is.
f.Rebuild();
const std::uint32_t second = f.Configure(400, 250);
Expect(f.Sent(), { "commit" }, "a configure for the window's size while a swapchain waits for its first frame: not acknowledged in the listener either");
Check(!f.Begin(), "nor is there a size for the frame to take");
f.Present();
Expect(f.Sent(), { std::format("ack {}", second) }, "that frame acknowledges it and sends no destination: the surface's size is the one it has");
}
// A rebuild that threw leaves the window's sizes ahead of the swapchain
// and stays pending for the next Render(). A configure for that size is
// not answered by what the surface shows: it waits for the frame too.
{
Fixture f = fixture(2.0f, 640, 480);
f.Frame();
f.Sent();
Window& window = f.window();
// A size is taken and its rebuild throws: RebuildSwapchain has set
// its flag and made nothing.
f.Configure(400, 300);
Check(window.TakeDeferredSize() && window.width == 800 && window.height == 600, "a size is taken, and the rebuild for it throws");
window.swapchainRebuildPending = true;
f.Sent();
const std::uint32_t serial = f.Configure(400, 300);
Expect(f.Sent(), { "commit" },
"a configure for the size a pending rebuild is for: not acknowledged in the listener, though the window's size says so already");
Check(window.deferredLogicalWidth == 0 && window.unackedConfigure == serial && f.owed == 2,
"no size waits, the serial does, and onFrameOwed fired");
Check(f.Begin() && window.width == 800 && window.height == 600 && !window.swapchainRebuildPending,
"the next frame makes the swapchain that waited");
f.Present();
Expect(Sorted(f.Sent()), Sorted({ std::format("ack {}", serial), "destination 400x300" }),
"the frame of the swapchain made at last brings the destination and the acknowledgement");
}
// A present that finds the swapchain out of date queues nothing, and
// Render() makes the swapchain again after it. What went out before
// that present is not sent a second time, and a configure that comes in
// between waits for the first frame of the swapchain made after it.
{
Fixture f = fixture(2.0f, 640, 480);
f.Frame();
f.Sent();
Window& window = f.window();
const std::uint32_t serial = f.Configure(400, 300);
f.Sent();
Check(f.Begin(), "a frame takes a size");
// The present that follows returns VK_ERROR_OUT_OF_DATE_KHR:
// presentedGeneration stays, and a rebuild waits.
window.SendFrameSurfaceState();
window.swapchainRebuildPending = true;
Expect(Sorted(f.Sent()), Sorted({ std::format("ack {}", serial), "destination 400x300" }),
"its destination and acknowledgement go out before its present, which finds the swapchain out of date");
const std::uint32_t next = f.Configure(400, 300);
Expect(f.Sent(), { "commit" }, "a configure for that size before the swapchain is made again: not acknowledged in the listener");
Check(f.Begin(), "the next frame makes the swapchain");
f.Present();
Expect(f.Sent(), { std::format("ack {}", next) }, "and acknowledges, without sending the destination a second time");
Check(NothingWaits(window), "after it nothing is owed");
}
// Without wp_viewporter there is no destination, and the scale is 1.
{
Fixture f = fixture(1.0f, 320, 240, false);
f.Frame();
Expect(f.Sent(), {}, "without a viewport the first frame sends nothing");
Window& window = f.window();
const std::uint32_t serial = f.Configure(400, 300);
Expect(f.Sent(), { "commit" }, "without a viewport: a configure for a new size still waits for its frame");
Check(f.Begin() && window.width == 400 && window.height == 300, "the frame takes the size");
f.Present();
Expect(f.Sent(), { std::format("ack {}", serial) }, "and acknowledges, with no destination");
}
// The scale that counts for the pixels is the one of the moment the frame
// takes the size. The destination is the configured size whatever the
// scale does.
{
Fixture f = fixture(2.0f, 640, 480);
f.Frame();
f.Sent();
Window& window = f.window();
const std::uint32_t serial = f.Configure(400, 300);
Scale(window, 180);
Check(f.Begin() && window.width == 600 && window.height == 450,
std::format("a scale that changes before the frame: the size is taken at the new one ({}x{} at 1.5)", window.width, window.height));
f.Sent();
f.Present();
Expect(Sorted(f.Sent()), Sorted({ std::format("ack {}", serial), "destination 400x300" }),
"and the destination is the size the compositor configured");
}
// The scale changes between the frame's start and its present: a
// listener of the frame dispatched the event (it made a window, or read
// the clipboard). The swapchain was made for the old scale, and the
// destination is still the configured size, not that swapchain's pixels
// over the new scale (534x400).
{
Fixture f = fixture(2.0f, 640, 480);
f.Frame();
f.Sent();
Window& window = f.window();
const std::uint32_t serial = f.Configure(400, 300);
Check(f.Begin() && window.width == 800 && window.height == 600, "the frame takes a size at scale 2");
Scale(window, 180);
f.Sent();
f.Present();
Expect(Sorted(f.Sent()), Sorted({ std::format("ack {}", serial), "destination 400x300" }),
"a scale that changes while the frame is recorded: its present still sends the configured size");
Check(NothingWaits(window), "and nothing is owed after it");
}
// A new size and a new scale that together come to the pixels the
// swapchain has: an output whose scale changes under a window that fills
// it. No swapchain is made, and the surface still has to be told its new
// size, in the commit that acknowledges the configure. First the
// configure, then the scale.
{
Fixture f = fixture(2.0f, 640, 480);
f.Frame();
Expect(f.Sent(), { "destination 320x240" }, "a window of 640x480 pixels at scale 2 is 320x240");
Window& window = f.window();
const std::uint32_t serial = f.Configure(640, 480);
Expect(f.Sent(), { "commit" }, "a configure for 640x480 at scale 2: a new size, which waits");
Check(f.owed == 1, "onFrameOwed fired");
Scale(window, 120);
Check(!f.Begin() && window.width == 640 && window.height == 480,
"the scale becomes 1 before the frame: the size comes to the pixels the swapchain has, and none is made");
f.Present();
Expect(Sorted(f.Sent()), Sorted({ std::format("ack {}", serial), "destination 640x480" }),
"the frame brings the surface its new size with the acknowledgement");
Check(NothingWaits(window), "after it nothing is owed");
const std::uint32_t again = f.Configure(640, 480);
Expect(f.Sent(), { std::format("ack {}", again), "commit" }, "and the same configure again is answered by what the surface shows");
}
// The other order: the scale first, then the configure, whose size is in
// pixels the one the swapchain has.
{
Fixture f = fixture(1.5f, 600, 450);
f.Frame();
Expect(f.Sent(), { "destination 400x300" }, "a window of 600x450 pixels at scale 1.5 is 400x300");
Window& window = f.window();
Scale(window, 240);
const std::uint32_t serial = f.Configure(300, 225);
Expect(f.Sent(), { "commit" },
"the scale becomes 2, then a configure for 300x225, the pixels the swapchain has: not acknowledged in the listener, as the surface is 400x300");
Check(window.deferredLogicalWidth == 300 && window.deferredLogicalHeight == 225 && f.owed == 1, "the size waits, and onFrameOwed fired");
Check(!f.Begin() && window.width == 600 && window.height == 450, "the frame makes no swapchain");
f.Present();
Expect(Sorted(f.Sent()), Sorted({ std::format("ack {}", serial), "destination 300x225" }),
"and brings the surface its new size with the acknowledgement");
}
// The size the surface has, after the scale changed: the buffers are
// made again for the new scale, and the surface is sent nothing.
{
Fixture f = fixture(2.0f, 640, 480);
f.Frame();
f.Sent();
Window& window = f.window();
Scale(window, 180);
const std::uint32_t serial = f.Configure(320, 240);
Expect(f.Sent(), { "commit" }, "a configure for the surface's size after the scale changed: it waits for buffers at the new scale");
Check(f.Begin() && window.width == 480 && window.height == 360,
std::format("the frame makes the swapchain again for the scale ({}x{} at 1.5)", window.width, window.height));
f.Present();
Expect(f.Sent(), { std::format("ack {}", serial) }, "and acknowledges, with no destination: the surface's size is the one it has");
}
// A fractional scale, with the numbers of #201's trace: a phone at 2.85
// whose maximized window is configured 392x796. The destination is that
// size, where it used to be worked back from the 1118x2269 pixels to
// 393x797, and the window is left alone when the compositor configures
// it at the size it has, where it used to grow with each such configure
// until it was 400x800.
{
Fixture f = fixture(2.85f, 1140, 2280);
f.Frame();
Expect(f.Sent(), { "destination 400x800" }, "a window of 1140x2280 pixels at scale 2.85 is 400x800");
Window& window = f.window();
const std::uint32_t serial = f.Configure(392, 796);
f.Sent();
Check(f.Begin() && window.width == 1118 && window.height == 2269,
std::format("392x796 at scale 2.85 is taken as {}x{} pixels", window.width, window.height));
f.Present();
Expect(Sorted(f.Sent()), Sorted({ std::format("ack {}", serial), "destination 392x796" }),
"and the destination is 392x796, the configured size itself");
for (int i = 0; i < 3; ++i) {
const std::uint32_t again = f.Configure(392, 796);
Expect(f.Sent(), { std::format("ack {}", again), "commit" }, "the compositor configures the window at the size it has: acknowledged at once");
Check(!f.Begin() && window.width == 1118 && window.height == 2269, "and the window does not grow");
f.Present();
Expect(f.Sent(), {}, "nor is the surface sent anything");
}
}
// A window the application sized, whose pixels do not come to a whole
// surface-local size: 320x240 at 1.75 is shown at 183x138. When the
// compositor configures that size, the window takes the pixels for it
// once, and is then left alone.
{
Fixture f = fixture(1.75f, 320, 240);
f.Frame();
Expect(f.Sent(), { "destination 183x138" }, "a window of 320x240 pixels at scale 1.75 is shown at 183x138");
Window& window = f.window();
const std::uint32_t serial = f.Configure(183, 138);
f.Sent();
Check(f.Begin() && window.width == 321 && window.height == 242,
std::format("configured at 183x138, it takes the pixels for that size ({}x{})", window.width, window.height));
f.Present();
Expect(f.Sent(), { std::format("ack {}", serial) }, "and the surface, which has that size, is sent no destination");
const std::uint32_t again = f.Configure(183, 138);
Expect(f.Sent(), { std::format("ack {}", again), "commit" }, "the same configure again is acknowledged at once");
Check(!f.Begin() && window.width == 321 && window.height == 242, "and changes nothing");
}
// A swapchain made for another reason (a present mode, a swapchain out
// of date) after the scale changed, with no configure in between. A
// window the compositor sized keeps the surface's size and takes the
// pixels for it at the new scale; one the application sized keeps its
// pixels, and the surface takes the size they come to, as it always did.
{
Fixture f = fixture(2.0f, 640, 480);
f.Frame();
f.Configure(400, 300);
f.Frame();
f.Sent();
Window& window = f.window();
Check(window.width == 800 && window.height == 600 && window.logicalConfigured, "a window the compositor sized, 400x300 at scale 2");
Scale(window, 180);
f.Rebuild();
Check(window.width == 600 && window.height == 450 && window.logicalWidth == 400 && window.logicalHeight == 300,
std::format("a swapchain made after the scale became 1.5: the pixels for 400x300 at it ({}x{})", window.width, window.height));
f.Present();
Expect(f.Sent(), {}, "and the surface, still 400x300, is sent nothing");
}
{
Fixture f = fixture(2.0f, 640, 480);
f.Frame();
f.Sent();
Window& window = f.window();
Check(!window.logicalConfigured, "a window the application sized, 640x480 pixels at scale 2");
Scale(window, 120);
f.Rebuild();
Check(window.width == 640 && window.height == 480, "a swapchain made after the scale became 1: the pixels stay");
f.Present();
Expect(f.Sent(), { "destination 640x480" }, "and the surface takes the size they come to at it");
}
// A Resize from a listener of the frame waits in pixels, for that
// frame's present.
{
Fixture f = fixture(2.0f, 640, 480);
f.Frame();
f.Sent();
Window& window = f.window();
window.recording = true;
window.Resize(1000, 700);
window.recording = false;
Check(window.width == 640 && window.deferredWidth == 1000, "a Resize during a frame waits");
Check(f.Begin() && window.width == 1000 && window.height == 700 && window.deferredWidth == 0 && window.deferredHeight == 0,
"and is taken at the frame boundary");
f.Present();
Expect(f.Sent(), { "destination 500x350" }, "the first frame at it brings the surface the size the pixels come to");
}
// Of a Resize and a configured size, the one asked for last is taken.
// The Resize first: the compositor's later size takes its place.
{
Fixture f = fixture(2.0f, 640, 480);
f.Frame();
f.Sent();
Window& window = f.window();
window.recording = true;
window.Resize(1200, 800);
window.recording = false;
f.Configure(400, 300);
Check(window.deferredWidth == 0 && window.deferredHeight == 0 && window.deferredLogicalWidth == 400,
"a configure after a Resize that waits: the compositor's size waits in its place");
Check(f.Begin() && window.width == 800 && window.height == 600,
std::format("and is the one taken ({}x{})", window.width, window.height));
Check(!f.Begin(), "a second take finds nothing");
}
// The same when the compositor's later size is the one the window has:
// the Resize is dropped then too, and the window stays as it is. The
// configure comes while the frame is being recorded, as the Resize did.
{
Fixture f = fixture(1.0f, 800, 600);
f.Frame();
f.Sent();
Window& window = f.window();
window.recording = true;
window.Resize(1000, 700);
const std::uint32_t serial = f.Configure(800, 600);
Expect(f.Sent(), { std::format("ack {}", serial), "commit" },
"a configure for the size the window has, after a Resize that waits: acknowledged at once, as the surface shows that size");
Check(window.deferredWidth == 0 && window.deferredHeight == 0, "the Resize waits no more");
f.Present();
window.recording = false;
Check(!f.Begin() && window.width == 800 && window.height == 600,
std::format("after the frame the window is still the size the compositor configured ({}x{})", window.width, window.height));
Expect(f.Sent(), {}, "and nothing more is sent");
}
// The configure first, then a Resize in the same frame: the
// application's later size takes the compositor's place. The serial is
// acknowledged by the frame being recorded, which no size waits behind
// any more.
{
Fixture f = fixture(2.0f, 640, 480);
f.Frame();
f.Sent();
Window& window = f.window();
window.recording = true;
const std::uint32_t serial = f.Configure(400, 300);
window.Resize(1000, 700);
Check(window.deferredLogicalWidth == 0 && window.deferredLogicalHeight == 0 && window.deferredWidth == 1000,
"a Resize after a configure that waits: the application's size waits in its place");
f.Sent();
f.Present();
window.recording = false;
Expect(f.Sent(), { std::format("ack {}", serial) }, "the frame acknowledges the configure");
Check(f.Begin() && window.width == 1000 && window.height == 700 && !window.logicalConfigured,
std::format("and the size taken after it is the application's ({}x{})", window.width, window.height));
f.Present();
Expect(f.Sent(), { "destination 500x350" }, "which the surface takes with its first frame");
}
// And a Resize outside a frame to the size the window has: the
// compositor's size that waited is dropped, and nothing is rebuilt.
{
Fixture f = fixture(2.0f, 640, 480);
f.Frame();
f.Sent();
Window& window = f.window();
const std::uint32_t serial = f.Configure(400, 300);
f.Sent();
window.Resize(640, 480);
Check(window.deferredLogicalWidth == 0 && window.deferredLogicalHeight == 0 && window.unackedConfigure == serial,
"a Resize to the size the window has, after a configure that waits: the size waits no more, the serial does");
Check(!f.Begin() && window.width == 640 && window.height == 480, "the next frame makes no swapchain");
f.Present();
Expect(f.Sent(), { std::format("ack {}", serial) }, "and acknowledges the configure");
}
// The events: onToplevelState first, then onFrameOwed with the states set.
{
Fixture f = fixture(1.0f, 320, 240);
f.Frame();
f.Sent();
Window& window = f.window();
std::vector<std::string> order;
EventListener<void> stateSub(&window.onToplevelState, [&] { order.push_back("state"); });
EventListener<void> owedSub(&window.onFrameOwed, [&] { order.push_back(window.activated ? "owed, activated" : "owed"); });
f.Configure(400, 300, { XDG_TOPLEVEL_STATE_ACTIVATED });
Check(order == std::vector<std::string>{ "state", "owed, activated" },
"onFrameOwed fires after onToplevelState, with the configure's states set");
if (order != std::vector<std::string>{ "state", "owed, activated" }) std::println(" fired: {}", order);
}
// A listener of onToplevelState destroys the window: the handler fires
// nothing more on it. Another window is made in its place, at the same
// address, so an event fired through the old pointer would show.
{
Fixture f = fixture(1.0f, 320, 240);
f.Frame();
f.Sent();
int firedOnReplacement = 0;
std::optional<EventListener<void>> replacementSub;
EventListener<void> stateSub(&f.window().onToplevelState, [&] {
f.holder.reset();
Window& replacement = f.holder.emplace();
replacementSub.emplace(&replacement.onFrameOwed, [&] { ++firedOnReplacement; });
});
f.Configure(400, 300, { XDG_TOPLEVEL_STATE_ACTIVATED });
Check(firedOnReplacement == 0 && f.owed == 0,
"a window destroyed from onToplevelState: onFrameOwed does not fire through the handler's pointer");
replacementSub.reset();
}
Check(std::ranges::adjacent_find(acknowledged, std::greater_equal{}) == acknowledged.end() && !acknowledged.empty(),
std::format("each of the {} acknowledgements names a later serial than the one before", acknowledged.size()));
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;
}

View file

@ -0,0 +1,742 @@
//SPDX-License-Identifier: LGPL-3.0-only
//SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
// Issue #199, against a compositor: at a resize the surface takes its new
// size in the commit that brings the first buffer of that size, not before.
// The size is the viewport's destination, state the next wl_surface.commit
// applies. A rebuild used to send it at once, and the first commit after it
// was not the new frame's: the configure listener committed, and so does a
// consumer that asks for a frame callback. That commit showed the old buffer
// scaled to the new size until the next frame. The configure was acknowledged
// in the listener too, so the compositor took that scaled frame for the
// answer.
//
// ConfigureResize pins the library's own requests without a compositor. This
// test adds the half only a real connection has: the buffer is attached and
// the surface committed by the Vulkan driver, inside vkQueuePresentKHR. It
// runs with WAYLAND_DEBUG set and stderr in a file, so libwayland writes
// every request of the process there in the order they go out, the driver's
// among them, and replays that log as the compositor reads it: a buffer and a
// destination are pending until a commit applies them. Checked:
//
// - at every commit, the destination in effect belongs to the buffer in
// effect, to within one surface-local pixel at the window's scale (one
// of the two is rounded from the other). Covers the window's first
// frame, a Resize from the application with a commit before the next
// frame, and a size the compositor configures
// - Resize outside a frame still makes the swapchain at once and fires
// onResize from the call
// - every acknowledgement of a configure that asked for a size is
// committed with a buffer of that size in effect, and with that size
// itself as the destination, not one worked back from the buffer's
// pixels (#201): the frame's commit for a new size, the listener's own
// where the surface has the size already
// - a configure for a new size, got by asking the compositor to maximize
// the window: its dispatch leaves the swapchain and the window's size
// alone and fires onFrameOwed, not onResize; the next Render() makes the
// swapchain and fires onResize once
// - the same under StartUpdate, when the window asks to be restored: with
// a configure unacknowledged the frame callbacks keep coming, and the
// frame of the next one takes the size and answers it, without a call
// to Render() from here. A compositor that held the callbacks back for
// the acknowledgement would stall every window that updates that way
// - the compositor raises no protocol error over any of it, and the
// validation layer no error (only with CRAFTER_GRAPHICS_VALIDATION set)
//
// The window is maximized for a moment, which shows. The compositor may
// configure the window at other moments too, and with other sizes than the
// test asked for (KWin configures a window at the size it has): the checks
// on the log hold for every configure, and the steps take the first size
// that comes. A compositor that configures no new size at all
// (one that tiles, or a phone's, where every window is maximized already)
// leaves the steps undriven, which the test reports as a SKIP line and not
// as a failure (for the step under StartUpdate it then holds the log to
// that: no configure for another size after the request); so it
// does for a driver whose buffers' sizes are not in the log, for a
// compositor without wp_viewporter, where a surface is as large as its
// buffer, and for the frame loop's step where the window gets no frame
// callbacks to begin with (a locked session, a screen that is off). The
// log is kept when a check fails.
//
// `ResizeViewport --keyboard` is the manual probe for a phone, and the case
// #199 was found in: it asks for text input (Window::SetTextInput) and takes
// it back three times, which brings the compositor's on-screen keyboard up
// and down, and where that resizes the window it holds every one of those
// resizes to the same checks. It needs the window to have the keyboard focus
// and the screen to be on and unlocked, exits 77 where no keyboard resized
// anything, and keeps its log, whose times say how long each resize took.
//
// Needs a live Wayland compositor and a Vulkan device.
#include <wayland-client.h>
#include <fcntl.h>
#include <unistd.h>
#include <cstdio>
#include <cstdlib>
#include "vulkan/vulkan.h"
#include "../../lib/xdg-shell-client-protocol.h"
import Crafter.Graphics;
import Crafter.Event;
import std;
using namespace Crafter;
namespace fs = std::filesystem;
namespace {
int failures = 0;
void Check(bool ok, std::string_view what) {
std::println("{} {}", ok ? "PASS" : "FAIL", what);
if (!ok) ++failures;
}
// stderr into `path` while it lives, where libwayland writes WAYLAND_DEBUG.
struct StderrTo {
int saved = -1;
explicit StderrTo(const fs::path& path) {
std::fflush(stderr);
const int file = open(path.c_str(), O_WRONLY | O_CREAT | O_TRUNC | O_CLOEXEC, 0600);
if (file < 0) return;
saved = dup(STDERR_FILENO);
dup2(file, STDERR_FILENO);
close(file);
}
~StderrTo() {
std::fflush(stderr);
if (saved < 0) return;
dup2(saved, STDERR_FILENO);
close(saved);
}
};
// A line the test writes into the log between libwayland's, with the
// window's scale at that moment.
void Mark(std::string_view name, float scale) {
std::println(stderr, "MARK {} {}", name, scale);
std::fflush(stderr);
}
// One line of WAYLAND_DEBUG:
// [03:13:48.807586] {Default Queue} -> wp_viewport#21.set_destination(229, 172)
// [03:13:48.807664] -> wl_surface#3.attach(wl_buffer#36, 0, 0)
// [03:13:48.905714] {Default Queue} xdg_toplevel#16.configure(0, 0, array[0])
// A request has the arrow, an event has not. Older libwayland writes no
// queue name and an `@` for the `#`, which reads the same here.
struct Message {
bool request = false;
std::string interface;
std::uint32_t id = 0;
std::string name;
std::vector<std::string> arguments;
};
std::optional<std::uint32_t> Number(std::string_view text) {
std::uint32_t value = 0;
const auto [end, error] = std::from_chars(text.data(), text.data() + text.size(), value);
if (error != std::errc() || end != text.data() + text.size()) return std::nullopt;
return value;
}
// The id of an object argument: "wl_buffer#36", "new id wl_buffer#36".
std::optional<std::uint32_t> ObjectId(std::string_view argument) {
const std::size_t mark = argument.find_last_of("#@");
if (mark == std::string_view::npos) return std::nullopt;
return Number(argument.substr(mark + 1));
}
std::optional<Message> Parse(std::string_view line) {
const std::size_t open = line.find('(');
const std::size_t close = line.rfind(')');
if (open == std::string_view::npos || close == std::string_view::npos || close < open) return std::nullopt;
const std::size_t space = line.rfind(' ', open);
const std::size_t start = space == std::string_view::npos ? 0 : space + 1;
const std::string_view target = line.substr(start, open - start);
const std::size_t mark = target.find_first_of("#@");
const std::size_t dot = target.rfind('.');
if (mark == std::string_view::npos || dot == std::string_view::npos || dot < mark) return std::nullopt;
const std::optional<std::uint32_t> id = Number(target.substr(mark + 1, dot - mark - 1));
if (!id) return std::nullopt;
Message message;
message.request = line.substr(0, start).find("->") != std::string_view::npos;
message.interface = target.substr(0, mark);
message.id = *id;
message.name = target.substr(dot + 1);
for (std::string_view rest = line.substr(open + 1, close - open - 1); !rest.empty();) {
const std::size_t comma = rest.find(", ");
message.arguments.emplace_back(rest.substr(0, comma));
if (comma == std::string_view::npos) break;
rest.remove_prefix(comma + 2);
}
return message;
}
struct Extent {
int width = 0;
int height = 0;
bool operator==(const Extent&) const = default;
};
// What one wl_surface.commit of the window's surface applied and left in
// effect, as the compositor has it.
struct Commit {
std::size_t line = 0; // in the log, from 1
bool attached = false; // this commit brought a buffer
std::optional<Extent> buffer; // the buffer in effect; empty when its size is not in the log
bool hasBuffer = false;
std::optional<Extent> destination; // the viewport's destination in effect
std::vector<std::uint32_t> acknowledged; // the configures this commit answers
};
// A configure of the window, as the compositor's two events gave it: the
// toplevel's size, surface-local and 0 for no preference, and the surface's
// serial.
struct Configure {
std::size_t line = 0;
std::uint32_t serial = 0;
Extent size;
};
struct Replay {
std::vector<Commit> commits;
std::vector<Configure> configures;
std::size_t requests = 0; // on the window's surface
std::vector<float> scales; // every scale the window had at a mark
std::map<std::string, std::size_t> marks; // the log line of each mark, the last of a name
};
// The window's objects, by their ids on the connection.
struct Objects {
std::uint32_t surface = 0;
std::uint32_t viewport = 0; // 0 without wp_viewporter
std::uint32_t xdgSurface = 0;
std::uint32_t xdgToplevel = 0;
};
// Replays `log` for the window's objects: the pending state each request
// sets, what each commit of the surface applies, and the configures that
// came in between.
Replay ReplayLog(const fs::path& log, const Objects& objects) {
Replay replay;
std::map<std::uint32_t, Extent> buffers; // wl_buffer id to its size, from the request that made it
std::vector<float>& scales = replay.scales;
Extent toplevelSize;
bool pendingAttach = false;
std::optional<Extent> pendingBuffer;
std::optional<Extent> pendingDestination;
std::vector<std::uint32_t> pendingAcknowledged;
Commit state;
std::ifstream file(log);
std::string text;
for (std::size_t number = 1; std::getline(file, text); ++number) {
if (text.starts_with("MARK ")) {
// "MARK <name> <scale>"
const std::size_t space = text.rfind(' ');
float scale = 0.0f;
const auto [end, error] = std::from_chars(text.data() + space + 1, text.data() + text.size(), scale);
if (error == std::errc() && scale > 0.0f && !std::ranges::contains(scales, scale)) scales.push_back(scale);
if (space > 5) replay.marks[text.substr(5, space - 5)] = number;
continue;
}
const std::optional<Message> message = Parse(text);
if (!message) continue;
const std::vector<std::string>& arguments = message->arguments;
const auto integer = [&](std::size_t index) -> std::optional<int> {
if (index >= arguments.size()) return std::nullopt;
int value = 0;
const auto [end, error] = std::from_chars(arguments[index].data(), arguments[index].data() + arguments[index].size(), value);
if (error != std::errc()) return std::nullopt;
return value;
};
if (!message->request) {
// The two events of a configure. Others are not the replay's.
if (message->interface == "xdg_toplevel" && message->id == objects.xdgToplevel && message->name == "configure") {
toplevelSize = { integer(0).value_or(0), integer(1).value_or(0) };
} else if (message->interface == "xdg_surface" && message->id == objects.xdgSurface && message->name == "configure") {
if (const auto serial = arguments.empty() ? std::nullopt : Number(arguments[0])) {
replay.configures.push_back({ number, *serial, toplevelSize });
}
}
continue;
}
// The requests that make a buffer and say how large: a dmabuf's, and
// a wl_shm pool's (llvmpipe).
if (message->interface == "zwp_linux_buffer_params_v1" && message->name == "create_immed" && arguments.size() >= 3) {
const auto id = ObjectId(arguments[0]);
const auto width = integer(1), height = integer(2);
if (id && width && height) buffers[*id] = { *width, *height };
} else if (message->interface == "wl_shm_pool" && message->name == "create_buffer" && arguments.size() >= 4) {
const auto id = ObjectId(arguments[0]);
const auto width = integer(2), height = integer(3);
if (id && width && height) buffers[*id] = { *width, *height };
} else if (message->interface == "wl_buffer" && message->name == "destroy") {
// Its id may name another buffer later; what a commit put in
// effect keeps its size.
buffers.erase(message->id);
} else if (objects.viewport != 0 && message->interface == "wp_viewport" && message->id == objects.viewport && message->name == "set_destination") {
const auto width = integer(0), height = integer(1);
if (width && height) pendingDestination = Extent{ *width, *height };
} else if (message->interface == "xdg_surface" && message->id == objects.xdgSurface && message->name == "ack_configure") {
if (const auto serial = arguments.empty() ? std::nullopt : Number(arguments[0])) pendingAcknowledged.push_back(*serial);
} else if (message->interface == "wl_surface" && message->id == objects.surface) {
++replay.requests;
if (message->name == "attach") {
pendingAttach = true;
pendingBuffer.reset();
const auto id = arguments.empty() ? std::nullopt : ObjectId(arguments[0]);
if (id && buffers.contains(*id)) pendingBuffer = buffers[*id];
} else if (message->name == "commit") {
state.line = number;
state.attached = pendingAttach;
if (pendingAttach) {
state.hasBuffer = true;
state.buffer = pendingBuffer;
}
if (pendingDestination) state.destination = pendingDestination;
state.acknowledged = std::move(pendingAcknowledged);
replay.commits.push_back(state);
pendingAttach = false;
pendingBuffer.reset();
pendingDestination.reset();
pendingAcknowledged.clear();
}
}
}
return replay;
}
// Whether `destination` is the size of `buffer` at `scale`, to within one
// surface-local pixel: the library rounds one up from the other, the
// destination from the pixels of a window the application sized, the pixels
// from the destination of one the compositor sized.
bool Belongs(Extent destination, Extent buffer, float scale) {
return std::abs(destination.width * scale - buffer.width) <= scale + 0.01f
&& std::abs(destination.height * scale - buffer.height) <= scale + 0.01f;
}
// As the configure listener turns a surface-local length into pixels.
std::uint32_t Pixels(std::int32_t logical, float scale) {
return static_cast<std::uint32_t>(std::ceil(logical * scale));
}
// Dispatches until `done`, for at most `limit`. False when the display fails.
template <class Done>
bool Pump(Done&& done, std::chrono::milliseconds limit) {
const auto until = std::chrono::steady_clock::now() + limit;
while (true) {
if (wl_display_roundtrip(Device::display) == -1) return false;
if (done() || std::chrono::steady_clock::now() >= until) return true;
std::this_thread::sleep_for(std::chrono::milliseconds(5));
}
}
// A roundtrip fails, and the display keeps the error, once the compositor
// has raised a protocol error over anything sent before it.
bool NoProtocolError() {
return wl_display_roundtrip(Device::display) != -1 && wl_display_get_error(Device::display) == 0;
}
// What the window's part of the test leaves for the log's replay.
struct Scenario {
Objects objects;
// --keyboard: how often a frame took a size the compositor configured
// after the keyboard was asked to come or go.
int keyboardResizes = 0;
// Set when the step under StartUpdate saw no configure leave a frame
// owed after the window asked to be restored: the surface's size at
// that moment. The log has to agree that the compositor asked for no
// other, or the window missed one.
std::optional<Extent> restoreUndriven;
};
// How often --keyboard brings the keyboard up and down.
constexpr int kKeyboardRounds = 3;
Scenario Drive(bool keyboard) {
Scenario scenario;
Window window(320, 240, "ResizeViewport test");
scenario.objects.surface = wl_proxy_get_id(reinterpret_cast<wl_proxy*>(window.surface));
scenario.objects.xdgSurface = wl_proxy_get_id(reinterpret_cast<wl_proxy*>(window.xdgSurface));
scenario.objects.xdgToplevel = wl_proxy_get_id(reinterpret_cast<wl_proxy*>(window.xdgToplevel));
if (window.wpViewport != nullptr) scenario.objects.viewport = wl_proxy_get_id(reinterpret_cast<wl_proxy*>(window.wpViewport));
Mark("window", window.scale);
bool inRender = false;
int resizesInRender = 0;
int resizesElsewhere = 0;
int owed = 0;
EventListener<void> resizeSub(&window.onResize, [&] { ++(inRender ? resizesInRender : resizesElsewhere); });
EventListener<void> owedSub(&window.onFrameOwed, [&] { ++owed; });
const auto render = [&](int frames) {
for (int i = 0; i < frames; ++i) {
inRender = true;
window.Render();
inRender = false;
}
Mark("frames", window.scale);
};
// The first frames, and whatever the compositor has to say of the new
// window (the decoration's configure, the scale).
render(Window::numFrames * 2);
if (!NoProtocolError()) {
Check(false, "no protocol error over the first frames");
return scenario;
}
render(1);
// The manual probe: a text field gets the focus and loses it again, and
// the compositor's keyboard resizes the window each time, where it is
// one that does. Each resize is a configure like any other: a commit
// that is no frame's, as a consumer makes one to ask for a frame
// callback, and then the frame.
if (keyboard) {
for (int round = 0; round < kKeyboardRounds; ++round) {
for (const bool up : { true, false }) {
const std::string mark = std::format("keyboard-{}-{}", up ? "up" : "down", round);
Mark(mark, window.scale);
window.SetTextInput(up, 0, static_cast<std::int32_t>(window.height) - 64, static_cast<std::int32_t>(window.width), 48);
if (!Pump([&] { return window.deferredLogicalWidth != 0; }, std::chrono::seconds(3))) {
Check(false, "the display answers after SetTextInput");
return scenario;
}
if (window.deferredLogicalWidth == 0) continue;
wl_surface_commit(window.surface);
render(Window::numFrames * 2);
++scenario.keyboardResizes;
}
}
Device::CheckVkResult(vkQueueWaitIdle(Device::queue));
Check(NoProtocolError(), "no protocol error over the keyboard's resizes");
return scenario;
}
// The application's own Resize, then a commit that is not a frame's, as
// a consumer makes one to ask for a frame callback, then the frames.
{
const std::uint32_t width = window.width + 80;
const std::uint32_t height = window.height + 60;
const std::uint64_t generation = window.swapchainGeneration;
const int resizesBefore = resizesElsewhere;
Mark("resize", window.scale);
window.Resize(width, height);
Check(window.width == width && window.height == height && window.swapchainGeneration != generation,
std::format("Resize outside a frame makes the swapchain at once ({}x{})", window.width, window.height));
Check(resizesElsewhere == resizesBefore + 1, "and fires onResize from the call");
wl_surface_commit(window.surface);
render(Window::numFrames * 2);
}
// A size from the compositor. Asking to be maximized gets one where the
// compositor has floating windows.
const std::uint32_t floatingWidth = window.width;
const std::uint32_t floatingHeight = window.height;
bool maximized = false;
{
const std::uint32_t widthBefore = window.width;
const std::uint32_t heightBefore = window.height;
const std::uint64_t generation = window.swapchainGeneration;
const int resizesBefore = resizesInRender + resizesElsewhere;
const int owedBefore = owed;
Mark("maximize", window.scale);
xdg_toplevel_set_maximized(window.xdgToplevel);
// A size that waits, or one already taken, which is what the check
// below is there to refuse.
const auto configured = [&] {
return window.deferredLogicalWidth != 0 || window.width != widthBefore || window.height != heightBefore;
};
if (!Pump(configured, std::chrono::seconds(3))) {
Check(false, "the display answers after set_maximized");
return scenario;
}
if (!configured()) {
std::println("SKIP the compositor configured no new size for set_maximized, so a configure's resize was not driven here");
} else {
maximized = true;
const std::int32_t logicalWidth = window.deferredLogicalWidth;
const std::int32_t logicalHeight = window.deferredLogicalHeight;
Check(window.width == widthBefore && window.height == heightBefore && window.swapchainGeneration == generation,
std::format("a configure for {}x{}: its dispatch leaves the window's size and the swapchain alone", logicalWidth, logicalHeight));
Check(resizesInRender + resizesElsewhere == resizesBefore, "onResize has not fired");
Check(owed > owedBefore, "onFrameOwed has");
Check(window.unackedConfigure.has_value(), "the configure waits for its frame");
// A consumer's request for a frame, as above.
wl_surface_commit(window.surface);
const int inRenderBefore = resizesInRender;
render(1);
Check(window.width == Pixels(logicalWidth, window.scale) && window.height == Pixels(logicalHeight, window.scale)
&& window.swapchainGeneration != generation,
std::format("the next Render() makes the swapchain at the configured size ({}x{})", window.width, window.height));
Check(window.logicalWidth == logicalWidth && window.logicalHeight == logicalHeight
&& (window.wpViewport == nullptr || (window.sentLogicalWidth == logicalWidth && window.sentLogicalHeight == logicalHeight)),
std::format("and the surface's size is the configured one ({}x{})", window.logicalWidth, window.logicalHeight));
Check(resizesInRender == inRenderBefore + 1 && resizesElsewhere + resizesInRender == resizesBefore + 1,
"and fires onResize once, from inside it");
Check(!window.unackedConfigure && window.deferredLogicalWidth == 0 && window.presentedGeneration == window.swapchainGeneration,
"after that frame nothing is owed");
render(Window::numFrames * 2);
}
}
// Back, so the window is not left filling the screen, and this time
// under the frame loop the examples run: StartUpdate's frame callbacks
// call Update, and nothing here calls Render(). The compositor's size
// for the restored window has to be taken, and its configure answered,
// by the frame of the next callback: a compositor that kept the
// callbacks back until its configure was acknowledged would leave the
// two waiting for each other.
if (maximized) {
// The frames the loop draws, and those of them drawn once the
// swapchain has been made again.
std::uint64_t generation = window.swapchainGeneration;
int loopFrames = 0;
int framesAfterRebuild = 0;
EventListener<FrameTime> updateSub(&window.onUpdate, [&](FrameTime) {
++loopFrames;
if (window.swapchainGeneration != generation) ++framesAfterRebuild;
});
window.StartUpdate();
// The request for the first callback is surface state: a commit
// applies it. Each frame's present applies the next.
wl_surface_commit(window.surface);
// The callbacks have to be coming before the configure for their
// going on after it to say anything. A window that is not being
// shown gets none (a locked session, a screen that is off), and
// then its configure waits until it is, by design. And nothing may
// be waiting when the step starts to count: a size the compositor
// configured in the meantime (see the top of the file) is the
// loop's to take first, or its rebuild would be counted against the
// configure the step is about.
bool connected = Pump([&] { return loopFrames >= Window::numFrames && window.deferredLogicalWidth == 0 && !window.unackedConfigure; },
std::chrono::seconds(2));
const bool shown = loopFrames >= Window::numFrames;
// From here: what the first onFrameOwed finds, which is nothing
// rebuilt yet. The loop may have taken a size already, so this is
// where the step starts counting.
const std::uint32_t widthBefore = window.width;
const std::uint32_t heightBefore = window.height;
const Extent surfaceBefore{ window.logicalWidth, window.logicalHeight };
const int resizesBefore = resizesInRender + resizesElsewhere;
generation = window.swapchainGeneration;
framesAfterRebuild = 0;
bool owedHere = false;
bool untouchedAtOwed = false;
EventListener<void> owedAtRestore(&window.onFrameOwed, [&] {
if (owedHere) return;
owedHere = true;
untouchedAtOwed = window.width == widthBefore && window.height == heightBefore && window.swapchainGeneration == generation
&& resizesInRender + resizesElsewhere == resizesBefore;
});
if (connected) {
Mark("restore", window.scale);
xdg_toplevel_unset_maximized(window.xdgToplevel);
connected = shown
? Pump([&] { return framesAfterRebuild >= Window::numFrames && !window.unackedConfigure; }, std::chrono::seconds(3))
: Pump([&] { return window.deferredLogicalWidth != 0; }, std::chrono::seconds(1));
}
window.StopUpdate();
Mark("restored", window.scale);
if (!connected) {
Check(false, "the display answers after unset_maximized");
return scenario;
}
if (!shown) {
std::println("SKIP the compositor sends this window no frame callbacks (is the session locked, or the screen off?), so the frame loop was not driven here");
// The frames below take the size the compositor restored, or
// else the one the window had.
if (window.deferredLogicalWidth == 0) window.Resize(floatingWidth, floatingHeight);
} else if (!owedHere) {
std::println("SKIP the compositor configured no size for unset_maximized, so the frame loop had no configure to answer here");
scenario.restoreUndriven = surfaceBefore;
// The size is the window's to choose then: the one it had.
window.Resize(floatingWidth, floatingHeight);
} else if (window.swapchainGeneration == generation && !window.unackedConfigure && window.deferredLogicalWidth == 0) {
std::println("SKIP the compositor took its size back before a frame, so the frame loop had no configure left to answer here");
} else {
Check(untouchedAtOwed, "under StartUpdate, a configure for a new size: at onFrameOwed nothing has been rebuilt");
Check(window.swapchainGeneration != generation && (window.width != widthBefore || window.height != heightBefore),
std::format("the loop's next frame takes the size, with no call from here ({}x{})", window.width, window.height));
Check(framesAfterRebuild >= Window::numFrames, std::format("and the frame callbacks keep coming ({} frames since)", framesAfterRebuild));
Check(!window.unackedConfigure && window.presentedGeneration == window.swapchainGeneration,
"after those frames no configure waits for an answer");
}
render(Window::numFrames * 2);
}
Device::CheckVkResult(vkQueueWaitIdle(Device::queue));
Check(NoProtocolError(), "no protocol error over the resizes");
return scenario;
}
} // namespace
int main(int argc, char** argv) {
const bool keyboard = argc > 1 && std::string_view(argv[1]) == "--keyboard";
const fs::path log = fs::temp_directory_path() / std::format("crafter-resize-viewport-{}.log", getpid());
// Read when the display connects, in Device::Initialize. libwayland
// colours the log when FORCE_COLOR says so, also into a file, and the
// replay reads plain text.
setenv("WAYLAND_DEBUG", "1", 1);
unsetenv("FORCE_COLOR");
setenv("NO_COLOR", "1", 1);
Scenario scenario;
std::optional<std::string> thrown;
{
StderrTo redirect(log);
try {
Device::Initialize();
Device::validationErrorCount = 0;
scenario = Drive(keyboard);
if (Device::display != nullptr) wl_display_flush(Device::display);
} catch (const std::exception& error) {
thrown = error.what();
}
}
if (thrown) {
std::println("FAIL the run threw: {}", *thrown);
std::println(" the log is {}", log.string());
return EXIT_FAILURE;
}
if (std::getenv("CRAFTER_GRAPHICS_VALIDATION") != nullptr) {
Check(Device::validationErrorCount == 0,
std::format("no Vulkan validation errors ({} seen)", Device::validationErrorCount));
}
const Replay replay = ReplayLog(log, scenario.objects);
Check(replay.requests != 0 && !replay.commits.empty(),
std::format("the WAYLAND_DEBUG log has the surface's requests ({} of them, {} commits)", replay.requests, replay.commits.size()));
// Every commit: is the destination in effect the buffer's own?
std::size_t compared = 0;
std::size_t wrong = 0;
std::set<std::pair<int, int>> sizesShown;
for (const Commit& commit : replay.commits) {
if (!commit.hasBuffer || !commit.buffer || !commit.destination) continue;
++compared;
sizesShown.insert({ commit.buffer->width, commit.buffer->height });
// At any scale the window had: a scale that changes between two
// marks is not placed more closely than that.
const bool belongs = std::ranges::any_of(replay.scales, [&](float scale) { return Belongs(*commit.destination, *commit.buffer, scale); });
if (belongs) continue;
if (wrong++ < 5) {
std::println(" log line {}: a commit{} shows the {}x{} buffer at {}x{}", commit.line, commit.attached ? "" : " without a buffer",
commit.buffer->width, commit.buffer->height, commit.destination->width, commit.destination->height);
}
}
if (scenario.objects.viewport == 0) {
std::println("SKIP the compositor offers no wp_viewporter: a surface is as large as its buffer, and there is no destination to check");
} else if (compared == 0) {
std::println("SKIP the log has no buffer whose size it gives, so no commit could be checked against its destination");
} else {
Check(wrong == 0, std::format("at each of {} commits the destination in effect is the size of the buffer in effect ({} are not)", compared, wrong));
// A --keyboard run on a compositor without one resizes nothing.
if (!keyboard || scenario.keyboardResizes != 0) {
Check(sizesShown.size() >= 2, std::format("and the surface showed buffers of {} sizes over the run", sizesShown.size()));
}
}
// Every acknowledgement: the commit that carries it says "this answers
// the configure", so the buffer in effect with it has to be of the size
// that configure asked for, to within the pixel the rounding of the
// scale may add, and the destination in effect has to be that size
// itself: the surface's size is the compositor's to give, and the
// destination used to be worked back from the buffer's pixels, to
// more than was configured where the scale does not divide them
// (#201). For a new size that is the frame's commit; where
// the surface has the size already it is the listener's own. A
// configure without a size asks for none, and before the window's
// first frame there is no buffer to hold to it.
std::size_t acknowledged = 0;
std::size_t misplaced = 0;
std::size_t sized = 0;
std::size_t missized = 0;
for (const Commit& commit : replay.commits) {
for (const std::uint32_t serial : commit.acknowledged) {
const auto asked = std::ranges::find(replay.configures, serial, &Configure::serial);
if (asked == replay.configures.end()) {
Check(false, std::format("log line {}: the acknowledged configure {} is in the log", commit.line, serial));
continue;
}
if (asked->size.width <= 0 || asked->size.height <= 0 || !commit.hasBuffer || !commit.buffer) continue;
if (commit.destination) {
++sized;
if (*commit.destination != asked->size && missized++ < 5) {
std::println(" log line {}: configure {} for {}x{} is acknowledged by a commit that leaves the surface at {}x{}", commit.line, serial,
asked->size.width, asked->size.height, commit.destination->width, commit.destination->height);
}
}
++acknowledged;
const bool fits = std::ranges::any_of(replay.scales, [&](float scale) {
return std::abs(commit.buffer->width - asked->size.width * scale) <= 1.0f
&& std::abs(commit.buffer->height - asked->size.height * scale) <= 1.0f;
});
if (fits) continue;
if (misplaced++ < 5) {
std::println(" log line {}: configure {} for {}x{} is acknowledged by a commit{} that leaves the {}x{} buffer in effect", commit.line,
serial, asked->size.width, asked->size.height, commit.attached ? "" : " without a buffer", commit.buffer->width,
commit.buffer->height);
}
}
}
if (acknowledged == 0) {
std::println("SKIP the compositor configured no size once the window had a buffer, so no acknowledgement could be held to one");
} else {
Check(misplaced == 0, std::format("each of {} acknowledgements of a size is committed with a buffer of that size in effect ({} are not)",
acknowledged, misplaced));
if (sized != 0) {
Check(missized == 0, std::format("and each of {} with that size itself as the surface's, the destination in effect ({} are not)", sized, missized));
}
}
// The step under StartUpdate that found nothing to answer: between the
// window's request to be restored and the end of the step, the log must
// have no configure for another size than the surface had. One there
// would have left a frame owed, and the step would have seen it.
if (scenario.restoreUndriven) {
const auto from = replay.marks.find("restore");
const auto to = replay.marks.find("restored");
std::size_t sent = 0;
std::size_t missed = 0;
if (from != replay.marks.end() && to != replay.marks.end()) {
for (const Configure& configure : replay.configures) {
if (configure.line <= from->second || configure.line >= to->second) continue;
++sent;
if (configure.size.width <= 0 || configure.size.height <= 0 || configure.size == *scenario.restoreUndriven) continue;
++missed;
std::println(" log line {}: configure {} for {}x{} came after the window asked to be restored", configure.line, configure.serial,
configure.size.width, configure.size.height);
}
}
Check(from != replay.marks.end() && to != replay.marks.end() && missed == 0,
std::format("the log agrees: after the window asked to be restored no configure asked for another size than its {}x{} ({} came)",
scenario.restoreUndriven->width, scenario.restoreUndriven->height, sent));
}
if (keyboard) {
std::println("the keyboard resized the window {} times in {} rounds", scenario.keyboardResizes, kKeyboardRounds);
if (scenario.keyboardResizes == 0 && failures == 0) {
std::println("SKIP no on-screen keyboard resized the window: nothing of --keyboard was driven");
std::error_code ignored;
fs::remove(log, ignored);
return 77;
}
}
if (failures != 0) {
std::println("{} check(s) failed", failures);
std::println("the log is {}", log.string());
return EXIT_FAILURE;
}
if (keyboard) {
std::println("the log is {}", log.string());
} else {
std::error_code ignored;
fs::remove(log, ignored);
}
std::println("all checks passed");
return EXIT_SUCCESS;
}

View file

@ -17,10 +17,10 @@
// large as its buffer, so surface-local pointer positions and configure
// sizes are already physical pixels;
// - the window renders, resizes, renders again and closes, and the
// compositor raises no protocol error over any of it. Resize sets the
// viewport's destination only when there is a viewport; the new size
// itself is not checked, since Resize stores it before it does anything
// else.
// compositor raises no protocol error over any of it. The first
// frame at a size sets the viewport's destination only when there is a
// viewport; the new size itself is not checked, since Resize stores it
// before it does anything else.
//
// The test hides the globals the compositor offers: it nulls the Device
// statics between Initialize and the Window, which is the state a compositor