Skip to content

Truly independent web browser

18.7 KB
Raw Blame
"""Launch Ladybird on a fixture page and connect to it via NSAccessibility/AXUIElement."""

from __future__ import annotations

import json
import os
import pathlib
import shutil
import subprocess
import tempfile
import time

from contextlib import contextmanager
from typing import Callable
from typing import Optional

from AppKit import NSWorkspace
from ApplicationServices import AXIsProcessTrusted
from ApplicationServices import AXUIElementCopyAttributeValue
from ApplicationServices import AXUIElementCreateApplication
from ApplicationServices import kAXChildrenAttribute
from ApplicationServices import kAXFocusedWindowAttribute
from ApplicationServices import kAXMainWindowAttribute
from ApplicationServices import kAXRoleAttribute
from ApplicationServices import kAXTitleAttribute
from ApplicationServices import kAXWindowsAttribute
from Foundation import NSDate
from Foundation import NSRunLoop

REPO_ROOT = pathlib.Path(__file__).resolve().parents[4]

DEFAULT_BINARY = REPO_ROOT / "Build" / "release" / "bin" / "Ladybird.app" / "Contents" / "MacOS" / "Ladybird"

FIXTURE_DIR = pathlib.Path(__file__).resolve().parents[2] / "AccessibilityBridge" / "input"


def _ax_attr(elem, key):
    """Read one AX attribute. Returns None on any error (element gone, attribute unsupported, etc.)."""
    if elem is None:
        return None
    try:
        err, value = AXUIElementCopyAttributeValue(elem, key, None)
    except Exception:
        return None
    return None if err != 0 else value


def wait_for(
    predicate: Callable[[], bool],
    *,
    timeout: float = 15.0,
    interval: float = 0.1,
    description: str = "condition",
) -> bool:
    """Polls predicate() until it returns truthy or timeout expires.

    Returns whatever the final predicate call returned (truthy = success). The test file is responsible for asserting on
    the return value when it needs to fail the test on timeout; this helper never raises on timeout by itself — so
    callers can build their own error messages."""

    deadline = time.monotonic() + timeout
    result = False
    while time.monotonic() < deadline:
        result = predicate()
        if result:
            return result
        time.sleep(interval)
    return result


def _make_profile_directory() -> str:
    """A self-contained profile for one launch, marked past its first run.

    Ladybird shows about:welcome ahead of any launch URL until the profile has completed its first run
    (Application::initialize), and a --temporary-profile never has — so the test page would open as a second tab behind
    the welcome page. A --profile-path profile whose Settings.json already says the first run is complete opens the
    test page as the only tab. And it isolates the launch the same way --temporary-profile does: without a profile of
    its own, the launch hands its URL to any browser already running on the default profile and exits, and the tests
    would read (and write) whoever's real profile. The caller removes the directory when it stops the browser.
    """
    root = tempfile.mkdtemp(prefix="ladybird-ax-profile-")
    config = os.path.join(root, "config")
    os.makedirs(config, mode=0o700)
    with open(os.path.join(config, "Settings.json"), "w", encoding="utf-8") as f:
        json.dump({"firstRunComplete": True}, f)
    return root


class LaunchServicesProcess:
    def __init__(self, launcher, application):
        self.launcher = launcher
        self.application = application
        self.pid = application.processIdentifier()

    def poll(self):
        return self.launcher.poll()

    def terminate(self):
        self.application.terminate()

    def kill(self):
        self.application.forceTerminate()

    def wait(self, timeout=None):
        return self.launcher.wait(timeout=timeout)


