mirror of
https://github.com/storytold/gridcraft.git
synced 2026-12-03 22:41:38 +00:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
687ecd3a12 | ||
|
|
0f8a55b580 | ||
|
|
ee8f7a5668 | ||
|
|
47055d4f58 | ||
|
|
73da9c65c8 |
@@ -0,0 +1,14 @@
|
||||
[package]
|
||||
name = "browser-print-probe"
|
||||
version = "0.1.0"
|
||||
edition = "2024"
|
||||
publish = false
|
||||
|
||||
[lib]
|
||||
crate-type = ["cdylib"]
|
||||
|
||||
[workspace]
|
||||
|
||||
[dependencies]
|
||||
craft-print = { path = "../../shared/crates/print" }
|
||||
wasm-bindgen = "=0.2.129"
|
||||
@@ -0,0 +1,190 @@
|
||||
"""Use real Chrome print preview on an isolated runner, then inspect the saved PDFs."""
|
||||
import functools
|
||||
import http.server
|
||||
import io
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import shutil
|
||||
import subprocess
|
||||
import threading
|
||||
import time
|
||||
import sys
|
||||
|
||||
from PIL import Image, ImageGrab
|
||||
from reportlab.pdfgen import canvas
|
||||
from selenium import webdriver
|
||||
from selenium.webdriver.chrome.service import Service
|
||||
from selenium.webdriver.firefox.service import Service as FirefoxService
|
||||
from selenium.webdriver.common.by import By
|
||||
from selenium.webdriver.support import expected_conditions as EC
|
||||
from selenium.webdriver.support.ui import WebDriverWait
|
||||
|
||||
|
||||
SITE = Path(__file__).resolve().parent
|
||||
RESULTS = Path("browser-capture").resolve()
|
||||
COLORS = {"first": [(220, 40, 50), (25, 55, 215)], "second": [(0, 160, 45)]}
|
||||
|
||||
|
||||
def fixture(name, colors):
|
||||
doc = canvas.Canvas(str(SITE / f"{name}.pdf"), pagesize=(612, 792))
|
||||
for index, rgb in enumerate(colors):
|
||||
doc.drawString(72, 690, f"{name} document page {index + 1}")
|
||||
doc.setFillColorRGB(*(v / 255 for v in rgb))
|
||||
doc.rect(145, 245, 322, 302, fill=1, stroke=0)
|
||||
doc.showPage()
|
||||
doc.save()
|
||||
|
||||
|
||||
def wait_for_pdf(before, name):
|
||||
deadline = time.monotonic() + 60
|
||||
while time.monotonic() < deadline:
|
||||
found = set(RESULTS.glob("*.pdf")) - before
|
||||
if len(found) > 1:
|
||||
raise RuntimeError(f"multiple outputs for {name}: {found}")
|
||||
if found:
|
||||
path = next(iter(found))
|
||||
if path.read_bytes().rstrip().endswith(b"%%EOF"):
|
||||
return path.rename(RESULTS / f"{name}-captured.pdf")
|
||||
time.sleep(0.25)
|
||||
raise TimeoutError(f"{name} produced no complete PDF")
|
||||
|
||||
|
||||
def inspect_pdf(path, colors):
|
||||
info = subprocess.check_output(["pdfinfo", path], text=True)
|
||||
pages = next(int(line.split()[1]) for line in info.splitlines() if line.startswith("Pages:"))
|
||||
assert pages == len(colors), (path, pages, colors)
|
||||
prefix = path.with_suffix("")
|
||||
subprocess.run(["pdftoppm", "-r", "36", "-png", path, prefix], check=True)
|
||||
for index, rgb in enumerate(colors, start=1):
|
||||
with Image.open(f"{prefix}-{index}.png") as image:
|
||||
actual = image.convert("RGB").getpixel((image.width // 2, image.height // 2))
|
||||
assert max(abs(a - b) for a, b in zip(actual, rgb)) < 20, (index, actual, rgb)
|
||||
print(f"{path.name} page {index}: {actual}", flush=True)
|
||||
|
||||
|
||||
def wait_preview(name, color, visible):
|
||||
"""Observe the actual X11 surface. The host page contains no colour marks."""
|
||||
deadline = time.monotonic() + 40
|
||||
while True:
|
||||
image = ImageGrab.grab().convert("RGB")
|
||||
# A half-page solid rectangle survives Chrome's print-preview scaling.
|
||||
pixels = image.resize((320, 240)).getdata()
|
||||
count = sum(max(abs(a - b) for a, b in zip(pixel, color)) < 18 for pixel in pixels)
|
||||
if (count > 300) == visible:
|
||||
image.save(RESULTS / f"{name}.png")
|
||||
print(f"{name}: {count} matching preview pixels", flush=True)
|
||||
return
|
||||
if time.monotonic() >= deadline:
|
||||
image.save(RESULTS / f"{name}-timeout.png")
|
||||
raise TimeoutError(f"{name}: matching preview pixels = {count}")
|
||||
time.sleep(0.35)
|
||||
|
||||
|
||||
def cancel_then_save(driver, *, gtk_picker=False):
|
||||
before = set(RESULTS.glob("*.pdf"))
|
||||
WebDriverWait(driver, 30).until(EC.element_to_be_clickable((By.ID, "first"))).click()
|
||||
wait_preview("before-cancel", COLORS["first"][0], True)
|
||||
subprocess.run(["xdotool", "key", "Escape"], check=True)
|
||||
wait_preview("after-cancel", COLORS["first"][0], False)
|
||||
assert set(RESULTS.glob("*.pdf")) == before, "cancel created a PDF"
|
||||
WebDriverWait(driver, 30).until(EC.element_to_be_clickable((By.ID, "second"))).click()
|
||||
wait_preview("next-document", COLORS["second"][0], True)
|
||||
subprocess.run(["xdotool", "key", "Return"], check=True)
|
||||
if gtk_picker:
|
||||
# Firefox's GTK dialog has already focused the filename when it covers
|
||||
# the green preview. The selected filename stem excludes its extension.
|
||||
wait_preview("gtk-file-picker", COLORS["second"][0], False)
|
||||
subprocess.run(["xdotool", "key", "ctrl+a"], check=True)
|
||||
subprocess.run(["xdotool", "type", "--clearmodifiers", str(RESULTS / "retry.pdf")], check=True)
|
||||
subprocess.run(["xdotool", "key", "Return"], check=True)
|
||||
# Chrome's Save as PDF destination opens the native Save File dialog.
|
||||
deadline = time.monotonic() + 25
|
||||
while not gtk_picker and time.monotonic() < deadline:
|
||||
if set(RESULTS.glob("*.pdf")) != before:
|
||||
break
|
||||
title = subprocess.run(["xdotool", "getwindowfocus", "getwindowname"], capture_output=True, text=True)
|
||||
# Firefox's GTK picker can be a transient without a separate window title.
|
||||
image = io.BytesIO()
|
||||
ImageGrab.grab().save(image, format="PNG")
|
||||
words = subprocess.run(["tesseract", "stdin", "stdout", "--psm", "6"], input=image.getvalue(), capture_output=True, check=True).stdout.decode()
|
||||
if "save" in title.stdout.lower() or ("Name:" in words and "Save" in words):
|
||||
print("Native Save File dialog is visible", flush=True)
|
||||
subprocess.run(["xdotool", "key", "ctrl+l"], check=True)
|
||||
subprocess.run(["xdotool", "type", "--clearmodifiers", str(RESULTS / "retry.pdf")], check=True)
|
||||
subprocess.run(["xdotool", "key", "Return"], check=True)
|
||||
break
|
||||
time.sleep(0.25)
|
||||
pdf = wait_for_pdf(before, "after-cancel")
|
||||
inspect_pdf(pdf, COLORS["second"])
|
||||
assert set(RESULTS.glob("*.pdf")) == before | {pdf}
|
||||
|
||||
|
||||
def firefox_probe(url):
|
||||
options = webdriver.FirefoxOptions()
|
||||
options.set_preference("print_printer", "Mozilla Save to PDF")
|
||||
options.set_preference("print.save_print_settings", True)
|
||||
with webdriver.Firefox(options=options, service=FirefoxService(shutil.which("geckodriver"))) as driver:
|
||||
print("Firefox", driver.capabilities["browserVersion"], flush=True)
|
||||
driver.get(url)
|
||||
try:
|
||||
driver.find_element(By.ID, "control").click()
|
||||
yellow = (240, 185, 20)
|
||||
wait_preview("firefox-parent-preview", yellow, True)
|
||||
subprocess.run(["xdotool", "key", "Escape"], check=True)
|
||||
wait_preview("firefox-parent-dismissed", yellow, False)
|
||||
cancel_then_save(driver, gtk_picker=True)
|
||||
finally:
|
||||
ImageGrab.grab().save(RESULTS / "firefox-last-screen.png")
|
||||
|
||||
|
||||
def main():
|
||||
RESULTS.mkdir()
|
||||
for name, colors in COLORS.items():
|
||||
fixture(name, colors)
|
||||
handler = functools.partial(http.server.SimpleHTTPRequestHandler, directory=SITE)
|
||||
with http.server.ThreadingHTTPServer(("127.0.0.1", 0), handler) as server:
|
||||
threading.Thread(target=server.serve_forever, daemon=True).start()
|
||||
url = f"http://127.0.0.1:{server.server_port}/"
|
||||
# This disposable browser cannot contact the system CUPS server.
|
||||
os.environ["CUPS_SERVER"] = str(RESULTS / "absent-cups.sock")
|
||||
if "--firefox" in sys.argv:
|
||||
firefox_probe(url)
|
||||
return
|
||||
options = webdriver.ChromeOptions()
|
||||
cancellation = "--cancel" in sys.argv
|
||||
if not cancellation:
|
||||
options.add_argument("--kiosk-printing")
|
||||
options.add_argument("--no-first-run")
|
||||
options.add_experimental_option("prefs", {
|
||||
"download.default_directory": str(RESULTS),
|
||||
"savefile.default_directory": str(RESULTS),
|
||||
"printing.print_preview_sticky_settings.appState": json.dumps({
|
||||
"version": 2, "recentDestinations": [{"id": "Save as PDF", "origin": "local"}],
|
||||
"selectedDestinationId": "Save as PDF",
|
||||
}),
|
||||
})
|
||||
options.set_capability("goog:loggingPrefs", {"browser": "ALL"})
|
||||
with webdriver.Chrome(options=options, service=Service(shutil.which("chromedriver"))) as driver:
|
||||
print("Chrome", driver.capabilities["browserVersion"], flush=True)
|
||||
driver.get(url)
|
||||
try:
|
||||
if cancellation:
|
||||
cancel_then_save(driver)
|
||||
return
|
||||
for name in ("control", "first", "second"):
|
||||
before = set(RESULTS.glob("*.pdf"))
|
||||
WebDriverWait(driver, 30).until(EC.element_to_be_clickable((By.ID, name))).click()
|
||||
pdf = wait_for_pdf(before, name)
|
||||
if name == "control":
|
||||
text = subprocess.check_output(["pdftotext", pdf, "-"], text=True)
|
||||
assert "Parent page control only" in text, text
|
||||
else:
|
||||
inspect_pdf(pdf, COLORS[name])
|
||||
finally:
|
||||
(RESULTS / "browser-log.json").write_text(json.dumps(driver.get_log("browser"), indent=2))
|
||||
driver.save_screenshot(str(RESULTS / "last-view.png"))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,22 @@
|
||||
<!doctype html>
|
||||
<meta charset="utf-8">
|
||||
<title>Parent page control</title>
|
||||
<style>
|
||||
#control-marker { display: none; }
|
||||
@media print { #control-marker { display: block; } }
|
||||
</style>
|
||||
<p>Parent page control only</p>
|
||||
<svg id="control-marker" width="360" height="340"><rect width="360" height="340" fill="rgb(240,185,20)"/></svg>
|
||||
<button id="control" onclick="setTimeout(() => window.print(), 0)">Print parent</button>
|
||||
<button id="first" disabled>Print first PDF</button>
|
||||
<button id="second" disabled>Print second PDF</button>
|
||||
<script type="module">
|
||||
import init, { print_document } from "./pkg/browser_print_probe.js";
|
||||
await init();
|
||||
for (const id of ["first", "second"]) {
|
||||
const pdf = new Uint8Array(await (await fetch("./" + id + ".pdf")).arrayBuffer());
|
||||
const button = document.getElementById(id);
|
||||
button.addEventListener("click", () => print_document(pdf));
|
||||
button.disabled = false;
|
||||
}
|
||||
</script>
|
||||
@@ -0,0 +1,7 @@
|
||||
use wasm_bindgen::prelude::*;
|
||||
|
||||
/// Exercise the same shared entry point as the GridCraft web print service.
|
||||
#[wasm_bindgen]
|
||||
pub fn print_document(bytes: &[u8]) -> Result<(), JsValue> {
|
||||
craft_print::browser::print_pdf(bytes).map_err(|error| JsValue::from_str(&error))
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
name: Verify browser print output
|
||||
on:
|
||||
push:
|
||||
branches: [verify/gridcraft-browser-output-4859]
|
||||
permissions:
|
||||
contents: read
|
||||
jobs:
|
||||
browser-print:
|
||||
runs-on: ubuntu-24.04
|
||||
timeout-minutes: 30
|
||||
steps:
|
||||
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1
|
||||
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1
|
||||
with:
|
||||
repository: storytold/craft-libs
|
||||
ref: e0646e91ad432c43358137d0d894877216fa91ed
|
||||
path: shared
|
||||
- uses: storytold/craft-common-actions/actions/install-apt-packages@main
|
||||
with:
|
||||
packages: xvfb xauth xdotool tesseract-ocr poppler-utils python3-selenium python3-reportlab python3-pil
|
||||
- name: Build the shared browser entry point as WebAssembly
|
||||
working-directory: .github/print-probe
|
||||
env:
|
||||
CARGO_PROFILE_DEV_DEBUG: 0
|
||||
run: |
|
||||
set -euo pipefail
|
||||
rustup target add wasm32-unknown-unknown
|
||||
cp ../../shared/Cargo.lock Cargo.lock
|
||||
cargo build --target wasm32-unknown-unknown
|
||||
archive="$RUNNER_TEMP/wasm-bindgen.tar.gz"
|
||||
curl --fail --location --silent --show-error https://github.com/wasm-bindgen/wasm-bindgen/releases/download/0.2.129/wasm-bindgen-0.2.129-x86_64-unknown-linux-musl.tar.gz -o "$archive"
|
||||
echo "82d12bb940e2d4e72e0d5605387fc1b8ca179044e012b620f0ce4e7440e8320e $archive" | sha256sum --check
|
||||
tar -xf "$archive" -C "$RUNNER_TEMP" wasm-bindgen-0.2.129-x86_64-unknown-linux-musl/wasm-bindgen
|
||||
"$RUNNER_TEMP/wasm-bindgen-0.2.129-x86_64-unknown-linux-musl/wasm-bindgen" --target web --out-dir pkg target/wasm32-unknown-unknown/debug/browser_print_probe.wasm
|
||||
- name: Verify the Firefox print dialog and inspect its output
|
||||
run: |
|
||||
firefox --version
|
||||
geckodriver --version
|
||||
xvfb-run -a /usr/bin/python3 .github/print-probe/capture.py --firefox
|
||||
- name: Preserve output and diagnostics
|
||||
if: always()
|
||||
uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9
|
||||
with:
|
||||
name: firefox-print-output
|
||||
path: browser-capture
|
||||
if-no-files-found: warn
|
||||
retention-days: 7
|
||||
Reference in New Issue
Block a user