mirror of
https://github.com/storytold/gridcraft.git
synced 2026-12-02 22:31:17 +00:00
Compare commits
6
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
222e12d1f3 | ||
|
|
0f8a55b580 | ||
|
|
ee8f7a5668 | ||
|
|
47055d4f58 | ||
|
|
73da9c65c8 | ||
|
|
71ec2b9aa0 |
@@ -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,188 @@
|
||||
"""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):
|
||||
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)
|
||||
# Chrome's Save as PDF destination opens the native Save File dialog.
|
||||
deadline = time.monotonic() + 25
|
||||
while 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)
|
||||
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)
|
||||
matrix = "--matrix" in sys.argv
|
||||
driver.get(url + ("?matrix" if matrix else ""))
|
||||
try:
|
||||
if cancellation:
|
||||
cancel_then_save(driver)
|
||||
return
|
||||
for name in (("range", "large", "plotter") if matrix else ("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 matrix:
|
||||
verifier = Path("acceptance/crates/print/examples/print_acceptance/verify.py")
|
||||
args = {"range": ["2", "4"], "large": list(map(str, range(1, 105))), "plotter": ["--plotter", "1"]}
|
||||
subprocess.run([sys.executable, verifier, pdf, *args[name]], check=True)
|
||||
elif 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,30 @@
|
||||
<!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();
|
||||
const matrix = new URLSearchParams(location.search).has("matrix");
|
||||
for (const id of matrix ? ["range", "large", "plotter"] : ["first", "second"]) {
|
||||
if (matrix) {
|
||||
const button = document.createElement("button");
|
||||
button.id = id;
|
||||
button.disabled = true;
|
||||
button.textContent = "Print " + id;
|
||||
document.body.append(button);
|
||||
}
|
||||
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,11 @@
|
||||
#[path = "../../acceptance/crates/print/examples/print_acceptance/fixture.rs"]
|
||||
mod fixture;
|
||||
|
||||
fn main() -> std::io::Result<()> {
|
||||
let dest = std::path::Path::new(env!("CARGO_MANIFEST_DIR"));
|
||||
let large: Vec<_> = (1..=104).collect();
|
||||
for (name, pages, plotter) in [("range", &[2, 4][..], false), ("large", large.as_slice(), false), ("plotter", &[1][..], true)] {
|
||||
std::fs::write(dest.join(format!("{name}.pdf")), fixture::pdf(pages, plotter))?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
@@ -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,55 @@
|
||||
name: Verify browser print output
|
||||
on:
|
||||
push:
|
||||
branches: [verify/gridcraft-browser-print-matrix-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: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1
|
||||
with:
|
||||
repository: storytold/craft-libs
|
||||
ref: cd03603db5426352c127148014a3d8fa635ae76c
|
||||
path: acceptance
|
||||
sparse-checkout: crates/print/examples/print_acceptance
|
||||
- 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: Generate the shared numbered and large-image fixtures
|
||||
working-directory: .github/print-probe
|
||||
run: |
|
||||
CARGO_MANIFEST_DIR="$PWD" rustc --edition 2024 numbered.rs -o "$RUNNER_TEMP/numbered"
|
||||
"$RUNNER_TEMP/numbered"
|
||||
- name: Print selected pages, 104 pages, and a 24 by 36 inch image in Chrome
|
||||
run: xvfb-run -a /usr/bin/python3 .github/print-probe/capture.py --matrix
|
||||
- name: Preserve output and diagnostics
|
||||
if: always()
|
||||
uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9
|
||||
with:
|
||||
name: chromium-print-matrix
|
||||
path: browser-capture
|
||||
if-no-files-found: warn
|
||||
retention-days: 7
|
||||
Generated
+1
@@ -3078,6 +3078,7 @@ dependencies = [
|
||||
name = "gridcraft-web"
|
||||
version = "0.20.0"
|
||||
dependencies = [
|
||||
"craft-print",
|
||||
"craft-web-api",
|
||||
"craft-web-host",
|
||||
"eframe",
|
||||
|
||||
@@ -25,9 +25,10 @@ log = { workspace = true }
|
||||
serde_json = { workspace = true }
|
||||
|
||||
[target.'cfg(target_arch = "wasm32")'.dependencies]
|
||||
craft-print = { workspace = true }
|
||||
eframe = { workspace = true, features = ["default_fonts", "wgpu", "accesskit"] }
|
||||
rfd = { workspace = true }
|
||||
wasm-bindgen = "0.2"
|
||||
wasm-bindgen-futures = "0.4"
|
||||
js-sys = "0.3"
|
||||
web-sys = { version = "0.3", features = ["Window", "Document", "Element", "Event", "EventTarget", "HtmlElement", "HtmlCanvasElement", "HtmlAnchorElement", "HtmlIFrameElement", "Blob", "BlobPropertyBag", "Url", "Location", "CssStyleDeclaration", "Clipboard", "ClipboardItem", "Navigator", "MessageEvent", "UrlSearchParams", "AddEventListenerOptions", "Storage", "CustomEvent", "CustomEventInit"] }
|
||||
web-sys = { version = "0.3", features = ["Window", "Document", "Element", "Event", "EventTarget", "HtmlElement", "HtmlCanvasElement", "HtmlAnchorElement", "Blob", "BlobPropertyBag", "Url", "Location", "CssStyleDeclaration", "Clipboard", "ClipboardItem", "Navigator", "MessageEvent", "UrlSearchParams", "Storage", "CustomEvent", "CustomEventInit"] }
|
||||
|
||||
@@ -228,7 +228,7 @@ fn services(inbox: Inbox, ctx: egui::Context) -> Services {
|
||||
}
|
||||
})),
|
||||
print: Some(Box::new(|bytes: &[u8]| {
|
||||
if let Err(e) = print_pdf(bytes) {
|
||||
if let Err(e) = craft_print::browser::print_pdf(bytes) {
|
||||
log::error!("print failed: {e}");
|
||||
}
|
||||
})),
|
||||
@@ -280,75 +280,6 @@ fn copy_html(html: &str, text: &str) -> Result<(), String> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Opens `bytes` (a PDF) as an object URL in a hidden iframe and calls the iframe's own
|
||||
/// `print()` once it has finished loading — the standard way to drive the browser's native print
|
||||
/// dialog on a PDF without a download or a popup window the browser might block. The blob URL and
|
||||
/// the iframe are both cleaned up once the print dialog closes, so repeated prints don't leak
|
||||
/// them.
|
||||
fn print_pdf(bytes: &[u8]) -> Result<(), String> {
|
||||
let js = |e: wasm_bindgen::JsValue| format!("{e:?}");
|
||||
let window = web_sys::window().ok_or("no window")?;
|
||||
let document = window.document().ok_or("no document")?;
|
||||
|
||||
let iframe: web_sys::HtmlIFrameElement = document.create_element("iframe").map_err(js)?.dyn_into().map_err(|_| "not an iframe")?;
|
||||
iframe.style().set_property("display", "none").map_err(js)?;
|
||||
let body = document.body().ok_or("no body")?;
|
||||
|
||||
let parts = js_sys::Array::of1(&js_sys::Uint8Array::from(bytes));
|
||||
let opts = web_sys::BlobPropertyBag::new();
|
||||
opts.set_type("application/pdf");
|
||||
let blob = web_sys::Blob::new_with_u8_array_sequence_and_options(&parts, &opts).map_err(js)?;
|
||||
let url = web_sys::Url::create_object_url_with_blob(&blob).map_err(js)?;
|
||||
|
||||
if let Err(e) = body.append_child(&iframe) {
|
||||
cleanup_print(&iframe, &url);
|
||||
return Err(js(e));
|
||||
}
|
||||
|
||||
// `onload` fires once the PDF has actually rendered inside the iframe;
|
||||
// printing before that would show a blank page. Set the handler BEFORE
|
||||
// `src` so a fast/cached load can't fire before we're listening.
|
||||
let iframe_for_load = iframe.clone();
|
||||
let url_for_cleanup = url.clone();
|
||||
let on_load = wasm_bindgen::closure::Closure::once_into_js(move || {
|
||||
iframe_for_load.set_onload(None);
|
||||
if let Err(e) = print_loaded_pdf(&iframe_for_load, &url_for_cleanup) {
|
||||
cleanup_print(&iframe_for_load, &url_for_cleanup);
|
||||
log::error!("print failed: {e:?}");
|
||||
}
|
||||
});
|
||||
iframe.set_onload(Some(on_load.unchecked_ref()));
|
||||
iframe.set_src(&url);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn cleanup_print(iframe: &web_sys::HtmlIFrameElement, url: &str) {
|
||||
// Both operations are idempotent: print can fail after dispatching `afterprint`.
|
||||
web_sys::Url::revoke_object_url(url).ok();
|
||||
iframe.remove();
|
||||
}
|
||||
|
||||
fn print_loaded_pdf(iframe: &web_sys::HtmlIFrameElement, url: &str) -> Result<(), JsValue> {
|
||||
let content_window = iframe.content_window().ok_or_else(|| JsValue::from_str("no print content window"))?;
|
||||
let iframe_for_cleanup = iframe.clone();
|
||||
let url_for_cleanup = url.to_owned();
|
||||
let on_after_print = wasm_bindgen::closure::Closure::once(move || {
|
||||
cleanup_print(&iframe_for_cleanup, &url_for_cleanup);
|
||||
});
|
||||
// Listen before `print()`, which can dispatch `afterprint` before it returns.
|
||||
// A one-shot listener also releases the callback when the dialog closes or is cancelled.
|
||||
let options = web_sys::AddEventListenerOptions::new();
|
||||
options.set_once(true);
|
||||
let callback = on_after_print.as_ref().unchecked_ref();
|
||||
content_window.add_event_listener_with_callback_and_add_event_listener_options("afterprint", callback, &options)?;
|
||||
if let Err(e) = content_window.print() {
|
||||
let _ = content_window.remove_event_listener_with_callback("afterprint", callback);
|
||||
return Err(e);
|
||||
}
|
||||
let _ = on_after_print.into_js_value();
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn mime_for(name: &str) -> &'static str {
|
||||
match name.rsplit('.').next().map(str::to_ascii_lowercase).as_deref() {
|
||||
Some("xlsx") => "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
|
||||
|
||||
Reference in New Issue
Block a user