diff options
| -rw-r--r-- | build.zig | 12 | ||||
| -rw-r--r-- | build/snap.zig | 23 | ||||
| -rw-r--r-- | docs/next-tests.md | 11 | ||||
| -rw-r--r-- | docs/typ/building.typ | 7 | ||||
| -rw-r--r-- | test/gui-goldens.txt | 34 | ||||
| -rw-r--r-- | test/gui_golden.py | 239 | ||||
| -rw-r--r-- | test/gui_monkey.py | 179 | ||||
| -rw-r--r-- | test/process.zig | 68 | ||||
| -rw-r--r-- | test/process/window.zig | 364 | ||||
| -rw-r--r-- | test/process_test.zig | 1 | ||||
| -rw-r--r-- | test/record_demos.py | 2 |
11 files changed, 476 insertions, 464 deletions
@@ -1705,18 +1705,6 @@ pub fn build(b: *std.Build) void { syntax_test_step.dependOn(&run_syntax_test.step); if (testMatch(b, unit_profile, test_filters, syntax_test_step)) |check| check.addArtifactArg(syntax_test); - // The GUI's effects under random input in a hidden test window, each - // Motion x Lift x Bloom (test/gui_monkey.py): a gate, run by hand, - // since it needs a Wayland display. - const monkey_gui_step = b.step("monkey-gui", "random input to hidden GUI test windows across the effect settings (-Dplatform=gui; -- [--seed N] [--steps M])"); - if (platform == .gui) { - const run_monkey_gui = b.addSystemCommand(&.{ "python3", "-B", "test/gui_monkey.py" }); - run_monkey_gui.addArtifactArg(exe); - run_monkey_gui.addPassthruArgs(); - run_monkey_gui.setCwd(b.path(".")); - run_monkey_gui.has_side_effects = true; - monkey_gui_step.dependOn(&run_monkey_gui.step); - } else monkey_gui_step.dependOn(&b.addFail("monkey-gui needs -Dplatform=gui").step); const history = b.addExecutable(.{ .name = "pardes-history", diff --git a/build/snap.zig b/build/snap.zig index 544144d9..d29eac42 100644 --- a/build/snap.zig +++ b/build/snap.zig @@ -68,6 +68,29 @@ pub fn addTty(b: *std.Build, opts: struct { run_process_test.addPassthruArgs(); run_process_test.has_side_effects = true; b.step("process-test", "run the process tests: real sessions driven over their sockets (-- [filter])").dependOn(&run_process_test.step); + // The window's own, run in full when asked (test/process/window.zig): + // the monkey over every Motion x Lift x Bloom, and the frames against + // this machine's goldens (PARDES_GUI_GOLDEN=update rewrites them). + const monkey_gui_step = b.step("monkey-gui", "random input to the hidden window across the effect settings (-Dplatform=gui; PARDES_GUI_MONKEY_SEED, _STEPS)"); + const gui_golden_step = b.step("gui-golden", "the hidden window's scenes against test/gui-goldens.txt, this machine's (-Dplatform=gui; PARDES_GUI_GOLDEN=update rewrites)"); + if (opts.gui) { + const run_monkey_gui = b.addRunArtifact(process_test); + run_monkey_gui.addArtifactArg(opts.exe); + run_monkey_gui.addArgs(&.{ "--backend=gui", "window: a monkey" }); + run_monkey_gui.setEnvironmentVariable("PARDES_GUI_MONKEY", "all"); + run_monkey_gui.has_side_effects = true; + monkey_gui_step.dependOn(&run_monkey_gui.step); + const run_gui_golden = b.addRunArtifact(process_test); + run_gui_golden.addArtifactArg(opts.exe); + run_gui_golden.addArgs(&.{ "--backend=gui", "window: its scenes" }); + run_gui_golden.setEnvironmentVariable("PARDES_GUI_GOLDEN", b.graph.environ_map.get("PARDES_GUI_GOLDEN") orelse "check"); + run_gui_golden.setCwd(b.path(".")); + run_gui_golden.has_side_effects = true; + gui_golden_step.dependOn(&run_gui_golden.step); + } else { + monkey_gui_step.dependOn(&b.addFail("monkey-gui needs -Dplatform=gui").step); + gui_golden_step.dependOn(&b.addFail("gui-golden needs -Dplatform=gui").step); + } const run_snap = b.addRunArtifact(snap); run_snap.addArtifactArg(opts.exe); run_snap.addPrefixedFileArg("--lspmock=", lspmock.getEmittedBin()); diff --git a/docs/next-tests.md b/docs/next-tests.md index a16a7cf9..b05e9352 100644 --- a/docs/next-tests.md +++ b/docs/next-tests.md @@ -48,7 +48,8 @@ agent's survey. The `e2e` line (kbdin, mousein) is its first step. new_pane, execute). - **agent_session_test.py is kept,** run by hand: it tests the agent_session.py tool. - - **Still Python in the build:** gui_monkey.py (monkey-gui, for T4). + - **No Python left in the build:** gui_monkey.py and gui_golden.py are + test/process/window.zig's two cases (T4, below). Each backend's own (2026-11-04, the user: an effect's test is the backend's): @@ -108,7 +109,13 @@ agent's survey. The `e2e` line (kbdin, mousein) is its first step. The window (T4): its core is the one T1 drives, so a behaviour the cells show is tested at T1; T4 is for what only pixels show (scene effects, -images, fonts, edges). test/gui_golden.py's 17 frame hashes +images, fonts, edges). Built (2026-11-04): test/process/window.zig's +monkey (a smoke run in process-test, all 40 Motion x Lift x Bloom with +`zig build monkey-gui -Dplatform=gui`) drives the window's own input +(Detached.typeKeys and mouse: its pty and OSC 777) and checks it settles, +alive, with no crash record; its goldens (`zig build gui-golden +-Dplatform=gui`, PARDES_GUI_GOLDEN=update to rewrite) hash 17 scenes' +frames from Detached.capture. The old notes: test/gui_golden.py's 17 frame hashes (test/gui-goldens.txt) are an exact gate for one machine, never a CI one, and move to the Zig runner with T2. gui.zig's own tests: 19 M, 17 B, 47 U. diff --git a/docs/typ/building.typ b/docs/typ/building.typ index 24229f08..99a83589 100644 --- a/docs/typ/building.typ +++ b/docs/typ/building.typ @@ -80,7 +80,10 @@ zig build kitty-harness kitty graphics through a pane end to end (a fake kitt zig build syntax-test tree-sitter tests without building the editor zig build syntax deterministic per-byte highlighting snapshots zig build behaviour-test behaviour through the 9P tree, in process (test/behaviour/) -zig build process-test real sessions over their sockets: mounts, flags, shells (test/process/) +zig build process-test real sessions over their sockets: mounts, flags, shells (test/process/); + -Dplatform=gui runs each case on the hidden window instead +zig build monkey-gui random input to the hidden window, every effect setting (-Dplatform=gui) +zig build gui-golden the hidden window's scenes against this machine's goldens (-Dplatform=gui) zig build monkey-session random in-process 9P requests checking the documented rules zig build 9p-test freestanding protocol tests zig build 9p-io-test native 9P transports and client @@ -128,7 +131,7 @@ zig build cheatsheet render the cheatsheet PDF (needs typst) A release passes all of these first: `unit-test` with `-Dplatform=tui` and with `-Dplatform=gui`, `core-test`, `behaviour-test`, `process-test`, `snap`, the GUI goldens -(`python3 -B test/gui_golden.py <a Debug pardes-gui>`, a hidden window), +(`zig build gui-golden -Dplatform=gui`, a hidden window; `PARDES_GUI_GOLDEN=update` rewrites them), `web`, and the ReleaseSafe tui and ReleaseFast gui builds. The committed `docs/typ/cheatsheet-a4.pdf` is rendered again when the docs change. diff --git a/test/gui-goldens.txt b/test/gui-goldens.txt index 0d782af4..5132981f 100644 --- a/test/gui-goldens.txt +++ b/test/gui-goldens.txt @@ -1,17 +1,17 @@ -01-boot 6b879535ac5d120a468290175f508064a11f257a0f52924fee423df11686ffb3 -02-second-document e07139723a029c1bebcd5ca19da86f3e0cc2af20abc4cf540fc551ae8d65ad2b -03-notice 8ad2e24e5cb5eb8ef9234a6ebd14916e5780764c5f8a2a119f3a8901dc1b042e -04-context-rows-mid-thumb 19b1a173848a1b8895c39c58107df1512bf7b314a032d525ce815ba94180266a -05-body-selection 533db971a21519eba77effc1c5d6222257348602131d24130d8dea62a44d698b -06-tag-focus-selection 711220bcec560f6ba6204a694827ed58c374ecce8325c5c459154e8f2319f252 -07-prompt-notice 1d02541031d04d2a0a861102648295f6cd5b30d33b6c0dd4e55f6076d7a5c005 -08-wide-glyph-edges ddfe437d9cf36063bb09cddc36bac4bcd30b29c4bcb0d6453f9706c0c222b187 -09-collapsed-focus-tint d2f3edb45e23f84e5f3c792b388c77dd70e0e8a15a5b2bd85e0917f019de1421 -10-tagbottom 6347013122c19b7ee6505d3e7138d9fa353d8b9d8213fbb847615b75b0ddb0e5 -12-multiline-tag 48d4a0c0f45a1709d8e3dea3056e1147ab29bfe3fd6980b4568333b8183828d6 -13-image ca5c7d92e688b4c4b8a1d7f7075c55acb049bd89b49488effd2de74056f92bdf -14-theme-ink a7cdb4de4a2a6ff3ee58040ff5052f36ac60ad1ab8d132d7832059692e96fd73 -15-theme-acme-light e3af35d1e5ae57cb74af807940a76beebf510ed04a2437f4be1f4a53133af48b -16-debug ed971e715e45fa04f0ecddefd6b0d0b1285c912d6940ca9632a7defc377bbe61 -17-terminal a09b53740c0a6fecd354c4f9b67ef0131b19aef92af55488cdead77b030d1062 -18-mid-transition 7d09ffede92fde77722cebc91d68b6f800dd1f2bfba0afb9480ab926f001b894 +01-boot 239162cabddeed8a2edbf2d8170d158dc7d413b8fda251945c95a1573e8c1298 +02-second-document 04173d1c7aab94791cb4babc272710597cd8684b23f92e50a4892fc08df1807f +03-notice de5203c9cacb096d2976a3c6267cb1bcdc5af087b5690ca77ebc092a14cdc5d9 +04-context-rows-mid-thumb c42a08e9fe5bb00a98c78dd54fd52eff75e207767275e879b16a974ff0f361c9 +05-body-selection 05c75c7993e6d3107ddc5d908405a8a941f94467486f36a97b659833c5e50dc0 +06-tag-focus-selection ff202b98fa512254deca1dc01d4a19c0fab176bc9f9c703a1dc53d9a3741cda5 +07-prompt-notice c4d90e8f52d020c4e713c7ec0f1e5a4e73a4b6608cedf663ddac10c394e292cf +08-wide-glyph-edges 124b79077f1d204cb9f435f63f7cece52e199bde628491dfa083ec67054a6721 +09-collapsed-focus-tint 3d2c00a08659d37c8ad2da6c474b3dcad844905f2f5c5b68e95f2f0d72b3647e +10-tagbottom a3926b7a9fe16b102e876ba0c536d9de4f043376c0d100e302b785c03fd81ad8 +12-multiline-tag a04558e6f11835c13bbe81b90d31cc24d6b5b4c4220a358e4b79546ae61e8a89 +13-image 4b7af674aa77394a94ed942e7144cb2244c5189fc982dd3c69f542fb0204801e +14-theme-ink bed6e49e993e963d509d75e65f7f15ce28f72e239a063294ba72b3e5247a8f38 +15-theme-acme-light 5d2ffe65bd57afb5380891c32499e6523f5663986cef1212f2431a7559437ba1 +16-debug e7a50fbb37b8a6a7ff172ff583154626eb3f5bec5e1ac4e0d17751bce50c24dd +17-terminal e3208d4378cce3d0762c8d1073e90487da40af44a0d6e4a7f3256e0ee73ee700 +18-mid-transition 2f22bd0dbf72ec1073d794b1b442e1213491a6e80e2c6a275cf8e0c836adb22a diff --git a/test/gui_golden.py b/test/gui_golden.py deleted file mode 100644 index 9afc9c19..00000000 --- a/test/gui_golden.py +++ /dev/null @@ -1,239 +0,0 @@ -#!/usr/bin/env python3 -"""Hash settled SDL frames of a fixed set of scenes, to prove a GUI refactor -left every pixel where it was. - -python3 -B test/gui_golden.py <pardes-gui binary> compare -python3 -B test/gui_golden.py <pardes-gui binary> --update rewrite goldens - -The window is hidden (PARDES_TEST renders into an offscreen capture texture), -and the capture carries PARDES_TEST_PAD leftover pixels so edge bugs show. -GPU rasterisation differs between machines and drivers: the goldens in -test/gui-goldens.txt are a LOCAL gate for one machine, never a CI one. Each -scene waits until the window says it is idle (its status file) before it is -hashed, so a loaded machine gives the same frames. -""" -import argparse -import hashlib -import os -from pathlib import Path -import tempfile -import shutil -import time - -from fs import session -from ui_review import require, wait_for - -GOLDENS = Path(__file__).resolve().parent / 'gui-goldens.txt' - -ZIG = b'''const std = @import("std"); - -pub const Shape = union(enum) { - circle: f32, - square: f32, - - pub fn area(shape: Shape) f32 { - return switch (shape) { - .circle => |r| std.math.pi * r * r, - .square => |s| s * s, - }; - } -}; - -pub fn main() void { - var total: f32 = 0; - const shapes = [_]Shape{ .{ .circle = 1 }, .{ .square = 2 } }; - for (shapes) |shape| { -''' + b''.join(b' total += shape.area() * %d; // line %d\n' % (n, n) for n in range(60)) + b''' } - std.debug.print("{d}\\n", .{total}); -} -''' - - -def ppm(width, height): - rows = [] - for y in range(height): - rows.append(bytes(v for x in range(width) for v in ((x * 255) // width, (y * 255) // height, 128))) - return b'P6\n%d %d\n255\n' % (width, height) + b''.join(rows) - - -def panes(client): - serials = [int(row.split()[0]) for row in client.read('/index').decode().splitlines() if row.strip()] - return {serial: client.read(f'/pane/{serial}/tag').decode(errors='replace') for serial in serials} - - -def status(root): - """The window's (step, frames captured, idle), or None before the first.""" - try: - step, frames, idle = (root / 'status').read_text().split()[:3] - return int(step), int(frames), idle == '1' - except (FileNotFoundError, ValueError): - return None - - -def settled(root): - """The capture once the window says it is idle: a loop step past the one - current when this was asked, with nothing owing a frame (the window's - status file, gui.zig writeTestStatus). Every command before this call has - been served by then (a 9P write returns once the core has it), so the - frame is the scene's however loaded the machine is; the digest of it.""" - deadline = time.monotonic() + 60 - start = None - while time.monotonic() < deadline: - now = status(root) - if now is not None: - if start is None: - start = now[0] - elif now[0] >= start + 2 and now[2] and now[1] > 0: - data = (root / 'latest.ppm').read_bytes() - if data.startswith(b'P6'): - return hashlib.sha256(data).hexdigest() - time.sleep(.02) - raise RuntimeError('the window never went idle') - - -def run(args): - results = [] - # A fixed directory: the paths it holds are drawn in the tags. - root = Path(tempfile.gettempdir()) / 'pardes-gui-golden' - shutil.rmtree(root, ignore_errors=True) - root.mkdir(mode=0o700) - # Captures go outside the session's own directory: a file written there - # every frame is a change in the directory its panes look at, which - # would ask for another frame, and so on for ever. - captures = Path(tempfile.gettempdir()) / 'pardes-gui-golden-captures' - shutil.rmtree(captures, ignore_errors=True) - captures.mkdir(mode=0o700) - name = 'gui-golden' - config = root / 'config/pardes' - config.mkdir(parents=True) - # No linger: a dismissed message is gone, not caught part way, when a - # scene settles. - (config / 'init').write_text('Shell /bin/sh\nTheme forge\nMessageLinger 0\n') - source = root / 'shapes.zig' - source.write_bytes(ZIG) - notes = root / 'notes.txt' - notes.write_bytes(b'Pardes GUI golden\n\nA second document, opened by Look.\n' * 4) - wide = root / 'wide.txt' - # One of the two alignments puts a wide glyph across the body's right edge. - wide.write_bytes(('x' + '\u754c' * 80 + '\n' + '\u754c' * 80 + '\n').encode()) - image = root / 'ramp.ppm' - image.write_bytes(ppm(96, 64)) - # The session points XDG_RUNTIME_DIR at its own root, so the caller's - # Wayland socket is passed as an absolute path. - display = Path(os.environ.get('WAYLAND_DISPLAY', 'wayland-0')) - if not display.is_absolute(): - display = Path(os.environ.get('XDG_RUNTIME_DIR', '/run/user/%d' % os.getuid())) / display - # The virtual clock: a transition's frames are the same frames on any - # machine, so one partway through can be hashed too. - inherited = {'PARDES_TEST': '1', 'PARDES_TEST_CLOCK': '1', 'PARDES_TEST_COLS': '120', 'PARDES_TEST_ROWS': '40', - 'PARDES_TEST_PAD': '7', 'PARDES_TEST_CAPTURE_DIR': str(captures), - 'SDL_VIDEODRIVER': 'wayland', 'WAYLAND_DISPLAY': str(display)} - launch = ['-c', 'stty cols 120 rows 40; exec "$@"', name, str(args.binary.resolve()), - '--9p=' + name, str(source)] - handles = {} - with session('/bin/sh', root, name, socket_name=name, tty=True, - launch=launch, inherited=inherited, terminal=handles) as (client, _): - first = require(wait_for(lambda: next((s for s, tag in panes(client).items() - if 'shapes.zig' in tag), None)), 'source pane missing') - - def scene(label, frame='latest.ppm'): - settled(captures) - results.append((label, hashlib.sha256((captures / frame).read_bytes()).hexdigest())) - if args.keep: - args.keep.mkdir(parents=True, exist_ok=True) - shutil.copyfile(captures / frame, args.keep / (label + '.ppm')) - print(label, results[-1][1][:16], flush=True) - - def mouse(kind, button, x, y): - # The test shell's stdin takes window-pixel mouse events. - os.write(handles['input_fd'], f'\x1b]777;mouse;{kind};{button};{x};{y}\x07'.encode()) - time.sleep(.1) - - def serial_of(word): - return require(wait_for(lambda: next((s for s, tag in panes(client).items() if word in tag), None)), - word + ' missing') - - scene('01-boot') - client.write(f'/pane/{first}/look', f'{notes}\n'.encode()) - notes_pane = serial_of('notes.txt') - scene('02-second-document') - client.write(f'/pane/{first}/ctl', b'Msg a golden notice\n') - scene('03-notice') - client.write(f'/pane/{first}/ctl', b'TreeContext\n') - client.write(f'/pane/{first}/dot', b'45\n') - scene('04-context-rows-mid-thumb') - client.write(f'/pane/{first}/dot', b'40,43\n') - scene('05-body-selection') - # A press and a drag along the source's tag: the tag takes the - # keyboard with a selection and a caret. The pointer then rests on - # empty body space, far right. - mouse('down', 1, 500, 87) - mouse('motion', 1, 620, 87) - mouse('up', 1, 620, 87) - mouse('motion', 0, 1880, 1300) - scene('06-tag-focus-selection') - os.write(handles['input_fd'], b'\x1b') - time.sleep(.2) - scratch = int(client.read('/pane/new')) - client.write(f'/pane/{scratch}/exec', b'Save\n') - scene('07-prompt-notice') - os.write(handles['input_fd'], b'\x1b') - time.sleep(.2) - client.write(f'/pane/{scratch}/exec', b'Del\n') - client.write(f'/pane/{first}/look', f'{wide}\n'.encode()) - wide_pane = serial_of('wide.txt') - client.write(f'/pane/{wide_pane}/name', ('x' + '\u754c' * 70 + '\n').encode()) - client.write('/ctl', b'Wrap off\n') - scene('08-wide-glyph-edges') - client.write('/ctl', b'Wrap on\n') - client.write(f'/pane/{wide_pane}/exec', b'Del\n') - client.write('/ctl', b'FocusTint on\n') - client.write(f'/pane/{notes_pane}/ctl', b'Collapse\n') - scene('09-collapsed-focus-tint') - client.write(f'/pane/{notes_pane}/ctl', b'Collapse\n') - client.write('/ctl', b'Tagbottom\n') - scene('10-tagbottom') - client.write('/ctl', b'Tagbottom\n') - client.write(f'/pane/{first}/tag', b' Second\nthird line of the tag') - scene('12-multiline-tag') - client.write(f'/pane/{first}/look', f'{image}\n'.encode()) - serial_of('ramp.ppm') - scene('13-image') - client.write('/ctl', b'Theme ink\n') - scene('14-theme-ink') - client.write('/ctl', b'Theme acme\n') - scene('15-theme-acme-light') - client.write('/ctl', b'Debug\n') - scene('16-debug') - client.write('/ctl', b'Debug\n') - # A terminal pane: raw rows, ANSI colours, a hidden prompt. - before = set(panes(client)) - client.write(f'/pane/{first}/exec', b'Term\n') - terminal = require(wait_for(lambda: next((s for s in panes(client) if s not in before), None)), 'Term missing') - client.write(f'/pane/{terminal}/pty/data', b"PS1='$ '; clear; printf '\\033[1;36mcolour\\033[0m plain \\033[32mgreen\\033[0m\\n'\r") - require(wait_for(lambda: b'green' in client.read(f'/pane/{terminal}/body')), 'terminal output missing') - scene('17-terminal') - # Partway through a transition: the panes, the picture among them, - # sliding over for a new column, frame 6 of PanelSlide's 12. Its - # chrome slides with each pane. - client.write('/ctl', b'PanelSlide\n') - client.write(f'/pane/{first}/exec', b'Newcol\n') - require(wait_for(lambda: (captures / 'transition-6.ppm').exists()), 'transition frame 6 never drawn') - scene('18-mid-transition', 'transition-6.ppm') - lines = ''.join(f'{label} {digest}\n' for label, digest in results) - if args.update: - GOLDENS.write_text(lines) - print('updated', GOLDENS) - return - expected = dict(line.split() for line in GOLDENS.read_text().splitlines() if line.strip()) - bad = [label for label, digest in results if expected.get(label) != digest] - require(not bad, 'frames changed: ' + ', '.join(bad)) - print(f'{len(results)} GUI frames byte-identical') - - -if __name__ == '__main__': - parser = argparse.ArgumentParser(description=__doc__) - parser.add_argument('binary', type=Path) - parser.add_argument('--update', action='store_true') - parser.add_argument('--keep', type=Path, help='copy each hashed frame here as <scene>.ppm') - run(parser.parse_args()) diff --git a/test/gui_monkey.py b/test/gui_monkey.py deleted file mode 100644 index 540c377a..00000000 --- a/test/gui_monkey.py +++ /dev/null @@ -1,179 +0,0 @@ -#!/usr/bin/env python3 -"""A monkey over the GUI's effects: for each Motion x Lift x Bloom, a hidden -test window gets a random burst of clicks, drags, wheels, keys, new and -joined columns, opened files and theme changes, then must settle (its -frames stop changing) with no crash record and its process alive. - -gui_monkey.py <pardes-gui> [outdir] [--seed N] [--steps N]; `zig build -monkey-gui -Dplatform=gui -- [--seed N] [--steps N]` runs it on the built -window. Exits 1 when any combination failed; what failed is in outdir. -""" -import argparse -import hashlib -import itertools -import os -import random -import shutil -import sys -import tempfile -import time -from pathlib import Path - -sys.path.insert(0, str(Path(__file__).resolve().parent)) -from fs import session # noqa: E402 - -MOTIONS = ['off', 'crisp', 'smooth', 'bouncy', 'playful'] -LIFTS = ['off', 'shadow', 'rim', 'auto'] -BLOOMS = ['0', '2'] -THEMES = ['lapis', 'lapis_plain', 'forge', 'acme', 'dusk', 'daybreak'] -W, H = 1280, 840 - - -def settled(cap, timeout=20): - latest = cap / 'latest.ppm' - previous = None - deadline = time.monotonic() + timeout - while time.monotonic() < deadline: - time.sleep(.4) - try: - data = latest.read_bytes() - except FileNotFoundError: - continue - digest = hashlib.sha256(data).hexdigest() - if digest == previous: - return True - previous = digest - return False - - -def run(binary, out, motion, lift, bloom, seed, steps): - rng = random.Random(seed) - root = Path(tempfile.mkdtemp(prefix='pardes-gui-monkey-')) - cap = root / 'cap' - cap.mkdir() - (root / 'config/pardes').mkdir(parents=True) - (root / 'config/pardes/init').write_text( - f'Shell /bin/sh\nMessageLinger 0\nMotion {motion}\nLift {lift}\nBloom {bloom}\nPanelSlide\nSelectionGlow on\nHoverGlow on\n') - src = root / 'a.zig' - src.write_text(''.join(f'pub fn f{n}(x: u32) u32 {{ return x * {n}; }} // a line\n' for n in range(200))) - for name in ('b.txt', 'c.txt'): - (root / name).write_text(''.join(f'{name} line {n} with some words\n' for n in range(80))) - display = Path(os.environ.get('XDG_RUNTIME_DIR', '/run/user/%d' % os.getuid())) / os.environ.get('WAYLAND_DISPLAY', 'wayland-0') - env = {'PARDES_TEST': '1', 'PARDES_TEST_CLOCK': '1', 'PARDES_TEST_COLS': '80', 'PARDES_TEST_ROWS': '28', 'PARDES_TEST_PAD': '0', - 'PARDES_TEST_CAPTURE_DIR': str(cap), 'SDL_VIDEODRIVER': 'wayland', 'WAYLAND_DISPLAY': str(display)} - name = 'monkey' - launch = ['-c', 'stty cols 80 rows 28; exec "$@"', name, str(binary.resolve()), '--9p=' + name, str(src)] - handles = {} - verdict = 'ok' - log = [] - try: - with session('/bin/sh', root, name, socket_name=name, tty=True, launch=launch, inherited=env, terminal=handles) as (client, _): - fd = handles['input_fd'] - time.sleep(1.0) - - def mouse(kind, button, x, y): - os.write(fd, f'\x1b]777;mouse;{kind};{button};{x};{y}\x07'.encode()) - - def first(): - rows = client.read('/index').decode().splitlines() - return int(rows[0].split()[0]) if rows else None - - for _ in range(steps): - x, y = rng.randrange(W), rng.randrange(H) - action = rng.randrange(12) - try: - if action in (0, 1): - mouse('down', 1, x, y); mouse('up', 1, x, y); log.append(f'click {x},{y}') - elif action == 2: - x2, y2 = rng.randrange(W), rng.randrange(H) - mouse('down', 1, x, y) - for i in range(1, 6): - mouse('motion', 1, x + (x2 - x) * i // 5, y + (y2 - y) * i // 5) - mouse('up', 1, x2, y2); log.append(f'drag {x},{y}->{x2},{y2}') - elif action == 3: - amount = rng.choice([-6, -2, 2, 6]) - os.write(fd, f'\x1b]777;mouse;wheel;{amount};{x};{y}\x07'.encode()); log.append(f'wheel {amount}') - elif action == 4: - mouse('motion', 0, x, y); log.append(f'hover {x},{y}') - elif action == 5: - client.write('/ctl', b'Newcol\n'); log.append('Newcol') - elif action == 6: - serial = first() - if serial is not None: - target = root / rng.choice(['b.txt', 'c.txt', 'a.zig']) - client.write(f'/pane/{serial}/look', f'{target}\n'.encode()); log.append(f'look {target.name}') - elif action == 7: - serial = first() - if serial is not None: - # Delcol too: the last column's going leaves an - # empty window now (acme's), not a quit. - word = rng.choice(['Joincol', 'Collapse', 'Delcol']) - try: - client.write(f'/pane/{serial}/exec', (word + '\n').encode()) - except OSError: - pass - log.append(word) - else: - # An empty window: pane/new makes its column and a pane. - try: - client.read('/pane/new') - except OSError: - pass - log.append('pane/new (empty window)') - elif action == 8: - os.write(fd, rng.choice([b'j', b'k', b'10j', b'gg', b'w', b'%', b'v5j', b'\x1b'])) - log.append('keys') - elif action == 9: - theme = rng.choice(THEMES) - client.write('/ctl', f'Theme {theme}\n'.encode()); log.append(f'Theme {theme}') - elif action == 10: - mouse('down', 3, x, y); mouse('up', 3, x, y); log.append(f'look-click {x},{y}') - else: - time.sleep(rng.choice([0, .05, .2])); log.append('pause') - except OSError as why: - log.append(f'refused: {why}') - time.sleep(.03) - if not settled(cap): - verdict = 'never settled' - try: - os.kill(handles['pid'], 0) - except OSError: - verdict = 'process gone' - client.read('/index') - except Exception as why: # noqa: BLE001 - verdict = f'failed: {type(why).__name__}: {str(why)[:300]}' - crashes = list((root / 'config').rglob('*crash*')) - if crashes: - verdict = 'crash record: ' + ', '.join(str(c) for c in crashes) - label = f'{motion}-{lift}-bloom{bloom}' - if verdict != 'ok': - (out / f'{label}.log').write_text('\n'.join(log) + '\n' + verdict + '\n') - for c in crashes: - shutil.copy(c, out / f'{label}-{c.name}') - if (cap / 'latest.ppm').exists(): - shutil.copy(cap / 'latest.ppm', out / f'{label}-last.ppm') - shutil.rmtree(root, ignore_errors=True) - return label, verdict - - -def main(): - ap = argparse.ArgumentParser() - ap.add_argument('binary', type=Path) - ap.add_argument('out', type=Path, nargs='?') - ap.add_argument('--seed', type=int, default=1) - ap.add_argument('--steps', type=int, default=60) - args = ap.parse_args() - if args.out is None: - args.out = Path(tempfile.mkdtemp(prefix='pardes-gui-monkey-out-')) - args.out.mkdir(parents=True, exist_ok=True) - bad = 0 - for n, (motion, lift, bloom) in enumerate(itertools.product(MOTIONS, LIFTS, BLOOMS)): - label, verdict = run(args.binary, args.out, motion, lift, bloom, args.seed * 1000 + n, args.steps) - print(f'{label}: {verdict}', flush=True) - bad += verdict != 'ok' - print(f'{bad} of {len(MOTIONS) * len(LIFTS) * len(BLOOMS)} combinations failed; logs in {args.out}', flush=True) - sys.exit(1 if bad else 0) - - -if __name__ == '__main__': - main() diff --git a/test/process.zig b/test/process.zig index bba795de..00f288a7 100644 --- a/test/process.zig +++ b/test/process.zig @@ -546,6 +546,8 @@ pub const Detached = struct { root: ?[]const u8 = null, /// The name its socket is linked as, when `--9p=<name>` names one. socket: ?[]const u8 = null, + /// Its startup file (`config/pardes/init` in the root), written first. + init: ?[]const u8 = null, }; /// A session of the backend's: `pardes --detach=<name>`, or the window @@ -577,6 +579,13 @@ pub const Detached = struct { errdefer if (d.cap_len > 0) removeDir(d.captures()); const dir = d.root(); var bufs: [6][4096]u8 = undefined; + if (opts.init) |text| { + const cfg = try std.fmt.bufPrintSentinel(&bufs[5], "{s}/config", .{dir}, 0); + _ = libc.mkdir(cfg, 0o755); + const pcfg = try std.fmt.bufPrintSentinel(&bufs[5], "{s}/config/pardes", .{dir}, 0); + _ = libc.mkdir(pcfg, 0o755); + try eh.writeFile(try std.fmt.bufPrintSentinel(&bufs[5], "{s}/config/pardes/init", .{dir}, 0), text); + } const fixture = if (opts.file) |f| try std.fmt.bufPrintSentinel(&bufs[0], "{s}", .{f}, 0) else blk: { const path = try std.fmt.bufPrintSentinel(&bufs[0], "{s}/{s}.txt", .{ dir, name }, 0); try eh.writeFile(path, "initial\n"); @@ -672,12 +681,33 @@ pub const Detached = struct { return d.cap_buf[0..d.cap_len]; } - /// The window's frame once it is idle: a loop step two past the one - /// current when this was asked, nothing owing a frame (gui.zig's - /// writeTestStatus). Every request before this one has been served (a - /// 9P write returns once the core has it), so the frame is the scene's - /// however loaded the machine is. A binary PPM (P6), kept by the caller. + /// The window's frame once it is idle (`settle`): a binary PPM (P6), + /// kept by the caller. pub fn frame(d: *Detached, gpa: std.mem.Allocator) ![]u8 { + return d.capture(gpa, "latest.ppm"); + } + + /// A capture the window wrote (`latest.ppm`, a transition's + /// `transition-<n>.ppm`), once it is there and the window is idle. + pub fn capture(d: *Detached, gpa: std.mem.Allocator, name: []const u8) ![]u8 { + try d.settle(gpa); + var path: [256]u8 = undefined; + const at = try std.fmt.bufPrint(&path, "{s}/{s}", .{ d.captures(), name }); + const deadline = eh.nowMs() + 30_000; + while (eh.nowMs() < deadline) : (sleepMs(20)) { + const got = readWhole(gpa, at) catch continue; + if (std.mem.startsWith(u8, got, "P6")) return got; + gpa.free(got); + } + return error.NoCapture; + } + + /// Until the window is idle: a loop step two past the one current when + /// this was asked, nothing owing a frame (gui.zig's writeTestStatus). + /// Every request before this one has been served (a 9P write returns + /// once the core has it), so what it then shows is the scene's however + /// loaded the machine is. + pub fn settle(d: *Detached, gpa: std.mem.Allocator) !void { if (d.cap_len == 0) return error.NotAWindow; var path: [128]u8 = undefined; const status_path = try std.fmt.bufPrint(&path, "{s}/status", .{d.captures()}); @@ -694,16 +724,25 @@ pub const Detached = struct { first_step = step; continue; }; - if (step >= first + 2 and idle and frames > 0) { - var ppm: [128]u8 = undefined; - const got = try readWhole(gpa, try std.fmt.bufPrint(&ppm, "{s}/latest.ppm", .{d.captures()})); - if (std.mem.startsWith(u8, got, "P6")) return got; - gpa.free(got); - } + if (step >= first + 2 and idle and frames > 0) return; } return error.NeverIdle; } + /// Keys typed at the window as its terminal gives them (its pty). + pub fn typeKeys(d: *Detached, bytes: []const u8) !void { + if (d.cap_len == 0) return error.NotAWindow; + if (libc.write(d.child.master, bytes.ptr, bytes.len) != @as(isize, @intCast(bytes.len))) return error.ShortWrite; + } + + /// A mouse event at window pixels, as the window's test shell takes + /// one (OSC 777): `kind` down, up, motion or wheel; `button` 1 left, + /// 2 middle, 3 right, 0 none, a wheel's amount for wheel. + pub fn mouse(d: *Detached, kind: []const u8, button: i32, x: u32, y: u32) !void { + var buf: [96]u8 = undefined; + try d.typeKeys(try std.fmt.bufPrint(&buf, "\x1b]777;mouse;{s};{d};{d};{d}\x07", .{ kind, button, x, y })); + } + fn removeRoot(d: *Detached) void { var cmd: [4200]u8 = undefined; if (std.fmt.bufPrintSentinel(&cmd, "rm -rf -- '{s}'", .{d.root()}, 0)) |c| { @@ -1055,7 +1094,7 @@ fn removeDir(path: []const u8) void { } else |_| {} } -fn readWhole(gpa: std.mem.Allocator, path: []const u8) ![]u8 { +pub fn readWhole(gpa: std.mem.Allocator, path: []const u8) ![]u8 { var buf: [4096]u8 = undefined; const z = try std.fmt.bufPrintSentinel(&buf, "{s}", .{path}, 0); const fd = libc.open(z, .{}, @as(libc.mode_t, 0)); @@ -1072,3 +1111,8 @@ fn readWhole(gpa: std.mem.Allocator, path: []const u8) ![]u8 { } return out.toOwnedSlice(gpa); } + +/// `data` written to `path` whole (made or truncated). +pub fn writeFile(a: std.mem.Allocator, path: []const u8, data: []const u8) !void { + try eh.writeFile(try std.fmt.allocPrintSentinel(a, "{s}", .{path}, 0), data); +} diff --git a/test/process/window.zig b/test/process/window.zig new file mode 100644 index 00000000..63247122 --- /dev/null +++ b/test/process/window.zig @@ -0,0 +1,364 @@ +//! The window's own (T4 of docs/next-tests.md): what only its pixels and +//! its own input show, on the hidden window `zig build process-test +//! -Dplatform=gui` drives. test/gui_monkey.py and test/gui_golden.py, here. +const std = @import("std"); +const process = @import("../process.zig"); +extern "c" fn system(cmd: [*:0]const u8) c_int; + +pub const cases = .{ + .{ "window: a monkey over the effects: random clicks, drags, wheels, keys, columns, looks and themes, then it settles, alive, with no crash record", monkey }, + .{ "window: its scenes are the frames test/gui-goldens.txt hashes (PARDES_GUI_GOLDEN=check|update, this machine's)", goldens }, +}; + +fn envOr(name: [*:0]const u8, default: []const u8) []const u8 { + return if (std.c.getenv(name)) |v| std.mem.span(v) else default; +} + +/// The serial of the first pane whose tag holds `word`, waited for. +fn paneWith(f: *process.Files, word: []const u8) !u32 { + const deadline = process.nowMs() + 10_000; + while (process.nowMs() < deadline) : (process.nap(50)) { + var rows = std.mem.tokenizeScalar(u8, try f.read("/index"), '\n'); + while (rows.next()) |row| { + const serial = std.fmt.parseInt(u32, row[0 .. std.mem.indexOfScalar(u8, row, ' ') orelse continue], 10) catch continue; + if (process.has(try f.read(f.at("/pane/{d}/tag", .{serial})), word)) return serial; + } + } + std.debug.print("no pane's tag holds {s}\n", .{word}); + return error.NoSuchPane; +} + +const motions = [_][]const u8{ "off", "crisp", "smooth", "bouncy", "playful" }; +const lifts = [_][]const u8{ "off", "shadow", "rim", "auto" }; +const blooms = [_][]const u8{ "0", "2" }; +const themes = [_][]const u8{ "lapis", "lapis_plain", "forge", "acme", "dusk", "daybreak" }; + +/// test/gui_monkey.py's: each Motion x Lift x Bloom gets a random burst, +/// then must settle with its process alive and no crash record. Two +/// combinations and 30 steps in process-test; PARDES_GUI_MONKEY=all runs +/// all 40 (`zig build monkey-gui`), PARDES_GUI_MONKEY_SEED and _STEPS +/// choose the rest. +fn monkey(gpa: std.mem.Allocator, exe: [:0]const u8) !void { + try process.only(.gui); + const all = std.mem.eql(u8, envOr("PARDES_GUI_MONKEY", ""), "all"); + const seed = try std.fmt.parseInt(u64, envOr("PARDES_GUI_MONKEY_SEED", "1"), 10); + const steps = try std.fmt.parseInt(usize, envOr("PARDES_GUI_MONKEY_STEPS", if (all) "60" else "30"), 10); + var failed: usize = 0; + var n: usize = 0; + for (motions) |m| for (lifts) |l| for (blooms) |b| { + defer n += 1; + // The smoke run: the quietest combination and the busiest. + if (!all and n != 0 and n != motions.len * lifts.len * blooms.len - 1) continue; + if (!try monkeyOne(gpa, exe, m, l, b, seed * 1000 + n, steps)) failed += 1; + }; + if (failed > 0) return error.MonkeyFailed; +} + +fn monkeyOne(gpa: std.mem.Allocator, exe: [:0]const u8, motion: []const u8, lift: []const u8, bloom: []const u8, seed: u64, steps: usize) !bool { + var arena = std.heap.ArenaAllocator.init(gpa); + defer arena.deinit(); + const a = arena.allocator(); + const init = try std.fmt.allocPrint(a, "Shell /bin/sh\nMessageLinger 0\nMotion {s}\nLift {s}\nBloom {s}\nPanelSlide\nSelectionGlow on\nHoverGlow on\n", .{ motion, lift, bloom }); + var d = try process.Detached.start(gpa, exe, "monkey", .{ .init = init, .env = &.{ + .{ "PARDES_TEST_CLOCK", "1" }, .{ "PARDES_TEST_COLS", "80" }, .{ "PARDES_TEST_ROWS", "28" }, .{ "PARDES_TEST_PAD", "0" }, + } }); + defer d.deinit(); + const f = &d.files; + var src: std.ArrayList(u8) = .empty; + for (0..200) |k| try src.print(a, "pub fn f{d}(x: u32) u32 {{ return x * {d}; }} // a line\n", .{ k, k }); + try d.put("a.zig", src.items); + for ([_][]const u8{ "b.txt", "c.txt" }) |name| { + var text: std.ArrayList(u8) = .empty; + for (0..80) |k| try text.print(a, "{s} line {d} with some words\n", .{ name, k }); + try d.put(name, text.items); + } + const names = [_][]const u8{ "b.txt", "c.txt", "a.zig" }; + var prng = std.Random.DefaultPrng.init(seed); + const r = prng.random(); + const w: u32 = 1280; + const h: u32 = 840; + var log: std.ArrayList(u8) = .empty; + for (0..steps) |_| { + const x = r.uintLessThan(u32, w); + const y = r.uintLessThan(u32, h); + const action = r.uintLessThan(u32, 12); + // A refusal is part of the burst (a Delcol of the last column, a + // look at a moved pane): logged, never the verdict. + step(&d, f, a, r, action, x, y, &names, &log) catch |err| try log.print(a, "refused {t}\n", .{err}); + process.nap(30); + } + var verdict: []const u8 = "ok"; + d.settle(gpa) catch { + verdict = "never settled"; + }; + if (d.exited(0) != null) verdict = "process gone"; + _ = f.read("/index") catch { + verdict = "no /index"; + }; + const config = try std.fmt.allocPrint(a, "{s}/config/pardes", .{d.root()}); + if (process.entries(a, config)) |listed| { + for (listed) |name| if (process.has(name, "crash")) { + verdict = try std.fmt.allocPrint(a, "crash record {s}", .{name}); + }; + } else |_| {} + const ok = std.mem.eql(u8, verdict, "ok"); + if (!ok) std.debug.print("monkey {s}-{s}-bloom{s} (seed {d}): {s}\n{s}", .{ motion, lift, bloom, seed, verdict, log.items }); + return ok; +} + +fn step(d: *process.Detached, f: *process.Files, a: std.mem.Allocator, r: std.Random, action: u32, x: u32, y: u32, names: []const []const u8, log: *std.ArrayList(u8)) !void { + switch (action) { + 0, 1 => { + try d.mouse("down", 1, x, y); + try d.mouse("up", 1, x, y); + try log.print(a, "click {d},{d}\n", .{ x, y }); + }, + 2 => { + const x2 = r.uintLessThan(u32, 1280); + const y2 = r.uintLessThan(u32, 840); + try d.mouse("down", 1, x, y); + for (1..6) |i| { + const k: i64 = @intCast(i); + try d.mouse("motion", 1, @intCast(@as(i64, x) + @divTrunc((@as(i64, x2) - x) * k, 5)), @intCast(@as(i64, y) + @divTrunc((@as(i64, y2) - y) * k, 5))); + } + try d.mouse("up", 1, x2, y2); + try log.print(a, "drag {d},{d}->{d},{d}\n", .{ x, y, x2, y2 }); + }, + 3 => { + const amount = ([_]i32{ -6, -2, 2, 6 })[r.uintLessThan(usize, 4)]; + try d.mouse("wheel", amount, x, y); + try log.print(a, "wheel {d}\n", .{amount}); + }, + 4 => { + try d.mouse("motion", 0, x, y); + try log.print(a, "hover {d},{d}\n", .{ x, y }); + }, + 5 => { + try log.print(a, "Newcol\n", .{}); + try f.write("/ctl", "Newcol\n"); + }, + 6 => if (try firstPane(f)) |serial| { + const target = names[r.uintLessThan(usize, names.len)]; + try log.print(a, "look {s}\n", .{target}); + try f.write(f.at("/pane/{d}/look", .{serial}), f.at("{s}/{s}\n", .{ d.root(), target })); + }, + 7 => if (try firstPane(f)) |serial| { + // Delcol too: the last column's going leaves an empty window + // (acme's), not a quit. + const word = ([_][]const u8{ "Joincol", "Collapse", "Delcol" })[r.uintLessThan(usize, 3)]; + try log.print(a, "{s}\n", .{word}); + try f.write(f.at("/pane/{d}/exec", .{serial}), f.at("{s}\n", .{word})); + } else { + // An empty window: pane/new makes its column and a pane. + try log.print(a, "pane/new (empty window)\n", .{}); + _ = try f.newPane(); + }, + 8 => { + const keys = ([_][]const u8{ "j", "k", "10j", "gg", "w", "%", "v5j", "\x1b" })[r.uintLessThan(usize, 8)]; + try log.print(a, "keys\n", .{}); + try d.typeKeys(keys); + }, + 9 => { + const theme = themes[r.uintLessThan(usize, themes.len)]; + try log.print(a, "Theme {s}\n", .{theme}); + try f.write("/ctl", f.at("Theme {s}\n", .{theme})); + }, + 10 => { + try d.mouse("down", 3, x, y); + try d.mouse("up", 3, x, y); + try log.print(a, "look-click {d},{d}\n", .{ x, y }); + }, + else => { + process.nap(([_]u32{ 0, 50, 200 })[r.uintLessThan(usize, 3)]); + try log.print(a, "pause\n", .{}); + }, + } +} + +fn firstPane(f: *process.Files) !?u32 { + const index = try f.read("/index"); + const end = std.mem.indexOfScalar(u8, index, ' ') orelse return null; + return std.fmt.parseInt(u32, index[0..end], 10) catch null; +} + +/// test/gui_golden.py's scenes, each frame's sha256 against +/// test/gui-goldens.txt: an exact gate for one machine (a GPU, a driver, +/// software rendering here draw their own pixels), never a CI one, so it +/// runs only when asked: PARDES_GUI_GOLDEN=check, or =update to rewrite the +/// goldens; PARDES_GUI_GOLDEN_KEEP=<dir> keeps each frame as <scene>.ppm. +/// The root is fixed: its paths are drawn in the tags. +fn goldens(gpa: std.mem.Allocator, exe: [:0]const u8) !void { + try process.only(.gui); + const mode = envOr("PARDES_GUI_GOLDEN", ""); + if (!std.mem.eql(u8, mode, "check") and !std.mem.eql(u8, mode, "update")) return error.SkipZigTest; + var arena = std.heap.ArenaAllocator.init(gpa); + defer arena.deinit(); + const a = arena.allocator(); + const root = "/tmp/pardes-gui-golden"; + _ = system("rm -rf -- /tmp/pardes-gui-golden"); + if (std.c.mkdir(root, 0o700) != 0) return error.NoRoot; + defer _ = system("rm -rf -- /tmp/pardes-gui-golden"); + var zig: std.ArrayList(u8) = .empty; + try zig.appendSlice(a, + \\const std = @import("std"); + \\ + \\pub const Shape = union(enum) { + \\ circle: f32, + \\ square: f32, + \\ + \\ pub fn area(shape: Shape) f32 { + \\ return switch (shape) { + \\ .circle => |r| std.math.pi * r * r, + \\ .square => |s| s * s, + \\ }; + \\ } + \\}; + \\ + \\pub fn main() void { + \\ var total: f32 = 0; + \\ const shapes = [_]Shape{ .{ .circle = 1 }, .{ .square = 2 } }; + \\ for (shapes) |shape| { + \\ + ); + for (0..60) |n| try zig.print(a, " total += shape.area() * {d}; // line {d}\n", .{ n, n }); + try zig.appendSlice(a, " }\n std.debug.print(\"{d}\\n\", .{total});\n}\n"); + try process.writeFile(a, root ++ "/shapes.zig", zig.items); + var notes: std.ArrayList(u8) = .empty; + for (0..4) |_| try notes.appendSlice(a, "Pardes GUI golden\n\nA second document, opened by Look.\n"); + try process.writeFile(a, root ++ "/notes.txt", notes.items); + // One of the two alignments puts a wide glyph across the body's right edge. + var wide: std.ArrayList(u8) = .empty; + try wide.append(a, 'x'); + for (0..80) |_| try wide.appendSlice(a, "\u{754c}"); + try wide.append(a, '\n'); + for (0..80) |_| try wide.appendSlice(a, "\u{754c}"); + try wide.append(a, '\n'); + try process.writeFile(a, root ++ "/wide.txt", wide.items); + var ppm: std.ArrayList(u8) = .empty; + try ppm.print(a, "P6\n{d} {d}\n255\n", .{ 96, 64 }); + for (0..64) |yy| for (0..96) |xx| try ppm.appendSlice(a, &.{ @intCast(xx * 255 / 96), @intCast(yy * 255 / 64), 128 }); + try process.writeFile(a, root ++ "/ramp.ppm", ppm.items); + + var d = try process.Detached.start(gpa, exe, "gui-golden", .{ + .root = root, + .file = root ++ "/shapes.zig", + .init = "Shell /bin/sh\nTheme forge\nMessageLinger 0\n", + // The virtual clock: a transition's frames are the same frames on + // any machine, so one partway through can be hashed too. + .env = &.{ .{ "PARDES_TEST_CLOCK", "1" }, .{ "PARDES_TEST_COLS", "120" }, .{ "PARDES_TEST_ROWS", "40" }, .{ "PARDES_TEST_PAD", "7" } }, + }); + defer d.deinit(); + const f = &d.files; + var results: std.ArrayList(u8) = .empty; + const keep = std.c.getenv("PARDES_GUI_GOLDEN_KEEP"); + const Scene = struct { + fn shot(dd: *process.Detached, al: std.mem.Allocator, out: *std.ArrayList(u8), kept: ?[*:0]const u8, label: []const u8, file: []const u8) !void { + const bytes = try dd.capture(al, file); + var digest: [32]u8 = undefined; + std.crypto.hash.sha2.Sha256.hash(bytes, &digest, .{}); + try out.print(al, "{s} {x}\n", .{ label, digest }); + if (kept) |dir| try process.writeFile(al, try std.fmt.allocPrint(al, "{s}/{s}.ppm", .{ std.mem.span(dir), label }), bytes); + std.debug.print("{s} {x}\n", .{ label, digest[0..8] }); + } + }; + const shot = Scene.shot; + const first = try paneWith(f, "shapes.zig"); + try shot(&d, a, &results, keep, "01-boot", "latest.ppm"); + try f.write(f.at("/pane/{d}/look", .{first}), root ++ "/notes.txt\n"); + const notes_pane = try paneWith(f, "notes.txt"); + try shot(&d, a, &results, keep, "02-second-document", "latest.ppm"); + try f.write(f.at("/pane/{d}/ctl", .{first}), "Msg a golden notice\n"); + try shot(&d, a, &results, keep, "03-notice", "latest.ppm"); + try f.write(f.at("/pane/{d}/ctl", .{first}), "TreeContext\n"); + try f.write(f.at("/pane/{d}/dot", .{first}), "45\n"); + try shot(&d, a, &results, keep, "04-context-rows-mid-thumb", "latest.ppm"); + try f.write(f.at("/pane/{d}/dot", .{first}), "40,43\n"); + try shot(&d, a, &results, keep, "05-body-selection", "latest.ppm"); + // A press and a drag along the source's tag: the tag takes the keyboard + // with a selection and a caret. The pointer then rests on empty body + // space, far right. + for ([_]struct { []const u8, i32, u32, u32 }{ .{ "down", 1, 500, 87 }, .{ "motion", 1, 620, 87 }, .{ "up", 1, 620, 87 }, .{ "motion", 0, 1880, 1300 } }) |ev| { + try d.mouse(ev[0], ev[1], ev[2], ev[3]); + process.nap(100); + } + try shot(&d, a, &results, keep, "06-tag-focus-selection", "latest.ppm"); + try d.typeKeys("\x1b"); + process.nap(200); + const scratch = try f.newPane(); + try f.write(f.at("/pane/{d}/exec", .{scratch}), "Save\n"); + try shot(&d, a, &results, keep, "07-prompt-notice", "latest.ppm"); + try d.typeKeys("\x1b"); + process.nap(200); + try f.write(f.at("/pane/{d}/exec", .{scratch}), "Del\n"); + try f.write(f.at("/pane/{d}/look", .{first}), root ++ "/wide.txt\n"); + const wide_pane = try paneWith(f, "wide.txt"); + var name: std.ArrayList(u8) = .empty; + try name.append(a, 'x'); + for (0..70) |_| try name.appendSlice(a, "\u{754c}"); + try name.append(a, '\n'); + try f.write(f.at("/pane/{d}/name", .{wide_pane}), name.items); + try f.write("/ctl", "Wrap off\n"); + try shot(&d, a, &results, keep, "08-wide-glyph-edges", "latest.ppm"); + try f.write("/ctl", "Wrap on\n"); + try f.write(f.at("/pane/{d}/exec", .{wide_pane}), "Del\n"); + try f.write("/ctl", "FocusTint on\n"); + try f.write(f.at("/pane/{d}/ctl", .{notes_pane}), "Collapse\n"); + try shot(&d, a, &results, keep, "09-collapsed-focus-tint", "latest.ppm"); + try f.write(f.at("/pane/{d}/ctl", .{notes_pane}), "Collapse\n"); + try f.write("/ctl", "Tagbottom\n"); + try shot(&d, a, &results, keep, "10-tagbottom", "latest.ppm"); + try f.write("/ctl", "Tagbottom\n"); + try f.write(f.at("/pane/{d}/tag", .{first}), " Second\nthird line of the tag"); + try shot(&d, a, &results, keep, "12-multiline-tag", "latest.ppm"); + try f.write(f.at("/pane/{d}/look", .{first}), root ++ "/ramp.ppm\n"); + _ = try paneWith(f, "ramp.ppm"); + try shot(&d, a, &results, keep, "13-image", "latest.ppm"); + try f.write("/ctl", "Theme ink\n"); + try shot(&d, a, &results, keep, "14-theme-ink", "latest.ppm"); + try f.write("/ctl", "Theme acme\n"); + try shot(&d, a, &results, keep, "15-theme-acme-light", "latest.ppm"); + try f.write("/ctl", "Debug\n"); + try shot(&d, a, &results, keep, "16-debug", "latest.ppm"); + try f.write("/ctl", "Debug\n"); + // A terminal pane: raw rows, ANSI colours, a hidden prompt. + const before = try f.read("/index"); + try f.write(f.at("/pane/{d}/exec", .{first}), "Term\n"); + const terminal = blk: { + const deadline = process.nowMs() + 10_000; + while (process.nowMs() < deadline) : (process.nap(50)) { + var rows = std.mem.tokenizeScalar(u8, try f.read("/index"), '\n'); + while (rows.next()) |row| { + const head = row[0 .. std.mem.indexOfScalar(u8, row, ' ') orelse continue]; + if (std.mem.indexOf(u8, before, f.at("{s} ", .{head})) == null) break :blk try std.fmt.parseInt(u32, head, 10); + } + } + return error.NoTerminal; + }; + try f.write(f.at("/pane/{d}/pty/data", .{terminal}), "PS1='$ '; clear; printf '\\033[1;36mcolour\\033[0m plain \\033[32mgreen\\033[0m\\n'\r"); + { + const deadline = process.nowMs() + 10_000; + while (!process.has(try f.read(f.at("/pane/{d}/body", .{terminal})), "green")) : (process.nap(50)) + if (process.nowMs() > deadline) return error.NoTerminalOutput; + } + try shot(&d, a, &results, keep, "17-terminal", "latest.ppm"); + // Partway through a transition: the panes, the picture among them, + // sliding over for a new column, frame 6 of PanelSlide's 12. + try f.write("/ctl", "PanelSlide\n"); + try f.write(f.at("/pane/{d}/exec", .{first}), "Newcol\n"); + try shot(&d, a, &results, keep, "18-mid-transition", "transition-6.ppm"); + + const goldens_path = "test/gui-goldens.txt"; + if (std.mem.eql(u8, mode, "update")) { + try process.writeFile(a, goldens_path, results.items); + std.debug.print("updated {s}\n", .{goldens_path}); + return; + } + const want = try process.readWhole(a, goldens_path); + var bad: usize = 0; + var got = std.mem.tokenizeScalar(u8, results.items, '\n'); + while (got.next()) |line| if (std.mem.indexOf(u8, want, line) == null) { + bad += 1; + std.debug.print("frame changed: {s}\n", .{line[0..std.mem.indexOfScalar(u8, line, ' ').?]}); + }; + if (bad > 0) return error.FramesChanged; +} diff --git a/test/process_test.zig b/test/process_test.zig index 67f28f53..e363c78a 100644 --- a/test/process_test.zig +++ b/test/process_test.zig @@ -17,6 +17,7 @@ const files = .{ @import("process/root_ctl.zig"), @import("process/terminals.zig"), @import("process/tree.zig"), + @import("process/window.zig"), }; pub fn main(init: std.process.Init) !void { diff --git a/test/record_demos.py b/test/record_demos.py index 4468ffb6..22dc8b7e 100644 --- a/test/record_demos.py +++ b/test/record_demos.py @@ -285,7 +285,7 @@ class Session: return None def settle(self): - """The frame once the window says it is idle (test/gui_golden.py).""" + """The frame once the window says it is idle (test/process.zig's Detached.settle).""" deadline = time.monotonic() + 60 start = None while time.monotonic() < deadline: |
