mirror of
https://github.com/marcoallegretti/WEFT_OS.git
synced 2026-11-22 08:13:59 +00:00
test: verify native pointer and keyboard input through weft-compositor
Nothing checked that input reaches a page through the compositor; the Servo hosts' input forwarding had only been compiled. tests/frame/check_input.py runs weft-servo-shell with tests/frame/input.html on the nested desktop and injects real X input with xdotool into weft-compositor's window. The compositor's winit backend routes it through its seat to the Wayland client, which has no X display. The page must react in its presented pixels: clicks 6 px either side of the boundary between its halves change only the half under the pointer, and the a and Shift+a key presses arrive with the right key value and modifier. The harness gives the compositor's X window input focus, as a window manager would; the client's keyboard focus comes from the compositor's click-to-focus. The nested desktop setup shared with check_frame.py moves to tests/frame/session.py. Xvfb now reports the display it picked through -displayfd, so concurrent runs cannot share an X server, and a run clears only the logs and capture it writes. Validation: - check_input.py: 3 of 3 runs pass; two concurrent runs pass - negative pages fail: no script; left click handled by the right half; an element extending the left half 20 px across the boundary; a key handler ignoring Shift - check_frame.py --host system, --host app, --host app --slow-style 3 pass after the refactor - unverified: key release and repeat, pointer motion and button release events, wheel, focus loss, non-US layouts, non-ASCII text, scale changes, weft-app-shell input
This commit is contained in:
parent
64f8cff6fd
commit
ae176aae93
6 changed files with 460 additions and 212 deletions
|
|
@ -116,9 +116,16 @@ exercised is listed as unverified.
|
|||
the software path (Ubuntu 24.04, x86_64; `check_frame.py --host system`,
|
||||
`--host app` and `--host app --slow-style 3`, five runs each). The EGL path,
|
||||
DRM sessions, resize, output scale and idle wakeup are unverified.
|
||||
- **Input:** keyboard and pointer events are forwarded through
|
||||
`WebView::notify_input_event`; delivery through the compositor is
|
||||
unverified.
|
||||
- **Input:** `tests/frame/check_input.py` verifies, on the same nested
|
||||
setup, that left clicks 6 px either side of a boundary reach the element
|
||||
under the pointer, and that `a` and `Shift+a` key presses reach the page with
|
||||
the right key value and modifier, using real X input that `weft-compositor`
|
||||
routes to `weft-servo-shell` (three runs). The harness gives the compositor's
|
||||
X window input focus, as a window manager would; the client's keyboard focus
|
||||
comes from the compositor's click-to-focus. Unverified: key release and
|
||||
repeat, pointer motion, enter/leave and button release events, other buttons,
|
||||
wheel, focus loss, non-US layouts, non-ASCII text, scale changes and
|
||||
`weft-app-shell` input.
|
||||
- **`backdrop-filter`**: the parsing (Stylo `f1ba496`) and rendering (Servo
|
||||
`8e7dc40`, `f0bb1aa`) patches are selected by the lockfile; rendering is
|
||||
unverified.
|
||||
|
|
|
|||
|
|
@ -67,6 +67,16 @@ reveals the page so premature readiness becomes visible.
|
|||
|
||||
Logs and the last capture are written to `target/frame-check`.
|
||||
|
||||
`tests/frame/check_input.py` uses the same nested desktop to send real X
|
||||
pointer and keyboard input (with `xdotool`) through `weft-compositor` to
|
||||
`weft-servo-shell` showing `tests/frame/input.html`, and checks that the
|
||||
page reacts to clicks on either side of a boundary and to the `a` and
|
||||
`Shift+a` keys. Logs and the last capture are written to `target/input-check`.
|
||||
|
||||
```sh
|
||||
python3 tests/frame/check_input.py
|
||||
```
|
||||
|
||||
## Demo apps (wasm32-wasip2)
|
||||
|
||||
Each demo is a standalone crate in `examples/`. Pre-built `app.wasm` binaries are committed. To rebuild:
|
||||
|
|
|
|||
|
|
@ -17,27 +17,22 @@ early readiness observable: the page stays hidden until a stylesheet that a
|
|||
local HTTP server delivers after the delay reveals it, so a host that reports
|
||||
READY before the document has loaded shows no page within the grace period.
|
||||
|
||||
Requires Xvfb, xwd and ImageMagick's convert. Processes are started from
|
||||
argument arrays and are always terminated before the harness exits.
|
||||
Requires Xvfb, xwd and ImageMagick's convert; see session.py.
|
||||
"""
|
||||
|
||||
import argparse
|
||||
import http.server
|
||||
import os
|
||||
import re
|
||||
import shutil
|
||||
import signal
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
import threading
|
||||
import time
|
||||
from pathlib import Path
|
||||
|
||||
sys.dont_write_bytecode = True
|
||||
from session import ROOT, Desktop, SessionError, bounding_box, missing_tools, parse_ppm # noqa: E402
|
||||
|
||||
|
||||
HERE = Path(__file__).resolve().parent
|
||||
ROOT = HERE.parents[1]
|
||||
SCREEN = (1024, 768)
|
||||
COLORS = {
|
||||
"red": (255, 0, 0),
|
||||
"green": (0, 255, 0),
|
||||
|
|
@ -46,52 +41,6 @@ COLORS = {
|
|||
}
|
||||
MIN_SIDE = 40
|
||||
MIN_TEXT_PIXELS = 30
|
||||
ANSI_ESCAPE = re.compile(r"\x1b\[[0-9;]*m")
|
||||
|
||||
|
||||
def parse_ppm(data):
|
||||
"""Decode a binary P6 PPM into (width, height, bytes)."""
|
||||
tokens = []
|
||||
index = 0
|
||||
while len(tokens) < 4:
|
||||
while data[index:index + 1].isspace():
|
||||
index += 1
|
||||
if data[index:index + 1] == b"#":
|
||||
index = data.index(b"\n", index) + 1
|
||||
continue
|
||||
end = index
|
||||
while not data[end:end + 1].isspace():
|
||||
end += 1
|
||||
tokens.append(data[index:end])
|
||||
index = end
|
||||
magic, width, height, maxval = tokens
|
||||
if magic != b"P6" or int(maxval) != 255:
|
||||
raise ValueError("expected an 8-bit P6 image")
|
||||
width, height = int(width), int(height)
|
||||
pixels = data[index + 1:index + 1 + width * height * 3]
|
||||
if len(pixels) != width * height * 3:
|
||||
raise ValueError("truncated image")
|
||||
return width, height, pixels
|
||||
|
||||
|
||||
def bounding_box(width, height, pixels, color):
|
||||
"""Return (x0, y0, x1, y1) of pixels exactly matching color, or None."""
|
||||
target = bytes(color)
|
||||
xs, ys = [], []
|
||||
for y in range(0, height, 2):
|
||||
row = pixels[y * width * 3:(y + 1) * width * 3]
|
||||
start = row.find(target)
|
||||
while start != -1:
|
||||
if start % 3 == 0:
|
||||
xs.append(start // 3)
|
||||
ys.append(y)
|
||||
start = row.find(target, start + 3)
|
||||
else:
|
||||
# A match spanning two pixels; realign on the next byte.
|
||||
start = row.find(target, start + 1)
|
||||
if not xs:
|
||||
return None
|
||||
return min(xs), min(ys), max(xs), max(ys)
|
||||
|
||||
|
||||
def dark_pixels(width, pixels, box):
|
||||
|
|
@ -183,57 +132,6 @@ def hidden_until_styled(page, destination, port):
|
|||
return destination
|
||||
|
||||
|
||||
def capture(display):
|
||||
xwd = subprocess.run(["xwd", "-root", "-silent", "-display", display],
|
||||
capture_output=True, check=True, timeout=20)
|
||||
ppm = subprocess.run(["convert", "xwd:-", "ppm:-"], input=xwd.stdout,
|
||||
capture_output=True, check=True, timeout=20)
|
||||
return ppm.stdout
|
||||
|
||||
|
||||
def free_display():
|
||||
for number in range(90, 140):
|
||||
if not Path(f"/tmp/.X11-unix/X{number}").exists() and \
|
||||
not Path(f"/tmp/.X{number}-lock").exists():
|
||||
return f":{number}"
|
||||
raise RuntimeError("no free X display number")
|
||||
|
||||
|
||||
def start(command, log, env):
|
||||
return subprocess.Popen(command, stdout=log, stderr=subprocess.STDOUT, env=env,
|
||||
start_new_session=True)
|
||||
|
||||
|
||||
def signal_group(process, signum):
|
||||
try:
|
||||
os.killpg(process.pid, signum)
|
||||
except ProcessLookupError:
|
||||
pass
|
||||
|
||||
|
||||
def stop(process):
|
||||
"""Terminate the process and everything left in its process group."""
|
||||
if process is None:
|
||||
return
|
||||
signal_group(process, signal.SIGTERM)
|
||||
try:
|
||||
process.wait(timeout=10)
|
||||
except subprocess.TimeoutExpired:
|
||||
signal_group(process, signal.SIGKILL)
|
||||
process.wait(timeout=10)
|
||||
signal_group(process, signal.SIGKILL)
|
||||
|
||||
|
||||
def wait_for(predicate, timeout, interval=0.5):
|
||||
deadline = time.monotonic() + timeout
|
||||
while time.monotonic() < deadline:
|
||||
result = predicate()
|
||||
if result:
|
||||
return result
|
||||
time.sleep(interval)
|
||||
return None
|
||||
|
||||
|
||||
def main(argv=None):
|
||||
parser = argparse.ArgumentParser(description=__doc__,
|
||||
formatter_class=argparse.RawDescriptionHelpFormatter)
|
||||
|
|
@ -255,98 +153,33 @@ def main(argv=None):
|
|||
name = "weft-servo-shell" if args.host == "system" else "weft-app-shell"
|
||||
args.shell = ROOT / "target/debug" / name
|
||||
|
||||
for tool in ("Xvfb", "xwd", "convert"):
|
||||
if shutil.which(tool) is None:
|
||||
print(f"missing required tool: {tool}", file=sys.stderr)
|
||||
return 2
|
||||
for binary in (args.compositor, args.shell):
|
||||
if not binary.is_file():
|
||||
print(f"missing binary: {binary}", file=sys.stderr)
|
||||
missing = missing_tools() + [str(b) for b in (args.compositor, args.shell) if not b.is_file()]
|
||||
if missing:
|
||||
print("missing: " + ", ".join(missing), file=sys.stderr)
|
||||
return 2
|
||||
|
||||
args.output.mkdir(parents=True, exist_ok=True)
|
||||
runtime = Path(tempfile.mkdtemp(prefix="weft-frame-"))
|
||||
runtime.chmod(0o700)
|
||||
display = free_display()
|
||||
base_env = {key: value for key, value in os.environ.items()
|
||||
if key not in ("DISPLAY", "WAYLAND_DISPLAY", "WAYLAND_SOCKET")}
|
||||
base_env["XDG_RUNTIME_DIR"] = str(runtime)
|
||||
base_env.setdefault("RUST_LOG", "info")
|
||||
|
||||
page = args.page
|
||||
style_server = None
|
||||
try:
|
||||
with Desktop(args.compositor, args.output, outputs=["frame.ppm"]) as desktop:
|
||||
page = args.page
|
||||
if args.slow_style:
|
||||
style_server = slow_style_server(args.slow_style)
|
||||
page = hidden_until_styled(args.page, runtime / "page.html",
|
||||
page = hidden_until_styled(args.page, desktop.runtime / "page.html",
|
||||
style_server.server_address[1])
|
||||
|
||||
processes = []
|
||||
logs = {name: open(args.output / f"{name}.log", "w", encoding="utf-8")
|
||||
for name in ("xvfb", "compositor", "shell")}
|
||||
try:
|
||||
xvfb = start(["Xvfb", display, "-screen", "0", f"{SCREEN[0]}x{SCREEN[1]}x24",
|
||||
"-nolisten", "tcp"], logs["xvfb"], base_env)
|
||||
processes.append(xvfb)
|
||||
if not wait_for(lambda: Path(f"/tmp/.X11-unix/X{display[1:]}").exists(), 15):
|
||||
print("Xvfb did not start", file=sys.stderr)
|
||||
return 1
|
||||
|
||||
compositor_env = dict(base_env, DISPLAY=display)
|
||||
compositor = start([str(args.compositor), "--winit"], logs["compositor"],
|
||||
compositor_env)
|
||||
processes.append(compositor)
|
||||
compositor_log = args.output / "compositor.log"
|
||||
|
||||
def socket_name():
|
||||
if compositor.poll() is not None:
|
||||
return "exited"
|
||||
text = ANSI_ESCAPE.sub("", compositor_log.read_text(encoding="utf-8",
|
||||
errors="replace"))
|
||||
match = re.search(r'socket_name="([^"]+)"', text)
|
||||
return match and match.group(1)
|
||||
|
||||
socket = wait_for(socket_name, 30)
|
||||
if socket in (None, "exited"):
|
||||
print(f"compositor did not open a Wayland socket; see {compositor_log}",
|
||||
file=sys.stderr)
|
||||
return 1
|
||||
|
||||
shell_env = dict(base_env, WAYLAND_DISPLAY=socket)
|
||||
if args.host == "system":
|
||||
shell_env["WEFT_SYSTEM_UI_HTML"] = str(page.resolve())
|
||||
command = [str(args.shell)]
|
||||
shell = desktop.launch_client(
|
||||
"shell", [args.shell], {"WEFT_SYSTEM_UI_HTML": str(page.resolve())})
|
||||
else:
|
||||
shell_env["WEFT_APP_STORE"] = str(install_app(runtime / "store", page))
|
||||
command = [str(args.shell), APP_ID, "1"]
|
||||
shell = start(command, logs["shell"], shell_env)
|
||||
processes.append(shell)
|
||||
shell_log = args.output / "shell.log"
|
||||
|
||||
def ready_printed():
|
||||
text = shell_log.read_text(encoding="utf-8", errors="replace")
|
||||
return any(line.strip() == "READY" for line in text.splitlines())
|
||||
|
||||
problems = ["no frame captured"]
|
||||
screenshot = None
|
||||
ready_at = None
|
||||
deadline = time.monotonic() + args.timeout
|
||||
while time.monotonic() < deadline:
|
||||
if shell.poll() is not None:
|
||||
problems = [f"shell exited with status {shell.returncode}"]
|
||||
break
|
||||
if args.host == "app" and ready_at is None and ready_printed():
|
||||
ready_at = time.monotonic()
|
||||
ready = ready_at is not None
|
||||
screenshot = capture(display)
|
||||
problems = evaluate(*parse_ppm(screenshot))
|
||||
if ready and problems and time.monotonic() - ready_at > COMPOSITE_GRACE:
|
||||
problems = [f"page not on screen {COMPOSITE_GRACE:g} s after READY"] + problems
|
||||
break
|
||||
if not problems and (args.host == "system" or ready):
|
||||
break
|
||||
if not problems:
|
||||
problems = ["frame presented but READY not printed"]
|
||||
time.sleep(1)
|
||||
store = install_app(desktop.runtime / "store", page)
|
||||
shell = desktop.launch_client(
|
||||
"shell", [args.shell, APP_ID, "1"], {"WEFT_APP_STORE": str(store)})
|
||||
problems, screenshot = watch(desktop, shell, args)
|
||||
except SessionError as error:
|
||||
print(error, file=sys.stderr)
|
||||
return 1
|
||||
finally:
|
||||
if style_server is not None:
|
||||
style_server.shutdown()
|
||||
|
||||
if screenshot is not None:
|
||||
(args.output / "frame.ppm").write_bytes(screenshot)
|
||||
|
|
@ -356,14 +189,32 @@ def main(argv=None):
|
|||
return 1
|
||||
print(f"frame check passed; capture in {args.output / 'frame.ppm'}")
|
||||
return 0
|
||||
finally:
|
||||
for process in reversed(processes):
|
||||
stop(process)
|
||||
if style_server is not None:
|
||||
style_server.shutdown()
|
||||
for log in logs.values():
|
||||
log.close()
|
||||
shutil.rmtree(runtime, ignore_errors=True)
|
||||
|
||||
|
||||
def watch(desktop, shell, args):
|
||||
"""Capture until the frame matches, the host exits or the time runs out."""
|
||||
def ready_printed():
|
||||
return any(line.strip() == "READY" for line in desktop.log_text("shell").splitlines())
|
||||
|
||||
problems = ["no frame captured"]
|
||||
screenshot = None
|
||||
ready_at = None
|
||||
deadline = time.monotonic() + args.timeout
|
||||
while time.monotonic() < deadline:
|
||||
if shell.poll() is not None:
|
||||
return [f"shell exited with status {shell.returncode}"], screenshot
|
||||
if args.host == "app" and ready_at is None and ready_printed():
|
||||
ready_at = time.monotonic()
|
||||
screenshot = desktop.capture()
|
||||
problems = evaluate(*parse_ppm(screenshot))
|
||||
if ready_at is not None and problems and time.monotonic() - ready_at > COMPOSITE_GRACE:
|
||||
return [f"page not on screen {COMPOSITE_GRACE:g} s after READY"] + problems, screenshot
|
||||
if not problems and (args.host == "system" or ready_at is not None):
|
||||
return [], screenshot
|
||||
if not problems:
|
||||
problems = ["frame presented but READY not printed"]
|
||||
time.sleep(1)
|
||||
return problems, screenshot
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
|
|
|
|||
140
tests/frame/check_input.py
Normal file
140
tests/frame/check_input.py
Normal file
|
|
@ -0,0 +1,140 @@
|
|||
"""Check that native pointer and keyboard input reaches a page through weft-compositor.
|
||||
|
||||
The harness runs weft-servo-shell with `input.html` on a nested desktop (see
|
||||
session.py) and injects real X input into the compositor's window with
|
||||
xdotool (after giving that window X input focus, since Xvfb runs without a
|
||||
window manager), which weft-compositor's winit backend receives and routes to
|
||||
the focused Wayland client. Each step must change the page as the page's script
|
||||
defines, as seen in the presented pixels:
|
||||
|
||||
1. A click 6 px inside the left half's right edge turns only the left half
|
||||
green; the right half must stay blue.
|
||||
2. Typing `a` turns the right half yellow.
|
||||
3. Typing `Shift+a` turns the right half magenta, which checks the modifier.
|
||||
4. A click 6 px inside the right half's left edge turns the right half white.
|
||||
|
||||
The two clicks straddle the boundary between the halves, so a pointer
|
||||
position that is scaled or offset by more than a few pixels fails.
|
||||
|
||||
Requires Xvfb, xwd, ImageMagick's convert and xdotool.
|
||||
"""
|
||||
|
||||
import argparse
|
||||
import shutil
|
||||
import subprocess
|
||||
import sys
|
||||
import time
|
||||
from pathlib import Path
|
||||
|
||||
sys.dont_write_bytecode = True
|
||||
from session import ROOT, Desktop, SessionError, bounding_box, missing_tools, parse_ppm # noqa: E402
|
||||
|
||||
|
||||
HERE = Path(__file__).resolve().parent
|
||||
RED, GREEN, BLUE = (255, 0, 0), (0, 255, 0), (0, 0, 255)
|
||||
WHITE, YELLOW, MAGENTA = (255, 255, 255), (255, 255, 0), (255, 0, 255)
|
||||
MIN_SIDE = 40
|
||||
|
||||
|
||||
def region(screenshot, color):
|
||||
"""Bounding box of `color` if it covers a page half, else None."""
|
||||
box = bounding_box(*parse_ppm(screenshot), color)
|
||||
if box and box[2] - box[0] >= MIN_SIDE and box[3] - box[1] >= MIN_SIDE:
|
||||
return box
|
||||
return None
|
||||
|
||||
|
||||
STARTUP_TIMEOUT = 120.0
|
||||
EDGE_INSET = 6
|
||||
|
||||
|
||||
class Steps:
|
||||
def __init__(self, desktop, shell, timeout):
|
||||
self.desktop = desktop
|
||||
self.shell = shell
|
||||
self.timeout = timeout
|
||||
self.screenshot = None
|
||||
self.xdotool_path = shutil.which("xdotool")
|
||||
|
||||
def expect(self, description, present, absent=(), timeout=None):
|
||||
"""Wait until every colour in `present` and none in `absent` is shown."""
|
||||
deadline = time.monotonic() + (self.timeout if timeout is None else timeout)
|
||||
while time.monotonic() < deadline:
|
||||
if self.shell.poll() is not None:
|
||||
raise AssertionError(f"shell exited with status {self.shell.returncode}")
|
||||
self.screenshot = self.desktop.capture()
|
||||
boxes = {color: region(self.screenshot, color) for color in present}
|
||||
if all(boxes.values()) and not any(region(self.screenshot, c) for c in absent):
|
||||
return boxes
|
||||
time.sleep(0.5)
|
||||
raise AssertionError(f"{description}: expected page state not shown")
|
||||
|
||||
def xdotool(self, *arguments):
|
||||
subprocess.run([self.xdotool_path, *arguments], env={"DISPLAY": self.desktop.display},
|
||||
check=True, timeout=20)
|
||||
|
||||
def click(self, x, y):
|
||||
self.xdotool("mousemove", "--sync", str(x), str(y))
|
||||
self.xdotool("click", "1")
|
||||
|
||||
|
||||
def run(steps):
|
||||
boxes = steps.expect("initial page", [RED, BLUE], timeout=STARTUP_TIMEOUT)
|
||||
# Xvfb runs without a window manager, so give the compositor's window the
|
||||
# X input focus that a real session's window manager would.
|
||||
steps.xdotool("search", "--class", "weft-compositor", "windowfocus", "--sync")
|
||||
left, right = boxes[RED], boxes[BLUE]
|
||||
middle = (left[1] + left[3]) // 2
|
||||
steps.click(left[2] - EDGE_INSET, middle)
|
||||
steps.expect("click near the right edge of the left half", [GREEN, BLUE],
|
||||
absent=[RED, WHITE])
|
||||
steps.xdotool("key", "a")
|
||||
steps.expect("key a", [GREEN, YELLOW], absent=[BLUE])
|
||||
steps.xdotool("key", "shift+a")
|
||||
steps.expect("key Shift+a", [GREEN, MAGENTA], absent=[YELLOW])
|
||||
steps.click(right[0] + EDGE_INSET, middle)
|
||||
steps.expect("click near the left edge of the right half", [GREEN, WHITE],
|
||||
absent=[MAGENTA, RED])
|
||||
|
||||
|
||||
def main(argv=None):
|
||||
parser = argparse.ArgumentParser(description=__doc__,
|
||||
formatter_class=argparse.RawDescriptionHelpFormatter)
|
||||
parser.add_argument("--compositor", type=Path, default=ROOT / "target/debug/weft-compositor")
|
||||
parser.add_argument("--shell", type=Path, default=ROOT / "target/debug/weft-servo-shell")
|
||||
parser.add_argument("--page", type=Path, default=HERE / "input.html")
|
||||
parser.add_argument("--timeout", type=float, default=30.0,
|
||||
help="seconds to wait for each expected page state")
|
||||
parser.add_argument("--output", type=Path, default=ROOT / "target/input-check",
|
||||
help="directory for logs and the last capture")
|
||||
args = parser.parse_args(argv)
|
||||
|
||||
missing = missing_tools() + [tool for tool in ("xdotool",) if shutil.which(tool) is None]
|
||||
missing += [str(b) for b in (args.compositor, args.shell) if not b.is_file()]
|
||||
if missing:
|
||||
print("missing: " + ", ".join(missing), file=sys.stderr)
|
||||
return 2
|
||||
|
||||
try:
|
||||
with Desktop(args.compositor, args.output, outputs=["input.ppm"]) as desktop:
|
||||
shell = desktop.launch_client("shell", [args.shell],
|
||||
{"WEFT_SYSTEM_UI_HTML": str(args.page.resolve())})
|
||||
steps = Steps(desktop, shell, args.timeout)
|
||||
try:
|
||||
run(steps)
|
||||
except AssertionError as failure:
|
||||
print(f"input check failed: {failure}", file=sys.stderr)
|
||||
print(f"logs and last capture in {args.output}", file=sys.stderr)
|
||||
return 1
|
||||
finally:
|
||||
if steps.screenshot is not None:
|
||||
(args.output / "input.ppm").write_bytes(steps.screenshot)
|
||||
except SessionError as error:
|
||||
print(error, file=sys.stderr)
|
||||
return 1
|
||||
print("input check passed")
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
31
tests/frame/input.html
Normal file
31
tests/frame/input.html
Normal file
|
|
@ -0,0 +1,31 @@
|
|||
<!DOCTYPE html>
|
||||
<html>
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<title>WEFT input reference</title>
|
||||
<style>
|
||||
html, body { margin: 0; padding: 0; width: 100%; height: 100%; overflow: hidden; }
|
||||
body { display: grid; grid-template-columns: 1fr 1fr; }
|
||||
#left { background: rgb(255, 0, 0); }
|
||||
#right { background: rgb(0, 0, 255); }
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<div id="left"></div>
|
||||
<div id="right"></div>
|
||||
<script>
|
||||
// Each input the harness sends changes one half to a colour it checks for.
|
||||
const left = document.getElementById("left");
|
||||
const right = document.getElementById("right");
|
||||
left.addEventListener("click", () => { left.style.background = "rgb(0, 255, 0)"; });
|
||||
right.addEventListener("click", () => { right.style.background = "rgb(255, 255, 255)"; });
|
||||
document.addEventListener("keydown", (event) => {
|
||||
if (event.key === "a" && !event.shiftKey) {
|
||||
right.style.background = "rgb(255, 255, 0)";
|
||||
} else if (event.key === "A" && event.shiftKey) {
|
||||
right.style.background = "rgb(255, 0, 255)";
|
||||
}
|
||||
});
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
209
tests/frame/session.py
Normal file
209
tests/frame/session.py
Normal file
|
|
@ -0,0 +1,209 @@
|
|||
"""Nested WEFT desktop for graphical tests: Xvfb, weft-compositor and Wayland clients.
|
||||
|
||||
`Desktop` starts Xvfb and weft-compositor with its winit backend, launches
|
||||
clients on the compositor's Wayland socket, captures the X screen and
|
||||
terminates every process it started when the `with` block ends. Processes are
|
||||
started from argument arrays in their own process groups.
|
||||
"""
|
||||
|
||||
import os
|
||||
import re
|
||||
import shutil
|
||||
import signal
|
||||
import subprocess
|
||||
import tempfile
|
||||
import time
|
||||
from pathlib import Path
|
||||
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[2]
|
||||
SCREEN = (1024, 768)
|
||||
ANSI_ESCAPE = re.compile(r"\x1b\[[0-9;]*m")
|
||||
REQUIRED_TOOLS = ("Xvfb", "xwd", "convert")
|
||||
|
||||
|
||||
class SessionError(Exception):
|
||||
"""The nested desktop could not be started."""
|
||||
|
||||
|
||||
def parse_ppm(data):
|
||||
"""Decode a binary P6 PPM into (width, height, bytes)."""
|
||||
tokens = []
|
||||
index = 0
|
||||
while len(tokens) < 4:
|
||||
while data[index:index + 1].isspace():
|
||||
index += 1
|
||||
if data[index:index + 1] == b"#":
|
||||
index = data.index(b"\n", index) + 1
|
||||
continue
|
||||
end = index
|
||||
while not data[end:end + 1].isspace():
|
||||
end += 1
|
||||
tokens.append(data[index:end])
|
||||
index = end
|
||||
magic, width, height, maxval = tokens
|
||||
if magic != b"P6" or int(maxval) != 255:
|
||||
raise ValueError("expected an 8-bit P6 image")
|
||||
width, height = int(width), int(height)
|
||||
pixels = data[index + 1:index + 1 + width * height * 3]
|
||||
if len(pixels) != width * height * 3:
|
||||
raise ValueError("truncated image")
|
||||
return width, height, pixels
|
||||
|
||||
|
||||
def bounding_box(width, height, pixels, color):
|
||||
"""Return (x0, y0, x1, y1) of pixels exactly matching color, or None."""
|
||||
target = bytes(color)
|
||||
xs, ys = [], []
|
||||
for y in range(0, height, 2):
|
||||
row = pixels[y * width * 3:(y + 1) * width * 3]
|
||||
start = row.find(target)
|
||||
while start != -1:
|
||||
if start % 3 == 0:
|
||||
xs.append(start // 3)
|
||||
ys.append(y)
|
||||
start = row.find(target, start + 3)
|
||||
else:
|
||||
# A match spanning two pixels; realign on the next byte.
|
||||
start = row.find(target, start + 1)
|
||||
if not xs:
|
||||
return None
|
||||
return min(xs), min(ys), max(xs), max(ys)
|
||||
|
||||
|
||||
def pixel(width, pixels, x, y):
|
||||
offset = (y * width + x) * 3
|
||||
return tuple(pixels[offset:offset + 3])
|
||||
|
||||
|
||||
def missing_tools():
|
||||
return [tool for tool in REQUIRED_TOOLS if shutil.which(tool) is None]
|
||||
|
||||
|
||||
def wait_for(predicate, timeout, interval=0.5):
|
||||
deadline = time.monotonic() + timeout
|
||||
while time.monotonic() < deadline:
|
||||
result = predicate()
|
||||
if result:
|
||||
return result
|
||||
time.sleep(interval)
|
||||
return None
|
||||
|
||||
|
||||
def _signal_group(process, signum):
|
||||
try:
|
||||
os.killpg(process.pid, signum)
|
||||
except ProcessLookupError:
|
||||
pass
|
||||
|
||||
|
||||
def _stop(process):
|
||||
"""Terminate the process and everything left in its process group."""
|
||||
_signal_group(process, signal.SIGTERM)
|
||||
try:
|
||||
process.wait(timeout=10)
|
||||
except subprocess.TimeoutExpired:
|
||||
_signal_group(process, signal.SIGKILL)
|
||||
process.wait(timeout=10)
|
||||
_signal_group(process, signal.SIGKILL)
|
||||
|
||||
|
||||
class Desktop:
|
||||
"""Xvfb plus weft-compositor; logs are written to `output/<name>.log`."""
|
||||
|
||||
def __init__(self, compositor, output, outputs=()):
|
||||
"""`outputs` names further files in `output` that this run will write."""
|
||||
self.compositor = Path(compositor)
|
||||
self.output = Path(output)
|
||||
self.own_outputs = ["xvfb.log", "compositor.log", "shell.log", *outputs]
|
||||
self.processes = []
|
||||
self.logs = {}
|
||||
|
||||
def __enter__(self):
|
||||
self.output.mkdir(parents=True, exist_ok=True)
|
||||
for name in self.own_outputs:
|
||||
(self.output / name).unlink(missing_ok=True)
|
||||
self.runtime = Path(tempfile.mkdtemp(prefix="weft-desktop-"))
|
||||
self.runtime.chmod(0o700)
|
||||
self.env = {key: value for key, value in os.environ.items()
|
||||
if key not in ("DISPLAY", "WAYLAND_DISPLAY", "WAYLAND_SOCKET")}
|
||||
self.env["XDG_RUNTIME_DIR"] = str(self.runtime)
|
||||
self.env.setdefault("RUST_LOG", "info")
|
||||
try:
|
||||
self._start_display()
|
||||
self._start_compositor()
|
||||
except BaseException:
|
||||
self.__exit__(None, None, None)
|
||||
raise
|
||||
return self
|
||||
|
||||
def __exit__(self, *exc):
|
||||
for process in reversed(self.processes):
|
||||
_stop(process)
|
||||
for log in self.logs.values():
|
||||
log.close()
|
||||
shutil.rmtree(self.runtime, ignore_errors=True)
|
||||
return False
|
||||
|
||||
def launch(self, name, command, env=None):
|
||||
"""Start a process with its output in `<name>.log`."""
|
||||
log = open(self.output / f"{name}.log", "w", encoding="utf-8")
|
||||
self.logs[name] = log
|
||||
process = subprocess.Popen([str(part) for part in command], stdout=log,
|
||||
stderr=subprocess.STDOUT, env=dict(self.env, **(env or {})),
|
||||
start_new_session=True)
|
||||
self.processes.append(process)
|
||||
return process
|
||||
|
||||
def launch_client(self, name, command, env=None):
|
||||
"""Start a Wayland client of the compositor."""
|
||||
return self.launch(name, command, dict(env or {}, WAYLAND_DISPLAY=self.socket))
|
||||
|
||||
def log_text(self, name):
|
||||
text = (self.output / f"{name}.log").read_text(encoding="utf-8", errors="replace")
|
||||
return ANSI_ESCAPE.sub("", text)
|
||||
|
||||
def capture(self):
|
||||
"""Return the X screen as a P6 PPM."""
|
||||
xwd = subprocess.run(["xwd", "-root", "-silent", "-display", self.display],
|
||||
capture_output=True, check=True, timeout=20)
|
||||
ppm = subprocess.run(["convert", "xwd:-", "ppm:-"], input=xwd.stdout,
|
||||
capture_output=True, check=True, timeout=20)
|
||||
return ppm.stdout
|
||||
|
||||
def _start_display(self):
|
||||
# Xvfb picks a free display itself and writes its number to the pipe
|
||||
# once it accepts connections, so concurrent runs cannot share one.
|
||||
read_end, write_end = os.pipe()
|
||||
log = open(self.output / "xvfb.log", "w", encoding="utf-8")
|
||||
self.logs["xvfb"] = log
|
||||
try:
|
||||
xvfb = subprocess.Popen(
|
||||
["Xvfb", "-displayfd", str(write_end), "-screen", "0",
|
||||
f"{SCREEN[0]}x{SCREEN[1]}x24", "-nolisten", "tcp"],
|
||||
stdout=log, stderr=subprocess.STDOUT, env=self.env,
|
||||
start_new_session=True, pass_fds=(write_end,))
|
||||
finally:
|
||||
os.close(write_end)
|
||||
self.processes.append(xvfb)
|
||||
with os.fdopen(read_end) as reported:
|
||||
number = reported.readline().strip()
|
||||
if not number.isdigit() or xvfb.poll() is not None:
|
||||
raise SessionError("Xvfb did not start")
|
||||
self.display = f":{number}"
|
||||
|
||||
def _start_compositor(self):
|
||||
compositor = self.launch("compositor", [self.compositor, "--winit"],
|
||||
{"DISPLAY": self.display})
|
||||
|
||||
def socket_name():
|
||||
if compositor.poll() is not None:
|
||||
return "exited"
|
||||
match = re.search(r'socket_name="([^"]+)"', self.log_text("compositor"))
|
||||
return match and match.group(1)
|
||||
|
||||
socket = wait_for(socket_name, 30)
|
||||
if socket in (None, "exited"):
|
||||
raise SessionError("compositor did not open a Wayland socket; see "
|
||||
f"{self.output / 'compositor.log'}")
|
||||
self.socket = socket
|
||||
Loading…
Reference in a new issue