Skip to content

RediWM is a Wayland compositor written in Zig (OpenGL ES) that includes everything in one process

24.1 KB
Raw Blame
#!/usr/bin/env python3
"""Integration tests for standalone rediwm-pdf in a headless Wayland session."""
import os
from pathlib import Path
import subprocess
import shutil
import tempfile
import time
import sys
import warnings
import cairo
from PIL import Image, ImageChops
from ipc_client import IPCClient, ROOT
from files_browser import wait_for


def generate_fixture_pdf(path: Path):
    surface = cairo.PDFSurface(str(path), 300, 400)
    cr = cairo.Context(surface)

    # Page 1: Blue rectangle
    cr.set_source_rgb(0, 0, 1)
    cr.rectangle(20, 30, 80, 100)
    cr.fill()
    cr.select_font_face("Sans", cairo.FONT_SLANT_NORMAL, cairo.FONT_WEIGHT_NORMAL)
    cr.set_font_size(16)
    cr.move_to(30, 160)
    cr.show_text("Page 1 Content")
    # Strip along the bottom edge: visible only when the whole page fits.
    cr.set_source_rgb(1, 0, 1)
    cr.rectangle(0, 380, 300, 20)
    cr.fill()
    surface.show_page()

    # Page 2: Red rectangle
    cr.set_source_rgb(1, 0, 0)
    cr.rectangle(40, 50, 90, 80)
    cr.fill()
    cr.move_to(30, 160)
    cr.show_text("Page 2 Content")
    surface.show_page()

    surface.finish()


def generate_tall_pdf(path: Path):
    """One tall page: fit width rasterizes it in tiles. Its top is a blue left
    half and a red right half."""
    surface = cairo.PDFSurface(str(path), 400, 1600)
    cr = cairo.Context(surface)
    cr.set_source_rgb(0, 0, 1)
    cr.rectangle(0, 0, 200, 400)
    cr.fill()
    cr.set_source_rgb(1, 0, 0)
    cr.rectangle(200, 0, 200, 400)
    cr.fill()
    surface.finish()


class FakePrintPortal:
    """org.freedesktop.portal.Print on a private bus. Records each document it
    is handed. PreparePrint dismissal and submitted job failures are separate."""

    XML = """<node><interface name="org.freedesktop.portal.Print">
      <method name="PreparePrint"><arg type="s" direction="in"/><arg type="s" direction="in"/>
        <arg type="a{sv}" direction="in"/><arg type="a{sv}" direction="in"/>
        <arg type="a{sv}" direction="in"/><arg type="o" direction="out"/></method>
      <method name="Print"><arg type="s" direction="in"/><arg type="s" direction="in"/>
        <arg type="h" direction="in"/><arg type="a{sv}" direction="in"/><arg type="o" direction="out"/></method>
    </interface></node>"""

    def __init__(self):
        import threading
        from gi.repository import Gio, GLib
        self.GLib = GLib
        self.jobs = []
        self.response = 0
        self.prepare_response = 0
        self.dialogs = []
        self.daemon = subprocess.Popen(["dbus-daemon", "--session", "--nofork", "--print-address=1"],
                                       stdout=subprocess.PIPE, text=True)
        self.address = self.daemon.stdout.readline().strip()
        flags = Gio.DBusConnectionFlags.AUTHENTICATION_CLIENT | Gio.DBusConnectionFlags.MESSAGE_BUS_CONNECTION
        self.conn = Gio.DBusConnection.new_for_address_sync(self.address, flags, None, None)
        with warnings.catch_warnings():
            warnings.simplefilter("ignore", DeprecationWarning)  # register_object's closure-less form
            self.conn.register_object("/org/freedesktop/portal/desktop",
                                      Gio.DBusNodeInfo.new_for_xml(self.XML).interfaces[0], self.call, None, None)
        self.conn.call_sync("org.freedesktop.DBus", "/org/freedesktop/DBus", "org.freedesktop.DBus", "RequestName",
                            GLib.Variant("(su)", ("org.freedesktop.portal.Desktop", 4)), None,
                            Gio.DBusCallFlags.NONE, 3000, None)
        self.loop = GLib.MainLoop()
        threading.Thread(target=self.loop.run, daemon=True).start()

    def call(self, conn, sender, _path, _interface, method, params, invocation):
        args = params.unpack()
        options = args[-1]
        request = "/org/freedesktop/portal/desktop/request/%s/%s" % (
            sender[1:].replace(".", "_"), options.get("handle_token", "t"))
        results = {}
        if method == "PreparePrint":
            self.dialogs.append(args)
            response = self.prepare_response
            if response == 0:
                results = {"token": self.GLib.Variant("u", 42)}
        else:
            parent, title, index, options = args
            assert options.get("token") == 42, "Print must use the confirmed dialog token"
            fd = invocation.get_message().get_unix_fd_list().get(index)
            with os.fdopen(fd, "rb") as document:
                data = document.read()
            self.jobs.append({"parent": parent, "title": title, "data": data, "options": options})
            response = self.response
        conn.emit_signal(sender, request, "org.freedesktop.portal.Request", "Response",
                         self.GLib.Variant("(ua{sv})", (response, results)))
        # Exercise a response arriving before the method reply, including the
        # transition from PreparePrint to Print with another watch installed.
        invocation.return_value(self.GLib.Variant("(o)", (request,)))

    def close(self):
        self.loop.quit()
        self.conn.close_sync(None)
        self.daemon.terminate()
        self.daemon.wait(timeout=5)


