From 61f2698d13559267466f154b35dbe72e02b5513c Mon Sep 17 00:00:00 2001 From: Jorijn van der Graaf Date: Fri, 27 Nov 2026 10:07:37 +0100 Subject: [PATCH] fix(wayland): take a new preferred scale at a frame boundary, and convert input with the scale the window draws at xdg_surface_handle_preferred_scale set Window::scale and did nothing else (#165). The buffers' size and the surface's follow the scale only where the window works one out from the other, which it did when it made a swapchain and when a frame took a configured size. So a scale that changed by itself, with no configure (the issue's case is a window moved to an output of another scale), reached them only at the next of those, and until then the window drew at the old scale. The pointer's and the touches' positions are turned into pixels with Window::scale, and the text input's caret back into surface-local units with it, so those were converted with the new scale while the frames were still drawn at the old one. The issue suggests making the swapchain again in the listener. That predates 89111e0, which moved the configure's rebuild out of its listener into Render() for #199 and #200; the scale takes the same way. Window: the listener keeps the scale in a new member, preferredScale, as wp_fractional_scale_v1 sends it, in 120ths, and Window::scale is the scale the window draws at. MatchSizesToScale, where the window works out the size it was not given from the one it was, sets it from preferredScale where it takes a new scale, and nothing else in the library sets it. TakeDeferredSize takes a preferredScale that is not the scale the window draws at, at a frame boundary of Render(), as it takes a configured size, and with one where one waits. A window the compositor sized keeps its surface's size and takes the pixels for it at the new scale, so Render() makes the swapchain again there and onResize fires where those pixels differ. One the application sized keeps its pixels and makes no swapchain, and its surface takes the size they come to at the new scale, which the next frame sends with its buffer (SendFrameSurfaceState). Before the start of the next frame the scale is taken only with a swapchain made where it gives the window new pixels: a window the compositor sized whose surface comes to other pixels at it, as after a present or with the swapchain a SetPresentMode makes outside a frame. Anywhere else it would change only the conversions and the size the surface is to take, which goes out with the next frame, and until that frame's commit the compositor maps the surface, and the pointer and the touches on it, by the destination it has: a click in between would be converted for a frame not drawn yet, landing where the new scale puts it on the one drawn at the old scale, and the onResize of a swapchain made for another reason at the pixels the window has would not tell the application of the scale. So a scale that leaves the pixels as they are waits for the start of the next frame (for a window the application sized, whose pixels are its own, and one the compositor sized that it leaves at its pixels), also where a present mode, a rebuild that waited or a Resize makes a swapchain before then, and so does a configured size that comes to the pixels the window has with it (an output's scale changed under a window that fills it). TakeDeferredSize and RebuildIfDeferred are told which of the two boundaries they run at (FrameBoundary), and MatchSizesToScale whether it takes the scale whatever it does to the pixels (takeScale), as at a frame's start and in the constructor. The listener sends no request and makes no Vulkan call, so the window goes on drawing at the old scale, and converting with it, until then; a scale that a listener of a frame dispatched is taken at the boundary after its present where it gives the window new pixels, and at the start of the next frame otherwise. From the window's first swapchain on, the listener fires onFrameOwed where the scale is not the one the window draws at, so that a window that draws on demand learns that a frame is owed, as it does from a configure; for a window the application sized no onResize comes. Before the first swapchain the listener only keeps the scale, which the constructor takes before it makes the swapchain, as it did. A scale of 0, with which no size can be worked out, is not taken. Where MatchSizesToScale changes the scale, it takes what the window holds in pixels of the scale before to the new one: currentMousePos, lastMousePos and mouseDelta, and the touch slots of the window's fingers. The compositor gives those in surface-local units and sends nothing for a pointer or a finger that rests, so a pointer resting over the window would otherwise stand at the old scale's pixels in the frames drawn at the new one until it moved, and the next delta would be the change of grid. The pointer's position as the compositor gave it is kept beside, in surface-local units, in a new member, surfaceMousePos, which no scale moves. And it sends the caret SetTextInput was given again, converted with the new scale, as the window does when the keyboard focus comes back: for a window the application sized, the surface changes size around pixels that stay, and the rectangle the input method holds would otherwise stay in the old units. The configure listener's test for a configure at the size the window has compares the buffers with the pixels for that size at preferredScale, the scale the frame takes with the size, as it compared them at Window::scale while the listener set that. While a new scale waits it finds no configure at the size the window has: one for the size the surface has waits for the frame that takes the scale and takes its size with it, so that the window is not made one the compositor sized while it draws at the scale before, at pixels that are not that size's at the scale it draws at. Input: Map took its delta for MouseDeltaBind from currentMousePos and a last position of its own, which the window's conversion does not reach, so a pointer that rests would read the change of grid as a delta at the Map's next Tick, which a camera bound to MouseDeltaBind turns by. On Wayland it takes it from surfaceMousePos, as the surface-local motion since its last Tick in the window's pixels of now: none for a pointer that rests, whatever scales the window took in between, where a last position taken along to each new scale would come back with a float residue through two of them. A position the application writes into currentMousePos itself does not reach it there. Device: the pointer's and the touches' handlers keep the position the compositor gave in surfaceMousePos (the first finger's for the pointer it stands in for), and touch_down, touch_motion and an enter's move work it into the pixels they store with the scale in force at the store. They store after listeners, of onTouchDown, onTouchMove and onMouseEnter, that may take a new scale (a SetPresentMode outside a frame for a window the compositor sized, the Render() of a frame callback one of them dispatched), and a position worked out before those listeners would be in the pixels of the scale before. The conversions read Window::scale, which is now the scale of the frames drawn since the boundary that took it. Docs: the README, the consumer notes and the guide's gotchas say what scale and preferredScale are and when a scale is taken; the first two said that scale could be newer than the sizes (#165). The README, the consumer notes and the comment on SetTextInput say what goes to the new scale with it, and that the caret is sent again; the consumer notes name surfaceMousePos, the Map's delta from it, and that a position the application writes into currentMousePos does not reach the Map. The bug-prover lens section names preferredScale as what changes in any dispatch, and the scale among what waits for a frame boundary, and that before the next frame's start it is taken only where it gives the window new pixels; the consumer notes, that a size configured during a frame waits with a new scale where the two come to the pixels the window has. Tests: ConfigureResize names the scale in 120ths, as the compositor does, and drives the scale's listener on a window whose surfaces are proxies. The listener sends nothing, leaves the scale and both sizes as they are, and fires onFrameOwed. Until a frame boundary takes the scale, a pointer motion to the surface's middle is at the middle of the buffers drawn at the scale before, and so is a finger that goes down there on the window the application sized; a caret given in the pixels of the window the compositor sized goes to a text input proxy converted with that scale. The next boundary takes it: a window the compositor sized keeps 400x300 and goes from 800x600 to 600x450 pixels at 1.5, which makes the swapchain, and its surface is sent nothing; one the application sized keeps its 640x480 pixels and makes no swapchain, and its surface goes from 320x240 to 640x480 at 1, sent with the frame. After it the motion, the finger's move and the caret are converted with the new scale. And before any new motion or call, the boundary has taken what the window held to the new scale: the pointer of the window the compositor sized is at the middle of the new buffers, the one the first finger stands in for on the other window is where its surface-local place comes to, a second finger that went down before the boundary lifts after it where its surface-local place comes to, and each boundary sends the caret again, converted, with no SetTextInput. An Input::Map attached to the window and ticked across a boundary that takes 1.5 reads no delta for a pointer that rests, and a motion of 10 units after it as 15 pixels; ticked across two boundaries between two Ticks on a window the compositor sized, 1.75 taken by a swapchain made outside a frame at the pixels it gives the window and 1 again by a frame's start, with the pointer resting at surface 100.25, it reads no delta and fires no event. On a window the compositor sized, a listener of onTouchDown, of onTouchMove and of onMouseEnter that takes a scale that waits has the click the finger stands in for, the finger's move and the move after the enter in the pixels of that scale. A scale that comes back before a frame owes nothing; one that comes while a frame is being recorded leaves that frame at the scale it began with, and the window the compositor sized takes it at the boundary after the present, with its new pixels, where the one the application sized takes it at the next frame's start: the boundary after the present takes nothing, a motion after it is still at the pixels of the frame on screen, and the caret is sent again only at the next frame's start (the fixture steps the boundary after the present, End, apart from the next frame's start, Begin); a configure that comes with it to the pixels the window has waits for that start as well, which takes the two together, the frame bringing the surface its size and the acknowledgement, and so does a scale that leaves a small window the compositor sized at its pixels; a configure without a size while a scale waits is acknowledged in the listener, and one for the size the surface has waits for the frame that takes the scale, also where its pixels at that scale are the window's (101x101 pixels at 2, a surface of 51x51, a scale of 237/120); before the first swapchain the listener only keeps the scale, which MatchSizesToScale takes, and a scale of 0 is not taken. In the cases there were, the check that nothing is owed counts a scale that waits as well, the frame whose scale changes while it is recorded is followed to the boundary that takes it, a swapchain made between frames is checked to leave no scale waiting for a window the compositor sized, and for one the application sized to take none, a motion until the next frame's start landing at the pixels of the frame on screen, also where the swapchain is made after a present that found it out of date, with a configure that comes with the scale to the window's pixels waiting too, and the case of a scale and then a configure counts onFrameOwed for both. ResizeViewport drives the scale against the compositor, where it has the fractional scale and the viewporter: on its window as the application sized it, and maximized where the compositor configures a size for that, it calls the listener with a scale the window does not draw at and then with the compositor's own. Each time it checks that the listener rebuilds nothing and fires onFrameOwed, that the next Render() takes the scale, with no swapchain and no onResize for the application's size and with a new swapchain and one onResize from inside Render() for the maximized one, and that a pointer motion to the surface's middle is at the buffers' middle, to within the rounding of one size from the other, before that Render() and after it, and that the pointer, resting across that Render(), is where its surface-local place comes to at the new scale. The log's checks hold each of those commits to its buffer at the scales the marks name. --- .review-gates/lenses/repo-bug-prover.md | 22 +- AGENTS.consumer.md | 6 +- AGENTS.template.md | 6 +- README.md | 24 +- implementations/Crafter.Graphics-Device.cpp | 32 +- implementations/Crafter.Graphics-Input.cpp | 17 + implementations/Crafter.Graphics-Window.cpp | 187 ++++- interfaces/Crafter.Graphics-Input.cppm | 9 + interfaces/Crafter.Graphics-Window.cppm | 108 ++- tests/ConfigureResize/main.cpp | 732 ++++++++++++++++++-- tests/ResizeViewport/main.cpp | 118 +++- 11 files changed, 1110 insertions(+), 151 deletions(-) diff --git a/.review-gates/lenses/repo-bug-prover.md b/.review-gates/lenses/repo-bug-prover.md index 58377e2..f6bcd45 100644 --- a/.review-gates/lenses/repo-bug-prover.md +++ b/.review-gates/lenses/repo-bug-prover.md @@ -31,9 +31,16 @@ The execution contexts to enumerate, beside the charter's: 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 + dispatched it, after its present, and so does a scale the compositor + asks for by itself, which is taken before the start of the next frame + only with a swapchain made where it gives the window new pixels, and + otherwise waits, with a size configured with it that comes to the + pixels the window has, for that start, the frame drawn at it bringing + the surface any new size it is to take. The swapchain is made again + there, and `onResize` + fires, only where the size or the scale changes the pixels, which a + size and a scale that change together need not, nor a new scale for a + window the application sized; 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. @@ -50,9 +57,12 @@ The execution contexts to enumerate, beside the charter's: `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. + compositor's preferred scale (`Window::preferredScale`) changes in any + dispatch: between a configure and the frame that takes its size, and in + the middle of a frame. `Window::scale`, which the pointer, the touches + and the caret are converted with, follows it only in the constructor, + before the first swapchain, at a frame boundary of `Render()`, and with + a swapchain made at the pixels it gives the window. 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` diff --git a/AGENTS.consumer.md b/AGENTS.consumer.md index 8a0dbe5..b9a0dbe 100644 --- a/AGENTS.consumer.md +++ b/AGENTS.consumer.md @@ -31,9 +31,9 @@ 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`) 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). +- 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, unless it comes with a new scale to the pixels the window has: then both wait for the next `Render()`, see below.) 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`) fires from the configure, after `onToplevelState`, whenever the configure leaves a frame owed, and from a scale the compositor asks for by itself (below), 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 scale the window draws at, its buffers' pixels per surface-local unit (1 where the compositor has no `wp_fractional_scale_v1` or no `wp_viewporter`), which the pointer's and the touches' positions are turned into pixels with and the caret `SetTextInput` gives is turned back into surface-local units with; `preferredScale` is the scale the compositor asked for last, in 120ths as `wp_fractional_scale_v1` sends it (120 is 1). The two sizes are worked out from one another only when a size or a scale is taken at a frame boundary of `Render()` and when a swapchain is made, where `preferredScale` becomes `scale` as below, so while a frame is being recorded `scale` is the one the two sizes were worked out with, and from a new scale to the boundary that takes it only `preferredScale` has it. 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 the compositor asks for by itself, with no configure (#165's case is a window moved to an output of another scale), is taken at the start of the next `Render()`, and sooner only with a swapchain made where it gives the window new pixels (a window the compositor sized whose surface comes to other pixels at it); one named before the window's first swapchain is taken by the constructor. From the window's first swapchain on `onFrameOwed` fires at it where it is not the scale the window draws at (#165). A window the compositor sized keeps its surface's size and takes the pixels for it at the new scale, so the swapchain is made again where they differ and `onResize` fires; one the application sized keeps its pixels, nothing is rebuilt and `onResize` does not fire, and its surface takes the size those pixels come to at the new scale with that frame. Anywhere else a scale would change only the conversions, a frame before the surface's size, which the compositor maps the pointer and the touches by until that frame's commit, so it waits for the next `Render()`'s start, a swapchain made for another reason (a present mode, a `Resize`) notwithstanding, and a size configured with it that comes to the pixels the window has waits with it. Until it is taken the window draws at the scale before and converts the pointer, the touches and the caret with that one; where it is taken, the positions the window holds (`currentMousePos`, `lastMousePos`, `mouseDelta`, the fingers down) go to the new scale, `surfaceMousePos`, the pointer's position as the compositor gave it in surface-local units, stays where it is, and an `Input::Map` attached to the window takes its delta from that, so that neither delta jumps (a position the application writes into `currentMousePos` itself does not reach the Map), and the caret goes to the input method again, converted. - 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, hints)` tells the compositor's input method a text field has focus, which opens an on-screen keyboard on a phone. `purpose` is what the field holds (`TextInputPurpose::Normal`, `Alpha`, `Digits`, `Number`, `Phone`, `Url`, `Email`, `Name`, `Password`, `Pin`, `Date`, `Time`, `Datetime`, `Terminal`), by which the keyboard picks its layout, and `hints` how it treats what is typed (`kTextInputHintCompletion`, `Spellcheck`, `AutoCapitalization`, `Lowercase`, `Uppercase`, `Titlecase`, `HiddenText`, `SensitiveData`, `Latin`, `Multiline`, or-ed together). Without `hints` a field gets `TextInputDefaultHints(purpose)`: completion, spellcheck and capitals for `Normal`, hidden and not learnt for `Password` and `Pin`, none for the rest; `kTextInputHintNone` asks for none. Name the purpose of every field that is not prose. Call it again when the caret moves, with the same purpose and hints. A call that changes either while a field has focus tells the input method the focus moved to another field (it enables anew), which ends the composition under way without an `onPreedit`, as `SetTextInput(false)` does, so commit or drop your composing text first. A move to another field of the same purpose and hints looks to the window like a caret that moved and sends no enable: call `SetTextInput(false)` before the new field's `SetTextInput(true, ...)`. The input method's changes come in batches (text-input-v3's `done`), each fired as `onTextInputDelete`, `onTextInput` and `onPreedit` in that order, and the batches in the order they arrived: one that arrives while a listener of another is running (the listener made a `Window` or called `Clipboard::GetText`, which dispatch the events) waits until that one is through. Only these wait: a key, pointer or touch event the same dispatch brings fires at once, before a batch that waits. +- `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, hints)` tells the compositor's input method a text field has focus, which opens an on-screen keyboard on a phone. `purpose` is what the field holds (`TextInputPurpose::Normal`, `Alpha`, `Digits`, `Number`, `Phone`, `Url`, `Email`, `Name`, `Password`, `Pin`, `Date`, `Time`, `Datetime`, `Terminal`), by which the keyboard picks its layout, and `hints` how it treats what is typed (`kTextInputHintCompletion`, `Spellcheck`, `AutoCapitalization`, `Lowercase`, `Uppercase`, `Titlecase`, `HiddenText`, `SensitiveData`, `Latin`, `Multiline`, or-ed together). Without `hints` a field gets `TextInputDefaultHints(purpose)`: completion, spellcheck and capitals for `Normal`, hidden and not learnt for `Password` and `Pin`, none for the rest; `kTextInputHintNone` asks for none. Name the purpose of every field that is not prose. Call it again when the caret moves, with the same purpose and hints; on Wayland the window sends the caret it holds again, converted, when its scale changes, and a caret that the new scale moves in pixels is one that moved. A call that changes either while a field has focus tells the input method the focus moved to another field (it enables anew), which ends the composition under way without an `onPreedit`, as `SetTextInput(false)` does, so commit or drop your composing text first. A move to another field of the same purpose and hints looks to the window like a caret that moved and sends no enable: call `SetTextInput(false)` before the new field's `SetTextInput(true, ...)`. The input method's changes come in batches (text-input-v3's `done`), each fired as `onTextInputDelete`, `onTextInput` and `onPreedit` in that order, and the batches in the order they arrived: one that arrives while a listener of another is running (the listener made a `Window` or called `Clipboard::GetText`, which dispatch the events) waits until that one is through. Only these wait: a key, pointer or touch event the same dispatch brings fires at once, before a batch that waits. - 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. - On Wayland and Win32 a `Window` constructor that throws (a Vulkan error, or a surface that offers no format the swapchain can be written through as a storage image) leaves nothing of the window behind (#169): the destructor has run for what it had made by the time the exception reaches you, so on Wayland the window is not in `Device::windows` and its Wayland objects are destroyed, on Win32 its HWND is, and on both so is its Vulkan surface. The error can be caught and the program go on. @@ -130,7 +130,7 @@ Heap-only: check `Device::rayTracingSupported`, or expect `std::runtime_error` f ### Input -- `Window` events, `Event` 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`: whole detents, reinterpret the payload as `int32`, positive is wheel down, every backend normalised to one per notch), `onRawKeyDown`, `onRawKeyHold`, `onRawKeyUp` (`Event`, raw platform codes; `heldKeys`), `onTextInput` (`Event`, UTF-8; repeats are synthesised on Wayland), `onPreedit` and `onTextInputDelete` (input methods), `onTouchDown`, `onTouchMove`, `onTouchUp` (`Event`; the first finger also drives the pointer events), `onClose`, `onResize`, `onBeforeUpdate`, `onUpdate` (`Event`: `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". +- `Window` events, `Event` 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`: whole detents, reinterpret the payload as `int32`, positive is wheel down, every backend normalised to one per notch), `onRawKeyDown`, `onRawKeyHold`, `onRawKeyUp` (`Event`, raw platform codes; `heldKeys`), `onTextInput` (`Event`, UTF-8; repeats are synthesised on Wayland), `onPreedit` and `onTextInputDelete` (input methods), `onTouchDown`, `onTouchMove`, `onTouchUp` (`Event`; the first finger also drives the pointer events), `onClose`, `onResize`, `onBeforeUpdate`, `onUpdate` (`Event`: `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 or a new scale 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. - On Wayland a key's `onTextInput` comes from the compositor's keymap. Without one that loaded, keys still fire `onRawKeyDown` and `onRawKeyUp`, without text; a keymap that does not load, such as one of the `no_keymap` format or one the libxkbcommon the application runs with cannot compile, is ignored and leaves the one there was. `Device::xkb_keymap` and `Device::xkb_state` are that keymap and its state, for reading keysyms or modifiers yourself (the XKB keycode is the `KeyCode` plus 8): null until a keymap loads, and freed when the next one loads, so read them at each use and check for null. - `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. diff --git a/AGENTS.template.md b/AGENTS.template.md index 7b5a7b6..fdc5176 100644 --- a/AGENTS.template.md +++ b/AGENTS.template.md @@ -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/.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`, `InputTime` and `KeyboardKeymap` drive the Wayland listener callbacks directly (`KeyboardKeymap` with keymaps in memfds, each case in a child process), `TitleWayland` reads the requests a window sends off a `wl_display` connected to a socketpair, `TextInputContent` reads the text input's the same way and feeds its callbacks, 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. +- 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`, `InputTime` and `KeyboardKeymap` drive the Wayland listener callbacks directly (`KeyboardKeymap` with keymaps in memfds, each case in a child process), `TitleWayland` reads the requests a window sends off a `wl_display` connected to a socketpair, `TextInputContent` reads the text input's the same way and feeds its callbacks, 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; and for a scale the compositor asks for by itself (#165), which frame boundary takes it, and where a pointer motion, a touch and a caret land before and after. - 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), `WindowConstructorThrow` (fails the swapchain's capabilities query inside a window's constructor through `Device::vkGetPhysicalDeviceSurfaceCapabilities2KHR`, and finds the failed window's destroy requests in a `WAYLAND_DEBUG` log, as `ResizeViewport` reads its log), `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` and `WindowConstructorThrow` the connection's log. +- 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), `WindowConstructorThrow` (fails the swapchain's capabilities query inside a window's constructor through `Device::vkGetPhysicalDeviceSurfaceCapabilities2KHR`, and finds the failed window's destroy requests in a `WAYLAND_DEBUG` log, as `ResizeViewport` reads its log), `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`, a configured size, got by maximizing its window for a moment, and a scale, given by calling the fractional scale's listener, 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` and `WindowConstructorThrow` the connection's log. Conventions the existing tests follow: @@ -146,7 +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`. +- 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`, the scale the window draws at, ties them only where one is worked out from the other: when a configured size or a new scale is taken at a frame boundary and before every swapchain (`MatchSizesToScale`, which is also where `preferredScale`, the compositor's last word, becomes `scale`). The pointer, the touches and the caret are converted with `scale`, so it changes there and nowhere else (#165): in the constructor and at the start of a frame, and elsewhere only where it gives the window new pixels (`MatchSizesToScale`'s `takeScale`, `TakeDeferredSize`'s `FrameBoundary`). Once the window has its first swapchain, a new scale that leaves the pixels as they are, alone, with a configured size or with a swapchain made for another reason, waits for the next frame's start, as the compositor maps the surface, and the input on it, by the destination it has until that frame's commit. Nothing works the surface's size back from `width / scale` at another moment: the compositor's 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 buffers' rounding of #201, say) keeps to that, as the scale of #165 does: its listener only keeps it, and the frame boundary that takes it settles the sizes and leaves the destination to the frame. 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. diff --git a/README.md b/README.md index c83ce08..42e7e1a 100644 --- a/README.md +++ b/README.md @@ -119,11 +119,25 @@ shaded through an intersection shader with an any-hit cut-out. 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. + `width` and `height` are the pixels it comes to at `window.scale`, the + scale the window draws at. A scale the compositor asks for by itself + once the window is made (`window.preferredScale`, in 120ths) is taken + at the start of the next frame (#165): a window the compositor sized + takes the pixels for its surface's size at the new scale, and where + they differ the swapchain is made again and `onResize` fires; one the + application sized keeps its pixels, and its surface takes the size + they come to with that frame. It is taken sooner only with a swapchain + made where it gives the window new pixels, as after the present of a + frame it came during; anywhere else, with a swapchain made for another + reason too, it waits, and so does a configure that comes with it to + the pixels the window has, as until that frame the compositor maps the + surface, and the pointer on it, as before. Until it is taken the + window draws, and converts the pointer, the touches and the text + input's caret, at the scale before; once it is, the positions the + window holds in pixels go to the new scale and the caret goes to the + input method again. A window that draws on demand learns of a new size + or scale from `onFrameOwed`, which fires at the configure or the + scale. On Wayland and Win32 a `Window` constructor that throws (a Vulkan error, a surface that offers no format the swapchain can be written through as a storage image) leaves nothing of the window behind, so diff --git a/implementations/Crafter.Graphics-Device.cpp b/implementations/Crafter.Graphics-Device.cpp index be76687..c616bb0 100644 --- a/implementations/Crafter.Graphics-Device.cpp +++ b/implementations/Crafter.Graphics-Device.cpp @@ -607,6 +607,9 @@ void Device::PointerListenerHandleMotion(void* data, wl_pointer* wl_pointer, std } Vector pos(wl_fixed_to_double(surface_x), wl_fixed_to_double(surface_y)); Device::focusedWindow->lastInputTime = time; + // As the compositor gave it, which a new scale does not move, and in the + // pixels of the scale the window draws at. + Device::focusedWindow->surfaceMousePos = pos; Device::focusedWindow->PointerMove(pos * Device::focusedWindow->scale); } @@ -620,11 +623,18 @@ void Device::PointerListenerHandleEnter(void* data, wl_pointer* wl_pointer, std: window->cursorHotspotX_, window->cursorHotspotY_); } focusedWindow = window; - const Vector pos = Vector(wl_fixed_to_double(surface_x), wl_fixed_to_double(surface_y)) * window->scale; - window->PointerEnter(pos); + // As the compositor gave it, and in pixels at the scale in force + // when each is stored: a listener of onMouseEnter may take a new + // scale (a SetPresentMode outside a frame for a window the + // compositor sized, the Render() of a frame callback it + // dispatched), and the move after the enter is then in the + // pixels of that one. + const Vector local(wl_fixed_to_double(surface_x), wl_fixed_to_double(surface_y)); + window->surfaceMousePos = local; + window->PointerEnter(local * window->scale); // ~Window clears focusedWindow, should a listener destroy it. if (focusedWindow == window) { - window->PointerMove(pos); + window->PointerMove(local * window->scale); } return; } @@ -869,7 +879,8 @@ void Device::touch_down(void*, wl_touch*, std::uint32_t serial, std::uint32_t ti touchWindow = window; window->lastPointerSerial_ = serial; window->lastInputTime = time; - const Vector pos = Vector(wl_fixed_to_double(x), wl_fixed_to_double(y)) * window->scale; + const Vector local(wl_fixed_to_double(x), wl_fixed_to_double(y)); + const Vector pos = local * window->scale; if (TouchSlot* slot = SlotFor(id)) { slot->x = pos.x; slot->y = pos.y; @@ -879,7 +890,11 @@ void Device::touch_down(void*, wl_touch*, std::uint32_t serial, std::uint32_t ti if (window->primaryTouchId < 0) { window->primaryTouchId = id; focusedWindow = window; - window->currentMousePos = pos; + // In the pixels of the scale in force now: a listener of onTouchDown + // may have taken a new scale, which took the finger's slot along but + // not `pos`. + window->surfaceMousePos = local; + window->currentMousePos = local * window->scale; window->mouseLeftHeld = true; // The time once more: onTouchDown's listeners ran in between, and // one that dispatches Wayland events itself (it makes a window, or @@ -917,14 +932,17 @@ void Device::touch_motion(void*, wl_touch*, std::uint32_t time, std::int32_t id, TouchSlot* slot = SlotFor(id); if (slot != nullptr && slot->window != nullptr) window = slot->window; window->lastInputTime = time; - const Vector pos = Vector(wl_fixed_to_double(x), wl_fixed_to_double(y)) * window->scale; + const Vector local(wl_fixed_to_double(x), wl_fixed_to_double(y)); + const Vector pos = local * window->scale; if (slot != nullptr) { slot->x = pos.x; slot->y = pos.y; } window->onTouchMove.Invoke({ id, pos }); if (id == window->primaryTouchId) { - window->currentMousePos = pos; + // At the scale in force now, as in touch_down. + window->surfaceMousePos = local; + window->currentMousePos = local * window->scale; // Once more, as in touch_down: onTouchMove's listeners ran in between. window->lastInputTime = time; window->onMouseMove.Invoke(); diff --git a/implementations/Crafter.Graphics-Input.cpp b/implementations/Crafter.Graphics-Input.cpp index e1c2b15..79e750e 100644 --- a/implementations/Crafter.Graphics-Input.cpp +++ b/implementations/Crafter.Graphics-Input.cpp @@ -248,6 +248,9 @@ void Map::Attach(Window& w) { scrollAccumulator += (std::int32_t)delta; }); lastMousePos.reset(); + #ifdef CRAFTER_GRAPHICS_WINDOW_WAYLAND + lastSurfaceMousePos.reset(); + #endif scrollAccumulator = 0; } @@ -259,6 +262,9 @@ void Map::Detach() { window = nullptr; scrollAccumulator = 0; lastMousePos.reset(); + #ifdef CRAFTER_GRAPHICS_WINDOW_WAYLAND + lastSurfaceMousePos.reset(); + #endif rebind.reset(); } @@ -266,10 +272,21 @@ void Map::Tick() { // Mouse delta: derived from window position vs. last frame. Vector mouseDelta{ 0.0f, 0.0f }; if (window) { + #ifdef CRAFTER_GRAPHICS_WINDOW_WAYLAND + // From the pointer's surface-local position, which no scale moves, + // in the window's pixels of now: none for a pointer that rests, + // whatever scales the window took since the last Tick. + if (lastSurfaceMousePos.has_value()) { + mouseDelta.x = (window->surfaceMousePos.x - lastSurfaceMousePos->x) * window->scale; + mouseDelta.y = (window->surfaceMousePos.y - lastSurfaceMousePos->y) * window->scale; + } + lastSurfaceMousePos = window->surfaceMousePos; + #else if (lastMousePos.has_value()) { mouseDelta.x = window->currentMousePos.x - lastMousePos->x; mouseDelta.y = window->currentMousePos.y - lastMousePos->y; } + #endif lastMousePos = window->currentMousePos; } diff --git a/implementations/Crafter.Graphics-Window.cpp b/implementations/Crafter.Graphics-Window.cpp index e3fbf61..3d52376 100644 --- a/implementations/Crafter.Graphics-Window.cpp +++ b/implementations/Crafter.Graphics-Window.cpp @@ -396,9 +396,10 @@ Window::Window(std::uint32_t width, std::uint32_t height) : Window() { // through the viewport, which shows the width x height physical pixels of // 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 swapchain, or by - // the next size the compositor configures (#165). + // its buffer, and the compositor scales it up on a HiDPI output. The + // scale the compositor asks for while the loop below waits is taken by + // MatchSizesToScale before the first swapchain; one it asks for later, + // by a frame boundary of Render() (xdg_surface_handle_preferred_scale). 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); @@ -424,7 +425,7 @@ Window::Window(std::uint32_t width, std::uint32_t height) : Window() { if (Device::wpViewporter != nullptr) { wpViewport = wp_viewporter_get_viewport(Device::wpViewporter, surface); } - MatchSizesToScale(); + MatchSizesToScale(true); wl_surface_commit(surface); #endif @@ -828,13 +829,14 @@ void Window::RebuildSwapchain() { Device::DrainDeletions(); #ifdef CRAFTER_GRAPHICS_WINDOW_WAYLAND - // 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(); + // The buffers' size and the surface's, at the scale the window draws + // at, which takes one its listener kept only where it gives the window + // new pixels (MatchSizesToScale). 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(false); #endif RecreateSwapchainAndImages(); // Made, so nothing waits. Cleared only here: a rebuild that threw above @@ -847,6 +849,13 @@ void Window::RebuildSwapchain() { #ifdef CRAFTER_GRAPHICS_WINDOW_WAYLAND namespace { + // The scale a preferred_scale of `preferred` 120ths comes to, as `scale` + // holds it. MatchSizesToScale is the one place that stores it, so a + // scale the window draws at compares equal to this, exactly. + float ScaleOf(std::uint32_t preferred) { + return preferred / 120.0f; + } + // 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 @@ -862,7 +871,27 @@ namespace { } } -void Window::MatchSizesToScale() { +void Window::MatchSizesToScale(bool takeScale) { + // The scale the compositor asked for last becomes the one the window + // draws at, and converts the pointer, the touches and the caret with, + // at the start of a frame and in the constructor (takeScale), and + // elsewhere only where it gives the window new pixels: a window the + // compositor sized whose surface comes to other pixels at it, with no + // configured size waiting, which the next frame's start takes together + // with the scale. The swapchain made at those pixels is the one the + // application lays its next frame out for, from onResize. Anywhere else + // the scale would change only the conversions and the size the surface + // is to take, which goes out with the next frame, while until that + // frame's commit the compositor maps the surface, and the pointer and + // the touches on it, by the destination it has: so a swapchain made for + // a present mode, for a rebuild that waited or for a Resize of a window + // the application sized, whose pixels are its own, leaves the scale for + // the start of that frame. + const float before = scale; + const float newest = ScaleOf(preferredScale); + const bool newPixels = logicalConfigured && deferredLogicalWidth == 0 + && (ScaledPixels(logicalWidth, newest) != width || ScaledPixels(logicalHeight, newest) != height); + if (takeScale || newPixels) scale = newest; if (logicalConfigured) { width = ScaledPixels(logicalWidth, scale); height = ScaledPixels(logicalHeight, scale); @@ -870,10 +899,35 @@ void Window::MatchSizesToScale() { logicalWidth = SurfaceLength(width, scale); logicalHeight = SurfaceLength(height, scale); } + // What the window holds in pixels of the scale before goes to the new + // one. The compositor gives the pointer and the fingers in surface-local + // units and sends nothing for one that rests, so a position kept in the + // old pixels would be off by new/old in the frames drawn at the new + // scale until it moved (#165); lastMousePos and mouseDelta go with + // currentMousePos, so that the next delta is no jump; surfaceMousePos, + // the compositor's, which Input::Map takes its delta from, stays. The + // caret the + // application gave SetTextInput in pixels goes to the input method + // again, converted with the new scale, as it does when the keyboard + // focus comes back. In the constructor, which takes the first scale, + // the window holds none of these yet. + if (scale != before && before > 0.0f) { + const float ratio = scale / before; + currentMousePos = currentMousePos * ratio; + lastMousePos = lastMousePos * ratio; + mouseDelta = mouseDelta * ratio; + for (Device::TouchSlot& slot : Device::touchSlots) { + if (slot.used && slot.window == this) { + slot.x *= ratio; + slot.y *= ratio; + } + } + if (textInputActive_) Device::ApplyTextInput(this); + } } #endif -bool Window::TakeDeferredSize() { +bool Window::TakeDeferredSize(FrameBoundary boundary) { const std::uint32_t widthBefore = width; const std::uint32_t heightBefore = height; if (deferredWidth != 0) { @@ -891,26 +945,53 @@ bool Window::TakeDeferredSize() { #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(); + // here on, unchanged, and the pixels for it at the scale the compositor + // asked for last. 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. And a scale the compositor + // asked for with no size, which its listener only kept (#165): taken + // here as a configured size is, so the window draws at it from the next + // frame it records, and the pointer, the touches and the caret are + // converted with it from here. A window the compositor sized keeps the + // surface's size and takes new pixels for it, which the caller makes + // the swapchain at. One the application sized keeps its pixels, and its + // surface takes the size they come to at the new scale, which the next + // frame sends (SendFrameSurfaceState). + const float newest = ScaleOf(preferredScale); + const bool sized = deferredLogicalWidth != 0; + const bool rescaled = newest != scale; + if (sized || rescaled) { + // After a present, a new scale is taken only where it gives the + // window new pixels (see MatchSizesToScale), and a configured size + // that comes with it to the pixels the window has waits with it for + // the start of the next frame, the one that sends the surface that + // size: taken here, the scale would convert the pointer and the + // touches for a frame not drawn yet, while the compositor maps them + // by the destination it has and the application hit-tests in the + // layout of the frame on screen, and no onResize would say so. + const bool configured = sized || logicalConfigured; + const std::int32_t surfaceWidth = sized ? deferredLogicalWidth : logicalWidth; + const std::int32_t surfaceHeight = sized ? deferredLogicalHeight : logicalHeight; + const bool newPixels = configured && (ScaledPixels(surfaceWidth, newest) != width || ScaledPixels(surfaceHeight, newest) != height); + if (boundary == FrameBoundary::Start || !rescaled || newPixels) { + if (sized) { + logicalWidth = deferredLogicalWidth; + logicalHeight = deferredLogicalHeight; + logicalConfigured = true; + deferredLogicalWidth = 0; + deferredLogicalHeight = 0; + } + MatchSizesToScale(boundary == FrameBoundary::Start); + } } #endif return width != widthBefore || height != heightBefore; } -void Window::RebuildIfDeferred() { +void Window::RebuildIfDeferred(FrameBoundary boundary) { // The sizes are taken before the rebuild, so an onResize listener that // renders finds none waiting. - if (TakeDeferredSize() || swapchainRebuildPending) RebuildSwapchain(); + if (TakeDeferredSize(boundary) || swapchainRebuildPending) RebuildSwapchain(); } void Window::RecreateSwapchainAndImages() { @@ -1427,8 +1508,11 @@ void Window::Render() { // 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(); + // queue idle and no frame being recorded, as it does from Resize. And + // on Wayland a scale its listener kept (#165) is taken here, also one + // that the end of the frame before, or a swapchain made since, left for + // this frame, as it gave the window no new pixels (TakeDeferredSize). + RebuildIfDeferred(FrameBoundary::Start); // This frame's slot among the numFrames in flight. Its command buffer, // descriptor-heap copy and acquire semaphore were last used numFrames @@ -1669,11 +1753,13 @@ void Window::Render() { // The rebuild the frame held back: the present's, or a Resize or // SetPresentMode from one of its listeners, or on Wayland a size - // configured while they ran (a listener that dispatches events). + // configured while they ran (a listener that dispatches events), and a + // scale that came then, where it gives the window new pixels: otherwise + // it waits for the start of the next frame (TakeDeferredSize). // 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. - RebuildIfDeferred(); + RebuildIfDeferred(FrameBoundary::AfterPresent); } #ifdef CRAFTER_TIMING @@ -2080,14 +2166,22 @@ void Window::xdg_surface_handle_configure(void* data, xdg_surface* xdg_surface, 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. + // the buffers are the pixels for it at the scale the compositor + // asked for last, which the frame takes with the size: 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. And + // only where the window draws at that scale already: while a new + // one waits, the configure waits for the frame that takes the scale + // and the size together, so that a window the compositor sized + // always has the pixels its surface's size comes to at the scale it + // draws at. + const float newest = ScaleOf(window->preferredScale); 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; + && newest == window->scale + && ScaledPixels(window->pendingLogicalWidth, newest) == window->width + && ScaledPixels(window->pendingLogicalHeight, newest) == 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 @@ -2156,7 +2250,26 @@ void Window::SendFrameSurfaceState() { void Window::xdg_surface_handle_preferred_scale(void* data, wp_fractional_scale_v1*, std::uint32_t scale) { Window* window = reinterpret_cast(data); - window->scale = scale / 120.0f; + // A scale of 0 is none: the pixels worked out with it would be 0. + if (scale == 0) return; + // Kept, and nothing else, as a configure's size is: the window goes on + // drawing at the scale it draws at, and converting the pointer, the + // touches and the caret with it, until a frame boundary of Render() + // takes this one with the swapchain it may need (TakeDeferredSize). Set + // here, `scale` would convert positions for frames still drawn at the + // old one (#165), and would change in the middle of a frame whose + // listener dispatched this event. And no Vulkan call is made from inside + // the dispatch (#200). Before the window has its first swapchain the + // constructor takes the scale (MatchSizesToScale). + window->preferredScale = scale; + const bool hasSwapchain = window->configured && window->swapChain != VK_NULL_HANDLE; + // A scale the window draws at owes nothing, also one that comes back to + // it before a frame took the one between. + if (!hasSwapchain || ScaleOf(scale) == window->scale) return; + // A frame is owed, which a window that draws on demand learns of here, + // as of a configure's size: it gets no onResize where its pixels stay. + // The event last, since a listener may destroy the window. + window->onFrameOwed.Invoke(); } #endif diff --git a/interfaces/Crafter.Graphics-Input.cppm b/interfaces/Crafter.Graphics-Input.cppm index a1ea11d..b6cf255 100644 --- a/interfaces/Crafter.Graphics-Input.cppm +++ b/interfaces/Crafter.Graphics-Input.cppm @@ -131,6 +131,15 @@ export namespace Crafter::Input { // Mouse delta is computed from window.currentMousePos vs the // position observed last tick. nullopt before first tick. std::optional> lastMousePos; + #ifdef CRAFTER_GRAPHICS_WINDOW_WAYLAND + // The window's surfaceMousePos at the last tick, nullopt before the + // first. On Wayland the delta is the pointer's surface-local motion + // since then, in the window's pixels of now, and not the motion of + // currentMousePos, which the window takes along to each new scale: + // through two of them between two Ticks that keeps a float residue, + // which a pointer that rests would read as a delta (#165). + std::optional> lastSurfaceMousePos; + #endif // Rebind state. struct RebindState { diff --git a/interfaces/Crafter.Graphics-Window.cppm b/interfaces/Crafter.Graphics-Window.cppm index c2a3452..9549bb4 100644 --- a/interfaces/Crafter.Graphics-Window.cppm +++ b/interfaces/Crafter.Graphics-Window.cppm @@ -233,7 +233,9 @@ export namespace Crafter { // Tells the compositor's input method that a text field has focus // (an on-screen keyboard opens) and where its caret is, in physical // pixels, or that none has. Remembered: it is applied again whenever - // the keyboard focus comes back to this window. `purpose` says what + // the keyboard focus comes back to this window, and on Wayland + // whenever the window's scale changes, converted with the new one. + // `purpose` says what // the field holds and `hints` how the input method treats it // (kTextInputHint*, or-ed together); without hints the field gets // its purpose's usual ones, TextInputDefaultHints(purpose). The input @@ -316,6 +318,15 @@ export namespace Crafter { // pointer events the first finger stands in for are given the // touch's time again. std::uint32_t lastInputTime = 0; + // The pointer's position as the compositor last gave it, in + // surface-local units: a motion's, an enter's, the first finger's, + // which stands in for the pointer. A new scale does not move it, + // where it takes currentMousePos, which is it in pixels, along + // (MatchSizesToScale), and Input::Map takes the pointer's delta from + // it, so that a pointer that rests reads none whatever scales the + // window took between two of its Ticks. A position the application + // writes into currentMousePos itself is not in it. + Vector surfaceMousePos{ 0.0f, 0.0f }; // Wakes the event loop when `fd` becomes readable and calls // `onReadable` from it, which must consume what made the descriptor @@ -371,7 +382,12 @@ export namespace Crafter { // 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 + // configure's states set. It fires in the same way after a + // preferred scale that is not the one the window draws at: a frame + // boundary of Render() takes that scale (see preferredScale), with + // new pixels and onResize for a window the compositor sized where + // they differ, with the surface's new size and no onResize for one + // the application sized (#165). 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 @@ -379,7 +395,38 @@ export namespace Crafter { // inside a frame. Event onFrameOwed; + // The scale the window draws at: the buffers' pixels per + // surface-local unit, which width x height and logicalWidth x + // logicalHeight were last worked out with (MatchSizesToScale). The + // pointer's and the touches' positions are turned into pixels with + // it, and the caret SetTextInput gives back into surface-local + // units, so that they are in the units of the frames drawn at it. + // Where it changes, the positions the window holds in pixels go to + // the new one (currentMousePos, lastMousePos, mouseDelta, the + // fingers down; surfaceMousePos, the compositor's, stays, and + // Input::Map takes its delta from that), as the compositor sends + // nothing for a pointer or a finger that rests, and the caret goes + // to the input method again, converted with it. It changes only + // where the two sizes are worked out (MatchSizesToScale): in the + // constructor, at the start of a frame, and elsewhere only where it + // gives the window new pixels. 1 where the compositor has no + // wp_fractional_scale_v1 or no wp_viewporter. float scale = 1.0f; + // The scale the compositor asked for last, as + // wp_fractional_scale_v1's preferred_scale sends it: in 120ths, so + // 120 is a scale of 1. Its listener only keeps it. The window takes + // it into `scale` at the start of the next frame, and draws and + // converts input at the scale before until then (#165), and sooner + // only with a swapchain made where it gives the window new pixels: a + // window the compositor sized whose surface comes to other pixels at + // it, as after the present of the frame whose listener dispatched it + // or with the swapchain a SetPresentMode makes outside a frame. The + // constructor takes one named before the first swapchain. Anywhere + // else it would change only the conversions and the size the surface + // is to take, which goes out with the next frame, and until that + // frame's commit the compositor maps the surface, and the pointer + // and the touches on it, as before (MatchSizesToScale). + std::uint32_t preferredScale = 120; bool configured = false; // Pending size from the most recent xdg_toplevel.configure, in // surface-local (logical DP) units, until the xdg_surface.configure @@ -412,15 +459,21 @@ export namespace Crafter { 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(); + // Before a swapchain is made, and where a frame boundary takes a + // configured size or a new scale: works the size the window was not + // given out of the one it was, at the scale it draws at, which it + // first makes the one the compositor asked for last (preferredScale + // into scale) where takeScale says so (the start of a frame, the + // constructor) or the scale gives the window new pixels (see + // preferredScale). 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 a new scale reaches the buffers, or the + // surface, without moving a configured window off the size the + // compositor gave it. Where the scale changes, it also takes the + // positions the window holds in pixels to the new one and sends the + // caret again (see scale). No Vulkan call. + void MatchSizesToScale(bool takeScale); // 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. @@ -430,9 +483,9 @@ export namespace Crafter { // 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. + // the scale the compositor has asked for by then. 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 @@ -550,26 +603,37 @@ export namespace Crafter { // 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 + // sizes at the scale the window draws at, taking a new one only + // where it gives the window new pixels (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(); + // Render()'s two frame boundaries: its start, before the fence wait + // and the acquire, and its end, after the present. + enum class FrameBoundary { Start, AfterPresent }; // 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(); + // for last. On Wayland it takes a scale the compositor asked for + // and the window does not draw at yet as well, with or without a + // configured size: at the start of a frame, and after a present + // only where it gives the window new pixels (see preferredScale). + // Otherwise the scale, and a configured size that comes to the + // pixels the window has with it, wait for the next frame's start. + // True when + // width or height changed, so that the swapchain has to be made + // again. A configured size or a new scale may leave them as they + // are: then only the surface's size changes, which the next frame + // sends, or nothing but `scale` does. No Vulkan call: Render() + // rebuilds. + bool TakeDeferredSize(FrameBoundary boundary); // 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(); + void RebuildIfDeferred(FrameBoundary boundary); // Saves the frame the next Render() draws to a PNG at `path`, for // visual regression tests and screenshots: that Render copies the diff --git a/tests/ConfigureResize/main.cpp b/tests/ConfigureResize/main.cpp index 6ba91f4..8961179 100644 --- a/tests/ConfigureResize/main.cpp +++ b/tests/ConfigureResize/main.cpp @@ -23,8 +23,9 @@ // 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: +// end. `Begin`, `Present` and `End` below stand for Render()'s start, its +// present and its end after the present; 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 @@ -50,26 +51,83 @@ // 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 +// - the size is turned into pixels with the scale the compositor has asked +// for by 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. A +// scale that changes during a frame is taken at the boundary after its +// present // - 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 +// it at the new scale, which it draws at from that swapchain on, the +// next frame boundary having nothing left to take; one the application +// sized keeps its pixels and takes no scale there, as nothing of that +// swapchain needs it, and until the next frame's start takes it a motion +// is still at the pixels of the scale before, also where the swapchain +// is made after a present that found it out of date // - 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 // +// Issue #165: a scale the compositor asks for by itself, with no configure +// (a window that goes to an output of another scale). Its listener used to +// set Window::scale and nothing else: the buffers and the surface kept the +// old scale until something resized the window, while the pointer, the +// touches and the caret were converted with the new one. Asserts: +// +// - the listener sends nothing, leaves `scale` and both sizes as they +// are, and fires onFrameOwed; until a frame boundary takes the scale, a +// motion or a touch at the surface's middle is at the middle of the +// buffers drawn at the scale before, and a caret given in their pixels +// goes to the text input converted with that scale too +// - the next frame boundary takes it. A window the compositor sized keeps +// its surface's size and takes the pixels for it at the new scale, so +// the frame makes the swapchain; the surface is sent nothing. One the +// application sized keeps its pixels and makes no swapchain, and its +// surface takes the size they come to, which the frame sends. From then +// the pointer, the touches and the caret are converted with the new +// scale, and what the window held in pixels of the scale before is +// taken to it: a pointer and a finger that rest are where their +// surface-local places come to at the new scale, and the boundary sends +// the caret again, converted, with no SetTextInput; an Input::Map +// attached to the window and ticked across the boundary reads no delta +// for a pointer that rests, nor across two boundaries between two Ticks, +// and fires no event there +// - input whose listener takes a scale that waits (as a SetPresentMode +// outside a frame does for a window the compositor sized, at the new +// pixels the scale gives it): the click a finger stands in +// for, the finger's move and the move after an enter are in the pixels +// of that scale +// - a scale that comes while a frame is being recorded leaves that frame +// at the scale it began with, and the boundary after its present takes +// it only where it gives the window new pixels: a window the compositor +// sized whose surface comes to other pixels at it. Where it gives none +// (a window the application sized, one the compositor sized that it +// leaves at its pixels, a configure that comes with it to the pixels the +// window has), it waits, with the configure, for the start of the next +// frame, the +// one that sends the surface its new size: until then a motion is still +// at the pixels of the scale before and the caret is not sent again, as +// the compositor maps the surface as before until that frame's commit +// - a scale that comes back to the one the window draws at before a frame +// owes nothing, and fires nothing +// - a configure without a size while a scale waits is acknowledged in the +// listener, as the scale itself is answered by no acknowledgement; one +// for the size the surface has waits for the frame that takes the +// scale, also where its pixels at that scale are the window's, and the +// window does not become one the compositor sized before then +// - before the window has its first swapchain the listener only keeps the +// scale, which the constructor's MatchSizesToScale takes; a scale of 0 +// is not taken +// // No compositor and no GPU. Needs the Wayland backend, hence Linux only. #include @@ -80,9 +138,11 @@ #include #include "../../lib/xdg-shell-client-protocol.h" #include "../../lib/viewporter.h" +#include "../../lib/text-input-unstable-v3-client-protocol.h" import Crafter.Graphics; import Crafter.Event; +import Crafter.Math; import std; using namespace Crafter; @@ -117,6 +177,9 @@ std::vector acknowledged; // A compositor's serials: one counter, never reused. std::uint32_t lastSerial = 100; +// The text input whose caret Sent() reports, 0 while there is none. +std::uint32_t textInputId = 0; + // 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 @@ -131,7 +194,8 @@ struct Fixture { int owed = 0; std::optional> owedSub; - Fixture(wl_display* display, wl_registry* registry, int peer, float scale, std::uint32_t width, std::uint32_t height, bool viewport = true) + // `scale` in 120ths, as the compositor names it. + Fixture(wl_display* display, wl_registry* registry, int peer, std::uint32_t 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_registry_bind(registry, 1, &wl_surface_interface, 1)); @@ -143,13 +207,15 @@ struct Fixture { } surfaceId = wl_proxy_get_id(reinterpret_cast(window.surface)); xdgSurfaceId = wl_proxy_get_id(reinterpret_cast(window.xdgSurface)); - window.scale = scale; + // The scale the compositor named while the constructor waited. + window.preferredScale = 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(); + // The scale the window draws at, and the surface's size, from the + // constructor's pixels. + window.MatchSizesToScale(true); window.swapChain = reinterpret_cast(static_cast(0x1)); window.swapchainGeneration = 1; // Where the constructor lists it, and where the handler looks for a @@ -186,42 +252,52 @@ struct Fixture { } // 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. + // sizes at the scale it draws at, which takes a new one only where it + // gives the window new pixels, and a swapchain, which CreateSwapchain + // numbers, after which none waits to be made. void Rebuild() { Window& window = *holder; - window.MatchSizesToScale(); + window.MatchSizesToScale(false); ++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() { + // A frame boundary 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 Boundary(Window::FrameBoundary boundary) { Window& window = *holder; - if (!window.TakeDeferredSize() && !window.swapchainRebuildPending) return false; + if (!window.TakeDeferredSize(boundary) && !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. + // The start of Render(). + bool Begin() { return Boundary(Window::FrameBoundary::Start); } + + // 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; } + // The end of Render(), after the present: what the frame's listeners + // asked for while it was being recorded. + bool End() { return Boundary(Window::FrameBoundary::AfterPresent); } + // A whole frame. void Frame() { Begin(); Present(); + End(); } // What the window has sent to its surface, its xdg_surface and its // viewport since the last call, in order: "commit", "ack ", - // "destination x". A request is its object id, then its size and + // "destination x", and the caret it gave the text input, "caret + // , x". A request is its object id, then its size and // opcode in one word, then its arguments. Requests Sent() { wl_display_flush(display); @@ -249,6 +325,8 @@ struct Fixture { acknowledged.push_back(static_cast(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))); + } else if (textInputId != 0 && header[0] == textInputId && opcode == ZWP_TEXT_INPUT_V3_SET_CURSOR_RECTANGLE) { + requests.push_back(std::format("caret {},{} {}x{}", argument(0), argument(1), argument(2), argument(3))); } at += size; } @@ -259,7 +337,8 @@ struct Fixture { 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; + && window.sentLogicalWidth == window.logicalWidth && window.sentLogicalHeight == window.logicalHeight + && window.scale == window.preferredScale / 120.0f; } // The scale as the compositor names it, in 120ths. @@ -267,6 +346,20 @@ void Scale(Window& window, std::uint32_t scale120) { Window::xdg_surface_handle_preferred_scale(&window, nullptr, scale120); } +// Where the pointer is in the window's pixels after a motion to (x, y) on +// its surface, as the compositor reports it, in surface-local units. +Vector Motion(Window& window, double x, double y) { + Device::focusedWindow = &window; + Device::PointerListenerHandleMotion(nullptr, nullptr, 0, wl_fixed_from_double(x), wl_fixed_from_double(y)); + return window.currentMousePos; +} + +// Whether `position` is (x, y), saying where it is when it is not. +void CheckAt(Vector position, float x, float y, std::string_view what) { + Check(position.x == x && position.y == y, what); + if (position.x != x || position.y != y) std::println(" at {},{}, where {},{} was expected", position.x, position.y, x, y); +} + } // namespace int main() { @@ -283,14 +376,14 @@ int main() { } // 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) { + const auto fixture = [&](std::uint32_t 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); + Fixture f = fixture(240, 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"); @@ -300,7 +393,7 @@ int main() { // A new size, and the frame that answers it. { - Fixture f = fixture(2.0f, 640, 480); + Fixture f = fixture(240, 640, 480); f.Frame(); f.Sent(); Window& window = f.window(); @@ -329,7 +422,7 @@ int main() { // Several configures before a frame. { - Fixture f = fixture(1.0f, 320, 240); + Fixture f = fixture(120, 320, 240); f.Frame(); f.Sent(); Window& window = f.window(); @@ -351,7 +444,7 @@ int main() { // Nothing new while nothing is owed: answered in the listener, as before. { - Fixture f = fixture(2.0f, 640, 480); + Fixture f = fixture(240, 640, 480); f.Frame(); f.Sent(); Window& window = f.window(); @@ -370,7 +463,7 @@ int main() { // The compositor goes back to the size the window has before a frame. { - Fixture f = fixture(1.0f, 320, 240); + Fixture f = fixture(120, 320, 240); f.Frame(); f.Sent(); Window& window = f.window(); @@ -388,7 +481,7 @@ int main() { // A size that comes while a frame is being recorded. { - Fixture f = fixture(1.0f, 320, 240); + Fixture f = fixture(120, 320, 240); f.Frame(); f.Sent(); Window& window = f.window(); @@ -406,7 +499,7 @@ int main() { // A configure before the window's first frame. { - Fixture f = fixture(2.0f, 640, 480); + Fixture f = fixture(240, 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"); @@ -419,7 +512,7 @@ int main() { // its first frame brings the destination, and a configure before that // frame waits for it. { - Fixture f = fixture(2.0f, 640, 480); + Fixture f = fixture(240, 640, 480); f.Frame(); f.Sent(); Window& window = f.window(); @@ -451,7 +544,7 @@ int main() { // 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); + Fixture f = fixture(240, 640, 480); f.Frame(); f.Sent(); Window& window = f.window(); @@ -459,7 +552,7 @@ int main() { // 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"); + Check(window.TakeDeferredSize(Window::FrameBoundary::Start) && 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); @@ -479,7 +572,7 @@ int main() { // 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); + Fixture f = fixture(240, 640, 480); f.Frame(); f.Sent(); Window& window = f.window(); @@ -503,7 +596,7 @@ int main() { // Without wp_viewporter there is no destination, and the scale is 1. { - Fixture f = fixture(1.0f, 320, 240, false); + Fixture f = fixture(120, 320, 240, false); f.Frame(); Expect(f.Sent(), {}, "without a viewport the first frame sends nothing"); Window& window = f.window(); @@ -519,7 +612,7 @@ int main() { // takes the size. The destination is the configured size whatever the // scale does. { - Fixture f = fixture(2.0f, 640, 480); + Fixture f = fixture(240, 640, 480); f.Frame(); f.Sent(); Window& window = f.window(); @@ -540,7 +633,7 @@ int main() { // destination is still the configured size, not that swapchain's pixels // over the new scale (534x400). { - Fixture f = fixture(2.0f, 640, 480); + Fixture f = fixture(240, 640, 480); f.Frame(); f.Sent(); Window& window = f.window(); @@ -548,11 +641,20 @@ int main() { 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); + Check(window.scale == 2.0f && window.width == 800 && window.height == 600, + "a scale that changes while the frame is recorded: the frame goes on at the one it began with"); 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"); + "its present still sends the configured size"); + Check(!window.unackedConfigure && window.deferredLogicalWidth == 0 && window.scale == 2.0f, + "and answers the configure, with the scale still waiting"); + Check(f.End() && window.width == 600 && window.height == 450 && window.scale == 1.5f, + std::format("the boundary after the present takes the scale: {}x{} for 400x300 at 1.5", window.width, window.height)); + Check(!f.Begin(), "the next frame's start finds nothing left to take, and makes no swapchain"); + f.Present(); + Expect(f.Sent(), {}, "and the frame drawn at it sends the surface nothing, as its size is the one it has"); + Check(NothingWaits(window), "after it nothing is owed"); } // A new size and a new scale that together come to the pixels the @@ -561,7 +663,7 @@ int main() { // size, in the commit that acknowledges the configure. First the // configure, then the scale. { - Fixture f = fixture(2.0f, 640, 480); + Fixture f = fixture(240, 640, 480); f.Frame(); Expect(f.Sent(), { "destination 320x240" }, "a window of 640x480 pixels at scale 2 is 320x240"); Window& window = f.window(); @@ -583,7 +685,7 @@ int main() { // 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); + Fixture f = fixture(180, 600, 450); f.Frame(); Expect(f.Sent(), { "destination 400x300" }, "a window of 600x450 pixels at scale 1.5 is 400x300"); Window& window = f.window(); @@ -592,7 +694,8 @@ int main() { 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(window.deferredLogicalWidth == 300 && window.deferredLogicalHeight == 225 && f.owed == 2, + std::format("the size waits, and onFrameOwed fired for the scale and for the configure ({})", f.owed)); 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" }), @@ -602,7 +705,7 @@ int main() { // 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); + Fixture f = fixture(240, 640, 480); f.Frame(); f.Sent(); Window& window = f.window(); @@ -623,7 +726,7 @@ int main() { // 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); + Fixture f = fixture(342, 1140, 2280); f.Frame(); Expect(f.Sent(), { "destination 400x800" }, "a window of 1140x2280 pixels at scale 2.85 is 400x800"); Window& window = f.window(); @@ -649,7 +752,7 @@ int main() { // compositor configures that size, the window takes the pixels for it // once, and is then left alone. { - Fixture f = fixture(1.75f, 320, 240); + Fixture f = fixture(210, 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(); @@ -668,10 +771,12 @@ int main() { // 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. + // pixels for it at the new scale. One the application sized keeps its + // pixels and takes no scale: nothing of that swapchain needs it, and + // until the next frame, which sends the surface its new size, the + // compositor maps the surface as before. { - Fixture f = fixture(2.0f, 640, 480); + Fixture f = fixture(240, 640, 480); f.Frame(); f.Configure(400, 300); f.Frame(); @@ -681,13 +786,14 @@ int main() { 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)); + Check(window.width == 600 && window.height == 450 && window.logicalWidth == 400 && window.logicalHeight == 300 && window.scale == 1.5f, + std::format("a swapchain made after the scale became 1.5: the pixels for 400x300 at it ({}x{}), and the window draws at it", window.width, window.height)); + Check(!f.Begin(), "the next frame boundary finds nothing left to take"); f.Present(); Expect(f.Sent(), {}, "and the surface, still 400x300, is sent nothing"); } { - Fixture f = fixture(2.0f, 640, 480); + Fixture f = fixture(240, 640, 480); f.Frame(); f.Sent(); Window& window = f.window(); @@ -695,15 +801,511 @@ int main() { Scale(window, 120); f.Rebuild(); - Check(window.width == 640 && window.height == 480, "a swapchain made after the scale became 1: the pixels stay"); + Check(window.width == 640 && window.height == 480 && window.scale == 2.0f && window.logicalWidth == 320 && window.logicalHeight == 240, + "a swapchain made after the scale became 1 keeps the pixels and takes no scale: the window still draws at 2, its surface still 320x240"); + CheckAt(Motion(window, 160, 120), 320, 240, + "until the next frame a motion to the surface's middle is at the middle of the frame on screen, drawn at 2"); + Check(!f.Begin() && window.scale == 1.0f && window.logicalWidth == 640 && window.logicalHeight == 480, + "the next frame's start takes the scale, with no swapchain"); + CheckAt(window.currentMousePos, 160, 120, "the pointer, which has not moved, is where its surface-local (160,120) comes to at 1"); f.Present(); - Expect(f.Sent(), { "destination 640x480" }, "and the surface takes the size they come to at it"); + Expect(f.Sent(), { "destination 640x480" }, "and the surface takes the size the pixels come to at it with that frame"); + } + // The same with the swapchain made after a present that found it out of + // date, while a scale that came during the frame waited, and with a + // configure as well that comes with that scale to the pixels the window + // has: the boundary after the present makes the swapchain again and + // takes neither, and the next frame's start takes both. + { + Fixture f = fixture(240, 640, 480); + f.Frame(); + f.Sent(); + Window& window = f.window(); + f.Begin(); + Scale(window, 120); + f.Present(); + window.swapchainRebuildPending = true; + Check(f.End() && window.scale == 2.0f && window.logicalWidth == 320 && window.logicalHeight == 240, + "a present out of date after a scale came during its frame: the boundary after it makes the swapchain again and takes no scale"); + CheckAt(Motion(window, 160, 120), 320, 240, + "until the next frame a motion to the surface's middle is at the middle of the frame on screen, drawn at 2"); + Check(!f.Begin() && window.scale == 1.0f && window.logicalWidth == 640 && window.logicalHeight == 480, "the next frame's start takes it"); + f.Present(); + Expect(f.Sent(), { "destination 640x480" }, "and its frame brings the surface its size"); + + f.Begin(); + Scale(window, 192); + const std::uint32_t serial = f.Configure(400, 300); + f.Present(); + f.Sent(); + window.swapchainRebuildPending = true; + Check(f.End() && window.scale == 1.0f && window.width == 640 && window.height == 480 && window.deferredLogicalWidth == 400, + "a scale of 1.6 and a configure of 400x300 that come to those 640x480 pixels, and a present out of date: the swapchain is made again at them, and neither is taken"); + Check(!f.Begin() && window.scale == 1.6f && window.width == 640 && window.height == 480 && window.logicalWidth == 400 && window.logicalHeight == 300, + "the next frame's start takes both, with no swapchain"); + f.Present(); + Expect(Sorted(f.Sent()), Sorted({ std::format("ack {}", serial), "destination 400x300" }), + "and its frame brings the surface its size and the acknowledgement"); + Check(NothingWaits(window), "after it nothing is owed"); + } + + // Issue #165: a scale the compositor asks for by itself, with no + // configure, as when a window goes to an output of another scale. Its + // listener used to set the scale and nothing else, so the buffers and + // the surface kept the old one until something resized the window, + // while the pointer, the touches and the caret were converted with the + // new one. Now the listener only keeps it, the window draws at the scale + // it has and converts with that one until a frame boundary takes the + // new one, as it takes a configured size, and onFrameOwed fires. A + // window the compositor sized keeps its surface's size and takes new + // pixels for it: the frame makes the swapchain. + { + Fixture f = fixture(240, 640, 480); + f.Frame(); + f.Configure(400, 300); + f.Frame(); + f.Sent(); + f.owed = 0; + Window& window = f.window(); + Check(window.logicalConfigured && window.width == 800 && window.height == 600, "#165: a window the compositor sized, 400x300 at scale 2"); + // The caret goes to a text input the compositor gave this window. + zwp_text_input_v3* input = static_cast(wl_registry_bind(registry, 5, &zwp_text_input_v3_interface, 1)); + textInputId = wl_proxy_get_id(reinterpret_cast(input)); + Device::display = f.display; + Device::textInput = input; + Device::textInputWindow = &window; + + Scale(window, 180); + Expect(f.Sent(), {}, "a scale from the compositor: its listener sends nothing"); + Check(window.scale == 2.0f && window.width == 800 && window.height == 600 && window.logicalWidth == 400 && window.logicalHeight == 300 + && window.preferredScale == 180, + "the window still draws at 2, at 800x600 for its 400x300, and the scale waits"); + Check(f.owed == 1, std::format("onFrameOwed fired once ({})", f.owed)); + CheckAt(Motion(window, 200, 150), 400, 300, "a motion to the surface's middle is at the middle of the 800x600 buffers drawn at 2"); + window.SetTextInput(true, 120, 240, 6, 48); + Expect(f.Sent(), { "caret 60,120 3x24" }, "a caret given in those buffers' pixels goes to the text input at 2"); + + Check(f.Begin() && window.width == 600 && window.height == 450 && window.scale == 1.5f && window.logicalWidth == 400 && window.logicalHeight == 300, + std::format("the next frame takes the scale, with the pixels for 400x300 at 1.5 ({}x{}), and makes the swapchain at them", window.width, window.height)); + CheckAt(window.currentMousePos, 300, 225, + "the pointer, which has not moved, is at the middle of the 600x450 buffers: the boundary took its position to the new scale"); + Expect(f.Sent(), { "caret 80,160 4x32" }, "and sent the caret given in the pixels of 2 again, at 1.5, with no SetTextInput"); + CheckAt(Motion(window, 200, 150), 300, 225, "from there the motion to the surface's middle is at the middle of the 600x450 buffers"); + window.SetTextInput(true, 120, 240, 6, 48); + Expect(f.Sent(), { "caret 80,160 4x32" }, "and a caret given in their pixels goes to the text input at 1.5"); + f.Present(); + Expect(f.Sent(), {}, "the frame sends the surface nothing, as its size is the one it had"); + Check(NothingWaits(window) && f.owed == 1, "after it nothing is owed"); + + window.SetTextInput(false); + f.Sent(); + Device::textInputWindow = nullptr; + Device::textInput = nullptr; + Device::display = nullptr; + zwp_text_input_v3_destroy(input); + textInputId = 0; + } + + // A window the application sized keeps its pixels: no swapchain is made, + // and the surface takes the size they come to at the new scale, which + // the frame sends with its buffer. A finger that goes down while the + // scale waits and moves after the frame took it is at the buffers' + // middle both times. + { + Fixture f = fixture(240, 640, 480); + f.Frame(); + f.Sent(); + Window& window = f.window(); + std::vector> touches; + std::vector> lifts; + EventListener downSub(&window.onTouchDown, [&](TouchPoint point) { if (point.id == 0) touches.push_back(point.position); }); + EventListener moveSub(&window.onTouchMove, [&](TouchPoint point) { if (point.id == 0) touches.push_back(point.position); }); + EventListener upSub(&window.onTouchUp, [&](TouchPoint point) { if (point.id == 1) lifts.push_back(point.position); }); + zwp_text_input_v3* input = static_cast(wl_registry_bind(registry, 5, &zwp_text_input_v3_interface, 1)); + textInputId = wl_proxy_get_id(reinterpret_cast(input)); + Device::display = f.display; + Device::textInput = input; + Device::textInputWindow = &window; + window.SetTextInput(true, 120, 240, 6, 48); + Expect(f.Sent(), { "caret 60,120 3x24" }, "a caret given in the 640x480 pixels at 2 goes to the text input as such"); + + Scale(window, 120); + Expect(f.Sent(), {}, "a scale for a window the application sized: its listener sends nothing"); + Check(window.scale == 2.0f && window.width == 640 && window.height == 480 && window.logicalWidth == 320 && window.logicalHeight == 240 + && f.owed == 1, + "the window still draws at 2, at 640x480 for its 320x240, and onFrameOwed fired"); + CheckAt(Motion(window, 160, 120), 320, 240, "a motion to the surface's middle is at the middle of the 640x480 buffers"); + Device::touch_down(nullptr, nullptr, 1, 0, window.surface, 0, wl_fixed_from_double(160), wl_fixed_from_double(120)); + Check(touches.size() == 1, "a finger goes down"); + if (!touches.empty()) CheckAt(touches.back(), 320, 240, "at the surface's middle, which is the buffers' middle"); + Device::touch_down(nullptr, nullptr, 2, 0, window.surface, 1, wl_fixed_from_double(80), wl_fixed_from_double(60)); + + Check(!f.Begin() && window.width == 640 && window.height == 480 && window.scale == 1.0f && window.logicalWidth == 640 && window.logicalHeight == 480, + std::format("the next frame takes the scale with no swapchain: the pixels stay, and the surface is the {}x{} they come to at 1", window.logicalWidth, window.logicalHeight)); + CheckAt(window.currentMousePos, 160, 120, + "the pointer the first finger stands in for, which has not moved, is where its surface-local (160,120) comes to at 1"); + Expect(f.Sent(), { "caret 120,240 6x48" }, "taking the scale sends the caret again, at 1, with no SetTextInput, and nothing else"); + f.Present(); + Expect(f.Sent(), { "destination 640x480" }, "the frame brings the surface that size with its buffer"); + Device::touch_up(nullptr, nullptr, 3, 0, 1); + Check(lifts.size() == 1, "a second finger, down before the boundary, lifts after it without moving"); + if (!lifts.empty()) CheckAt(lifts.back(), 80, 60, "where its surface-local (80,60) comes to at 1"); + CheckAt(Motion(window, 320, 240), 320, 240, "and a motion to its middle is at the buffers' middle"); + Device::touch_motion(nullptr, nullptr, 0, 0, wl_fixed_from_double(320), wl_fixed_from_double(240)); + Check(touches.size() == 2, "the finger moves"); + if (touches.size() == 2) CheckAt(touches.back(), 320, 240, "to the surface's middle, which is the buffers' middle"); + Device::touch_up(nullptr, nullptr, 4, 0, 0); + Check(NothingWaits(window) && f.owed == 1, "after the frame nothing is owed"); + + window.SetTextInput(false); + f.Sent(); + Device::textInputWindow = nullptr; + Device::textInput = nullptr; + Device::display = nullptr; + zwp_text_input_v3_destroy(input); + textInputId = 0; + } + + // An Input::Map attached to the window keeps a last position of its own + // for MouseDeltaBind. Ticked across a boundary that takes a new scale, it + // reads no delta for a pointer that rests, and then the motion in the + // new pixels: 10 units at 1.5 are 15, read through a binding of a + // sixteenth, as the Map clamps an axis to 1. + { + Fixture f = fixture(240, 640, 480); + f.Frame(); + f.Configure(400, 300); + f.Frame(); + f.Sent(); + Window& window = f.window(); + Input::Map map; + Input::Action& look = map.AddAction("Look", Input::ActionType::Vector2); + look.bindings = { Input::MouseDeltaBind{ 1.0f / 16.0f } }; + map.Attach(window); + Motion(window, 200, 150); + map.Tick(); + Scale(window, 180); + Check(f.Begin() && window.scale == 1.5f, "an Input::Map's window takes a scale of 1.5 at a boundary"); + map.Tick(); + CheckAt(look.vector2, 0, 0, "the Map ticked across it reads no delta for the pointer, which rests"); + Motion(window, 210, 150); + map.Tick(); + CheckAt(look.vector2, 15.0f / 16.0f, 0, "and a motion of 10 units after it as 15 pixels, a sixteenth of which is 0.9375"); + map.Detach(); + f.Present(); + } + + // The same Map across two boundaries between two of its Ticks, on a + // window the compositor sized, 1.75 taken by a swapchain made outside a + // frame at the pixels it gives the window and 1 by the next frame's + // start, with the pointer resting at surface 100.25: no delta and no + // event, where a position taken along to each scale comes back with a + // float residue. + { + Fixture f = fixture(120, 640, 480); + f.Frame(); + f.Configure(640, 480); + f.Frame(); + f.Sent(); + Window& window = f.window(); + Input::Map map; + Input::Action& look = map.AddAction("Look", Input::ActionType::Vector2); + look.bindings = { Input::MouseDeltaBind{} }; + int changed = 0; + EventListener> changedSub(&look.onVector2Changed, [&](Vector) { ++changed; }); + map.Attach(window); + Motion(window, 100.25, 80); + map.Tick(); + Scale(window, 210); + f.Rebuild(); + Scale(window, 120); + f.Begin(); + Check(window.scale == 1.0f, "a scale of 1.75 taken by a swapchain, and 1 again by a frame boundary, between two Ticks"); + map.Tick(); + CheckAt(look.vector2, 0, 0, "the Map reads no delta for the pointer, which rests"); + Check(changed == 0, std::format("and fires no onVector2Changed ({})", changed)); + map.Detach(); + f.Present(); + } + + // Input whose listener takes a scale that waits, as a SetPresentMode + // outside a frame does for a window the compositor sized, through the + // swapchain it makes at the new pixels: the position the handler stores + // after the listener is in the pixels of that scale. A finger's down and + // the click of the pointer it stands in for, its move, and the move + // after an enter. + { + Fixture f = fixture(240, 640, 480); + f.Frame(); + f.Configure(320, 240); + f.Frame(); + f.Sent(); + Window& window = f.window(); + bool rebuild = false; + const auto takes = [&] { if (rebuild) { rebuild = false; f.Rebuild(); } }; + std::vector> at; + EventListener downSub(&window.onTouchDown, [&](TouchPoint) { takes(); }); + EventListener moveSub(&window.onTouchMove, [&](TouchPoint) { takes(); }); + EventListener enterSub(&window.onMouseEnter, [&] { takes(); }); + EventListener clickSub(&window.onMouseLeftClick, [&] { at.push_back(window.currentMousePos); }); + EventListener pointerSub(&window.onMouseMove, [&] { at.push_back(window.currentMousePos); }); + + Scale(window, 120); + rebuild = true; + Device::touch_down(nullptr, nullptr, 1, 0, window.surface, 0, wl_fixed_from_double(160), wl_fixed_from_double(120)); + Check(window.scale == 1.0f && at.size() == 1, "a listener of onTouchDown takes a scale of 1 that waited"); + if (at.size() == 1) CheckAt(at.back(), 160, 120, "the click is where the finger's surface-local (160,120) comes to at 1"); + Scale(window, 240); + rebuild = true; + Device::touch_motion(nullptr, nullptr, 0, 0, wl_fixed_from_double(100), wl_fixed_from_double(50)); + Check(window.scale == 2.0f && at.size() == 2, "a listener of onTouchMove takes a scale of 2 that waited"); + if (at.size() == 2) CheckAt(at.back(), 200, 100, "the move is where (100,50) comes to at 2"); + Device::touch_up(nullptr, nullptr, 2, 0, 0); + Scale(window, 180); + rebuild = true; + Device::PointerListenerHandleEnter(nullptr, nullptr, 3, window.surface, wl_fixed_from_double(100), wl_fixed_from_double(50)); + Check(window.scale == 1.5f && at.size() == 3, "a listener of onMouseEnter takes a scale of 1.5 that waited"); + if (at.size() == 3) CheckAt(at.back(), 150, 75, "the move after the enter is where (100,50) comes to at 1.5"); + Device::PointerListenerHandleLeave(nullptr, nullptr, 4, window.surface); + } + + // A scale that comes back to the one the window draws at before a frame + // took the one between: nothing is owed any more. + { + Fixture f = fixture(240, 640, 480); + f.Frame(); + f.Sent(); + Window& window = f.window(); + Scale(window, 180); + Scale(window, 240); + Check(f.owed == 1 && window.preferredScale == 240, std::format("onFrameOwed fired for the new scale and not for the one back ({})", f.owed)); + Check(!f.Begin() && window.scale == 2.0f && window.width == 640 && window.height == 480 && window.logicalWidth == 320, + "the next frame takes nothing"); + f.Present(); + Expect(f.Sent(), {}, "and sends nothing"); + Check(NothingWaits(window), "nothing is owed"); + } + + // A scale that comes while a frame is being recorded, as when a listener + // of the frame dispatched the event: the frame goes on at the scale it + // began with. A window the compositor sized takes the new one at the + // boundary after the present, with the pixels it needs, which the + // swapchain is made at there. + { + Fixture f = fixture(240, 640, 480); + f.Frame(); + f.Configure(400, 300); + f.Frame(); + f.Sent(); + Window& window = f.window(); + f.Begin(); + Scale(window, 180); + Check(window.scale == 2.0f && window.width == 800 && window.height == 600, + "a scale while a frame of a window the compositor sized is being recorded: the frame goes on at 2"); + f.Present(); + Expect(f.Sent(), {}, "its present sends nothing for the scale"); + Check(f.End() && window.scale == 1.5f && window.width == 600 && window.height == 450 && window.logicalWidth == 400 && window.logicalHeight == 300, + "the boundary after its present takes it, with the pixels for 400x300 at 1.5, and makes the swapchain at them"); + CheckAt(Motion(window, 200, 150), 300, 225, "from there a motion to the surface's middle is at the middle of the 600x450 buffers"); + Check(!f.Begin(), "the next frame's start finds nothing left to take, and makes no swapchain"); + f.Present(); + Expect(f.Sent(), {}, "and the next frame sends the surface nothing, as its size is the one it had"); + Check(NothingWaits(window), "after it nothing is owed"); + } + + // One the application sized takes it at the start of the next frame, + // the one that sends its surface the size it comes to, and not after the + // present, where it gives the window no new pixels: until that frame's + // commit the compositor maps the surface by the destination it has, so a + // motion in between is still at the pixels the scale before gives, + // those of the frame on screen, and the caret is not sent again before + // then. + { + Fixture f = fixture(240, 640, 480); + f.Frame(); + f.Sent(); + Window& window = f.window(); + zwp_text_input_v3* input = static_cast(wl_registry_bind(registry, 5, &zwp_text_input_v3_interface, 1)); + textInputId = wl_proxy_get_id(reinterpret_cast(input)); + Device::display = f.display; + Device::textInput = input; + Device::textInputWindow = &window; + window.SetTextInput(true, 120, 240, 6, 48); + Expect(f.Sent(), { "caret 60,120 3x24" }, "a caret given in the 640x480 pixels at 2 goes to the text input as such"); + + f.Begin(); + Scale(window, 120); + Check(window.scale == 2.0f && window.logicalWidth == 320 && window.logicalHeight == 240, + "a scale while a frame of a window the application sized is being recorded: the frame goes on at 2, its surface 320x240"); + f.Present(); + Expect(f.Sent(), {}, "its present sends nothing for the scale"); + Check(!f.End() && window.scale == 2.0f && window.logicalWidth == 320 && window.logicalHeight == 240, + "the boundary after its present takes nothing: the window still draws at 2, and its surface is still 320x240"); + Expect(f.Sent(), {}, "and sends nothing, the caret neither"); + CheckAt(Motion(window, 160, 120), 320, 240, + "until the next frame a motion to the surface's middle is at the middle of the frame on screen, drawn at 2"); + Check(!f.Begin() && window.scale == 1.0f && window.logicalWidth == 640 && window.logicalHeight == 480, + "the next frame's start takes it, with no swapchain: the surface is the 640x480 the pixels come to at 1"); + CheckAt(window.currentMousePos, 160, 120, "the pointer, which has not moved, is where its surface-local (160,120) comes to at 1"); + Expect(f.Sent(), { "caret 120,240 6x48" }, "and the caret goes to the text input again, at 1"); + f.Present(); + Expect(f.Sent(), { "destination 640x480" }, "the frame drawn at 1 brings the surface its size"); + Check(NothingWaits(window), "after it nothing is owed"); + + window.SetTextInput(false); + f.Sent(); + Device::textInputWindow = nullptr; + Device::textInput = nullptr; + Device::display = nullptr; + zwp_text_input_v3_destroy(input); + textInputId = 0; + } + + // A configure and a scale that come while a frame is being recorded and + // together come to the pixels the window has (an output's scale changed + // under a window that fills it): they give the window no new pixels, so + // the boundary after the present takes neither, and the next frame's start + // takes both, that frame bringing the surface its size and the + // acknowledgement. Until then a motion is still at the pixels of the + // frame on screen, and the caret is not sent again. + { + Fixture f = fixture(240, 640, 480); + f.Frame(); + f.Sent(); + Window& window = f.window(); + zwp_text_input_v3* input = static_cast(wl_registry_bind(registry, 5, &zwp_text_input_v3_interface, 1)); + textInputId = wl_proxy_get_id(reinterpret_cast(input)); + Device::display = f.display; + Device::textInput = input; + Device::textInputWindow = &window; + window.SetTextInput(true, 120, 240, 6, 48); + Expect(f.Sent(), { "caret 60,120 3x24" }, "a caret given in the 640x480 pixels at 2 goes to the text input as such"); + + f.Begin(); + Scale(window, 192); + const std::uint32_t serial = f.Configure(400, 300); + f.Present(); + Expect(f.Sent(), { "commit" }, "a scale of 1.6 and a configure of 400x300 during a frame: the configure's listener commits, and the present sends nothing"); + Check(!f.End() && window.scale == 2.0f && window.width == 640 && window.height == 480 && window.logicalWidth == 320 && window.logicalHeight == 240 + && window.deferredLogicalWidth == 400 && window.deferredLogicalHeight == 300 && window.unackedConfigure == serial, + "they come to the 640x480 pixels the window has: the boundary after the present takes neither, and the configure waits"); + Expect(f.Sent(), {}, "and sends nothing, the caret neither"); + CheckAt(Motion(window, 160, 120), 320, 240, + "until the next frame a motion to the surface's middle is at the middle of the frame on screen, drawn at 2"); + Check(!f.Begin() && window.scale == 1.6f && window.width == 640 && window.height == 480 && window.logicalWidth == 400 && window.logicalHeight == 300 + && window.logicalConfigured, + "the next frame's start takes both, with no swapchain: 400x300 at 1.6 is the 640x480 the window has"); + CheckAt(window.currentMousePos, 256, 192, "the pointer, which has not moved, is where its surface-local (160,120) comes to at 1.6"); + Expect(f.Sent(), { "caret 75,150 3x30" }, "and the caret goes to the text input again, at 1.6"); + f.Present(); + Expect(Sorted(f.Sent()), Sorted({ std::format("ack {}", serial), "destination 400x300" }), + "the frame drawn at 1.6 brings the surface its size and the acknowledgement"); + Check(NothingWaits(window), "after it nothing is owed"); + + window.SetTextInput(false); + f.Sent(); + Device::textInputWindow = nullptr; + Device::textInput = nullptr; + Device::display = nullptr; + zwp_text_input_v3_destroy(input); + textInputId = 0; + } + + // A window the compositor sized that a new scale leaves at its pixels, + // as it can one this small: the scale gives it no new pixels either, so + // it waits for the next frame's start too. + { + Fixture f = fixture(240, 640, 480); + f.Frame(); + f.Configure(50, 50); + f.Frame(); + f.Sent(); + Window& window = f.window(); + Check(window.logicalConfigured && window.width == 100 && window.height == 100, "a window the compositor sized, 50x50 at 2"); + f.Begin(); + Scale(window, 239); + f.Present(); + Check(!f.End() && window.scale == 2.0f && window.width == 100 && window.height == 100, + "a scale during its frame that leaves its 100x100 pixels: the boundary after the present takes nothing"); + Check(!f.Begin() && window.scale == 239 / 120.0f && window.width == 100 && window.height == 100 && window.logicalWidth == 50, + "the next frame's start takes it, with no swapchain"); + f.Present(); + Expect(f.Sent(), {}, "and the frame sends the surface nothing, as its size is the one it had"); + Check(NothingWaits(window), "after it nothing is owed"); + } + + // A configure without a size while a scale waits asks for nothing new, + // and is acknowledged in the listener as before: the scale is not the + // compositor's to be answered. + { + Fixture f = fixture(240, 640, 480); + f.Frame(); + f.Sent(); + Window& window = f.window(); + Scale(window, 180); + 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 a scale waits: acknowledged in the listener"); + Check(!f.Begin() && window.scale == 1.5f && window.logicalWidth == 427 && window.logicalHeight == 320, + std::format("the next frame takes the scale: 640x480 pixels at 1.5 are {}x{}", window.logicalWidth, window.logicalHeight)); + f.Present(); + Expect(f.Sent(), { "destination 427x320" }, "which it sends with its buffer"); + } + + // A configure for the size the surface has while a new scale waits, + // where its pixels at that scale are the ones the window has: 101x101 + // pixels at 2 are a surface of 51x51, which at 237/120 comes to 101x101 + // again, and at 2 to 102x102. It is no configure at the size the window + // has, since the window draws at the scale before: it waits for the + // frame that takes the scale and takes its size with it, and the window + // stays one the application sized until then, its pixels those of the + // surface it has at the scale it draws at. + { + Fixture f = fixture(240, 101, 101); + f.Frame(); + f.Sent(); + Window& window = f.window(); + Check(!window.logicalConfigured && window.logicalWidth == 51 && window.logicalHeight == 51, + "a window the application sized, 101x101 pixels at 2, its surface 51x51"); + Scale(window, 237); + const std::uint32_t serial = f.Configure(51, 51); + Expect(f.Sent(), { "commit" }, "a configure for 51x51 while a scale of 237/120 waits: not acknowledged in the listener"); + Check(!window.logicalConfigured && window.deferredLogicalWidth == 51 && window.deferredLogicalHeight == 51 + && window.unackedConfigure == serial && window.scale == 2.0f && window.width == 101 && window.height == 101, + "it waits, and the window stays one the application sized, at 101x101 drawn at 2"); + Check(!f.Begin() && window.logicalConfigured && window.scale == 237 / 120.0f && window.width == 101 && window.height == 101 + && window.logicalWidth == 51 && window.logicalHeight == 51, + "the next frame's start takes both, with no swapchain: 51x51 at 237/120 is the 101x101 the window has"); + f.Present(); + Expect(f.Sent(), { std::format("ack {}", serial) }, "and its frame acknowledges the configure, sending no destination: the surface's size is the one it has"); + Check(NothingWaits(window), "after it nothing is owed"); + } + + // Before the window has its first swapchain, as while the constructor + // waits for its first configure (KWin names the scale then): the + // listener keeps the scale and fires nothing, and the constructor takes + // it before it makes the swapchain. A scale of 0 is not taken at all. + { + // Value-initialized: the scale it takes converts the positions it + // holds, which a default-initialized window has none of. + Window window{}; + int owed = 0; + EventListener owedSub(&window.onFrameOwed, [&] { ++owed; }); + Scale(window, 0); + Check(window.preferredScale == 120, "a scale of 0 is not taken"); + Scale(window, 210); + Check(window.preferredScale == 210 && window.scale == 1.0f && owed == 0, + "a scale named before the window has a swapchain is kept, and fires nothing"); + window.width = 640; + window.height = 480; + window.MatchSizesToScale(true); + Check(window.scale == 1.75f && window.logicalWidth == 366 && window.logicalHeight == 275, + std::format("the constructor takes it before its first swapchain: 640x480 pixels at 1.75 are {}x{}", window.logicalWidth, window.logicalHeight)); } // A Resize from a listener of the frame waits in pixels, for that // frame's present. { - Fixture f = fixture(2.0f, 640, 480); + Fixture f = fixture(240, 640, 480); f.Frame(); f.Sent(); Window& window = f.window(); @@ -721,7 +1323,7 @@ int main() { // 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); + Fixture f = fixture(240, 640, 480); f.Frame(); f.Sent(); Window& window = f.window(); @@ -741,7 +1343,7 @@ int main() { // 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); + Fixture f = fixture(120, 800, 600); f.Frame(); f.Sent(); Window& window = f.window(); @@ -764,7 +1366,7 @@ int main() { // acknowledged by the frame being recorded, which no size waits behind // any more. { - Fixture f = fixture(2.0f, 640, 480); + Fixture f = fixture(240, 640, 480); f.Frame(); f.Sent(); Window& window = f.window(); @@ -787,7 +1389,7 @@ int main() { // 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); + Fixture f = fixture(240, 640, 480); f.Frame(); f.Sent(); Window& window = f.window(); @@ -804,7 +1406,7 @@ int main() { // The events: onToplevelState first, then onFrameOwed with the states set. { - Fixture f = fixture(1.0f, 320, 240); + Fixture f = fixture(120, 320, 240); f.Frame(); f.Sent(); Window& window = f.window(); @@ -822,7 +1424,7 @@ int main() { // 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); + Fixture f = fixture(120, 320, 240); f.Frame(); f.Sent(); diff --git a/tests/ResizeViewport/main.cpp b/tests/ResizeViewport/main.cpp index 11d4cb7..14be837 100644 --- a/tests/ResizeViewport/main.cpp +++ b/tests/ResizeViewport/main.cpp @@ -23,7 +23,7 @@ // 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 +// frame, a size the compositor configures, and the scales below // - 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 @@ -40,6 +40,21 @@ // 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 +// - a scale the compositor asks for by itself (#165), given by calling +// the fractional scale's listener as its event would, first with a +// scale the window does not draw at and then with the compositor's own +// again: the listener rebuilds nothing, leaves the scale the window +// draws at, and fires onFrameOwed, and the next Render() takes the +// scale. Before that Render() and after it a pointer motion to the +// surface's middle is at the middle of the buffers the window draws +// at, to within the rounding of one size from the other, and the +// pointer that rests across it is where its surface-local place comes +// to at the new scale. The window the application sized keeps its +// pixels, makes no swapchain and fires +// no onResize, and its surface takes the size they come to with that +// frame; maximized, the window the compositor sized keeps its surface's +// size and gets the swapchain made at the new pixels, firing onResize +// once from inside Render() // - the compositor raises no protocol error over any of it, and the // validation layer no error (only with CRAFTER_GRAPHICS_VALIDATION set) // @@ -55,8 +70,10 @@ // 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. +// callbacks to begin with (a locked session, a screen that is off). So it +// does for the scale's steps where the compositor has no fractional scale, +// whose listener the test then does not call. 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 @@ -320,6 +337,28 @@ std::uint32_t Pixels(std::int32_t logical, float scale) { return static_cast(std::ceil(logical * scale)); } +// As the window works out the surface-local length its pixels come to, +// for a window the application sized. +std::int32_t SurfaceLength(std::uint32_t pixels, float scale) { + return static_cast(std::ceil(pixels / scale)); +} + +// Whether a pointer motion to the middle of the window's surface, as the +// compositor reports it in surface-local units, is at the middle of its +// buffers. One size is rounded from the other, which puts up to half the +// scale (or half a pixel) between the two middles. focusedWindow is the +// window for the call alone: what the compositor's own pointer events set it +// to is put back. +bool MotionAtMiddle(Window& window) { + Window* const focused = Device::focusedWindow; + Device::focusedWindow = &window; + Device::PointerListenerHandleMotion(nullptr, nullptr, 0, wl_fixed_from_double(window.logicalWidth / 2.0), + wl_fixed_from_double(window.logicalHeight / 2.0)); + Device::focusedWindow = focused; + const float slack = std::max(0.5f, window.scale / 2.0f) + 0.01f; + return std::abs(window.currentMousePos.x - window.width / 2.0f) <= slack && std::abs(window.currentMousePos.y - window.height / 2.0f) <= slack; +} + // Dispatches until `done`, for at most `limit`. False when the display fails. template bool Pump(Done&& done, std::chrono::milliseconds limit) { @@ -377,6 +416,77 @@ Scenario Drive(bool keyboard) { Mark("frames", window.scale); }; + // #165: a scale the compositor asks for by itself, with no configure, as + // when the window goes to an output of another scale. The test cannot + // move the window, so it calls the fractional scale's listener as that + // event would, with a scale the window does not draw at, and then with + // the compositor's own again. Each time the listener rebuilds nothing + // and fires onFrameOwed, and the next Render() takes the scale: a window + // the compositor sized keeps its surface's size and gets the swapchain + // made at new pixels, with onResize from inside Render(); one the + // application sized keeps its pixels, and its surface takes the size + // they come to with that frame. The log's checks below hold every + // commit of it to its buffer at the scales the marks name. + const auto rescale = [&](std::string_view step) { + if (window.wp_scale == nullptr) { + std::println("SKIP the compositor offers no fractional scale (or no viewporter), so a scale was not driven for {}", step); + return; + } + const std::uint32_t own = window.preferredScale; + for (const std::uint32_t to : { own == 120 ? 210u : 120u, own }) { + const float scaleBefore = window.scale; + const std::uint32_t widthBefore = window.width; + const std::uint32_t heightBefore = window.height; + const std::int32_t logicalWidthBefore = window.logicalWidth; + const std::int32_t logicalHeightBefore = window.logicalHeight; + const std::uint64_t generation = window.swapchainGeneration; + const int resizesBefore = resizesInRender + resizesElsewhere; + const int inRenderBefore = resizesInRender; + const int owedBefore = owed; + const float scale = to / 120.0f; + Mark(std::format("scale-{}", step), window.scale); + Window::xdg_surface_handle_preferred_scale(&window, window.wp_scale, to); + Check(owed == owedBefore + 1, std::format("{}: a scale of {} from the compositor fires onFrameOwed", step, scale)); + Check(window.scale == scaleBefore && window.width == widthBefore && window.height == heightBefore + && window.logicalWidth == logicalWidthBefore && window.logicalHeight == logicalHeightBefore + && window.swapchainGeneration == generation && resizesInRender + resizesElsewhere == resizesBefore, + std::format("and its listener leaves the window at {}x{} drawn at {}, and the swapchain alone", window.width, window.height, window.scale)); + Check(MotionAtMiddle(window), std::format("until a frame takes the scale, a motion to the surface's middle is at the middle of the buffers drawn at {} ({},{})", + window.scale, window.currentMousePos.x, window.currentMousePos.y)); + render(1); + Check(window.scale == scale, std::format("the next Render() takes the scale ({})", window.scale)); + // The pointer rests where the motion before the Render() put it, + // at the middle of the surface as it was: what the window holds + // of it went to the new scale with no new motion. + const float restX = logicalWidthBefore / 2.0f * scale; + const float restY = logicalHeightBefore / 2.0f * scale; + Check(std::abs(window.currentMousePos.x - restX) <= 0.01f && std::abs(window.currentMousePos.y - restY) <= 0.01f, + std::format("the pointer, which has not moved, is at ({},{}), where that surface-local place comes to at {} ({},{})", + window.currentMousePos.x, window.currentMousePos.y, scale, restX, restY)); + Check(MotionAtMiddle(window), std::format("and from there that motion is at the middle of the {}x{} buffers ({},{})", + window.width, window.height, window.currentMousePos.x, window.currentMousePos.y)); + if (window.logicalConfigured) { + Check(window.logicalWidth == logicalWidthBefore && window.logicalHeight == logicalHeightBefore + && window.width == Pixels(logicalWidthBefore, scale) && window.height == Pixels(logicalHeightBefore, scale), + std::format("a window the compositor sized keeps its surface's {}x{} and takes the pixels for it ({}x{})", + window.logicalWidth, window.logicalHeight, window.width, window.height)); + Check(window.swapchainGeneration != generation && resizesInRender == inRenderBefore + 1 + && resizesInRender + resizesElsewhere == resizesBefore + 1, + "makes the swapchain at them, and fires onResize once, from inside Render()"); + } else { + Check(window.width == widthBefore && window.height == heightBefore && window.swapchainGeneration == generation + && resizesInRender + resizesElsewhere == resizesBefore, + std::format("a window the application sized keeps its {}x{} pixels: no swapchain is made, and onResize does not fire", window.width, window.height)); + Check(window.logicalWidth == SurfaceLength(widthBefore, scale) && window.logicalHeight == SurfaceLength(heightBefore, scale) + && window.sentLogicalWidth == window.logicalWidth && window.sentLogicalHeight == window.logicalHeight, + std::format("and its surface takes the {}x{} they come to, sent with that frame", window.logicalWidth, window.logicalHeight)); + } + Check(window.presentedGeneration == window.swapchainGeneration && window.scale == window.preferredScale / 120.0f, + "after that frame nothing is owed"); + render(Window::numFrames * 2); + } + }; + // The first frames, and whatever the compositor has to say of the new // window (the decoration's configure, the scale). render(Window::numFrames * 2); @@ -427,6 +537,7 @@ Scenario Drive(bool keyboard) { wl_surface_commit(window.surface); render(Window::numFrames * 2); } + rescale("a window the application sized"); // A size from the compositor. Asking to be maximized gets one where the // compositor has floating windows. @@ -477,6 +588,7 @@ Scenario Drive(bool keyboard) { Check(!window.unackedConfigure && window.deferredLogicalWidth == 0 && window.presentedGeneration == window.swapchainGeneration, "after that frame nothing is owed"); render(Window::numFrames * 2); + rescale("a window the compositor sized"); } }