Crafter.Graphics/tests/ResizeViewport/main.cpp
Jorijn van der Graaf 61f2698d13
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.
2026-11-27 15:41:23 +01:00

854 lines
46 KiB
C++

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