def print_helper(viewer_pid):
    """The viewer's unsandboxed print helper process, if it is running."""
    for entry in Path("/proc").iterdir():
        try:
            stat = (entry / "stat").read_text()
        except (OSError, ValueError):
            continue
        fields = stat[stat.rindex(")") + 2:].split()
        if "(rediwm-pdf-prnt)" in stat and int(fields[1]) == viewer_pid:
            return int(entry.name)
    return None


def gone(pid):
    try:
        return Path(f"/proc/{pid}/stat").read_text().split(") ")[1][0] == "Z"
    except OSError:
        return True


def run(scale: int = 1):
    with tempfile.TemporaryDirectory(prefix="rediwm-pdf-") as directory:
        tmp = Path(directory)
        doc_path = tmp / "document.pdf"
        generate_fixture_pdf(doc_path)

        config = tmp / "config.toml"
        config.write_text('[compositor]\nxwayland = false\n')

        env = dict(
            os.environ,
            HOME=str(tmp),
            XDG_RUNTIME_DIR=directory,
            XDG_CONFIG_HOME=str(tmp / "config"),
            XDG_DATA_HOME=str(tmp / "data"),
            XDG_DATA_DIRS=str(tmp / "data"),
            XDG_CONFIG_DIRS=str(tmp / "config"),
            XDG_CACHE_HOME=str(tmp / "cache"),
            XDG_STATE_HOME=str(tmp / "state"),
            REDIWM_CONFIG=str(config),
            WLR_BACKENDS="headless", REDIWM_FILES_DEVICES="0",
            WLR_HEADLESS_OUTPUTS="1",
            WLR_RENDERER=os.environ.get("REDIWM_TEST_RENDERER", "gles2"),
            REDIWM_SCALE=str(scale),
            DBUS_SESSION_BUS_ADDRESS="",
            DBUS_SYSTEM_BUS_ADDRESS="unix:path=/nonexistent-rediwm-test-system-bus",
        )
        env.pop("WAYLAND_DISPLAY", None)
        env.pop("REDIWM_SOCKET", None)
        processes = []

        def start(binary, *args, **extra):
            with (tmp / f"{binary}-{len(processes)}.log").open("w") as log:
                proc = subprocess.Popen(
                    [str(ROOT / "zig-out/bin" / binary), *args],
                    env=dict(env, **extra),
                    stdout=log,
                    stderr=log,
                )
            processes.append(proc)
            return proc

        try:
            start("rediwm")
            sock = wait_for(lambda: next(tmp.glob("rediwm-*.sock"), None), "IPC unavailable")
            display = next(p.name for p in tmp.glob("wayland-*") if not p.name.endswith(".lock"))

            with IPCClient(sock) as ipc:
                def windows(app):
                    return [w for w in ipc.get_windows() if w["app_id"] == app]

                def key(code, ctrl=False, shift=False):
                    if ctrl:
                        ipc.action('key', {"keycode": 29, "pressed": True})
                    if shift:
                        ipc.action('key', {"keycode": 42, "pressed": True})
                    for pressed in (True, False):
                        ipc.action('key', {"keycode": code, "pressed": pressed})
                    if shift:
                        ipc.action('key', {"keycode": 42, "pressed": False})
                    if ctrl:
                        ipc.action('key', {"keycode": 29, "pressed": False})
                    time.sleep(0.12)

                def viewer():
                    return next(iter(windows("rediwm-pdf")), None)

                def expect_title(prefix):
                    return wait_for(
                        lambda: (w := viewer()) and prefix in w["title"] and w,
                        f"viewer did not reach {prefix}",
                    )

                pdf_proc = start("rediwm-pdf", str(doc_path), WAYLAND_DISPLAY=display)
                win = wait_for(lambda: viewer(), "PDF viewer did not map")
                ipc.focus_window(win["id"])
                time.sleep(0.5)

                # Check initial title
                expect_title("(1/2)")
                assert len(windows("rediwm-pdf")) == 1
                assert win["sandbox"]["engine"] == "org.rediwm.pdf", win

                # Ctrl+O explains how to launch another viewer; it must not
                # expose a path field or replace this process's document.
                key(24, ctrl=True)
                key(1)
                expect_title("(1/2)")

                # Printing lives in a helper outside the sandbox. Without a
                # session bus, Ctrl+P reports that and the viewer carries on.
                helper = wait_for(lambda: print_helper(pdf_proc.pid), "print helper not running")
                key(25, ctrl=True)
                time.sleep(0.5)
                assert pdf_proc.poll() is None and not gone(helper)
                key(1)

                # Take screenshot to verify rendering
                shot_path = tmp / "screenshot.png"
                ipc.screenshot(path=str(shot_path))
                with Image.open(shot_path) as shot:
                    # Check for blue pixels from page 1
                    rgb = shot.convert("RGB")
                    colors = rgb.getcolors(rgb.width * rgb.height) or []
                    has_blue = any(b > 180 and r < 80 and g < 80 for n, (r, g, b) in colors)
                    assert has_blue, "Page 1 blue box did not render on screen"

                    # A new document opens fitted: the page's bottom edge is in
                    # the canvas (right of the 180px sidebar, below the 44px
                    # toolbar), not cut off at 100% zoom. Sidebar thumbnails
                    # also show the strip, hence the crop.
                    box = ipc.get_window_debug(win["id"])["client_box"]
                    canvas = rgb.crop(tuple(round(v * scale) for v in (
                        box["x"] + 180, box["y"] + 44,
                        box["x"] + box["width"], box["y"] + box["height"])))
                    canvas_colors = canvas.getcolors(canvas.width * canvas.height) or []
                    assert any(r > 200 and b > 200 and g < 60 for n, (r, g, b) in canvas_colors), \
                        "Page 1 bottom edge is clipped on open"

                # A horizontal drag selects characters, not the entire page.
                # Test forward/reverse, rotation, and Escape clearing copy state.
                box = ipc.get_window_debug(win["id"])["client_box"]
                page_scale = min(4 / 3, (box["width"] - 180 - 48) / 300,
                                 (box["height"] - 44 - 48) / 400)
                page_x = box["x"] + 180 + (box["width"] - 180 - 300 * page_scale) / 2
                page_y = box["y"] + 44 + 16
                measure = cairo.Context(cairo.ImageSurface(cairo.FORMAT_ARGB32, 1, 1))
                measure.select_font_face("Sans", cairo.FONT_SLANT_NORMAL, cairo.FONT_WEIGHT_NORMAL)
                measure.set_font_size(16)

                def clipboard():
                    return subprocess.check_output(["wl-paste", "--no-newline"],
                                                   env=dict(env, WAYLAND_DISPLAY=display), timeout=5).decode()

                def select_word(reverse=False, copy=True, word="Page", rotated=False):
                    prefix = "" if word == "Page" else "Page 1 "
                    first = 30 + measure.text_extents(prefix)[4]
                    last = first + measure.text_extents(word)[4]
                    if rotated:
                        fitted = min(4 / 3, (box["width"] - 180 - 48) / 400,
                                     (box["height"] - 44 - 48) / 300)
                        left = box["x"] + 180 + (box["width"] - 180 - 400 * fitted) / 2
                        points = [(left + (400 - 154) * fitted, page_y + first * fitted),
                                  (left + (400 - 154) * fitted, page_y + last * fitted)]
                    else:
                        points = [(page_x + first * page_scale, page_y + 154 * page_scale),
                                  (page_x + last * page_scale, page_y + 154 * page_scale)]
                    if reverse:
                        points.reverse()
                    ipc.move_cursor(round(points[0][0]), round(points[0][1]))
                    time.sleep(.08)
                    ipc.action("pointer_button", {"button": 272, "pressed": True})
                    ipc.move_cursor(round(points[1][0]), round(points[1][1]))
                    time.sleep(.08)
                    ipc.action("pointer_button", {"button": 272, "pressed": False})
                    if copy:
                        key(46, ctrl=True)
                        assert clipboard() == word, "drag copied more than the selected text"

                select_word()
                select_word(reverse=True)
                select_word(word="Content", copy=False)
                key(1)
                # Copying after Escape must leave the clipboard unchanged.
                key(46, ctrl=True)
                assert clipboard() == "Page"

                # Next page via keyboard shortcut (PageDown = keycode 109)
                key(109)
                time.sleep(0.3)
                expect_title("(2/2)")

                # Prev page via keyboard shortcut (PageUp = keycode 104)
                key(104)
                time.sleep(0.3)
                expect_title("(1/2)")

                # Rotate via keyboard shortcut R (keycode 19)
                key(19)
                time.sleep(0.3)

                key(102, ctrl=True)  # Start of the rotated document.
                select_word(rotated=True)

                # Close via Ctrl+W (keycode 17 = W)
                key(17, ctrl=True)
                wait_for(lambda: len(windows("rediwm-pdf")) == 0, "PDF viewer did not close")

                pdf_proc.wait(timeout=5)
                assert pdf_proc.returncode == 0, f"rediwm-pdf exited with code {pdf_proc.returncode}"
                wait_for(lambda: gone(helper), "print helper outlived the viewer")

                # The Print button hands the opened file to the print portal.
                portal = FakePrintPortal()
                try:
                    print_proc = start("rediwm-pdf", str(doc_path), WAYLAND_DISPLAY=display,
                                       DBUS_SESSION_BUS_ADDRESS=portal.address)
                    win = wait_for(viewer, "printing viewer did not map")
                    ipc.focus_window(win["id"])
                    expect_title("(1/2)")
                    box = ipc.get_window_debug(win["id"])["client_box"]
                    ipc.move_cursor(int(box["x"] + 612), int(box["y"] + 22))
                    time.sleep(0.1)
                    for pressed in (True, False):
                        ipc.action("pointer_button", {"button": 272, "pressed": pressed})
                    job = wait_for(lambda: portal.jobs and portal.jobs[0], "Print button did not reach the portal")
                    assert job["data"] == doc_path.read_bytes(), "printed bytes differ from the document"
                    assert job["title"] == doc_path.name and job["parent"] == "", job
                    # Answered requests free the helper for the next one.
                    key(25, ctrl=True)
                    wait_for(lambda: len(portal.jobs) == 2, "Ctrl+P did not print again")
                    assert portal.jobs[1]["data"] == job["data"]
                    def dialog_pixels():
                        shot = tmp / "print-dialog-check.png"
                        shot.unlink(missing_ok=True)
                        ipc.screenshot(path=str(shot))
                        with Image.open(shot) as im:
                            cx = box["x"] + box["width"] / 2
                            cy = box["y"] + box["height"] / 2
                            return im.convert("RGB").crop(tuple(round(v * scale) for v in
                                (cx - 210, cy - 85, cx + 210, cy + 85)))

                    baseline = dialog_pixels()
                    # Both cancellation and otherwise dismissed dialogs submit
                    # no job and leave the viewer usable without an error modal.
                    for response in (1, 2):
                        portal.prepare_response = response
                        dialogs = len(portal.dialogs)
                        key(25, ctrl=True)
                        wait_for(lambda: len(portal.dialogs) == dialogs + 1, "print dialog not requested")
                        time.sleep(.2)
                        assert len(portal.jobs) == 2, "dismissed print dialog submitted a job"
                        assert ImageChops.difference(baseline, dialog_pixels()).getbbox() is None, \
                            "dismissing the print dialog displayed an error"
                        key(109)
                        expect_title("(2/2)")
                        key(104)
                        expect_title("(1/2)")
                    # A submitted job failure still displays an error dialog.
                    portal.prepare_response = 0
                    portal.response = 2
                    key(25, ctrl=True)
                    wait_for(lambda: len(portal.jobs) == 3, "failed job not submitted")
                    time.sleep(.2)
                    assert ImageChops.difference(baseline, dialog_pixels()).getbbox() is not None, \
                        "a failed submitted job did not show an error"
                    key(1)
                    assert ImageChops.difference(baseline, dialog_pixels()).getbbox() is None, \
                        "Escape did not dismiss the job error"
                    key(109)
                    expect_title("(2/2)")
                    key(17, ctrl=True)
                    wait_for(lambda: not viewer(), "printing viewer did not close")
                    assert print_proc.wait(timeout=5) == 0
                finally:
                    portal.close()

                # Tiles are clipped in raster pixels: at any scale each one
                # shows its own part of the page, not a magnified corner.
                tall = tmp / "tall.pdf"
                generate_tall_pdf(tall)
                tall_proc = start("rediwm-pdf", str(tall), WAYLAND_DISPLAY=display)
                win = wait_for(viewer, "tall PDF viewer did not map")
                ipc.focus_window(win["id"])
                expect_title("(1/1)")
                key(11)  # 0: fit width

                tall_shot = tmp / "tall.png"

                def halves():
                    tall_shot.unlink(missing_ok=True)
                    ipc.screenshot(path=str(tall_shot))
                    box = ipc.get_window_debug(win["id"])["client_box"]
                    with Image.open(tall_shot) as shot:
                        top = shot.convert("RGB").crop(tuple(round(v * scale) for v in (
                            box["x"] + 180, box["y"] + 64, box["x"] + box["width"], box["y"] + 160)))
                    colors = top.getcolors(top.width * top.height) or []
                    blue = sum(n for n, (r, g, b) in colors if b > 200 and r < 60 and g < 60)
                    red = sum(n for n, (r, g, b) in colors if r > 200 and g < 60 and b < 60)
                    return red > 0 and 0.8 < blue / red < 1.25

                wait_for(halves, "fit width does not show the page's own halves")
                key(17, ctrl=True)
                wait_for(lambda: not viewer(), "tall PDF viewer did not close")
                assert tall_proc.wait(timeout=5) == 0

                # Files opens PDFs itself, without an installed MIME association.
                documents = tmp / "documents"
                documents.mkdir()
                selected_pdf = documents / "a document #.PDF"
                shutil.copyfile(doc_path, selected_pdf)
                files = start("rediwm-files", str(documents), WAYLAND_DISPLAY=display)
                file_win = wait_for(lambda: next(iter(windows("rediwm-files")), None), "Files did not map")
                ipc.focus_window(file_win["id"])
                time.sleep(.4)
                key(102)  # Home selects the PDF.
                key(57)   # Space opens our PDF viewer.
                win = expect_title(selected_pdf.name)
                assert win["sandbox"]["engine"] == "org.rediwm.pdf", win
                ipc.focus_window(win["id"])
                key(17, ctrl=True)
                wait_for(lambda: not viewer(), "Space-opened PDF did not close")

                ipc.focus_window(file_win["id"])
                time.sleep(.4)
                box = ipc.get_window_debug(file_win["id"])["client_box"]
                ipc.move_cursor(int(box["x"] + 260), int(box["y"] + 160))
                for _ in range(2):
                    for pressed in (True, False):
                        ipc.action('pointer_button', {"button": 272, "pressed": pressed})
                    time.sleep(.08)
                win = expect_title(selected_pdf.name)
                assert win["sandbox"]["engine"] == "org.rediwm.pdf", win
                ipc.focus_window(win["id"])
                key(17, ctrl=True)
                wait_for(lambda: not viewer(), "Double-clicked PDF did not close")
                files.terminate()
                files.wait(timeout=5)

                if shutil.which("qpdf"):
                    encrypted = tmp / "encrypted.pdf"
                    subprocess.run(["qpdf", "--encrypt", "secretpass", "ownerpass", "256",
                                    "--", str(doc_path), str(encrypted)], check=True)
                    protected_proc = start("rediwm-pdf", str(encrypted), WAYLAND_DISPLAY=display)
                    protected_win = wait_for(viewer, "encrypted PDF viewer did not map")
                    ipc.focus_window(protected_win["id"])
                    # The worker's password-required result reaches the UI
                    # after the initial window has mapped.
                    time.sleep(0.3)
                    ipc.type_text("wrongpassword")
                    key(28)
                    time.sleep(0.3)
                    expect_title("(1/0)")
                    # Replacing the pathname must not replace the open inode.
                    encrypted.unlink()
                    encrypted.write_bytes(b"not the selected PDF")
                    ipc.type_text("secretpass")
                    key(28)
                    expect_title("(1/2)")
                    assert protected_proc.poll() is None
                    key(17, ctrl=True)
                    wait_for(lambda: not windows("rediwm-pdf"), "encrypted viewer did not close")
                    assert protected_proc.wait(timeout=5) == 0
                else:
                    print("SKIP: encrypted UI retry test needs qpdf")

                # A sandboxed process needs its one document at startup.
                empty_proc = start("rediwm-pdf", WAYLAND_DISPLAY=display)
                empty_proc.wait(timeout=5)
                assert empty_proc.returncode != 0
                assert not windows("rediwm-pdf")

                print("PDF viewer integration test passed successfully!")

        except Exception:
            for path in tmp.glob("*.log"):
                print(path.name, path.read_text(errors="replace")[-4000:])
            raise
        finally:
            for p in reversed(processes):
                if p.poll() is None:
                    p.terminate()
                    try:
                        p.wait(timeout=2)
                    except subprocess.TimeoutExpired:
                        p.kill()


if __name__ == "__main__":
    run(int(os.environ.get("REDIWM_SCALE", "1")))