class LadybirdContext:
    """A running Ladybird process wrapped with NSAccessibility/AXUIElement discovery helpers.

    One context per test class; a new Ladybird process is spawned per context — so state from a previous test cannot
    leak. Use via AccessibilityBridgeMacTestCase or the ladybird_for_fixture context manager."""

    def __init__(
        self,
        url: str,
        binary: Optional[pathlib.Path] = None,
        *,
        wait_for_web_area: bool = True,
        environment: Optional[dict[str, str]] = None,
        launch_via_launch_services: bool = False,
    ):
        self._launch_via_launch_services = launch_via_launch_services
        self._environment = environment or {}
        self._url = url
        self._wait_for_web_area = wait_for_web_area
        if binary is not None:
            self._binary = pathlib.Path(binary)
        elif os.environ.get("LADYBIRD_BINARY"):
            self._binary = pathlib.Path(os.environ["LADYBIRD_BINARY"])
        else:
            self._binary = DEFAULT_BINARY
        self._process: Optional[subprocess.Popen] = None
        self._app = None
        self._web = None
        self._stderr_file: Optional[tempfile.NamedTemporaryFile] = None
        self._profile_directory: Optional[str] = None

    def __enter__(self) -> "LadybirdContext":
        self.start()
        return self

    def __exit__(self, *exc_info) -> None:
        self.stop()

    def start(self) -> None:
        # Guard both entry paths — the 'with' block, and setUpClass's direct start() call: If resource acquisition
        # raises after the temp file or process is created, neither __exit__ nor tearDownClass runs — so, clean up here.
        try:
            self._start_impl()
        except BaseException:
            self.stop()
            raise

    def _start_impl(self) -> None:
        """Spawns Ladybird and waits for its AXWebArea to become populated."""
        if not self._binary.exists():
            raise FileNotFoundError(
                f"Ladybird binary not found at {self._binary}. Build it with 'ninja -C Build/release ladybird'."
            )

        # macOS gates AXUIElement reads behind the Accessibility permission. If the test runner doesn't have it, every
        # AX call silently returns kAXErrorAPIDisabled and the harness hangs indefinitely — so fail loud; fail early.
        if not AXIsProcessTrusted():
            raise RuntimeError(
                "The test runner is not trusted for Accessibility (kAXErrorAPIDisabled). "
                "Grant the calling shell/IDE Accessibility permission in System Settings → "
                "Privacy & Security → Accessibility, then re-run."
            )

        env = os.environ.copy()
        env.update(self._environment)

        # Send stderr to a regular file rather than subprocess.PIPE: Ladybird debug builds (ENABLE_ALL_THE_DEBUG_MACROS)
        # produce huge stderr volumes (PROMISE_DEBUG, etc.). A pipe's kernel buffer is ~64 KB; once it fills, every
        # dbgln in WebContent blocks on write — which can wedge the engine before AX registration completes. A regular
        # file never backpressures the writer, and we still get the bytes for diagnostics on failure.
        self._stderr_file = tempfile.NamedTemporaryFile(prefix="ladybird-ax-stderr-", suffix=".log", delete=False)

        # --force-cpu-painting: skip the GPU/Metal path. Per Services/WebContent/main.cpp the CPU backend is what other
        # test harnesses use ("the GPU backend is not deterministic"), and these AX tests don't depend on rendering at
        # all — they inspect the NSAccessibility surface, which is independent of which painter ran.
        self._profile_directory = _make_profile_directory()
        # A data directory of its own, so the launch stays out of the user's crash-report store: Ladybird offers the
        # newest pending report from that store in a popover on every launch, and a crash here would land in it.
        env["XDG_DATA_HOME"] = os.path.join(self._profile_directory, "xdg-data")
        env["XDG_DOWNLOAD_DIR"] = os.path.join(self._profile_directory, "downloads")
        os.makedirs(env["XDG_DOWNLOAD_DIR"], mode=0o700)
        arguments = ["--force-cpu-painting", "--profile-path", self._profile_directory, self._url]
        if self._launch_via_launch_services:
            bundle = self._binary.parents[2].resolve()
            if bundle.suffix != ".app":
                raise RuntimeError("Native-key tests require a Ladybird application bundle")
            workspace = NSWorkspace.sharedWorkspace()
            previous_pids = {application.processIdentifier() for application in workspace.runningApplications()}
            command = [
                "/usr/bin/open",
                "-n",
                "-W",
                "-a",
                str(bundle),
                "--stderr",
                self._stderr_file.name,
                "--stdout",
                "/dev/null",
            ]
            for key, value in {
                **self._environment,
                "XDG_DATA_HOME": env["XDG_DATA_HOME"],
                "XDG_DOWNLOAD_DIR": env["XDG_DOWNLOAD_DIR"],
            }.items():
                command.extend(["--env", f"{key}={value}"])
            command.extend(["--args", *arguments])
            launcher = subprocess.Popen(command, stdout=subprocess.DEVNULL, stderr=self._stderr_file)
            self._process = launcher

            def find_application():
                NSRunLoop.currentRunLoop().runUntilDate_(NSDate.dateWithTimeIntervalSinceNow_(0.01))
                for application in workspace.runningApplications():
                    url = application.bundleURL()
                    if (
                        application.processIdentifier() not in previous_pids
                        and url is not None
                        and pathlib.Path(url.path()).resolve() == bundle
                    ):
                        return application
                return None

            application = wait_for(find_application, description="LaunchServices fixture application")
            if not application:
                raise RuntimeError(
                    f"LaunchServices didn't register the native-key fixture (launcher status {launcher.poll()}): {pathlib.Path(self._stderr_file.name).read_text()}"
                )
            self._process = LaunchServicesProcess(launcher, application)
        else:
            self._process = subprocess.Popen(
                [str(self._binary), *arguments],
                env=env,
                stdout=subprocess.DEVNULL,
                stderr=self._stderr_file,
            )

        self._app = AXUIElementCreateApplication(self._process.pid)
        startup_timeout = float(os.environ.get("LADYBIRD_AX_STARTUP_TIMEOUT", "60"))

        # A test that decides for itself when an assistive technology first reads the page waits for nothing here: Any
        # accessibility query into the window turns Qt's accessibility on, and with it the fetch of the page's tree.
        if not self._wait_for_web_area:
            return

        def _web_appeared() -> bool:
            web = self._find_web_area()
            if web is None:
                return False
            # Wait for the AXWebArea's children to populate — not just the AXWebArea itself. The web area can show up on
            # the AX surface before Ladybird has populated it with children — and, when tests run back-to-back, that
            # racy empty state can leak into tests as flaky "expected X in the tree" failures.
            children = _ax_attr(web, kAXChildrenAttribute)
            if not children:
                return False
            self._web = web
            return True

        if not wait_for(_web_appeared, timeout=startup_timeout, description="Ladybird AXWebArea to populate"):
            # Read the stderr file *before* stop() — stop() unlinks it.
            stderr = ""
            if self._stderr_file is not None:
                try:
                    with open(self._stderr_file.name, "rb") as f:
                        stderr = f.read().decode(errors="replace")
                except Exception:
                    pass
            ax_state = self._describe_ax_state()
            # Startup failures (Compositor/sandbox/IPC) log near the top of stderr, so keep the head too.
            if len(stderr) <= 6000:
                stderr_excerpt = stderr
            else:
                stderr_excerpt = stderr[:3000] + "\n...[truncated]...\n" + stderr[-3000:]
            raise RuntimeError(
                f"Ladybird did not register an AXWebArea on NSAccessibility within {startup_timeout:g}s.\n"
                f"URL: {self._url}\nBinary: {self._binary}\n"
                f"AX surface at timeout:\n{ax_state}\n"
                f"Stderr:\n{stderr_excerpt}"
            )

    def stop(self) -> None:
        if self._process is None:
            self._cleanup_stderr_file()
            self._cleanup_profile_directory()
            return
        try:
            self._process.terminate()
            try:
                self._process.wait(timeout=5)
            except subprocess.TimeoutExpired:
                self._process.kill()
                self._process.wait(timeout=5)
        finally:
            self._process = None
            self._app = None
            self._web = None
            self._cleanup_stderr_file()
            self._cleanup_profile_directory()

    def _cleanup_stderr_file(self) -> None:
        if self._stderr_file is None:
            return
        try:
            self._stderr_file.close()
        except Exception:
            pass
        try:
            os.unlink(self._stderr_file.name)
        except Exception:
            pass
        self._stderr_file = None

    def _cleanup_profile_directory(self) -> None:
        if self._profile_directory is None:
            return
        shutil.rmtree(self._profile_directory, ignore_errors=True)
        self._profile_directory = None

    def window(self):
        """The application's focused window, or else its main window. AppKit answers this without the web view."""
        return _ax_attr(self._app, kAXFocusedWindowAttribute) or _ax_attr(self._app, kAXMainWindowAttribute)

    def _find_web_area(self):
        """Walk from the application's focused/main window down to the document root, or None until the tree is there.

        Qt's element for the web view is itself an AXWebArea (WebContentViewAccessibility.mm swizzles its role), with
        the overlay's AXScrollArea inside it, and the document root inside that. Qt's element is there from the start;
        the root appears once the tree has arrived, so the root, and only the root, is what this returns."""
        window = self.window()
        if window is None:
            return None
        outer = _find_by_role(window, "AXWebArea")
        if outer is None:
            return None
        for child in _ax_attr(outer, kAXChildrenAttribute) or []:
            if (root := _find_by_role(child, "AXWebArea")) is not None:
                return root
        return None

    def _describe_ax_state(self) -> str:
        """Best-effort snapshot of what IS on the AX surface, to diagnose a missing AXWebArea on timeout."""
        lines = []
        if self._process is not None:
            code = self._process.poll()
            state = "alive" if code is None else f"exited with code {code}"
            lines.append(f"process: {state} (pid {self._process.pid})")
        lines.append(f"app AXRole: {_ax_attr(self._app, kAXRoleAttribute)!r}")
        windows = _ax_attr(self._app, kAXWindowsAttribute) or []
        focused = _ax_attr(self._app, kAXFocusedWindowAttribute)
        main = _ax_attr(self._app, kAXMainWindowAttribute)
        focused_str = "yes" if focused else "no"
        main_str = "yes" if main else "no"
        lines.append(f"windows: {len(windows)}; focused: {focused_str}; main: {main_str}")
        window = focused or main or (windows[0] if windows else None)
        if window is None:
            lines.append("no window on the AX surface to descend into")
        else:
            lines.append("window subtree (AXRole, depth<=4):")
            lines.extend("  " + line for line in _describe_subtree(window, max_depth=4))
        return "\n".join(lines)

    @property
    def app(self):
        """The application AXUIElement. Raises if start() hasn't completed."""
        if self._app is None:
            raise RuntimeError("Ladybird context not started. Call start() or use as context manager.")
        return self._app

    @property
    def web(self):
        """The AXWebArea (the document root in NSAccessibility terms). Raises if not yet present."""
        if self._web is None:
            raise RuntimeError("AXWebArea not present in Ladybird tree (start() may not have completed)")
        return self._web

    @property
    def pid(self) -> int:
        """The Ladybird process id. Raises if start() hasn't completed."""
        if self._process is None:
            raise RuntimeError("Ladybird context not started. Call start() or use as context manager.")
        return self._process.pid

    def find_web_area(self):
        """A fresh lookup of the AXWebArea from the application's window, bypassing the handle start() cached.

        The cached handle is what every test normally wants. This is for tests that check whether an element handle
        survives a tree update: they need a second, independent lookup to compare it against."""
        return self._find_web_area()


