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
|
||||
@@ -227,7 +227,11 @@ fn services(inbox: Inbox, ctx: egui::Context) -> Services {
|
||||
log::error!("download of {name} failed: {e}");
|
||||
}
|
||||
})),
|
||||
print: Some(Box::new(craft_print::browser::print_pdf)),
|
||||
print: Some(Box::new(|bytes: &[u8]| {
|
||||
if let Err(e) = craft_print::browser::print_pdf(bytes) {
|
||||
log::error!("print failed: {e}");
|
||||
}
|
||||
})),
|
||||
open_url: Some(Box::new(|url: &str| {
|
||||
if let Some(w) = web_sys::window()
|
||||
&& let gridcraft_engine::links::LinkKind::External(url) = gridcraft_engine::links::classify(url)
|
||||
|
||||
@@ -58,7 +58,7 @@ impl SheetApp {
|
||||
self.printing.begin(submit(bytes, self.printing.settings.clone())).map_err(|_| "A print job is already being submitted.".to_owned())?;
|
||||
self.print_feedback_seen = None;
|
||||
} else if let Some(print) = &self.services.print {
|
||||
print(&bytes)?;
|
||||
print(&bytes);
|
||||
} else {
|
||||
return Err("Printing is unavailable here; export a PDF instead.".into());
|
||||
}
|
||||
|
||||
@@ -39,10 +39,8 @@ pub(super) fn print(app: &mut SheetApp, ui: &mut Ui, bs: &mut Backstage, out: &m
|
||||
if ui.add_enabled_ui(can_print, |ui| square_button(ui, Icon::Print, lang.tr("Print"))).inner.clicked()
|
||||
&& app.commit_edit(0, 0, false, false)
|
||||
{
|
||||
match app.run("ui.printSubmit", params.clone()) {
|
||||
Ok(_) => out.close = app.services.print_native.is_none(),
|
||||
Err(error) => app.alert(error),
|
||||
}
|
||||
app.print_now(params.clone());
|
||||
out.close = app.services.print_native.is_none();
|
||||
}
|
||||
ui.add_space(16.0);
|
||||
egui::ComboBox::from_id_salt("backstage_print_scope")
|
||||
|
||||
@@ -4,7 +4,7 @@ type PickSave = Box<dyn Fn(&str) -> Option<String>>;
|
||||
type OpenUrl = Box<dyn Fn(&str)>;
|
||||
type CopyHtml = Box<dyn FnMut(&str, &str) -> Result<(), String>>;
|
||||
type Download = Box<dyn Fn(&str, &[u8])>;
|
||||
type PrintPdf = Box<dyn Fn(&[u8]) -> Result<(), String>>;
|
||||
type PrintPdf = Box<dyn Fn(&[u8])>;
|
||||
|
||||
/// Host services the platform shell provides (file pickers, opening URLs).
|
||||
#[derive(Default)]
|
||||
|
||||
@@ -21,10 +21,7 @@ fn harness(jobs: Rc<RefCell<Vec<Vec<u8>>>>) -> egui_kittest::Harness<'static, Sh
|
||||
app.run("cell.set", json!({"cell": "H20", "input": "Outside"})).unwrap();
|
||||
app.run("pageLayout.pageSetup", json!({"printArea": "F10:H20"})).unwrap();
|
||||
app.run("selection.set", json!({"range": "A1:B2"})).unwrap();
|
||||
app.services.print = Some(Box::new(move |bytes| {
|
||||
jobs.borrow_mut().push(bytes.to_vec());
|
||||
Ok(())
|
||||
}));
|
||||
app.services.print = Some(Box::new(move |bytes| jobs.borrow_mut().push(bytes.to_vec())));
|
||||
app.run("ui.backstage", json!({"page": "print"})).unwrap();
|
||||
let mut h = egui_kittest::Harness::builder().with_size(egui::vec2(1000.0, 800.0)).build_ui_state(
|
||||
|ui, app: &mut SheetApp| {
|
||||
@@ -79,30 +76,3 @@ fn the_preview_follows_the_selection_and_each_area_gets_its_own_page() {
|
||||
h.run_steps(4);
|
||||
assert!(h.query_by_label("Page 1 of 2").is_some(), "two areas, two pages");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn refused_browser_handoff_keeps_the_print_selection_available_for_retry() {
|
||||
let jobs = Rc::new(RefCell::new(Vec::new()));
|
||||
let mut h = harness(jobs.clone());
|
||||
choose_selection(&mut h);
|
||||
let accepted = h.state_mut().services.print.take();
|
||||
h.state_mut().services.print = Some(Box::new(|_| Err("The browser blocked the print window".into())));
|
||||
let error = h.state_mut().run("ui.printSubmit", json!({})).unwrap_err();
|
||||
assert!(error.contains("blocked the print window"));
|
||||
h.get_all_by_role_and_label(egui::accesskit::Role::Button, "Print").last().expect("Print button").click();
|
||||
h.run_steps(3);
|
||||
assert!(h.state().backstage.is_some());
|
||||
assert!(h.state().message.as_ref().unwrap().1.contains("blocked the print window"));
|
||||
assert!(jobs.borrow().is_empty());
|
||||
|
||||
h.state_mut().message = None;
|
||||
h.state_mut().services.print = accepted;
|
||||
h.run_steps(3);
|
||||
h.get_all_by_role_and_label(egui::accesskit::Role::Button, "Print").last().expect("Print button").click();
|
||||
h.run_steps(3);
|
||||
assert!(h.state().backstage.is_none());
|
||||
let jobs = jobs.borrow();
|
||||
assert_eq!(jobs.len(), 1);
|
||||
assert!(contains(&jobs[0], "(Inside) Tj"));
|
||||
assert!(!contains(&jobs[0], "(Outside) Tj"));
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user