mirror of
https://github.com/storytold/pdfcraft.git
synced 2026-12-03 04:26:26 -05:00
86 lines
3.8 KiB
Python
86 lines
3.8 KiB
Python
"""Verify raw Windows PostScript and decode its numbered sheets independently."""
|
|
import hashlib
|
|
import importlib.util
|
|
import json
|
|
from pathlib import Path
|
|
import re
|
|
import subprocess
|
|
import tempfile
|
|
|
|
|
|
ROOT = Path("captured-postscript")
|
|
VERIFY = Path("shared/crates/print/examples/print_acceptance/verify.py")
|
|
CASES = {"baseline": [1, 2, 3, 4], "range": [2, 4]}
|
|
spec = importlib.util.spec_from_file_location("numbered_sheets", VERIFY)
|
|
numbered_sheets = importlib.util.module_from_spec(spec)
|
|
spec.loader.exec_module(numbered_sheets)
|
|
|
|
|
|
def verify(folder, case, expected):
|
|
raw = folder / f"{case}.prn"
|
|
captured = raw.read_bytes()
|
|
# A printer may wrap the PostScript in PJL. Keep the spool bytes intact and
|
|
# pass only its DSC document to the independent interpreter.
|
|
start = captured.find(b"%!PS-Adobe-")
|
|
end = captured.rfind(b"%%EOF")
|
|
assert 0 <= start < end, f"{raw}: PostScript header or EOF missing"
|
|
payload = captured[start:end + len(b"%%EOF")] + b"\n"
|
|
pages = re.findall(rb"^%%Page:[ \t]+[^\r\n]*[ \t]+([0-9]+)[ \t]*\r?$", payload, flags=re.MULTILINE)
|
|
declared = re.findall(rb"^%%Pages:[ \t]+([0-9]+)(?:[ \t][^\r\n]*)?\r?$", payload, flags=re.MULTILINE)
|
|
assert [int(page) for page in pages] == list(range(1, len(expected) + 1)), (raw, pages)
|
|
assert declared and all(int(n) == len(expected) for n in declared), (raw, declared)
|
|
assert re.search(rb"^%%Trailer[ \t]*\r?$", payload, flags=re.MULTILINE), raw
|
|
summary = {
|
|
"sha256": hashlib.sha256(captured).hexdigest(),
|
|
"bytes": len(captured),
|
|
"postscript": payload.splitlines()[0].decode("ascii"),
|
|
"prefix_bytes": start,
|
|
"declared_pages": [int(n) for n in declared],
|
|
"page_ordinals": [int(page) for page in pages],
|
|
}
|
|
(folder / f"{case}-dsc.json").write_text(json.dumps(summary, indent=2) + "\n")
|
|
print(f"{raw}: {summary}", flush=True)
|
|
|
|
document = folder / f"{case}.ps"
|
|
document.write_bytes(payload)
|
|
pdf = folder / f"{case}-rendered.pdf"
|
|
subprocess.run(
|
|
["gs", "-q", "-dSAFER", "-dBATCH", "-dNOPAUSE", "-dNoOutputFonts", "-sDEVICE=pdfwrite", f"-sOutputFile={pdf}", document],
|
|
check=True, timeout=60,
|
|
)
|
|
with tempfile.TemporaryDirectory(prefix="craft-postscript-") as directory:
|
|
root = Path(directory)
|
|
subprocess.run(["pdftoppm", "-r", "36", pdf, root / "page"], check=True, timeout=60)
|
|
sheets = sorted(root.glob("page-*.ppm"), key=lambda path: int(path.stem.split("-")[-1]))
|
|
assert len(sheets) == len(expected), (pdf, len(sheets), expected)
|
|
# Windows' Color preference isn't reliable for the output PS class
|
|
# driver. Verify whichever mode the physical swatches actually use.
|
|
try:
|
|
numbered_sheets.verify_page(sheets[0], expected[0], plotter=False, gray=False)
|
|
grayscale = False
|
|
except ValueError:
|
|
numbered_sheets.verify_page(sheets[0], expected[0], plotter=False, gray=True)
|
|
grayscale = True
|
|
for sheet, page in zip(sheets[1:], expected[1:]):
|
|
numbered_sheets.verify_page(sheet, page, plotter=False, gray=grayscale)
|
|
print(f"{pdf}: verified IDs {expected} with {'gray' if grayscale else 'color'} swatches", flush=True)
|
|
info = subprocess.check_output(["pdfinfo", pdf], text=True)
|
|
(folder / f"{case}.pdfinfo").write_text(info)
|
|
|
|
|
|
def main():
|
|
failures = []
|
|
for model in ("ps-class", "imagesetter"):
|
|
folder = ROOT / model
|
|
for case, expected in CASES.items():
|
|
try:
|
|
verify(folder, case, expected)
|
|
except (AssertionError, OSError, ValueError, subprocess.SubprocessError) as error:
|
|
failures.append(f"{model}/{case}: {error}")
|
|
if failures:
|
|
raise SystemExit("\n".join(failures))
|
|
|
|
|
|
if __name__ == "__main__":
|
|
main()
|