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

Modern-Apps.git / pdf / src / main / rust / README.md

README.md36.6 KiBRenderedCodeRaw
1# pdf_render — memory-safe PDF renderer (Rust + JNI)
2
3Parses PDFs entirely in Rust with [`lopdf`] (no pdfium / no system PDF stack)
4and reduces each page to plain drawing primitives — text runs (with accurate
5advance), filled/stroked polygons, raster images (JPEG, JPEG2000 via openjp2,
6JBIG2 via hayro-jbig2, CCITTFax G3/G4 via the `fax` crate), clipping with bezier
7retention, axial/radial and mesh shadings, tiling/shading patterns (for both
8fills and strokes), Type 3 fonts, transparency groups, and ExtGState soft masks —
9for the "Open PDF (safe)" viewer. Built into `libpdf_render.so` and called from
10Kotlin via `PdfNative`.
11
12The point of "safe": all untrusted binary parsing happens in memory-safe Rust,
13and the JNI boundary only ever passes a flat little-endian buffer of geometry +
14UTF-8 text, so Kotlin never touches the raw PDF bytes.
15
16## Scope (implemented)
17
18- **PDF functions** (`functions.rs`): a full evaluator for all four function
19 types — Type 0 sampled (multilinear interpolation), Type 2 exponential, Type 3
20 stitching, and Type 4 PostScript calculator (a bounded stack machine over the
21 arithmetic/comparison/stack/control operator subset). Shared by colorspaces
22 and shadings.
23- **Text** with `/ToUnicode` decoding (1-byte simple fonts and 2-byte
24 Identity-H / Type0), full base encodings (WinAnsi, **real MacRoman**, Standard,
25 Symbol, ZapfDingbats), a comprehensive Adobe Glyph List, and embedded-program
26 encoding recovery: TrueType `cmap` (formats 0/2/4/6/8/10/12/13/14), **Type 1 `/FontFile`** clear-text
27 `/Encoding` scan, and **CFF `/FontFile3`** charset+Encoding recovery
28 (`cff.rs`). Text render modes 0–7 including the clip modes (4–7) and the
29 invisible mode 3, which emits a non-painting record so a scanned page's OCR
30 layer stays selectable and searchable. Accurate
31 glyph advance from `/Widths`/`/W`/`/DW` + `Tc`/`Tw`/`Th`.
32- **Encoding resolution follows the spec's priority order** (9.6.6.1): for a
33 symbolic font that declares neither `/Encoding` nor `/BaseEncoding`, the font
34 program's **built-in** encoding outranks any implicit base encoding, and
35 `/Differences` is layered on top of whichever base applies. StandardEncoding /
36 WinAnsi is backfilled only for codes the built-in encoding does not cover, so a
37 font whose symbolic flag is set spuriously still decodes. Previously the
38 implicit WinAnsi base populated every printable code and shadowed the built-in
39 encoding entirely, which made symbolic fonts render — and copy, and index —
40 Latin letters where the document wanted symbols. For symbolic TrueType the
41 `cmap` subtable precedence is also the spec's (9.6.6.4): **(3,0) Microsoft
42 Symbol before (1,0) Macintosh**, rather than whichever subtable the font
43 happened to store first. A symbolic font that carries only a (3,0)/(1,0)
44 subtable and **no Unicode subtable** no longer yields an empty map: `gid →
45 unicode` is recovered from the `post` table's glyph names through the Adobe
46 Glyph List, so such fonts are still selectable and searchable. Glyph names are
47 an authoritative Unicode source; Unicode is never invented from the raw
48 character code, which would corrupt the text index.
49- **Font parsing is cached per operation** (`FontCacheScope`): `FontInfo` — which
50 owns the whole decompressed embedded font program — used to be rebuilt on every
51 `interpret_content` call, so a font shared by *N* pages was parsed *N* times to
52 render and another *N* times to build the search index. The cache is keyed by
53 the font dictionary's object id *plus* a hash of that dictionary with every
54 indirect reference resolved, so a colliding id from another document cannot be
55 served, and is scoped to a single top-level operation, then dropped: even that
56 key is complete only while the document is unmutated, so a short-lived cache is
57 correct where a global one would serve stale fonts after a `docedit`. Direct
58 (non-indirect) font dictionaries have no id and are never cached.
59- **Embedded glyph outlines**: TrueType/OpenType, bare CFF (`/Type1C`,
60 `/CIDFontType0C`) and bare Type 1 programs are parsed and their real glyph
61 contours are emitted as vector fills/strokes (`outlines.rs`), so paint modes
62 0–2 draw the document's own typeface rather than a substitute. Type 2
63 charstrings (including the `flex`/`flex1`/`hflex`/`hflex1` operators of Adobe
64 TN#5177 §4.2) are interpreted by `ttf-parser`; the Type 1 interpreter in
65 `type1.rs` implements the equivalent `OtherSubrs` 0/1/2 flex protocol itself,
66 where the seven reference points must not restart the contour and the end point
67 must be returned for the trailing `pop pop setcurrentpoint`. `/CIDToGIDMap`
68 (`/Identity` or a stream) is applied when selecting CID glyphs, and a
69 present-but-zero entry — or a CID past the end of the stream — is honored as
70 `.notdef` (9.7.4.2) rather than falling through to identity and drawing an
71 unrelated glyph. Outline emission is never gated on a successful Unicode
72 mapping: a glyph with no `/ToUnicode` entry still paints. Fonts without a
73 usable program fall back to a substitute system typeface positioned by the
74 PDF's own metrics.
75- **Vertical writing** (`WMode 1`): the writing mode is taken from the `/Encoding`
76 CMap name, the Type0 dict and the descendant, and `/W2` //`DW2` drive the
77 vertical advance and position vector.
78- **Type 3 fonts**: glyph CharProc content streams are interpreted and drawn
79 (`draw.rs::show_string_type3`), mapped through the font matrix and bounded by
80 `MAX_TYPE3_GLYPHS` / `MAX_TYPE3_PRIMS_PER_GLYPH`. Hitting the per-glyph bound
81 cuts at the cap and appends whatever clip/group closers the cut orphaned
82 (innermost first), so an over-long glyph loses its tail rather than being dropped
83 and cannot leave the renderer's save/restore stack unbalanced for the rest of the
84 page. A soft-mask bracket is handled specially rather than truncated, because its
85 mask is the content that *follows* `SoftMaskContent` and appending a bare
86 `SoftMaskPop` would leave an empty mask: if the cap falls in the masked content the
87 surplus is dropped and the mask moved back on, so the glyph keeps both its content
88 and its real mask; if the cap falls inside the mask itself the bracket is completed
89 instead.
90- **Vector paths**: lines, rectangles, filled/stroked paths, flattened beziers
91 for drawing; clip paths retain the exact beziers via `PathOp`
92 (Move/Line/Cubic/Close) and are drawn in Kotlin with `cubicTo` (wire v4).
93- **Color**: `g/G/rg/RG/k/K` plus `CS/cs/SC/sc/SCN/scn`. Separation and DeviceN
94 evaluate their tint transforms through the full `PdfFunction` evaluator (any
95 function type, all N inputs), plus Lab, CalRGB/CalGray, ICCBased (alternate),
96 and Indexed. **Raster image samples** are converted through the same
97 colorspace machinery (with LUTs for single-component and indexed images), so
98 Separation/DeviceN/Lab/ICC images are colored correctly. Image transparency
99 covers `/SMask` (soft mask, with `/Matte` un-premultiplication), explicit
100 stencil `/Mask` images, and color-key masking compared against pre-conversion
101 samples (correct for CMYK/DeviceN, not just RGB). CMYK/YCCK JPEGs (including
102 Adobe APP14 inverted CMYK) are decoded in Rust; JPX honors its enumerated
103 color space (gray/RGB/YCC/CMYK + alpha).
104- **Shadings** (`images.rs` + `shading.rs`): Type 1 (function-based), Type 2
105 axial, Type 3 radial (all using `PdfFunction`), and real mesh shadings —
106 Type 4 free-form Gouraud (flag-driven triangle strips), Type 5 lattice
107 (`/VerticesPerRow`), and Type 6/7 Coons/tensor patches subdivided from their
108 actual boundary Bézier curves — Type 7 uses the full bicubic tensor surface
109 from its 4 interior control points. Radial (Type 3) shadings solve the true
110 circle-family parameter per pixel (honoring `/Extend` and non-negative radii),
111 rather than approximating them as axial. A byte-accurate `BitReader` handles
112 arbitrary `BitsPerCoordinate/Component/Flag`. Axial/radial/function shadings
113 are rasterized at a resolution derived from their device footprint (sharp when
114 zoomed) and, when they lack a `/BBox`, cover the current clip extent.
115- **Patterns** (`interpret.rs`): PatternType 2 (shading) patterns are rasterized
116 with the pattern `/Matrix` and clipped to the fill region; PatternType 1
117 (tiling) patterns replay their content stream tiled across the fill bbox
118 (colored and uncolored `/PaintType`), bounded by `MAX_PATTERN_RECURSION` and a
119 per-pattern tile cap. Both tiling and shading patterns are honored for
120 **strokes** too: the stroked path is converted to outline quads and the
121 pattern is painted within each segment (`paint_pattern_stroke`).
122- **Filters** (`filters.rs`): ASCIIHex, ASCII85, RunLength, LZW and Flate, both
123 now with PNG (Predictor 10–15) **and TIFF (Predictor 2, all of 1/2/4/8/16-bit)**
124 support; CCITT G3 (1-D) / G4 (2-D); JBIG2 and DCT/JPX passthrough. Decode
125 failures for JPX/CCITT/DCT no longer fall through to reinterpreting encoded
126 bytes as raw samples.
127- **Encryption** (`crypto.rs` + `decrypt.rs`): open and save with the Standard
128 security handler — RC4-128 and **AES-128 (V4/R4)** and **AES-256 (V5/R6)**.
129 `save_encrypted` defaults to AES-128.
130- **Wire format v10**: header `MAGIC 0x50444657 VERSION=10 f32 w,h u32 count`;
131 tags 1 Text, 2 Fill, 3 Stroke, 4 Image, 5 ClipPush (with a bezier-retentive
132 path-ops section), 6 ClipPop, 7 GroupPush, 8 GroupPop, 9 TextClipApply,
133 10 SoftMaskPush, 11 SoftMaskContent, 12 SoftMaskPop, 13 SoftMaskTransfer (a
134 256-byte `/TR` LUT, emitted only for a non-identity `/TR`), 14 ImageTiled (a
135 rasterized tiling-pattern cell plus its step and lattice extent, so a periodic
136 fill costs one bitmap rather than one image per tile). Tags 13 and 14 are
137 *tag*-gated rather than version-gated — a decoder that never sees one is
138 unaffected — so the declared version stays 10. Text carries its render
139 mode (v4); Text/Fill/Stroke each carry a per-primitive blend byte (v5); Text
140 also carries its device advance (v7) and bold/italic/family/outline flags plus
141 the horizontal scale (v8); images carry per-image alpha (v9) and blend (v10).
142 `SafePdfParser.kt` parses v10 and keeps the earlier versions as fallbacks. It is
143 also written to consume a **v11** that adds the per-image `/Interpolate` byte, but
144 that read is gated on v11 and Rust still declares v10, so the byte is neither
145 written nor read; the two sides are consistent, not desynchronized. Whoever bumps
146 Rust to v11 must start writing the byte in the same change (see the `/Interpolate`
147 limitation).
148- **Blend modes**: honored not just on transparency groups but on individual
149 fills, strokes and text — the graphics-state `/BM` travels with each Text/Fill/
150 Stroke primitive and is applied per-draw in Kotlin via `android.graphics.BlendMode`.
151 All separable and non-separable modes are supported natively with no per-device
152 caveat: the module's `minSdk` is 31 and that API is 29, so no fallback path is
153 needed.
154- **ExtGState soft masks** (`/SMask`): luminosity and alpha soft masks set via
155 `gs` apply to all subsequent drawing while active — fills, strokes, text,
156 images, shadings, and Form XObjects — not only forms. Rust brackets each
157 masked draw with SoftMaskPush/Content/Pop, rendering the `/G` group at the CTM
158 in effect when the mask was set; a `/BC` backdrop (luminosity masks) is painted
159 as a backdrop rectangle so uncovered areas take the backdrop luminance. Kotlin
160 composites with nested `saveLayer`s — a `DST_IN` mask layer, plus a
161 luminance→alpha `ColorMatrix` layer for luminosity masks. `/SMask /None`
162 clears the mask. An affine `/TR` is applied; see limitations for non-linear ones.
163- **Kotlin drawing**: bezier clips via `cubicTo`; text-clip modes accumulate
164 glyph outlines (`Paint.getTextPath`) and intersect them into the clip at the
165 `TextClipApply` marker; each blend mode maps directly to
166 `android.graphics.BlendMode`.
167- **Search**: a per-page text index stores both a lowercased (byte-aligned) and
168 original-case string, so case-sensitive and case-insensitive search are both
169 exact.
170- **Annotations / forms**: `subtype_code` covers the full ISO 32000 annotation
171 subtype set; text-field appearance regeneration honors `/Q` alignment,
172 multiline wrapping and comb (`/MaxLen`) fields, alongside checkboxes,
173 **radio-button groups** (setting one clears its siblings and updates the parent
174 `/V`) and **Choice fields** (records `/V` + the matched `/Opt` index in `/I`
175 with a regenerated appearance). Annotations that ship without an `/AP` stream
176 get a **synthesized appearance** for the common types — Square, Circle, Line,
177 Ink, Highlight, Underline and StrikeOut (via `/QuadPoints`, `/C`, `/IC`,
178 `/BS`).
179
180## Known cross-fix interaction risks (round-3 review)
181
182These came out of a review of the ~90 changes that landed across rounds 1 and 2,
183looking specifically for fixes that conflict, cancel or double-apply rather than
184for individually-wrong code. All were verified against the working tree. The
185first two are open because they live outside the reviewing agent's file set.
186
187- **Optional content does not gate form XObject content.** `oc_stack` is a local
188 in `interpret_content_seeded` and is not threaded into nested streams, so
189 `/OC1 BDC /Fm0 Do EMC` with `OC1` OFF paints the form's whole contents —
190 and, because the `/BBox` clip is suppressed by the same hidden flag, paints
191 them *unclipped*. Round 1 fixed the BMC/BDC/EMC balance and round 2 fixed the
192 text operators, but the `Do` recursion was never gated. An XObject's own `/OC`
193 key (§8.11.3.3) *is* honoured; it is only the BDC-bracket state that is lost.
194- **The §11.6.6 group alpha reset is disabled whenever a soft mask is active.**
195 Round 2 made the transparency-group push and the soft-mask bracket mutually
196 exclusive (`should_emit_group = is_transparency_group && !use_smask`), and the
197 reset of `alpha_fill`/`alpha_stroke` to 1.0 is gated on the push having
198 happened. A group form drawn with both `/ca < 1` and an `/SMask` therefore
199 applies `ca` to every element inside the group instead of once to the
200 composited result. Same hole when `MAX_PRIMITIVES` or the group-depth cap
201 demotes the push. Identical output for non-overlapping content; over-darkens
202 overlapping content.
203- **Annotation `/CA` used to be applied twice** — fixed. `render_annotation`
204 scaled the alpha of every prim it had just emitted, which hit both a nested
205 `GroupPush`'s alpha *and* every prim inside that group (CA² on the contents),
206 and also hit the soft-mask group's own prims, which `wrap_with_soft_mask`
207 appends after `SoftMaskContent` in the same range — so `/CA` altered the mask
208 rather than the content. It now wraps the appearance in one
209 `GroupPush{alpha: ca}`/`GroupPop`, which is the §12.5.2 + §11.6.6 model and
210 applies the opacity once, at composite time.
211
212Verified clean, with the evidence, so a future change knows what it is allowed to
213disturb:
214
215- **Mask polarity is inverted exactly once on every convention.** `/Decode` is
216 read in exactly five places in `images.rs`, and `decode_mask_stream_gray`
217 deliberately does not read it at all — polarity comes only from its
218 `MaskPolarity` argument, and the caller applies `/Decode` once afterwards. The
219 CCITT stencil path folds `/Decode` into its `black_bit` and then calls
220 `stencilize` with `invert: false` precisely so it is not re-applied. The CCITT
221 and JBIG2 stencil paths are now covered by tests as well as by reading —
222 including `/BlackIs1`, the second inversion source, and the `/BlackIs1` +
223 `/Decode [1 0]` pair that cancel. `stencilize` zeroes alpha and leaves the RGB
224 of a transparent pixel as the raster left it, so those tests state polarity in
225 terms of alpha; the colour beneath an unpainted pixel is not part of the
226 contract. The DCT and JPX mask branches remain untested.
227- **Neither round-2 cache leaks.** The font cache is a `thread_local` installed
228 by an RAII `FontCacheScope` (one per page render, one per search-index build)
229 and keyed by the font's `ObjectId` plus a hash of its dictionary with every
230 indirect reference *resolved* — not by resource name, so two
231 pages both binding `/F1` to different font objects stay distinct, and not by
232 the `Document`'s address, which is not an identity: `Document`s are held by
233 value in the registry's `IndexMap`, so one can be replaced at the address
234 another just vacated and a scope spanning both would serve the first
235 document's fonts for the second. Resolving through the references also catches
236 two font dicts that are byte-identical but whose `/Widths 7 0 R` names
237 different arrays. It has no
238 invalidation hook and needs none: it does not exist between operations, so a
239 `docedit` mutation cannot be served a stale entry. Residual fragility: the key
240 is complete only while the document is unmutated *within* a scope, which is
241 what scoping it to one top-level operation buys. The soft-mask
242 coalescing memo is a local in `interpret_content_seeded`, and its key includes
243 the group id, mask type, the CTM as exact `f64::to_bits()`, `/BC` and the whole
244 256-byte `/TR` LUT, so a mask cannot be reused at a different CTM.
245- **Clip and group brackets balance on every path**, including the truncation
246 and cap paths: every structural pop is emitted *without* a `MAX_PRIMITIVES`
247 guard while every content push has one, so the cap can never suppress a
248 closer, and the end-of-stream drain closes whatever is left.
249
250### Deliberate omission: GB18030's four-byte plane
251
252Now implemented. `EncodingCMap::code_len` dispatches on the first byte alone,
253which cannot see GB18030's four-byte plane (distinguished from its two-byte plane
254only by the second byte being `0x30`-`0x39`). Round 2 left this alone on the
255grounds that widening the lookahead for every font to fix a rare case was not
256obviously right. `code_len_at` resolves it as a *strict refinement* instead: it
257only ever chooses a longer range, and only when that range also matches the
258second byte. No other predefined codespace has two ranges of different length
259sharing a first byte, so for every font but GB18030 the answer is provably
260identical to `code_len` — which removes the tradeoff that made the deferral
261reasonable. `gb18030_four_byte_plane_needs_the_second_byte` asserts both halves,
262exhaustively over all 256 first bytes for the other families.
263
264
265## Genuinely unsupported (documented, not silently skipped)
266
267Per-feature spec coverage, and the rationale for each deliberately-ignored
268feature: [SPEC_COVERAGE.md](SPEC_COVERAGE.md).
269
270### An OCG listed in both `/ON` and `/OFF` renders as OFF
271
272§8.11.4.3 gives `/ON` and `/OFF` as overrides of `/BaseState` and does not spell
273out the result when the same group appears in both. `OcConfig::is_ocg_visible`
274applies them in the order Table 101 lists them — `/BaseState` (default ON), then
275`/ON`, then `/OFF` — so `/OFF` is applied last and wins, which is what mainstream
276viewers do and therefore how a file authored against them was meant to look.
277
278`/BlackPoint` on CIE-based spaces (§8.6.5.2, §8.6.5.4) is a genuine deviation of
279this kind: the conversion adapts from `/WhitePoint` only, so the effect is a
280slight shift in the darkest tones rather than missing content.
281
282> ### WARNING: Redaction does not remove content — it covers it
283>
284> **Do not rely on `/Redact` to scrub sensitive data.** Applying a redaction
285> paints an opaque box and deletes a text-showing operator only when its *start
286> point* falls inside the redaction rect. Everything else survives in the saved
287> file and stays extractable by any other tool: images, vector art, and any text
288> that begins outside the box and runs into it. The pre-redaction content stream
289> is left in the document.
290>
291> This is a **security** limitation, not a fidelity one — the page looks redacted
292> while the data is still there. The removal is a heuristic over text-showing
293> operators, not a content-stream rewrite. There is currently no user-facing
294> warning on the apply action.
295
296
297- **Public-key / certificate encryption** (`/Filter /Adobe.PubSec`): decryption
298 requires the recipient's private key, which the viewer does not possess.
299 Reported as `DecryptStatus::Unsupported`.
300- **Predefined *named* non-Identity CMaps** (`90ms-RKSJ-H`, `GBK-EUC-H`,
301 `ETen-B5-H`, `KSCms-UHC-H`, ...): the code→CID table of a predefined CMap is an
302 external Adobe resource that cannot be embedded, so CID lookups fall back to
303 identity and *glyph selection* for these encodings is wrong.
304 What *is* handled: the **codespace ranges** of every mixed-width family are
305 installed, so 1-byte and 2-byte codes are segmented correctly and the byte
306 stream no longer desynchronizes (9.7.6.2). This is the difference between "some
307 wrong glyphs" and "every character after the first 1-byte code is garbage",
308 because a mis-sized code shifts the whole remainder of the string. It also makes
309 `/ToUnicode` (which is keyed by *code*, not CID) resolve, so text extraction,
310 search and substitute-font painting work even where the embedded glyphs do not.
311 Covered families: Shift-JIS (`*-RKSJ-*`), Japanese EUC (`EUC-H/V`), GBK
312 (`GBK*`), EUC-CN (`GB*-EUC-*`), Big5 (`*-B5-*`, `B5pc-*`), Korean UHC/EUC-KR
313 (`*UHC*`, `KSC*`), and the variable-length `Uni*-UTF8-*` (1–4 byte) and
314 `Uni*-UTF16-*` (2/4-byte surrogate) families. `Identity-H/V`, the pure-2-byte
315 `Uni*-UCS2-*` families and the `<2121>`–`<7E7E>` ISO-2022 families (`H`, `V`,
316 `Add-H`, `Ext-H`) need no codespace and are fully segmented already.
317 `usecmap` is honored, inheriting the referenced predefined CMap's codespace.
318 **Embedded** CMap *streams* are parsed for real code→CID ranges, variable-length
319 codespaces and `/WMode`, and are fully supported.
320 Two known gaps: shipping the ~40 compiled predefined code→CID tables is the
321 remaining work (they are registry-specific integer tables that must be copied
322 from the Adobe resources — inventing values would silently select confidently
323 wrong glyphs, which is worse than the identity fallback); and `GBK2K-H`
324 (GB18030) has a 4-byte plane distinguished only by the *second* byte, which the
325 first-byte-only code-length dispatch cannot see, so those rare codes still
326 mis-segment.
327- **Vertical writing position vector `v_y` per CID**: `/W2` and `/DW2` are parsed
328 and applied — the vertical advance `w1_y`, the horizontal offset `v_x` and the
329 `[880 -1000]` `/DW2` default all drive layout — but a *CID-specific* `v_y` is
330 discarded and the `/DW2` value is used for every glyph. Also note the vertical
331 advance keeps applying `Tc`/`Tw` in the direction that widens the gap, which
332 deviates from the literal formula in 9.4.4 (where a positive `Tc` would tighten
333 negative-`w1` vertical text) in favour of matching the horizontal behaviour.
334- **CFF2 and other font programs `ttf-parser` cannot open**: an unparseable
335 `/FontFile[23]` yields no outline program, and the glyph falls back to being
336 painted with a substitute system typeface using the PDF's own widths. Text is
337 still positioned, selectable and searchable; only the glyph shapes are
338 approximate.
339- **Composite fonts with no `/ToUnicode`**: for a Type0 font that embeds no
340 outline program and supplies no `/ToUnicode`, the character codes are CIDs with
341 no recoverable Unicode meaning, so the extracted text is not trustworthy. The
342 proper fix is the predefined `Adobe-Japan1-UCS2`-style CID→Unicode tables,
343 which is the same compiled-table work as the entry above.
344- **Search matches the exact Unicode the PDF supplies, with no normalization**:
345 case folding is applied (and only where it preserves byte length, so the
346 lowercased and original-case page strings stay aligned for one span table), but
347 **ligatures are not expanded and diacritics are not folded**. Searching `find`
348 will not match text typeset with the `fi` ligature (U+FB01), and `café` will not
349 match `cafe`. The ligature case is the one users hit, because professionally
350 typeset PDFs use `fi`/`fl` routinely and whether the ligature survives into the
351 text depends entirely on what the font's `/ToUnicode` maps it to.
352- **Embedded font programs are never rasterized by the renderer**: glyphs either
353 arrive as real outline fills from the core, or are drawn with a substitute
354 system typeface chosen by generic family (sans/serif/mono) with synthesized
355 bold/italic. Positioning stays correct because the core supplies a per-glyph
356 origin and advance, but letterforms differ where no embedded outline is
357 available.
358- **Text clipping (`Tr` 4–7) clips with the substitute typeface's outline**, not
359 the embedded glyph outline, so a text-clipped region has the right position and
360 size but the wrong letterform edges.
361- **Transparency group `/K` (knockout) is ignored**: a knockout group renders as
362 if non-knockout, so overlapping elements inside one incorrectly show through
363 each other instead of each replacing the last (11.4.6 / 11.6.6).
364 `Canvas.saveLayer` composites each element against the running result rather
365 than against the group's initial backdrop, which is what knockout requires.
366- **Transparency group `/I false` (non-isolated) is ignored**: a non-isolated
367 group renders as isolated, so a group carrying a non-Normal blend mode fails to
368 blend with the page backdrop and looks flat or too opaque (11.4.5).
369 `saveLayer` always yields an isolated layer and there is no way to seed it with
370 the existing backdrop.
371 Both flags *are* parsed and carried over the wire (`u8 isolated, u8 knockout`);
372 neither variant is expressible with Canvas layers.
373- **Soft-mask `/TR` transfer functions are applied only when affine** (11.6.5.2):
374 the mask value is passed through `/TR`, carried to the renderer as a 256-entry
375 LUT (wire tag 13) and least-squares fitted to `gain * m + bias` in Kotlin.
376 Inverting and gain/bias curves fit exactly and are applied exactly — which
377 covers the case that matters, since an inverting `/TR` is the standard idiom for
378 "mask out where the group is bright" and ignoring it hid exactly the wrong half.
379 A *nearly* linear curve is accepted and applied as its best-fit line, the
380 tolerance being a maximum absolute error of `3/255`. Only a genuinely
381 non-linear `/TR` (gamma, threshold, sampled Type 0) is refused: it is detected,
382 logged once at parse time, and left **untransformed** rather than approximated,
383 because a wrong curve hides the wrong half of the group — the exact fault this
384 exists to prevent. What a user sees in that case is a mask with the wrong
385 falloff — a vignette that fades over the wrong distance, or a mask with visibly
386 wrong contrast — rather than a subtly approximated one, since the mask is applied
387 as though `/TR` were identity. An identity `/TR` never reaches the wire; it is
388 dropped in Rust, which is cheaper and indistinguishable from applying it.
389 The remaining gap is a platform one: a soft mask is composited in a
390 `Canvas.saveLayer`, whose only per-pixel hook is the affine
391 `ColorMatrixColorFilter`; Android has no alpha-LUT filter, a `saveLayer` exposes
392 no readable pixel buffer, and `RuntimeShader` cannot act as that filter.
393- **Overprint** (`/OP`, `/op`, `/OPM`): parsed into the graphics state but
394 deliberately not applied. Overprint controls which *device colorants* are left
395 unmarked (8.6.7) and has no meaning on an additive RGB compositor with no
396 separations. It was previously approximated as a Multiply blend, which was
397 actively harmful: `white MULTIPLY dst == dst` turned white knockout rectangles
398 into no-ops and let content that should have been covered show through.
399- **Incremental save / detached-signature verification**: `save_to` always
400 rewrites the whole document (no `/Prev` xref append), so cryptographic
401 signature *verification* and byte-range-preserving incremental updates are not
402 implemented. Signing scaffolding (`prepare_signature`) and detached CMS
403 creation exist, but existing signatures are not validated on open.
404- **`/Interpolate` is decided but never transmitted** (8.9.5.1): an image that asks
405 for smoothing and one that asks for none are filtered identically, so a magnified
406 QR code, barcode, scanned fax or 1-bit stencil turns into grey mush.
407 `image_should_interpolate` computes the right answer in Rust, but `Prim::Image`
408 has no field for it, the Image arm writes no interpolate byte, and the renderer
409 filters unconditionally. The same root cause has a second surface: a rasterized
410 tiling-pattern cell (`ImageTiled`) is drawn with bitmap filtering hard-coded on,
411 so a bilevel hatch pattern blurs when zoomed.
412 The two sides are consistent about it rather than desynchronized: the wire spec
413 defines the byte at v11 and the Kotlin decoder is written to consume it, but that
414 read is gated on v11 and Rust still declares v10 — so the byte is never written
415 and never read, and the gate fails safe. This is the same half-wired shape `/TR`
416 had before it was completed, which is why it can look finished from either side
417 alone. Whoever bumps Rust to v11 **must** write the byte in the same change;
418 `wire.rs` says so at the constant.
419- **A very dense page is truncated at 300,000 drawing primitives**: past that the
420 rest of the page is not emitted, so a large-format vector drawing — a map, CAD
421 sheet or dense chart — renders only partially. This is a memory floor rather
422 than a tunable: a `Prim` costs ~120–180 bytes in practice, so 300,000 is roughly
423 40–55 MB held simultaneously with the ~15 MB serialized wire copy, and a Rust
424 OOM is an uncatchable process abort. The cap is enforced at every
425 content-emitting push. The truncation is **silent**: nothing on the wire flags
426 it and the viewer surfaces no message, so the page simply renders its top
427 portion and looks as though it finished normally. The separate operator ceiling
428 (`MAX_CONTENT_OPS`, a *time* guard) sits deliberately above it at 1,000,000 so
429 it only catches pathological streams — it was formerly 200,000, which made it
430 the binding constraint and cut an ordinary dense vector page off at ~100,000
431 primitives, a third of what was already sanctioned.
432- **No per-page cap on shading memory**: a page with very many gradients can use a
433 lot of memory. Each shading raster is capped individually — 256 KB for
434 axial/radial gradients, 1 MB for function-based and mesh shadings — but nothing
435 bounds their total, so a page with hundreds of gradients holds every one at once.
436- **Some tiling patterns are drawn at reduced density over a large area**
437 (8.7.3.3): most tiled fills now repeat across the whole region at full density —
438 a cell made only of fills and strokes is rasterized **once** and emitted as a
439 periodic bitmap, so the tile count stops mattering. That includes *overlapping*
440 patterns, where `/XStep` or `/YStep` is smaller than the `/BBox` (8.7.3.1): such a
441 pattern is still periodic with period `(XStep, YStep)`, and the cell is drawn at
442 every lattice offset that reaches one period window, so the spill from
443 neighbouring cells is composited in rather than lost.
444 Two cases still fall back to replaying the cell per tile, where past 20,000 tiles
445 the lattice is thinned uniformly (stride = `ceil(sqrt(need / 20000))`) to stay
446 inside the primitive budget — the region remains **fully covered**, just coarser
447 than the document asks for: a cell containing **text**, an **image** or its own
448 **clipping/group** (the cell rasterizer has no glyph rasterizer and ignores
449 images, clips and groups, so rasterizing it would silently drop that content);
450 and a pattern overlapping so heavily that one period needs more than 64 cell
451 copies to resolve, which is bounded because the cost is per-period, not per-tile.
452- **Overlapping shapes under one soft mask blend slightly wrong**: where many
453 shapes overlap beneath a single partially-transparent `/SMask`, the composite in
454 the overlap region is a little off, because consecutive paints under the same
455 mask are coalesced into ONE masked layer and therefore composited as a group
456 rather than individually. The coalescing is deliberate and not a shortcut: one
457 bracket per painting operator re-expanded the mask for every operator and pushed
458 pages past the primitive cap, truncating real content — a visibly worse outcome
459 than a slight blend error.
460- **The search index is invalidated by an RAII guard, not by the mutators
461 themselves**: `ensure_index` is a pure memo keyed by handle and never re-reads
462 the document, so the "a search answers from the current document" contract rests
463 entirely on every mutating entry point dropping the entry. `invalidate_index`
464 used to have no callers at all, which meant redacting, annotating, filling a
465 form field or moving a page left search answering from the pre-edit text —
466 including, in the privacy-relevant case, surfacing and highlighting text that
467 had just been redacted. Each mutating `extern` fn in `jni_bindings.rs` now holds
468 an `InvalidateSearchIndex` guard for the whole call, so the eviction happens on
469 the unwind path too and a panic that leaves a document half-edited cannot leave
470 a matching index behind. The residual fragility is that it is per-entry-point
471 rather than structural: a *new* mutating binding that forgets the guard
472 reintroduces the staleness, because there is still no single accessor that
473 observes "this document changed".
474- **Form fields with no appearance stream are invisible**: a field that relies on
475 the viewer to build its own appearance (`/NeedAppearances` set, no `/AP`)
476 renders as nothing at all rather than as a box showing its value, because
477 appearance generation runs only when the user edits a field, not on load.
478- **Non-ASCII text typed into a form field or text annotation is mangled in the
479 saved file**: it displays correctly inside this app, but the generated
480 appearance stream writes UTF-8 bytes into a Latin-1 encoded font, so every other
481 viewer shows `é` where `é` was typed. The text is not lost, but the file is
482 wrong everywhere except here.
483- **Overlapping strokes in a translucent annotation darken where they cross**: a
484 semi-transparent Ink or Highlight annotation whose own strokes overlap is
485 composited per-stroke rather than as a single group, so intersections come out
486 darker than the author intended (11.6.2 wants group semantics).
487- **Multi-select list boxes collapse to a single selection**: choosing several
488 options stores only one, because the value setter takes a single string.
489- **Rich-text field formatting is dropped**: a field with `/RV` shows its plain
490 text — correct content, but no bold, italic or colour runs.
491- **Standard stamp annotations show their wording in a plain outlined box** instead
492 of real artwork: an Approved stamp renders as the word APPROVED in a rectangle,
493 because Acrobat's stamp graphics are not shipped.
494- **Pushbuttons are presented as toggleable checkboxes** even though a pushbutton
495 has no value.
496- **Physical page sizing (`/UserUnit`) is not surfaced**; page layout and
497 rendering are unaffected by it.
498- **True redaction**: see the highlighted warning at the top of this section —
499 `/Redact` covers content rather than removing it.
500- **Large JBIG2 images render as nothing at all**: a JBIG2 image wider or taller
501 than 20,000px, or over 16 megapixels, comes out fully transparent — a deliberate
502 memory guard in `jbig2.rs` with no partial-decode path.
503- **JBIG2 decode failures are silent**: an image that fails to decode renders as an
504 invisible gap rather than a placeholder, so a failure is indistinguishable from a
505 legitimately blank region. Deliberate (the red placeholder was removed), but it
506 means nothing signals the loss.
507- **CCITTFax `/EncodedByteAlign` and mixed 1-D/2-D G3 (`K > 0`)**: a G3/G4 fax
508 image with `/EncodedByteAlign true` renders as diagonal streaks or noise, since
509 each row must restart on a byte boundary. This is genuinely blocked by the `fax`
510 crate's API rather than merely unimplemented: `ByteReader`'s `partial`/`valid`
511 fields and `fill()` are private, its only public surface is `new` plus two debug
512 printers, and `Group3Decoder`/`Group4Decoder` own their reader internally, so
513 there is no way to realign the bit reader. `K > 0` is likewise a best-effort
514 attempt (try G3, then fall back to G4) rather than real per-row mode switching,
515 so a genuinely mixed page can decode partially or not at all. Pure G3/G4 — the
516 common cases — decode correctly.
517
518## Prerequisites (local + CI)
519
520`rustup target add aarch64-linux-android`. `./gradlew :pdf:assembleDebug`
521triggers `cargoNdkBuild` with NDK 29.
522
523## Host tests
524
525```sh
526cd pdf/src/main/rust
527cargo test
528```
529
530Covers PDF function evaluation (all four types), radial-shading parameterization,
531mesh-shading rasterization, stroke-outline quad generation, Type 3 glyph
532emission, image colorspace conversion, LZW/TIFF predictors, RC4/AES-128/AES-256
533save round-trips, CFF/Type 1 encoding recovery, Type 1 charstring `flex`
534(one contour, correct current point), mixed-width predefined-CMap codespace
535segmentation, the per-operation font cache (shared inside a scope, uncached
536without one), `Tw` applying only to single-byte code 32, the untrusted-font-data
537loop clamps, case-sensitive search, and the wire round-trip (including
538per-primitive blend and soft-mask markers).
539
540[`lopdf`]: https://crates.io/crates/lopdf