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

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

README.md35.7 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 v11**: header `MAGIC 0x50444657 VERSION=11 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. 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), blend (v10) and
142 the `/Interpolate` decision (v11).
143 `SafePdfParser.kt` parses v11 and keeps the earlier versions as fallbacks.
144- **Blend modes**: honored not just on transparency groups but on individual
145 fills, strokes and text — the graphics-state `/BM` travels with each Text/Fill/
146 Stroke primitive and is applied per-draw in Kotlin via `android.graphics.BlendMode`.
147 All separable and non-separable modes are supported natively with no per-device
148 caveat: the module's `minSdk` is 31 and that API is 29, so no fallback path is
149 needed.
150- **ExtGState soft masks** (`/SMask`): luminosity and alpha soft masks set via
151 `gs` apply to all subsequent drawing while active — fills, strokes, text,
152 images, shadings, and Form XObjects — not only forms. Rust brackets each
153 masked draw with SoftMaskPush/Content/Pop, rendering the `/G` group at the CTM
154 in effect when the mask was set; a `/BC` backdrop (luminosity masks) is painted
155 as a backdrop rectangle so uncovered areas take the backdrop luminance. Kotlin
156 composites with nested `saveLayer`s — a `DST_IN` mask layer, plus a
157 luminance→alpha `ColorMatrix` layer for luminosity masks. `/SMask /None`
158 clears the mask. An affine `/TR` is applied; see limitations for non-linear ones.
159- **Kotlin drawing**: bezier clips via `cubicTo`; text-clip modes accumulate
160 glyph outlines (`Paint.getTextPath`) and intersect them into the clip at the
161 `TextClipApply` marker; each blend mode maps directly to
162 `android.graphics.BlendMode`.
163- **Search**: a per-page text index stores both a lowercased (byte-aligned) and
164 original-case string, so case-sensitive and case-insensitive search are both
165 exact.
166- **Annotations / forms**: `subtype_code` covers the full ISO 32000 annotation
167 subtype set; text-field appearance regeneration honors `/Q` alignment,
168 multiline wrapping and comb (`/MaxLen`) fields, alongside checkboxes,
169 **radio-button groups** (setting one clears its siblings and updates the parent
170 `/V`) and **Choice fields** (records `/V` + the matched `/Opt` index in `/I`
171 with a regenerated appearance). Annotations that ship without an `/AP` stream
172 get a **synthesized appearance** for the common types — Square, Circle, Line,
173 Ink, Highlight, Underline and StrikeOut (via `/QuadPoints`, `/C`, `/IC`,
174 `/BS`).
175
176## Known cross-fix interaction risks (round-3 review)
177
178These came out of a review of the ~90 changes that landed across rounds 1 and 2,
179looking specifically for fixes that conflict, cancel or double-apply rather than
180for individually-wrong code. All were verified against the working tree. The
181first two are open because they live outside the reviewing agent's file set.
182
183- **Optional content does not gate form XObject content.** `oc_stack` is a local
184 in `interpret_content_seeded` and is not threaded into nested streams, so
185 `/OC1 BDC /Fm0 Do EMC` with `OC1` OFF paints the form's whole contents —
186 and, because the `/BBox` clip is suppressed by the same hidden flag, paints
187 them *unclipped*. Round 1 fixed the BMC/BDC/EMC balance and round 2 fixed the
188 text operators, but the `Do` recursion was never gated. An XObject's own `/OC`
189 key (§8.11.3.3) *is* honoured; it is only the BDC-bracket state that is lost.
190- **The §11.6.6 group alpha reset is disabled whenever a soft mask is active.**
191 Round 2 made the transparency-group push and the soft-mask bracket mutually
192 exclusive (`should_emit_group = is_transparency_group && !use_smask`), and the
193 reset of `alpha_fill`/`alpha_stroke` to 1.0 is gated on the push having
194 happened. A group form drawn with both `/ca < 1` and an `/SMask` therefore
195 applies `ca` to every element inside the group instead of once to the
196 composited result. Same hole when `MAX_PRIMITIVES` or the group-depth cap
197 demotes the push. Identical output for non-overlapping content; over-darkens
198 overlapping content.
199- **Annotation `/CA` used to be applied twice** — fixed. `render_annotation`
200 scaled the alpha of every prim it had just emitted, which hit both a nested
201 `GroupPush`'s alpha *and* every prim inside that group (CA² on the contents),
202 and also hit the soft-mask group's own prims, which `wrap_with_soft_mask`
203 appends after `SoftMaskContent` in the same range — so `/CA` altered the mask
204 rather than the content. It now wraps the appearance in one
205 `GroupPush{alpha: ca}`/`GroupPop`, which is the §12.5.2 + §11.6.6 model and
206 applies the opacity once, at composite time.
207
208Verified clean, with the evidence, so a future change knows what it is allowed to
209disturb:
210
211- **Mask polarity is inverted exactly once on every convention.** `/Decode` is
212 read in exactly five places in `images.rs`, and `decode_mask_stream_gray`
213 deliberately does not read it at all — polarity comes only from its
214 `MaskPolarity` argument, and the caller applies `/Decode` once afterwards. The
215 CCITT stencil path folds `/Decode` into its `black_bit` and then calls
216 `stencilize` with `invert: false` precisely so it is not re-applied. The CCITT
217 and JBIG2 stencil paths are now covered by tests as well as by reading —
218 including `/BlackIs1`, the second inversion source, and the `/BlackIs1` +
219 `/Decode [1 0]` pair that cancel. `stencilize` zeroes alpha and leaves the RGB
220 of a transparent pixel as the raster left it, so those tests state polarity in
221 terms of alpha; the colour beneath an unpainted pixel is not part of the
222 contract. The DCT and JPX mask branches remain untested.
223- **Neither round-2 cache leaks.** The font cache is a `thread_local` installed
224 by an RAII `FontCacheScope` (one per page render, one per search-index build)
225 and keyed by the font's `ObjectId` plus a hash of its dictionary with every
226 indirect reference *resolved* — not by resource name, so two
227 pages both binding `/F1` to different font objects stay distinct, and not by
228 the `Document`'s address, which is not an identity: `Document`s are held by
229 value in the registry's `IndexMap`, so one can be replaced at the address
230 another just vacated and a scope spanning both would serve the first
231 document's fonts for the second. Resolving through the references also catches
232 two font dicts that are byte-identical but whose `/Widths 7 0 R` names
233 different arrays. It has no
234 invalidation hook and needs none: it does not exist between operations, so a
235 `docedit` mutation cannot be served a stale entry. Residual fragility: the key
236 is complete only while the document is unmutated *within* a scope, which is
237 what scoping it to one top-level operation buys. The soft-mask
238 coalescing memo is a local in `interpret_content_seeded`, and its key includes
239 the group id, mask type, the CTM as exact `f64::to_bits()`, `/BC` and the whole
240 256-byte `/TR` LUT, so a mask cannot be reused at a different CTM.
241- **Clip and group brackets balance on every path**, including the truncation
242 and cap paths: every structural pop is emitted *without* a `MAX_PRIMITIVES`
243 guard while every content push has one, so the cap can never suppress a
244 closer, and the end-of-stream drain closes whatever is left.
245
246### Deliberate omission: GB18030's four-byte plane
247
248Now implemented. `EncodingCMap::code_len` dispatches on the first byte alone,
249which cannot see GB18030's four-byte plane (distinguished from its two-byte plane
250only by the second byte being `0x30`-`0x39`). Round 2 left this alone on the
251grounds that widening the lookahead for every font to fix a rare case was not
252obviously right. `code_len_at` resolves it as a *strict refinement* instead: it
253only ever chooses a longer range, and only when that range also matches the
254second byte. No other predefined codespace has two ranges of different length
255sharing a first byte, so for every font but GB18030 the answer is provably
256identical to `code_len` — which removes the tradeoff that made the deferral
257reasonable. `gb18030_four_byte_plane_needs_the_second_byte` asserts both halves,
258exhaustively over all 256 first bytes for the other families.
259
260
261## Genuinely unsupported (documented, not silently skipped)
262
263Per-feature spec coverage, and the rationale for each deliberately-ignored
264feature: [SPEC_COVERAGE.md](SPEC_COVERAGE.md).
265
266### An OCG listed in both `/ON` and `/OFF` renders as OFF
267
268§8.11.4.3 gives `/ON` and `/OFF` as overrides of `/BaseState` and does not spell
269out the result when the same group appears in both. `OcConfig::is_ocg_visible`
270applies them in the order Table 101 lists them — `/BaseState` (default ON), then
271`/ON`, then `/OFF` — so `/OFF` is applied last and wins, which is what mainstream
272viewers do and therefore how a file authored against them was meant to look.
273
274`/BlackPoint` on CIE-based spaces (§8.6.5.2, §8.6.5.4) is a genuine deviation of
275this kind: the conversion adapts from `/WhitePoint` only, so the effect is a
276slight shift in the darkest tones rather than missing content.
277
278> ### WARNING: Redaction does not remove content — it covers it
279>
280> **Do not rely on `/Redact` to scrub sensitive data.** Applying a redaction
281> paints an opaque box and deletes a text-showing operator only when its *start
282> point* falls inside the redaction rect. Everything else survives in the saved
283> file and stays extractable by any other tool: images, vector art, and any text
284> that begins outside the box and runs into it. The pre-redaction content stream
285> is left in the document.
286>
287> This is a **security** limitation, not a fidelity one — the page looks redacted
288> while the data is still there. The removal is a heuristic over text-showing
289> operators, not a content-stream rewrite. There is currently no user-facing
290> warning on the apply action.
291
292
293- **Public-key / certificate encryption** (`/Filter /Adobe.PubSec`): decryption
294 requires the recipient's private key, which the viewer does not possess.
295 Reported as `DecryptStatus::Unsupported`.
296- **Predefined *named* non-Identity CMaps** (`90ms-RKSJ-H`, `GBK-EUC-H`,
297 `ETen-B5-H`, `KSCms-UHC-H`, ...): the code→CID table of a predefined CMap is an
298 external Adobe resource that cannot be embedded, so CID lookups fall back to
299 identity and *glyph selection* for these encodings is wrong.
300 What *is* handled: the **codespace ranges** of every mixed-width family are
301 installed, so 1-byte and 2-byte codes are segmented correctly and the byte
302 stream no longer desynchronizes (9.7.6.2). This is the difference between "some
303 wrong glyphs" and "every character after the first 1-byte code is garbage",
304 because a mis-sized code shifts the whole remainder of the string. It also makes
305 `/ToUnicode` (which is keyed by *code*, not CID) resolve, so text extraction,
306 search and substitute-font painting work even where the embedded glyphs do not.
307 Covered families: Shift-JIS (`*-RKSJ-*`), Japanese EUC (`EUC-H/V`), GBK
308 (`GBK*`), EUC-CN (`GB*-EUC-*`), Big5 (`*-B5-*`, `B5pc-*`), Korean UHC/EUC-KR
309 (`*UHC*`, `KSC*`), and the variable-length `Uni*-UTF8-*` (1–4 byte) and
310 `Uni*-UTF16-*` (2/4-byte surrogate) families. `Identity-H/V`, the pure-2-byte
311 `Uni*-UCS2-*` families and the `<2121>`–`<7E7E>` ISO-2022 families (`H`, `V`,
312 `Add-H`, `Ext-H`) need no codespace and are fully segmented already.
313 `usecmap` is honored, inheriting the referenced predefined CMap's codespace.
314 **Embedded** CMap *streams* are parsed for real code→CID ranges, variable-length
315 codespaces and `/WMode`, and are fully supported.
316 Two known gaps: shipping the ~40 compiled predefined code→CID tables is the
317 remaining work (they are registry-specific integer tables that must be copied
318 from the Adobe resources — inventing values would silently select confidently
319 wrong glyphs, which is worse than the identity fallback); and `GBK2K-H`
320 (GB18030) has a 4-byte plane distinguished only by the *second* byte, which the
321 first-byte-only code-length dispatch cannot see, so those rare codes still
322 mis-segment.
323- **Vertical writing position vector `v_y` per CID**: `/W2` and `/DW2` are parsed
324 and applied — the vertical advance `w1_y`, the horizontal offset `v_x` and the
325 `[880 -1000]` `/DW2` default all drive layout — but a *CID-specific* `v_y` is
326 discarded and the `/DW2` value is used for every glyph. Also note the vertical
327 advance keeps applying `Tc`/`Tw` in the direction that widens the gap, which
328 deviates from the literal formula in 9.4.4 (where a positive `Tc` would tighten
329 negative-`w1` vertical text) in favour of matching the horizontal behaviour.
330- **CFF2 and other font programs `ttf-parser` cannot open**: an unparseable
331 `/FontFile[23]` yields no outline program, and the glyph falls back to being
332 painted with a substitute system typeface using the PDF's own widths. Text is
333 still positioned, selectable and searchable; only the glyph shapes are
334 approximate.
335- **Composite fonts with no `/ToUnicode`**: for a Type0 font that embeds no
336 outline program and supplies no `/ToUnicode`, the character codes are CIDs with
337 no recoverable Unicode meaning, so the extracted text is not trustworthy. The
338 proper fix is the predefined `Adobe-Japan1-UCS2`-style CID→Unicode tables,
339 which is the same compiled-table work as the entry above.
340- **Search matches the exact Unicode the PDF supplies, with no normalization**:
341 case folding is applied (and only where it preserves byte length, so the
342 lowercased and original-case page strings stay aligned for one span table), but
343 **ligatures are not expanded and diacritics are not folded**. Searching `find`
344 will not match text typeset with the `fi` ligature (U+FB01), and `café` will not
345 match `cafe`. The ligature case is the one users hit, because professionally
346 typeset PDFs use `fi`/`fl` routinely and whether the ligature survives into the
347 text depends entirely on what the font's `/ToUnicode` maps it to.
348- **Embedded font programs are never rasterized by the renderer**: glyphs either
349 arrive as real outline fills from the core, or are drawn with a substitute
350 system typeface chosen by generic family (sans/serif/mono) with synthesized
351 bold/italic. Positioning stays correct because the core supplies a per-glyph
352 origin and advance, but letterforms differ where no embedded outline is
353 available.
354- **Text clipping (`Tr` 4–7) clips with the substitute typeface's outline**, not
355 the embedded glyph outline, so a text-clipped region has the right position and
356 size but the wrong letterform edges.
357- **Transparency group `/K` (knockout) is ignored**: a knockout group renders as
358 if non-knockout, so overlapping elements inside one incorrectly show through
359 each other instead of each replacing the last (11.4.6 / 11.6.6).
360 `Canvas.saveLayer` composites each element against the running result rather
361 than against the group's initial backdrop, which is what knockout requires.
362- **Transparency group `/I false` (non-isolated) is ignored**: a non-isolated
363 group renders as isolated, so a group carrying a non-Normal blend mode fails to
364 blend with the page backdrop and looks flat or too opaque (11.4.5).
365 `saveLayer` always yields an isolated layer and there is no way to seed it with
366 the existing backdrop.
367 Both flags *are* parsed and carried over the wire (`u8 isolated, u8 knockout`);
368 neither variant is expressible with Canvas layers.
369- **Soft-mask `/TR` transfer functions are applied only when affine** (11.6.5.2):
370 the mask value is passed through `/TR`, carried to the renderer as a 256-entry
371 LUT (wire tag 13) and least-squares fitted to `gain * m + bias` in Kotlin.
372 Inverting and gain/bias curves fit exactly and are applied exactly — which
373 covers the case that matters, since an inverting `/TR` is the standard idiom for
374 "mask out where the group is bright" and ignoring it hid exactly the wrong half.
375 A *nearly* linear curve is accepted and applied as its best-fit line, the
376 tolerance being a maximum absolute error of `3/255`. Only a genuinely
377 non-linear `/TR` (gamma, threshold, sampled Type 0) is refused: it is detected,
378 logged once at parse time, and left **untransformed** rather than approximated,
379 because a wrong curve hides the wrong half of the group — the exact fault this
380 exists to prevent. What a user sees in that case is a mask with the wrong
381 falloff — a vignette that fades over the wrong distance, or a mask with visibly
382 wrong contrast — rather than a subtly approximated one, since the mask is applied
383 as though `/TR` were identity. An identity `/TR` never reaches the wire; it is
384 dropped in Rust, which is cheaper and indistinguishable from applying it.
385 The remaining gap is a platform one: a soft mask is composited in a
386 `Canvas.saveLayer`, whose only per-pixel hook is the affine
387 `ColorMatrixColorFilter`; Android has no alpha-LUT filter, a `saveLayer` exposes
388 no readable pixel buffer, and `RuntimeShader` cannot act as that filter.
389- **Overprint** (`/OP`, `/op`, `/OPM`): parsed into the graphics state but
390 deliberately not applied. Overprint controls which *device colorants* are left
391 unmarked (8.6.7) and has no meaning on an additive RGB compositor with no
392 separations. It was previously approximated as a Multiply blend, which was
393 actively harmful: `white MULTIPLY dst == dst` turned white knockout rectangles
394 into no-ops and let content that should have been covered show through.
395- **Incremental save / detached-signature verification**: `save_to` always
396 rewrites the whole document (no `/Prev` xref append), so cryptographic
397 signature *verification* and byte-range-preserving incremental updates are not
398 implemented. Signing scaffolding (`prepare_signature`) and detached CMS
399 creation exist, but existing signatures are not validated on open.
400- **`/Interpolate` on a rasterized tiling-pattern cell** (8.9.5.1): the v11
401 interpolate byte covers image XObjects and inline images, so a magnified
402 QR code, barcode, scanned fax or 1-bit stencil now keeps hard edges. A
403 rasterized tiling-pattern cell (`ImageTiled`) is still drawn with bitmap
404 filtering hard-coded on, so a bilevel hatch pattern blurs when zoomed; the
405 cell is a generated raster rather than a source image, so there is no
406 source `/Interpolate` value to carry for it.
407- **A very dense page is truncated at 300,000 drawing primitives**: past that the
408 rest of the page is not emitted, so a large-format vector drawing — a map, CAD
409 sheet or dense chart — renders only partially. This is a memory floor rather
410 than a tunable: a `Prim` costs ~120–180 bytes in practice, so 300,000 is roughly
411 40–55 MB held simultaneously with the ~15 MB serialized wire copy, and a Rust
412 OOM is an uncatchable process abort. The cap is enforced at every
413 content-emitting push. The truncation is **silent**: nothing on the wire flags
414 it and the viewer surfaces no message, so the page simply renders its top
415 portion and looks as though it finished normally. The separate operator ceiling
416 (`MAX_CONTENT_OPS`, a *time* guard) sits deliberately above it at 1,000,000 so
417 it only catches pathological streams — it was formerly 200,000, which made it
418 the binding constraint and cut an ordinary dense vector page off at ~100,000
419 primitives, a third of what was already sanctioned.
420- **No per-page cap on shading memory**: a page with very many gradients can use a
421 lot of memory. Each shading raster is capped individually — 256 KB for
422 axial/radial gradients, 1 MB for function-based and mesh shadings — but nothing
423 bounds their total, so a page with hundreds of gradients holds every one at once.
424- **Some tiling patterns are drawn at reduced density over a large area**
425 (8.7.3.3): most tiled fills now repeat across the whole region at full density —
426 a cell made only of fills and strokes is rasterized **once** and emitted as a
427 periodic bitmap, so the tile count stops mattering. That includes *overlapping*
428 patterns, where `/XStep` or `/YStep` is smaller than the `/BBox` (8.7.3.1): such a
429 pattern is still periodic with period `(XStep, YStep)`, and the cell is drawn at
430 every lattice offset that reaches one period window, so the spill from
431 neighbouring cells is composited in rather than lost.
432 Two cases still fall back to replaying the cell per tile, where past 20,000 tiles
433 the lattice is thinned uniformly (stride = `ceil(sqrt(need / 20000))`) to stay
434 inside the primitive budget — the region remains **fully covered**, just coarser
435 than the document asks for: a cell containing **text**, an **image** or its own
436 **clipping/group** (the cell rasterizer has no glyph rasterizer and ignores
437 images, clips and groups, so rasterizing it would silently drop that content);
438 and a pattern overlapping so heavily that one period needs more than 64 cell
439 copies to resolve, which is bounded because the cost is per-period, not per-tile.
440- **Overlapping shapes under one soft mask blend slightly wrong**: where many
441 shapes overlap beneath a single partially-transparent `/SMask`, the composite in
442 the overlap region is a little off, because consecutive paints under the same
443 mask are coalesced into ONE masked layer and therefore composited as a group
444 rather than individually. The coalescing is deliberate and not a shortcut: one
445 bracket per painting operator re-expanded the mask for every operator and pushed
446 pages past the primitive cap, truncating real content — a visibly worse outcome
447 than a slight blend error.
448- **The search index is invalidated by an RAII guard, not by the mutators
449 themselves**: `ensure_index` is a pure memo keyed by handle and never re-reads
450 the document, so the "a search answers from the current document" contract rests
451 entirely on every mutating entry point dropping the entry. `invalidate_index`
452 used to have no callers at all, which meant redacting, annotating, filling a
453 form field or moving a page left search answering from the pre-edit text —
454 including, in the privacy-relevant case, surfacing and highlighting text that
455 had just been redacted. Each mutating `extern` fn in `jni_bindings.rs` now holds
456 an `InvalidateSearchIndex` guard for the whole call, so the eviction happens on
457 the unwind path too and a panic that leaves a document half-edited cannot leave
458 a matching index behind. The residual fragility is that it is per-entry-point
459 rather than structural: a *new* mutating binding that forgets the guard
460 reintroduces the staleness, because there is still no single accessor that
461 observes "this document changed".
462- **Form fields with no appearance stream are invisible**: a field that relies on
463 the viewer to build its own appearance (`/NeedAppearances` set, no `/AP`)
464 renders as nothing at all rather than as a box showing its value, because
465 appearance generation runs only when the user edits a field, not on load.
466- **Text beyond WinAnsi typed into a form field or text annotation shows as
467 `?` in the generated appearance**: field values and annotation contents are
468 stored losslessly (PDFDocEncoding, or UTF-16BE where PDFDoc cannot hold
469 them), but the generated appearance paints with a WinAnsi simple font, so a
470 character it has no glyph for (CJK, emoji) is substituted in the baked
471 appearance stream.
472- **Overlapping strokes in a translucent annotation darken where they cross**: a
473 semi-transparent Ink or Highlight annotation whose own strokes overlap is
474 composited per-stroke rather than as a single group, so intersections come out
475 darker than the author intended (11.6.2 wants group semantics).
476- **Multi-select list boxes collapse to a single selection**: choosing several
477 options stores only one, because the value setter takes a single string.
478- **Rich-text field formatting is dropped**: a field with `/RV` shows its plain
479 text — correct content, but no bold, italic or colour runs.
480- **Standard stamp annotations show their wording in a plain outlined box** instead
481 of real artwork: an Approved stamp renders as the word APPROVED in a rectangle,
482 because Acrobat's stamp graphics are not shipped.
483- **Pushbuttons are presented as toggleable checkboxes** even though a pushbutton
484 has no value.
485- **Physical page sizing (`/UserUnit`) is not surfaced**; page layout and
486 rendering are unaffected by it.
487- **True redaction**: see the highlighted warning at the top of this section —
488 `/Redact` covers content rather than removing it.
489- **Large JBIG2 images render as nothing at all**: a JBIG2 image wider or taller
490 than 20,000px, or over 16 megapixels, comes out fully transparent — a deliberate
491 memory guard in `jbig2.rs` with no partial-decode path.
492- **JBIG2 decode failures are silent**: an image that fails to decode renders as an
493 invisible gap rather than a placeholder, so a failure is indistinguishable from a
494 legitimately blank region. Deliberate (the red placeholder was removed), but it
495 means nothing signals the loss.
496- **CCITTFax `/EncodedByteAlign` and mixed 1-D/2-D G3 (`K > 0`)**: a G3/G4 fax
497 image with `/EncodedByteAlign true` renders as diagonal streaks or noise, since
498 each row must restart on a byte boundary. This is genuinely blocked by the `fax`
499 crate's API rather than merely unimplemented: `ByteReader`'s `partial`/`valid`
500 fields and `fill()` are private, its only public surface is `new` plus two debug
501 printers, and `Group3Decoder`/`Group4Decoder` own their reader internally, so
502 there is no way to realign the bit reader. `K > 0` is likewise a best-effort
503 attempt (try G3, then fall back to G4) rather than real per-row mode switching,
504 so a genuinely mixed page can decode partially or not at all. Pure G3/G4 — the
505 common cases — decode correctly.
506
507## Prerequisites (local + CI)
508
509`rustup target add aarch64-linux-android`. `./gradlew :pdf:assembleDebug`
510triggers `cargoNdkBuild` with NDK 29.
511
512## Host tests
513
514```sh
515cd pdf/src/main/rust
516cargo test
517```
518
519Covers PDF function evaluation (all four types), radial-shading parameterization,
520mesh-shading rasterization, stroke-outline quad generation, Type 3 glyph
521emission, image colorspace conversion, LZW/TIFF predictors, RC4/AES-128/AES-256
522save round-trips, CFF/Type 1 encoding recovery, Type 1 charstring `flex`
523(one contour, correct current point), mixed-width predefined-CMap codespace
524segmentation, the per-operation font cache (shared inside a scope, uncached
525without one), `Tw` applying only to single-byte code 32, the untrusted-font-data
526loop clamps, case-sensitive search, and the wire round-trip (including
527per-primitive blend and soft-mask markers).
528
529[`lopdf`]: https://crates.io/crates/lopdf