Add floating placement memory and edge snapping

This commit is contained in:
Samuel Onoja committed 2026-10-01 11:24:56 +01:00
1 parent 9c99b13c31
commit b29d271252
12 files changed
+1277 -84

No files matched your search

+33 -15
View File
@@ -14,6 +14,26 @@ static struct wl_shm *shm;
static struct xdg_wm_base *wm;
static struct wl_surface *surface;
static struct wl_buffer *buffer;
static int width = 640, height = 480;
static int honor_configure;
static int buffer_width, buffer_height;
static void make_buffer(void) {
if (buffer && buffer_width == width && buffer_height == height) return;
int fd = memfd_create("floating-size-test", MFD_CLOEXEC);
size_t bytes = (size_t)width * height * 4;
if (fd < 0 || ftruncate(fd, bytes)) exit(3);
uint32_t *pixels = mmap(NULL, bytes, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
if (pixels == MAP_FAILED) exit(4);
for (size_t i = 0; i < (size_t)width * height; i++) pixels[i] = 0xff12ed34;
struct wl_shm_pool *pool = wl_shm_create_pool(shm, fd, bytes);
if (buffer) wl_buffer_destroy(buffer);
buffer = wl_shm_pool_create_buffer(pool, 0, width, height, width * 4, WL_SHM_FORMAT_XRGB8888);
wl_shm_pool_destroy(pool);
munmap(pixels, bytes);
close(fd);
buffer_width = width; buffer_height = height;
}
static void ping(void *data, struct xdg_wm_base *base, uint32_t serial) {
(void)data;
xdg_wm_base_pong(base, serial);
@@ -38,42 +58,40 @@ static const struct wl_registry_listener registry_listener = {global, removed};
static void configure(void *data, struct xdg_surface *xdg, uint32_t serial) {
(void)data;
xdg_surface_ack_configure(xdg, serial);
xdg_surface_set_window_geometry(xdg, 0, 0, 640, 480);
make_buffer();
xdg_surface_set_window_geometry(xdg, 0, 0, width, height);
wl_surface_attach(surface, buffer, 0, 0);
wl_surface_damage(surface, 0, 0, 640, 480);
wl_surface_damage(surface, 0, 0, width, height);
wl_surface_commit(surface);
}
static const struct xdg_surface_listener surface_listener = {.configure = configure};
static void size(void *data, struct xdg_toplevel *top, int32_t w, int32_t h,
struct wl_array *states) {
(void)data; (void)top; (void)w; (void)h; (void)states;
(void)data; (void)top; (void)states;
if (honor_configure) {
if (w > 0) width = w;
if (h > 0) height = h;
}
}
static void close_window(void *data, struct xdg_toplevel *top) {
(void)data; (void)top; exit(0);
}
static const struct xdg_toplevel_listener top_listener = {.configure = size, .close = close_window};
int main(void) {
int main(int argc, char **argv) {
if (argc >= 4) { width = atoi(argv[2]); height = atoi(argv[3]); }
honor_configure = argc >= 5;
if (width < 1 || height < 1 || width > 2048 || height > 2048) return 5;
struct wl_display *display = wl_display_connect(NULL);
if (!display) return 1;
struct wl_registry *registry = wl_display_get_registry(display);
wl_registry_add_listener(registry, &registry_listener, NULL);
if (wl_display_roundtrip(display) < 0 || !compositor || !shm || !wm) return 2;
int fd = memfd_create("floating-size-test", MFD_CLOEXEC);
size_t bytes = 640 * 480 * 4;
if (fd < 0 || ftruncate(fd, bytes)) return 3;
uint32_t *pixels = mmap(NULL, bytes, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
if (pixels == MAP_FAILED) return 4;
for (size_t i = 0; i < 640 * 480; i++) pixels[i] = 0xff12ed34;
struct wl_shm_pool *pool = wl_shm_create_pool(shm, fd, bytes);
buffer = wl_shm_pool_create_buffer(pool, 0, 640, 480, 640 * 4, WL_SHM_FORMAT_XRGB8888);
wl_shm_pool_destroy(pool);
close(fd);
surface = wl_compositor_create_surface(compositor);
struct xdg_surface *xdg = xdg_wm_base_get_xdg_surface(wm, surface);
xdg_surface_add_listener(xdg, &surface_listener, NULL);
struct xdg_toplevel *top = xdg_surface_get_toplevel(xdg);
xdg_toplevel_add_listener(top, &top_listener, NULL);
xdg_toplevel_set_app_id(top, "ferese.test.floating-size");
xdg_toplevel_set_app_id(top, argc >= 2 ? argv[1] : "ferese.test.floating-size");
xdg_toplevel_set_title(top, "Floating size regression");
wl_surface_commit(surface);
while (wl_display_dispatch(display) != -1) {}
+4 -2
View File
@@ -90,9 +90,11 @@ class FloatingSizeTest(unittest.TestCase):
bounds = mask.getbbox()
self.assertIsNotNone(bounds, "client content was not rendered")
# The shader antialiases the outermost pixel even at radius zero.
for actual, expected in zip((bounds[2] - bounds[0], bounds[3] - bounds[1]), (640, 480)):
scale = first["scale"]
expected_size = (round(640 * scale), round(480 * scale))
for actual, expected in zip((bounds[2] - bounds[0], bounds[3] - bounds[1]), expected_size):
self.assertTrue(expected - 2 <= actual <= expected,
f"floating content cropped: {bounds}, expected 640x480")
f"floating content cropped: {bounds}, expected {expected_size}")
finally:
process.terminate()
try:
@@ -0,0 +1,152 @@
"""FERESE_TEST_FLOATING=1 python3 scripts/tests/test_floating_placement_isolated.py
Real client mapping, remembered placement, and overlap on a disposable compositor.
Requires built debug ferese/feresectl, cc, wayland-scanner and a Wayland host.
"""
import json
import os
from pathlib import Path
import signal
import subprocess
import tempfile
import time
import unittest
@unittest.skipUnless(os.environ.get("FERESE_TEST_FLOATING") == "1", "nested test is opt-in")
class FloatingPlacementTest(unittest.TestCase):
def test_first_buffer_preserves_memory_and_new_windows_avoid_overlap(self):
repo = Path(__file__).resolve().parents[2]
with tempfile.TemporaryDirectory(prefix="ferese-placement-test-") as temporary:
root = Path(temporary)
protocols = subprocess.check_output(["pkg-config", "--variable=pkgdatadir", "wayland-protocols"], text=True).strip()
xml = str(Path(protocols) / "stable/xdg-shell/xdg-shell.xml")
for kind, output in [("client-header", "xdg-shell-client-protocol.h"), ("private-code", "xdg-shell-protocol.c")]:
subprocess.run(["wayland-scanner", kind, xml, str(root / output)], check=True)
flags = subprocess.check_output(["pkg-config", "--cflags", "--libs", "wayland-client"], text=True).split()
subprocess.run(["cc", "-Wall", "-Wextra", "-I", str(root), str(repo / "scripts/tests/fixtures/floating-size.c"),
str(root / "xdg-shell-protocol.c"), "-o", str(root / "client"), *flags], check=True)
runtime = root / "runtime"
runtime.mkdir(mode=0o700)
config = root / "config/ferese"
config.mkdir(parents=True)
(config / "config.kdl").write_text('animations { enabled #false; }\n' + ''.join(
f'window-rule app-id="ferese.test.placement.{app}" floating=#true\n' for app in ["remembered", "second", "third"]) +
'window-rule app-id="ferese.test.placement.fullscreen" floating=#true width=240 height=160 fullscreen=#true\n' +
'window-rule app-id="ferese.test.placement.maximized" floating=#true width=240 height=160\n')
state = root / "state/ferese"
state.mkdir(parents=True)
memory = state / "floating.json"
memory.write_text(json.dumps({"ferese.test.placement.remembered": {"output": "ferese-winit", "fractions": [.1, .1, .2, .2]}}))
before = memory.read_bytes()
display = Path(os.environ["WAYLAND_DISPLAY"])
if not display.is_absolute():
display = Path(os.environ["XDG_RUNTIME_DIR"]) / display
env = dict(os.environ, XDG_RUNTIME_DIR=str(runtime), XDG_CONFIG_HOME=str(root / "config"),
XDG_STATE_HOME=str(root / "state"), WAYLAND_DISPLAY=str(display))
env.pop("WAYLAND_SOCKET", None)
env.pop("FERESE_SHELL_CONTROL_SOCKET", None)
children = []
def launch(command, **kwargs):
child = subprocess.Popen(command, env=env, start_new_session=True, **kwargs)
children.append(child)
return child
def command(*args):
return json.loads(subprocess.check_output([str(repo / "target/debug/feresectl"), *args], env=env, timeout=5))
with (root / "compositor.log").open("w") as log:
try:
bus = launch(["dbus-daemon", "--session", "--nofork", "--print-address=1"], stdout=subprocess.PIPE, text=True)
env["DBUS_SESSION_BUS_ADDRESS"] = bus.stdout.readline().strip()
compositor = launch([str(repo / "target/debug/ferese"), "--backend", "nested"], stdout=log, stderr=log)
deadline = time.monotonic() + 10
while not (runtime / "ferese/control.sock").is_socket():
if compositor.poll() is not None or time.monotonic() > deadline:
self.fail((root / "compositor.log").read_text())
time.sleep(.025)
socket = next(p for p in runtime.glob("wayland-*") if not p.name.endswith(".lock"))
env["WAYLAND_DISPLAY"] = str(socket)
for app in ["remembered", "second", "third"]:
launch([str(root / "client"), "ferese.test.placement." + app, "240", "160"], stdout=log, stderr=log)
deadline = time.monotonic() + 5
while True:
windows = command("get-windows")
if any(w["app_id"] == "ferese.test.placement." + app and w["width"] == 240 and w["height"] == 160 for w in windows):
break
if time.monotonic() > deadline:
self.fail((root / "compositor.log").read_text() + repr(windows))
time.sleep(.025)
remembered = next(w for w in windows if w["app_id"].endswith("remembered"))
output = next(o for o in command("get-outputs") if o["enabled"])
self.assertAlmostEqual(remembered["x"], output["x"] + .1 * output["width"], delta=1)
self.assertAlmostEqual(remembered["y"], output["y"] + .1 * output["height"], delta=1)
for i, a in enumerate(windows):
for b in windows[i+1:]:
width = max(0, min(a["x"]+a["width"], b["x"]+b["width"])-max(a["x"], b["x"]))
height = max(0, min(a["y"]+a["height"], b["y"]+b["height"])-max(a["y"], b["y"]))
self.assertEqual(width * height, 0, repr(windows))
self.assertEqual(memory.read_bytes(), before, "mapping must not save geometry every frame")
# The third window is focused. Its old floating rectangle
# must survive a trip through the tiled layout.
third = next(w for w in windows if w["app_id"].endswith("third"))
command("toggle-floating")
command("toggle-floating")
deadline = time.monotonic() + 5
expected = tuple(third[k] for k in ["x", "y", "width", "height"])
while True:
restored = next(w for w in command("get-windows") if w["app_id"].endswith("third"))
actual = tuple(restored[k] for k in ["x", "y", "width", "height"])
if actual == expected:
break
if time.monotonic() > deadline:
self.fail(f"floating rectangle changed after toggling: {expected} -> {actual}")
time.sleep(.025)
self.assertEqual(memory.read_bytes(), before, "nested previews must not persist drag memory")
for mode in ["fullscreen", "maximized"]:
app = "ferese.test.placement." + mode
if mode == "maximized":
# Tree mode exercises the full-work-area maximization
# path; scrolling mode uses column maximization.
command("toggle-layout")
launch([str(root / "client"), app, "240", "160", "configured"], stdout=log, stderr=log)
if mode == "maximized":
deadline = time.monotonic() + 5
while not any(w["app_id"] == app and w["capture_width"] == 240 for w in command("get-windows")):
if time.monotonic() > deadline:
self.fail("maximized regression client did not map")
time.sleep(.025)
command("toggle-maximized")
deadline = time.monotonic() + 5
while True:
enlarged = next((w for w in command("get-windows") if w["app_id"] == app), None)
if enlarged and enlarged["capture_width"] > 240 and enlarged["capture_height"] > 160:
break
if time.monotonic() > deadline:
self.fail(f"{mode} client did not commit its enlarged buffer: {enlarged}")
time.sleep(.025)
command("toggle-" + mode)
deadline = time.monotonic() + 5
while True:
restored = next(w for w in command("get-windows") if w["app_id"] == app)
if (restored["width"], restored["height"], restored["capture_width"], restored["capture_height"]) == (240, 160, 240, 160):
break
if time.monotonic() > deadline:
self.fail(f"{mode} first buffer overwrote normal floating geometry: {restored}")
time.sleep(.025)
finally:
for child in reversed(children):
if child.poll() is None:
os.killpg(child.pid, signal.SIGTERM)
try:
child.wait(timeout=3)
except subprocess.TimeoutExpired:
os.killpg(child.pid, signal.SIGKILL)
child.wait(timeout=3)
if child.stdout is not None:
child.stdout.close()
if __name__ == "__main__":
unittest.main()