Modern Apps git
git clone https://git.maproj.org/Modern-Apps.git
cov/c3 ▾

Modern-Apps.git / pdf / src / main / rust / src / golden_tests_part4.rs

golden_tests_part4.rs379 lines · 16.3 KiBRaw
1/// The same per-glyph cap, but with a TRANSPARENCY GROUP open at the cut, not just
2/// a clip. Closing the open brackets means synthesising a `GroupPop` and a
3/// `ClipPop` in the right order; my sibling test above only exercises the clip
4/// branch, so a fix that handled `ClipPush` and forgot `GroupPush` would pass it
5/// and leave a `saveLayer` unbalanced for the rest of the page — which is worse
6/// than an unbalanced clip, because it leaks a whole compositing layer.
7#[test]
8fn type3_per_glyph_cap_closes_group_brackets_too() {
9 let mut doc = Document::with_version("1.7");
10 let wanted = MAX_TYPE3_PRIMS_PER_GLYPH * 3;
11 let mut form_src = String::from("1 0 0 rg\n");
12 for i in 0..wanted {
13 let y = (i % 600) as i64;
14 form_src.push_str(&format!("0 {y} 10 10 re f\n"));
15 }
16 // A transparency group, so `Do` emits GroupPush inside the form's BBox clip.
17 let form_id = doc.add_object(Stream::new(
18 dictionary! {
19 "Type" => "XObject", "Subtype" => "Form",
20 "BBox" => vec![0.into(), 0.into(), 700.into(), 700.into()],
21 "Group" => dictionary! { "Type" => "Group", "S" => "Transparency", "I" => true },
22 },
23 form_src.into_bytes(),
24 ));
25 let proc_id = doc.add_object(Stream::new(
26 dictionary! {},
27 b"q /Fm0 Do Q\n".to_vec(),
28 ));
29 let char_procs = doc.add_object(dictionary! { "a" => proc_id });
30 let encoding = doc.add_object(dictionary! {
31 "Type" => "Encoding",
32 "Differences" => vec![65.into(), "a".into()],
33 });
34 let font = dictionary! {
35 "Type" => "Font", "Subtype" => "Type3",
36 "FontMatrix" => vec![0.001.into(), 0.into(), 0.into(), 0.001.into(), 0.into(), 0.into()],
37 "FontBBox" => vec![0.into(), 0.into(), 750.into(), 750.into()],
38 "CharProcs" => char_procs, "Encoding" => encoding,
39 "FirstChar" => 65, "LastChar" => 65, "Widths" => vec![700.into()],
40 "Resources" => dictionary! { "XObject" => dictionary! { "Fm0" => form_id } },
41 };
42 let mut fonts = HashMap::new();
43 fonts.insert(b"F1".to_vec(), font_info(&doc, &font));
44 let gs = GraphicsState {
45 font_key: b"F1".to_vec(),
46 font_size: 100.0,
47 ..Default::default()
48 };
49 let mut prims = Vec::new();
50 show_string(&doc, &mut prims, &gs, &fonts, &IDENTITY, b"AA", 0);
51
52 let groups = count(&prims, |p| matches!(p, Prim::GroupPush { .. }));
53 println!(
54 "type3 group cap: {} prims, {} fills, {groups} GroupPush for 2 glyphs",
55 prims.len(),
56 count(&prims, |p| matches!(p, Prim::Fill { .. }))
57 );
58 assert!(
59 groups > 0,
60 "precondition: the CharProc's form must open a transparency group, else this \
61 test exercises the same branch as its sibling"
62 );
63 assert!(
64 prims.iter().any(|p| matches!(p, Prim::Fill { .. })),
65 "the capped glyph must still draw something"
66 );
67 let mut clip = 0i32;
68 let mut group = 0i32;
69 for (i, p) in prims.iter().enumerate() {
70 match p {
71 Prim::ClipPush { .. } => clip += 1,
72 Prim::ClipPop => {
73 clip -= 1;
74 assert!(clip >= 0, "prim {i}: unmatched ClipPop");
75 }
76 Prim::GroupPush { .. } => group += 1,
77 Prim::GroupPop => {
78 group -= 1;
79 assert!(group >= 0, "prim {i}: unmatched GroupPop would over-restore a saveLayer");
80 }
81 _ => {}
82 }
83 }
84 assert_eq!(
85 group, 0,
86 "{group} transparency group(s) left open by the per-glyph cut — a leaked \
87 saveLayer composites the whole rest of the page through this glyph's group"
88 );
89 assert_eq!(clip, 0, "{clip} clip level(s) left open by the per-glyph cut");
90}
91
92/// The per-glyph cap with a SOFT MASK in play. `interp2` reports the
93/// `SoftMaskPop` arm of the closer synthesis is deliberately not implemented,
94/// because a soft-mask bracket cannot be closed after the fact — so the question
95/// this test settles is not "does the arm work" but "can a cut orphan a soft-mask
96/// bracket at all". Consecutive fills under one `gs` coalesce into a single
97/// bracket, so a cut landing inside one is at least plausible.
98///
99/// Either outcome is informative: passing documents that soft-mask brackets are
100/// emitted retroactively around a completed range and therefore cannot be open at
101/// the cut (making the missing arm unreachable rather than a hole); failing means a
102/// capped glyph leaks a soft mask over the rest of the page.
103#[test]
104fn type3_per_glyph_cap_cannot_orphan_a_soft_mask_bracket() {
105 // Build a Type 3 font whose CharProc paints `fills` rectangles under an
106 // ExtGState soft mask, and return the prims one glyph emits.
107 let run = |fills: usize| -> Vec<Prim> {
108 let mut doc = Document::with_version("1.7");
109 let mask_content = Content {
110 operations: vec![
111 Operation::new("rg", vec![1.0.into(), 1.0.into(), 1.0.into()]),
112 Operation::new("re", vec![0.into(), 0.into(), 700.into(), 700.into()]),
113 Operation::new("f", vec![]),
114 ],
115 };
116 let mask_id = doc.add_object(Stream::new(
117 dictionary! {
118 "Type" => "XObject", "Subtype" => "Form",
119 "BBox" => vec![0.into(), 0.into(), 700.into(), 700.into()],
120 "Group" => dictionary! { "S" => "Transparency" },
121 },
122 mask_content.encode().unwrap(),
123 ));
124 let gs_id = doc.add_object(dictionary! {
125 "SMask" => dictionary! { "S" => "Luminosity", "G" => Object::Reference(mask_id) },
126 });
127 let mut proc_src = String::from("q\n/GS1 gs\n1 0 0 rg\n");
128 for i in 0..fills {
129 let y = (i % 600) as i64;
130 proc_src.push_str(&format!("0 {y} 10 10 re f\n"));
131 }
132 proc_src.push_str("Q\n");
133 let proc_id = doc.add_object(Stream::new(dictionary! {}, proc_src.into_bytes()));
134 let char_procs = doc.add_object(dictionary! { "a" => proc_id });
135 let encoding = doc.add_object(dictionary! {
136 "Type" => "Encoding",
137 "Differences" => vec![65.into(), "a".into()],
138 });
139 let font = dictionary! {
140 "Type" => "Font", "Subtype" => "Type3",
141 "FontMatrix" => vec![0.001.into(), 0.into(), 0.into(), 0.001.into(), 0.into(), 0.into()],
142 "FontBBox" => vec![0.into(), 0.into(), 750.into(), 750.into()],
143 "CharProcs" => char_procs, "Encoding" => encoding,
144 "FirstChar" => 65, "LastChar" => 65, "Widths" => vec![700.into()],
145 "Resources" => dictionary! { "ExtGState" => dictionary! { "GS1" => gs_id } },
146 };
147 let mut fonts = HashMap::new();
148 fonts.insert(b"F1".to_vec(), font_info(&doc, &font));
149 let gs = GraphicsState {
150 font_key: b"F1".to_vec(),
151 font_size: 100.0,
152 ..Default::default()
153 };
154 let mut prims = Vec::new();
155 show_string(&doc, &mut prims, &gs, &fonts, &IDENTITY, b"A", 0);
156 prims
157 };
158
159 // Precondition: WELL under the cap, the fixture must genuinely emit a soft-mask
160 // bracket. Without this, a zero-prim result below could just mean the mask was
161 // never set up and the test would be asserting nothing.
162 let small = run(4);
163 assert!(
164 count(&small, |p| matches!(p, Prim::SoftMaskPush { .. })) > 0,
165 "precondition: an uncapped glyph must emit a SoftMaskPush, else this test \
166 cannot say anything about orphaning one"
167 );
168 assert!(
169 small.iter().any(|p| matches!(p, Prim::Fill { .. })),
170 "precondition: an uncapped glyph must draw"
171 );
172
173 let prims = run(MAX_TYPE3_PRIMS_PER_GLYPH * 3);
174 let pushes = count(&prims, |p| matches!(p, Prim::SoftMaskPush { .. }));
175 let pops = count(&prims, |p| matches!(p, Prim::SoftMaskPop));
176 println!(
177 "type3 soft-mask cap: {} prims, {} fills, {pushes} SoftMaskPush / {pops} SoftMaskPop",
178 prims.len(),
179 count(&prims, |p| matches!(p, Prim::Fill { .. }))
180 );
181 assert_eq!(
182 pushes, pops,
183 "a capped glyph left {pushes} SoftMaskPush against {pops} SoftMaskPop — an \
184 orphaned soft mask composites the rest of the page through this glyph's mask"
185 );
186 assert!(
187 prims.iter().any(|p| matches!(p, Prim::Fill { .. })),
188 "the capped glyph vanished entirely. Avoiding an orphaned soft mask by cutting \
189 BEFORE the bracket degenerates when the mask opens at the start of the glyph, \
190 which is the normal shape for `q /GS1 gs <draw> Q` — there is nothing before \
191 it to keep. A glyph missing from the page is a worse regression than a glyph \
192 drawn without its mask."
193 );
194}
195
196// ===========================================================================
197// 10. Shading and patterns — §8.7
198
199fn tiling_pattern(doc: &mut Document, xstep: f64, ystep: f64) -> ObjectId {
200 let tile = Content {
201 operations: vec![
202 Operation::new("rg", vec![1.0.into(), 0.0.into(), 0.0.into()]),
203 Operation::new("re", vec![0.into(), 0.into(), 8.into(), 8.into()]),
204 Operation::new("f", vec![]),
205 ],
206 };
207 doc.add_object(Stream::new(
208 dictionary! {
209 "Type" => "Pattern", "PatternType" => 1, "PaintType" => 1, "TilingType" => 1,
210 "BBox" => vec![0.into(), 0.into(), 10.into(), 10.into()],
211 "XStep" => xstep, "YStep" => ystep,
212 "Resources" => dictionary! {},
213 },
214 tile.encode().unwrap(),
215 ))
216}
217
218fn fill_region(x0: f64, y0: f64, x1: f64, y1: f64) -> Vec<Vec<(f64, f64)>> {
219 vec![vec![(x0, y0), (x1, y0), (x1, y1), (x0, y1)]]
220}
221
222/// §8.7.3.1: a tiling pattern replicates across the WHOLE fill region on the
223/// `/XStep` x `/YStep` lattice. A small step over a large area must tile it, not
224/// paint a single cell in one corner.
225///
226/// Asserted on coverage rather than on prim counts, because the representation is
227/// an implementation choice: a non-overlapping periodic pattern may collapse to a
228/// single `ImageTiled` cell raster instead of one Fill per tile. What must hold
229/// either way is that ink reaches every corner of the region.
230#[test]
231fn tiling_pattern_with_a_small_step_covers_the_whole_region() {
232 let mut doc = Document::with_version("1.5");
233 let pid = tiling_pattern(&mut doc, 10.0, 10.0);
234 let region = fill_region(0.0, 0.0, 200.0, 200.0);
235 let mut prims = Vec::new();
236 paint_pattern_fill(
237 &doc, pid, &region, false, &IDENTITY, 0xFF00_0000, 1.0, BlendMode::Normal,
238 &HashMap::new(), &mut prims, 0, 0,
239 );
240 assert!(
241 prims.iter().any(is_ink),
242 "the pattern must paint something at all"
243 );
244 assert!(
245 ink_in_region(&prims, 0.0, 0.0, 20.0, 20.0),
246 "the origin corner must be tiled"
247 );
248 assert!(
249 ink_in_region(&prims, 180.0, 180.0, 201.0, 201.0),
250 "the far corner must be tiled too — this is the 'pattern painted one corner' bug"
251 );
252}
253
254/// §8.7.3.1: `/XStep` and `/YStep` are lattice *spacings*; a negative value is a
255/// magnitude, not a direction. The round-1 bug let a negative step invert the
256/// loop bounds so the pattern painted nothing at all.
257#[test]
258fn tiling_pattern_with_a_negative_step_still_paints() {
259 let mut doc = Document::with_version("1.5");
260 let pid = tiling_pattern(&mut doc, -10.0, -10.0);
261 let region = fill_region(0.0, 0.0, 100.0, 100.0);
262 let mut prims = Vec::new();
263 paint_pattern_fill(
264 &doc, pid, &region, false, &IDENTITY, 0xFF00_0000, 1.0, BlendMode::Normal,
265 &HashMap::new(), &mut prims, 0, 0,
266 );
267 assert!(
268 prims.iter().any(is_ink),
269 "a negative /XStep must tile by its magnitude, not paint nothing"
270 );
271 assert!(
272 ink_in_region(&prims, 0.0, 0.0, 20.0, 20.0)
273 && ink_in_region(&prims, 80.0, 80.0, 101.0, 101.0),
274 "and it must cover the region, not just one corner"
275 );
276}
277
278/// §8.9.5.2: a raster is placed by mapping the unit square through `ctm`, and
279/// sample row 0 is the TOP of the image — it pairs with `v = 1`, not `v = 0`.
280/// That convention is forced by real image XObjects, whose decoded JPEG/PNG
281/// scanlines arrive top-first, so every producer of a `Prim::Image` must match it.
282///
283/// A SYNTHETIC raster (axial/radial shading, mesh shading, pattern cell) is
284/// generated rather than decoded, so nothing forces its row order — if it writes
285/// row 0 at the LOW y of its bbox while still handing back a positive-`d`
286/// placement matrix, it renders vertically flipped while real images stay correct.
287///
288/// This is asserted on the shading's own geometry rather than against another
289/// raster, which is what makes it decisive: an axial shading running black at
290/// `y = 0` to white at `y = 100` has a known correct answer independent of any
291/// convention I might have misread. It also catches the cancelling double-fix —
292/// producer flipped AND consumer flipped looks right end-to-end but fails here.
293#[test]
294fn synthetic_shading_raster_pairs_row_zero_with_the_same_edge_as_a_real_image() {
295 let mut doc = Document::with_version("1.5");
296 let func_id = doc.add_object(dictionary! {
297 "FunctionType" => 2,
298 "Domain" => vec![0.into(), 1.into()],
299 "C0" => vec![0.0.into(), 0.0.into(), 0.0.into()], // black at t=0
300 "C1" => vec![1.0.into(), 1.0.into(), 1.0.into()], // white at t=1
301 "N" => 1,
302 });
303 // Vertical axis: t=0 at y=0 (black), t=1 at y=100 (white).
304 let sh_id = doc.add_object(dictionary! {
305 "ShadingType" => 2,
306 "ColorSpace" => "DeviceRGB",
307 "Coords" => vec![0.into(), 0.into(), 0.into(), 100.into()],
308 "Extend" => vec![Object::Boolean(true), Object::Boolean(true)],
309 "Function" => func_id,
310 });
311 let bytes = Content {
312 operations: vec![Operation::new("sh", vec![Object::Name(b"Sh0".to_vec())])],
313 }
314 .encode()
315 .unwrap();
316 let page_id = assemble(
317 &mut doc,
318 bytes,
319 dictionary! { "Shading" => dictionary! { "Sh0" => sh_id } },
320 dictionary! { "MediaBox" => vec![0.into(), 0.into(), 100.into(), 100.into()] },
321 dictionary! {},
322 );
323
324 let page = interpret_page(&doc, page_id).expect("interpret");
325 let (ctm, w, h, data) = page
326 .prims
327 .iter()
328 .find_map(|p| match p {
329 Prim::Image { ctm, w, h, data, format: 0, .. } => Some((*ctm, *w, *h, data.clone())),
330 _ => None,
331 })
332 .expect("the shading must emit a decoded raster");
333 assert!(w > 0 && h > 1, "need at least two rows to talk about orientation");
334
335 // Mean luminance of a raster row.
336 let row_luma = |row: u32| -> f64 {
337 let mut sum = 0f64;
338 let mut n = 0f64;
339 for x in 0..w {
340 let i = ((row * w + x) * 4) as usize;
341 if i + 2 < data.len() {
342 sum += (data[i] as f64 + data[i + 1] as f64 + data[i + 2] as f64) / 3.0;
343 n += 1.0;
344 }
345 }
346 if n == 0.0 { 0.0 } else { sum / n }
347 };
348 let (top_row, bottom_row) = (row_luma(0), row_luma(h - 1));
349 assert!(
350 (top_row - bottom_row).abs() > 16.0,
351 "the ramp must actually vary between the first and last row, else this test \
352 cannot detect an inversion (row0={top_row:.0}, row{}={bottom_row:.0})",
353 h - 1
354 );
355
356 // Where does each edge of the unit square land in page space?
357 let y_at_v0 = transform(&ctm, 0.5, 0.0).1;
358 let y_at_v1 = transform(&ctm, 0.5, 1.0).1;
359 // Row 0 pairs with v = 1 (§8.9.5.2), row h-1 with v = 0.
360 let (luma_at_v1, luma_at_v0) = (top_row, bottom_row);
361 let (low_y_luma, high_y_luma) = if y_at_v0 < y_at_v1 {
362 (luma_at_v0, luma_at_v1)
363 } else {
364 (luma_at_v1, luma_at_v0)
365 };
366 assert!(
367 low_y_luma < high_y_luma,
368 "the shading is vertically FLIPPED. Its function is black at t=0 (page y=0) \
369 and white at t=1 (page y=100), so once placed, the low-y edge must be dark \
370 and the high-y edge light. Got low-y luma {low_y_luma:.0} and high-y luma \
371 {high_y_luma:.0} (raster row0={top_row:.0}, row{}={bottom_row:.0}; v=0 lands \
372 at y={y_at_v0:.0}, v=1 at y={y_at_v1:.0}). Row 0 must pair with v=1, the same \
373 way a decoded image's first scanline does — a synthetic raster that writes \
374 row 0 at its bbox's low y while returning a positive-d matrix inverts. NOTE: \
375 if this fails after BOTH the raster producer and the Kotlin decoder were \
376 changed, the two flips cancelled and each looked correct in isolation.",
377 h - 1
378 );
379}