Oregami
Repositories/oxedyne/fe2o3

oxedyne/fe2o3/fe2o3_austenite/tests/pdf_links_eval.rs

7.3 KiB, 2 runs

created by r1870400018:74081, which is this file's identity for as long as the history lasts, whatever it is later renamed to

download · who wrote it · its history

1//! The link annotations of a PDF written through the evaluator are Typst's: a link around text covers the
2//! text, and a link around a block-level element, an image or a block, covers the element's whole frame, as
3//! Typst's frame modifiers make it. The expectation is Typst's own PDF of the same source, read back with
4//! the same reader.
5
6#![allow(dead_code)]
7
8#[path = "eval_oracle/mod.rs"]
9mod harness;
10
11use harness::oracle::Oracle;
12use harness::pdf::{
13 austenite_pdf,
14 typst_pdf,
15 work_dir,
16};
17
18use oxedyne_fe2o3_core::prelude::*;
19
20use std::path::Path;
21use std::process::Command;
22
23// A plain square badge, so the image case needs no file but this one.
24const BADGE: &str = r##"<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 300 160" width="300" height="160"><rect x="1.5" y="1.5" width="297" height="157" rx="18" fill="#fff" stroke="#000" stroke-width="3"/></svg>"##;
25
26// The badge in the shape a template puts it, centred in a block under a show rule for links; a linked
27// filled block; and a text link, which already worked, to hold the comparison to all three.
28const SOURCE: &str = r##"#set page(width: 300pt, height: 300pt, margin: 20pt)
29Text link: #link("https://example.com/text")[example text].
30
31#align(center)[#block[
32#show link: it => it
33#link("https://need2know.ai/no-ai/doc")[#image("badge.svg", height: 1.4cm)]
34]]
35
36#link("https://example.com/block")[#block(width: 36pt, height: 36pt, fill: black)]
37"##;
38
39// Every link annotation's URI and rectangle as a JSON list, read by pikepdf; None where the tool is not here.
40fn links(pdf: &Path) -> Option<Vec<(String, [f64; 4])>> {
41 let script = "import sys, pikepdf\n\
42 pdf = pikepdf.open(sys.argv[1])\n\
43 for p in pdf.pages:\n\
44 \tfor a in p.obj.get('/Annots', []):\n\
45 \t\tif a.get('/Subtype') == '/Link' and '/A' in a and '/URI' in a.A:\n\
46 \t\t\tr = [float(x) for x in a.Rect]\n\
47 \t\t\tprint(str(a.A.URI), min(r[0], r[2]), min(r[1], r[3]), max(r[0], r[2]), max(r[1], r[3]))\n";
48 let out = match Command::new("python3").arg("-c").arg(script).arg(pdf).output() {
49 Ok(o) if o.status.success() => String::from_utf8_lossy(&o.stdout).to_string(),
50 _ => return None,
51 };
52 let mut v = Vec::new();
53 for line in out.lines() {
54 let f: Vec<&str> = line.split_whitespace().collect();
55 if f.len() != 5 {
56 continue;
57 }
58 let mut r = [0.0; 4];
59 for i in 0..4 {
60 r[i] = f[i + 1].parse().unwrap_or(f64::NAN);
61 }
62 v.push((f[0].to_string(), r));
63 }
64 v.sort_by(|a, b| a.0.cmp(&b.0));
65 Some(v)
66}
67
68#[test]
69fn a_link_around_an_image_or_a_block_covers_its_whole_frame_as_typst_does() -> Outcome<()> {
70 if res!(Oracle::find()).is_none() {
71 return Ok(());
72 }
73 let dir = res!(work_dir("pdf-links-eval"));
74 res!(std::fs::write(dir.join("badge.svg"), BADGE));
75 let src = dir.join("main.typ");
76 res!(std::fs::write(&src, SOURCE));
77 let typst_out = dir.join("typst.pdf");
78 res!(typst_pdf(&src, &typst_out));
79 let made = res!(austenite_pdf(&src));
80 let ours = dir.join("austenite.pdf");
81 res!(std::fs::write(&ours, &made.bytes));
82 let (want, got) = match (links(&typst_out), links(&ours)) {
83 (Some(w), Some(g)) => (w, g),
84 _ => {
85 println!("[pdf-links] SKIPPED: python3 with pikepdf is not here");
86 return Ok(());
87 }
88 };
89 let uris = |v: &[(String, [f64; 4])]| v.iter().map(|(u, _)| u.clone()).collect::<Vec<_>>();
90 // Fixed by construction, so a comparison of two empty lists cannot pass.
91 assert_eq!(uris(&want), vec![
92 "https://example.com/block".to_string(),
93 "https://example.com/text".to_string(),
94 "https://need2know.ai/no-ai/doc".to_string(),
95 ], "Typst's links: {:?}", want);
96 assert_eq!(uris(&got), uris(&want), "the links differ from Typst's: {:?}", got);
97 for ((u, w), (_, g)) in want.iter().zip(got.iter()) {
98 if u.contains("/text") {
99 continue; // a text link's height follows the leading, compared elsewhere
100 }
101 for i in 0..4 {
102 assert!((w[i] - g[i]).abs() <= 0.5, "{}: rect {:?}, Typst's {:?}", u, g, w);
103 }
104 }
105 Ok(())
106}
107
108// A contents page, two labelled headings on pages of their own, a link to a label and two references.
109const INTERNAL: &str = r##"#set page(width: 300pt, height: 300pt, margin: 20pt)
110#set heading(numbering: "1.")
111#outline()
112#pagebreak()
113= Alpha <a>
114See #link(<b>)[the second] and @b.
115#pagebreak()
116= Beta <b>
117Back to @a.
118"##;
119
120// Every internal link annotation as (page it sits on, page it goes to, destination top), its destination
121// read wherever a writer may put it: an explicit `/Dest` array, a GoTo action, or a name looked up in the
122// catalogue's `/Dests` name tree or dictionary. None where python3 with pikepdf is not here.
123fn internal_links(pdf: &Path) -> Option<Vec<(usize, usize, f64)>> {
124 let script = "import sys, pikepdf\n\
125 pdf = pikepdf.open(sys.argv[1])\n\
126 idx = {p.obj.objgen: i for i, p in enumerate(pdf.pages)}\n\
127 names = {}\n\
128 r = pdf.Root\n\
129 if '/Names' in r and '/Dests' in r.Names:\n\
130 \tfor k, v in pikepdf.NameTree(r.Names.Dests).items(): names[str(k)] = v\n\
131 if '/Dests' in r:\n\
132 \tfor k, v in r.Dests.items(): names[str(k).lstrip('/')] = v\n\
133 for i, p in enumerate(pdf.pages):\n\
134 \tfor a in p.obj.get('/Annots', []):\n\
135 \t\tif a.get('/Subtype') != '/Link': continue\n\
136 \t\td = a.get('/Dest')\n\
137 \t\tif d is None and '/A' in a and a.A.get('/S') == '/GoTo': d = a.A.D\n\
138 \t\tif d is None: continue\n\
139 \t\tif not isinstance(d, pikepdf.Array):\n\
140 \t\t\td = names.get(str(d).lstrip('/'))\n\
141 \t\t\tif isinstance(d, pikepdf.Dictionary): d = d.D\n\
142 \t\tif d is None: print(i, -1, -1); continue\n\
143 \t\ty = float(d[3]) if len(d) > 3 and d[1] == '/XYZ' else -1\n\
144 \t\tprint(i, idx.get(d[0].objgen, -1), y)\n";
145 let out = match Command::new("python3").arg("-I").arg("-c").arg(script).arg(pdf).output() {
146 Ok(o) if o.status.success() => String::from_utf8_lossy(&o.stdout).to_string(),
147 _ => return None,
148 };
149 let mut v = Vec::new();
150 for line in out.lines() {
151 let f: Vec<&str> = line.split_whitespace().collect();
152 if f.len() != 3 {
153 continue;
154 }
155 let n = |s: &str| s.parse::<f64>().unwrap_or(f64::NAN);
156 v.push((n(f[0]) as usize, n(f[1]) as usize, n(f[2])));
157 }
158 v.sort_by(|a, b| (a.0, a.1).cmp(&(b.0, b.1)));
159 Some(v)
160}
161
162#[test]
163fn contents_entries_and_references_link_inside_the_document_as_typst_does() -> Outcome<()> {
164 if res!(Oracle::find()).is_none() {
165 return Ok(());
166 }
167 let dir = res!(work_dir("pdf-links-internal"));
168 let src = dir.join("main.typ");
169 res!(std::fs::write(&src, INTERNAL));
170 let typst_out = dir.join("typst.pdf");
171 res!(typst_pdf(&src, &typst_out));
172 let made = res!(austenite_pdf(&src));
173 let ours = dir.join("austenite.pdf");
174 res!(std::fs::write(&ours, &made.bytes));
175 let (want, got) = match (internal_links(&typst_out), internal_links(&ours)) {
176 (Some(w), Some(g)) => (w, g),
177 _ => {
178 println!("[pdf-links] SKIPPED: python3 with pikepdf is not here");
179 return Ok(());
180 }
181 };
182 let pages = |v: &[(usize, usize, f64)]| v.iter().map(|(a, b, _)| (*a, *b)).collect::<Vec<_>>();
183 // Fixed by construction: two contents entries on the first page, the link and the reference to Beta
184 // on the second, the reference back to Alpha on the third.
185 assert_eq!(pages(&want), vec![(0, 1), (0, 2), (1, 2), (1, 2), (2, 1)], "Typst's links: {:?}", want);
186 assert_eq!(pages(&got), pages(&want), "the internal links differ from Typst's: {:?}", got);
187 for ((_, _, w), (_, _, g)) in want.iter().zip(got.iter()) {
188 assert!((w - g).abs() <= 12.0, "a destination's top {} is not Typst's {}: {:?}", g, w, got);
189 }
190 Ok(())
191}