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

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

draw_part1.rs413 lines · 22.4 KiBRaw
1/// Emit one text primitive per glyph, each positioned at its exact device-space
2/// origin computed from the PDF glyph widths + text state. Drawing glyph-by-glyph
3/// (rather than one run) keeps kerned/justified text aligned even though a
4/// substitute system font renders the glyph shapes. Returns the total advance in
5/// text space so the caller can step the text matrix.
6///
7/// `ambient_resources` is the resource dictionary in force at the showing
8/// operator. Only Type 3 needs it: §9.6.5 makes a Type 3 font's own `/Resources`
9/// optional and says the names "shall be looked up in the resource dictionary of
10/// the page on which the font is used" when it is absent.
11#[allow(clippy::too_many_arguments)]
12pub(crate) fn show_string_in(
13 doc: &Document,
14 prims: &mut Vec<Prim>,
15 gs: &GraphicsState,
16 fonts: &HashMap<Vec<u8>, FontInfo>,
17 text_matrix: &Mat,
18 bytes: &[u8],
19 depth: u32,
20 ambient_resources: Option<&lopdf::Dictionary>,
21) -> f64 {
22 let tfs = gs.font_size;
23 let th = gs.h_scale;
24 let trm = mat_mul(text_matrix, &gs.ctm);
25 let y_scale = (trm[2] * trm[2] + trm[3] * trm[3]).sqrt();
26 // Device-space horizontal scale, used to convert glyph advances (user space)
27 // into the device advance carried on the wire for text selection/search.
28 let x_scale = (trm[0] * trm[0] + trm[1] * trm[1]).sqrt();
29 // Horizontal scale to put on the wire for the SUBSTITUTE face. Kotlin derives
30 // the glyph's em from `size` (= Tfs·y_scale) and multiplies its width by
31 // `h_scale`, so Th alone under-describes an anisotropic matrix: with
32 // x_scale != y_scale the outline path draws the glyph x_scale/y_scale wider
33 // than the substitute path does, and the two disagree about the SIZE of the
34 // same glyph. Folding the ratio in is exactly 1.0 for every isotropic matrix
35 // — including every pure rotation — so it changes nothing on ordinary pages.
36 // This is the only part of the mismatch expressible in the v8 wire; the glyph
37 // being axis-aligned under a rotated matrix needs a field that does not exist.
38 //
39 // Bounded here rather than at the consumer. A near-degenerate matrix makes the
40 // ratio enormous, and `th` is `Tz/100` whose product can overflow; the check is
41 // on the f32 that is actually serialized, because `f64 as f32` saturates to inf
42 // above ~3.4e38 and a finite f64 would otherwise sail through.
43 let aniso = if y_scale > 1e-9 { x_scale / y_scale } else { 1.0 };
44 let wire_h_scale = th * if aniso.is_finite() { aniso.clamp(0.01, 100.0) } else { 1.0 };
45 let wire_h_scale = {
46 let v = wire_h_scale as f32;
47 if v.is_finite() {
48 v
49 } else {
50 1.0
51 }
52 };
53 let size = (tfs * y_scale) as f32;
54 // `Tf`'s operand and the CTM are file input, and `size` is their product, so a
55 // non-finite value is reachable even with both validated — an f64 above the f32
56 // range saturates to inf on the cast. NaN then survives Kotlin's
57 // `coerceAtLeast` (a comparison) into `Paint.textSize` and the glyph vanishes.
58 // Zero is the honest substitute: the consumer floors it to one pixel.
59 let size = finite_or_zero(size);
60 // Modes 3 (invisible) and 7 (clip only) advance the pen but paint nothing.
61 let drawable = gs.render_mode != 3 && gs.render_mode != 7;
62 // Mode 3 is how a scan carries its OCR layer: nothing is painted, but the run
63 // must still reach the text index or the document is unsearchable. `argb: 0`
64 // here plus the `rm != 3` paint guard in SafePdfViewerScreen.kt keep it unseen.
65 let invisible = gs.render_mode == 3;
66 let clip_only = gs.render_mode == 7;
67
68 let fi = match fonts.get(&gs.font_key) {
69 Some(fi) => fi,
70 None => {
71 // No font metrics: emit the run at the origin and estimate advance.
72 let run_advance = bytes.len() as f64 * 0.5 * tfs * th;
73 // Mode 7 is included deliberately. §9.3.6 Table 106 separates 4-6 from 7
74 // only by whether ink is laid down; their §9.4.3 clip contribution is
75 // identical, and 4-6 already emit here. Excluding 7 made the operator a
76 // total no-op whenever the font resource was missing, which also broke the
77 // commitment in `hidden_render_mode`: it maps a 4-6 run inside an OFF
78 // optional-content group to 7 precisely so the clip still contributes, and
79 // that clip then disappeared. This gate and the latch must stay IDENTICAL:
80 // `latches_text_clip`'s no-font arm is `!bytes.is_empty()`, the same
81 // condition as here, so every clip it latches has a record to accumulate
82 // from. The latch does NOT follow prim emission — that predicate was
83 // considered and rejected there, and a run whose glyphs all drop still
84 // latches and clips to EMPTY. So narrowing this gate alone would not drop
85 // the clip, it would apply an empty one and blank the rest of the text
86 // object. The outline is a substitute face, so the shape is approximate;
87 // that is the same approximation 4-6 already accept.
88 if (drawable || invisible || clip_only) && !bytes.is_empty() {
89 let (x, y) = transform(&trm, 0.0, gs.rise);
90 let text: String =
91 bytes.iter().filter_map(|&b| char::from_u32(b as u32)).collect();
92 if !text.is_empty() {
93 prims.push(Prim::Text {
94 x: x as f32,
95 y: y as f32,
96 size,
97 argb: if invisible || clip_only { 0 } else { apply_alpha_to_argb(gs.fill, gs.alpha_fill) },
98 text,
99 stroke_argb: None,
100 stroke_width: None,
101 // The DEVICE advance of the whole run, which is what the
102 // wire contract says this field is and what the selection
103 // layer rescales a non-painted run to. `size` was one
104 // glyph's worth for a run of any length, so a mode-3 OCR
105 // run with no font resource had every selection rectangle
106 // piled onto its first character.
107 advance: finite_or_zero((run_advance * x_scale) as f32).max(size * 0.1),
108 render_mode: gs.render_mode as u8,
109 blend: gs.blend_mode,
110 is_bold: false,
111 is_italic: false,
112 font_family: 0,
113 outline: false,
114 h_scale: wire_h_scale,
115 });
116 }
117 }
118 return run_advance;
119 }
120 };
121
122 // Type 3 fonts: draw each glyph by interpreting its CharProc content stream.
123 if let Some(t3) = &fi.t3 {
124 return show_string_type3(doc, prims, gs, fi, t3, text_matrix, bytes, depth, ambient_resources);
125 }
126
127 let mut pen = 0.0_f64;
128 // §8.4.3.2: the line width is a distance in USER space, so the pen is scaled by
129 // the CTM alone. The text matrix and font size scale the GLYPH, not the pen —
130 // §9.3.6 does not override this. Scaling by Trm made a `12 0 0 12 ...` Tm (the
131 // shape cairo emits) paint a 0.5pt pen as 6pt, closing every counter.
132 let ctm = &gs.ctm;
133 let sx_ctm = (ctm[0] * ctm[0] + ctm[1] * ctm[1]).sqrt();
134 let sy_ctm = (ctm[2] * ctm[2] + ctm[3] * ctm[3]).sqrt();
135 let device_stroke_w = (gs.line_width * (sx_ctm + sy_ctm) * 0.5) as f32;
136 // Constant per-font attributes hoisted out of the per-glyph closure.
137 let bold = fi.style.bold;
138 let italic = fi.style.italic;
139 let family = fi.family;
140 let has_program = fi.glyph_program.is_some();
141 // Vertical writing mode (WMode 1): glyphs advance down the page and are
142 // positioned by the /W2 //DW2 position vector (PDF 9.4.4).
143 let vertical = fi.wmode == 1;
144
145 fi.for_each_code(bytes, |code, is_space| {
146 let w0 = fi.width(code); // horizontal glyph width (em)
147 let tx = w0 * tfs + gs.char_spacing + if is_space { gs.word_spacing } else { 0.0 };
148 let glyph_advance_user = tx * th; // accurate advance using /Widths /W
149 // Placement point (text space) and pen advance depend on writing mode.
150 // Vertical (PDF 9.4.4, 9.7.4.3): the glyph is offset by the position
151 // vector v and the pen advances by w1_y, both from /W2 //DW2 rather than
152 // assumed. Tc/Tw keep widening the gap as they do horizontally, which
153 // deviates from the literal `ty = w1*Tfs + Tc + Tw` in 9.4.4 (where a
154 // positive Tc would tighten negative-w1 vertical text) but matches the
155 // behaviour every horizontal path here already has.
156 let (place_x, place_y, advance) = if vertical {
157 let cid = fi.to_cid(code);
158 let (w1y, vx) = fi
159 .vertical_metrics
160 .get(&cid)
161 .copied()
162 .unwrap_or((fi.default_vertical.1, 0.5 * w0));
163 let vy = fi.default_vertical.0;
164 let extra = gs.char_spacing + if is_space { gs.word_spacing } else { 0.0 };
165 // Trise is part of §9.4.4's text-space parameter matrix, which does not
166 // depend on the writing mode: it displaces the glyph in text-space y in
167 // vertical writing exactly as it does in horizontal. Dropping it here put
168 // super/subscripts in vertical CJK back on the baseline.
169 (-vx * tfs * th, pen - vy * tfs + gs.rise, w1y * tfs - extra)
170 } else {
171 (pen, gs.rise, glyph_advance_user)
172 };
173 // Render modes 0-7 (PDF 9.3.6, Table 106) all emit something: 0-2 ink,
174 // 4-6 ink plus clip, 7 clip only, and 3 an invisible record that keeps the
175 // text selectable and searchable. An out-of-range Tr emits nothing.
176 if (0..=7).contains(&gs.render_mode) {
177 let (x, y) = transform(&trm, place_x, place_y);
178 let mut s = String::new();
179 fi.push_code(code, &mut s);
180 // `s` is the selection/search payload only. A glyph whose Unicode
181 // cannot be recovered (surrogate-range CID, code > 0x10FFFF, or a
182 // /ToUnicode entry mapping to an empty string) must still be PAINTED
183 // from its embedded outline, so nothing below is gated on `s` except
184 // the Prim::Text records that carry the text itself.
185 {
186 let fill_alpha = gs.alpha_fill;
187 let stroke_alpha = gs.alpha_stroke;
188 let has_fill = matches!(gs.render_mode, 0|2|4|6);
189 let has_stroke = matches!(gs.render_mode, 1|2|5|6);
190 let clip_only = gs.render_mode == 7;
191 let invisible = gs.render_mode == 3;
192 let rm = gs.render_mode as u8;
193 let glyph_device_adv = if vertical {
194 (advance.abs() * y_scale) as f32
195 } else {
196 (glyph_advance_user * x_scale) as f32
197 };
198 // Same reasoning as `size`. The selection layer rescales a
199 // non-painted run by `advance * scale / measured`, and its
200 // `advance > 0f` guard PASSES infinity, so one overflowed glyph
201 // would stretch every remaining glyph's rectangle in the run.
202 let glyph_device_adv = finite_or_zero(glyph_device_adv);
203 // Real embedded outline for every mode that lays down ink: 0-2 and
204 // 4-6. Restricting this to 0-2 meant an embedded font in a clip mode
205 // was PAINTED with a substitute system face — wrong letterforms,
206 // weight and widths — while its own outline sat unused, so the same
207 // font rendered correctly at Tr 0 and wrongly at Tr 4.
208 //
209 // 3 and 7 stay out, and 7 deliberately so: `has_fill` is 0|2|4|6 and
210 // `has_stroke` is 1|2|5|6, so mode 7 is in neither and this branch
211 // would emit no Fill, no Stroke, and a Text record tagged
212 // `outline: true` that the consumer drops before its clip
213 // accumulator — no ink AND no clip, which under an unconditional
214 // §9.4.3 clip is total content loss after every ET. Mode 7 has no
215 // ink to improve, so it keeps the substitute path.
216 let outline = if has_program && matches!(gs.render_mode, 0..=2 | 4..=6) {
217 crate::outlines::glyph_outline(fi, code)
218 } else {
219 None
220 };
221 if let Some((contours, upm)) = outline {
222 // Glyph space (font units) -> device: (1/upm) · [Tfs·Th,0,0,Tfs] ·
223 // translate(pen, rise) · Tm · CTM. Mirrors the Type 3 pipeline.
224 let font_matrix: Mat = [1.0 / upm, 0.0, 0.0, 1.0 / upm, 0.0, 0.0];
225 let scale_m: Mat = [tfs * th, 0.0, 0.0, tfs, 0.0, 0.0];
226 let place = translate(place_x, place_y);
227 let m1 = mat_mul(&scale_m, &mat_mul(&place, &trm));
228 let glyph_ctm = mat_mul(&font_matrix, &m1);
229 let dev: Vec<Vec<(f32, f32)>> = contours
230 .iter()
231 .map(|c| {
232 c.iter()
233 .map(|&(gx, gy)| {
234 let (dx, dy) = transform(&glyph_ctm, gx, gy);
235 (dx as f32, dy as f32)
236 })
237 .collect()
238 })
239 .collect();
240 if prims.len() < MAX_PRIMITIVES {
241 if has_fill {
242 prims.push(Prim::Fill {
243 argb: apply_alpha_to_argb(gs.fill, fill_alpha),
244 even_odd: false,
245 contours: dev.clone(),
246 blend: gs.blend_mode,
247 });
248 }
249 if has_stroke {
250 let sargb = apply_alpha_to_argb(gs.stroke, stroke_alpha);
251 for c in &dev {
252 if c.len() >= 2 {
253 prims.push(Prim::Stroke {
254 argb: sargb,
255 width: device_stroke_w.max(0.1),
256 dash: Vec::new(),
257 dash_phase: 0.0,
258 cap: gs.line_cap,
259 join: gs.line_join,
260 miter: gs.miter_limit as f32,
261 pts: c.clone(),
262 blend: gs.blend_mode,
263 });
264 }
265 }
266 }
267 // Non-painting Text carrying the glyph for selection/search.
268 // Skipped when no Unicode was recoverable — the ink above is
269 // already on the page either way.
270 //
271 // The two flags must DISAGREE between the mode groups, and
272 // they are the same two fields, so this branches rather than
273 // mirroring modes 0-2:
274 // 0-2: `outline: true` — the consumer skips the record
275 // entirely, which is right, the Fill/Stroke above is
276 // the ink and there is no clip to build.
277 // 4-6: `outline: false` so the record REACHES the clip
278 // accumulator (the consumer's `if prim.outline
279 // continue` sits above it), and `argb: 0` so it still
280 // paints nothing on top of the real contours above.
281 // The accumulator keys on render mode and text only —
282 // it never reads colour — so transparency costs the
283 // clip nothing. Same shape as the Type 3 record.
284 if !s.is_empty() {
285 let clip_mode = matches!(gs.render_mode, 4..=6);
286 prims.push(Prim::Text {
287 x: x as f32,
288 y: y as f32,
289 size,
290 argb: if clip_mode {
291 0
292 } else {
293 apply_alpha_to_argb(gs.fill, fill_alpha)
294 },
295 text: s.clone(),
296 advance: glyph_device_adv.max(size * 0.1),
297 stroke_argb: None,
298 stroke_width: None,
299 render_mode: rm,
300 blend: gs.blend_mode,
301 is_bold: bold,
302 is_italic: italic,
303 font_family: family,
304 outline: !clip_mode,
305 h_scale: wire_h_scale,
306 });
307 }
308 }
309 } else if !s.is_empty() && prims.len() < MAX_PRIMITIVES {
310 // Substitute-font path (no embedded program or glyph missing).
311 // Requires a string: there is no outline to fall back on, so a
312 // glyph with no recoverable Unicode simply cannot be drawn here.
313 if has_fill {
314 prims.push(Prim::Text {
315 x: x as f32,
316 y: y as f32,
317 size,
318 argb: apply_alpha_to_argb(gs.fill, fill_alpha),
319 text: s.clone(),
320 advance: glyph_device_adv.max(size * 0.1),
321 stroke_argb: if has_stroke { Some(apply_alpha_to_argb(gs.stroke, stroke_alpha)) } else { None },
322 stroke_width: if has_stroke { Some(device_stroke_w) } else { None },
323 render_mode: rm,
324 blend: gs.blend_mode,
325 is_bold: bold,
326 is_italic: italic,
327 font_family: family,
328 outline: false,
329 h_scale: wire_h_scale,
330 });
331 } else if has_stroke {
332 prims.push(Prim::Text {
333 x: x as f32,
334 y: y as f32,
335 size,
336 argb: apply_alpha_to_argb(gs.stroke, stroke_alpha), // stroke-only: use stroke color as fill for visibility (Kotlin draws stroke)
337 text: s.clone(),
338 advance: glyph_device_adv.max(size * 0.1),
339 stroke_argb: Some(apply_alpha_to_argb(gs.stroke, stroke_alpha)),
340 stroke_width: Some(device_stroke_w),
341 render_mode: rm,
342 blend: gs.blend_mode,
343 is_bold: bold,
344 is_italic: italic,
345 font_family: family,
346 outline: false,
347 h_scale: wire_h_scale,
348 });
349 } else if clip_only || invisible {
350 // Mode 7: no paint, but carry the glyph so Kotlin can add
351 // its outline to the clip at the text-clip-apply marker.
352 // Mode 3: paints nothing at all, but the glyph must still
353 // reach the text index -- a scanned page's OCR layer is
354 // drawn in mode 3, and dropping it is why such documents
355 // had no selectable or searchable text. Kotlin skips
356 // painting both modes.
357 prims.push(Prim::Text {
358 x: x as f32,
359 y: y as f32,
360 size,
361 argb: 0,
362 text: s.clone(),
363 advance: glyph_device_adv.max(size * 0.1),
364 stroke_argb: None,
365 stroke_width: None,
366 render_mode: rm,
367 blend: gs.blend_mode,
368 is_bold: bold,
369 is_italic: italic,
370 font_family: family,
371 outline: false,
372 h_scale: wire_h_scale,
373 });
374 }
375 }
376 }
377 }
378 pen += advance;
379 });
380 // No `prims.truncate(MAX_PRIMITIVES)` here. MAX_PRIMITIVES bounds PAINT
381 // primitives, and every push above is already gated on it, so a truncate can
382 // only ever fire on primitives this call did not emit — cutting the tail off
383 // a caller's ClipPush/ClipPop or SoftMaskPush/Pop bracket and leaving the
384 // renderer's stack unbalanced for the rest of the page. Structural prims are
385 // bounded transitively instead: each needs its own operator, and the operator
386 // loop is capped at MAX_CONTENT_OPS with nesting capped at MAX_CLIP_DEPTH.
387 pen
388}
389
390/// Clip and transparency-group brackets left open in `slice`, outermost first.
391/// `true` = clip, `false` = group. Soft-mask prims are ignored: a soft mask is
392/// not closable by appending a pop (see the per-glyph cap in `show_string_type3`).
393fn open_brackets(slice: &[Prim]) -> Vec<bool> {
394 let mut open: Vec<bool> = Vec::new();
395 for p in slice {
396 match p {
397 Prim::ClipPush { .. } => open.push(true),
398 Prim::GroupPush { .. } => open.push(false),
399 Prim::ClipPop | Prim::GroupPop => {
400 open.pop();
401 }
402 _ => {}
403 }
404 }
405 open
406}
407
408/// Append the matching pops for `open`, innermost first.
409fn push_closers(prims: &mut Vec<Prim>, mut open: Vec<bool>) {
410 while let Some(is_clip) = open.pop() {
411 prims.push(if is_clip { Prim::ClipPop } else { Prim::GroupPop });
412 }
413}