def _find_by_role(root, role_name: str, depth: int = 0):
    """Pre-order DFS for the first descendant with matching AXRole. Depth-capped to defeat pathological trees."""
    if root is None or depth > 30:
        return None
    if _ax_attr(root, kAXRoleAttribute) == role_name:
        return root
    for child in _ax_attr(root, kAXChildrenAttribute) or []:
        found = _find_by_role(child, role_name, depth + 1)
        if found is not None:
            return found
    return None


def _describe_subtree(root, *, max_depth: int, depth: int = 0) -> list[str]:
    """Shallow AXRole/AXTitle dump of an AX subtree, depth-capped, for timeout diagnostics."""
    if root is None:
        return []
    role = _ax_attr(root, kAXRoleAttribute)
    title = _ax_attr(root, kAXTitleAttribute)
    label = ("  " * depth) + str(role) + (f" {title!r}" if title else "")
    children = _ax_attr(root, kAXChildrenAttribute) or []
    if depth >= max_depth:
        if children:
            return [label, ("  " * (depth + 1)) + f"... {len(children)} children (depth-capped)"]
        return [label]
    out = [label]
    for child in children:
        out.extend(_describe_subtree(child, max_depth=max_depth, depth=depth + 1))
    return out


@contextmanager
def ladybird_for_fixture(fixture_name: str, binary: Optional[pathlib.Path] = None):
    """Context manager spawning Ladybird on input/<fixture_name>."""
    fixture_path = (FIXTURE_DIR / fixture_name).resolve()
    if not fixture_path.exists():
        raise FileNotFoundError(f"fixture HTML not found: {fixture_path}")
    url = fixture_path.as_uri()
    ctx = LadybirdContext(url, binary=binary)
    try:
        ctx.start()
        yield ctx
    finally:
        ctx.stop()