pdf: fix appearance matrix, font encoding, mask and link bugs (#321)
- Commit
610b17fa86f2f51ff9bbe9f16e180f133d49c2f2- Author
- vayun-mathur <[email protected]>
- When
- 2026-08-31 16:16 UTC (3 months ago)
- Parents
b3f5bad
Diff
pdf/src/main/java/com/vayunmathur/pdf/ui/SafePdfViewerScreen.kt
diff --git a/pdf/src/main/java/com/vayunmathur/pdf/ui/SafePdfViewerScreen.kt b/pdf/src/main/java/com/vayunmathur/pdf/ui/SafePdfViewerScreen.ktindex d29b7bc789..7019054582 100644--- a/pdf/src/main/java/com/vayunmathur/pdf/ui/SafePdfViewerScreen.kt+++ b/pdf/src/main/java/com/vayunmathur/pdf/ui/SafePdfViewerScreen.kt@@ -2902,7 +2902,14 @@ internal fun DrawScope.drawSafePage(page: SafePdfPage) { // standard faux-bold — and rendered it hollow. Only suppress the fill when // a stroke will actually be painted, since Rust's no-metrics path emits // mode 1 with no stroke colour and must still show something.- val willStroke = prim.strokeColor != null && prim.strokeWidth > 0f+ //+ // Width ZERO still strokes: §8.4.3.2 makes 0 the thinnest line the device+ // can render, not the absence of one, and draw.rs passes `device_stroke_w`+ // through without a floor (unlike the `.max(0.1)` on Prim::Stroke). Treating+ // it as "no stroke" made `0 w 1 Tr` fall through to the fill branch, which+ // for a stroke-only mode paints prim.color — Rust sets that to the STROKE+ // colour there — so hairline-outlined text came out solid.+ val willStroke = prim.strokeColor != null && prim.strokeWidth >= 0f val isStrokeOnly = willStroke && (rm == 1 || rm == 5) // v8: substitute the embedded font with a system typeface matching the@@ -2934,6 +2941,17 @@ internal fun DrawScope.drawSafePage(page: SafePdfPage) { // Mode 3 paints nothing (it is how scanned PDFs carry an invisible OCR // text layer) and mode 7 is clip-only. if (rm != 3 && rm != 7) {+ // FILL FIRST, THEN STROKE. Table 106 names modes 2 and 6 "Fill, then+ // stroke text", and the order is visible whenever the two colours+ // differ: stroking first let the fill paint over the inner half of the+ // stroke, so a black outline round white display text came out at half+ // its weight. Modes 1 and 5 take the stroke branch only.+ if (!isStrokeOnly) {+ textPaint.color = prim.color+ textPaint.textSize = ts+ textPaint.setBlend(prim.blend)+ nativeCanvas.drawText(prim.text, origin.x, origin.y, textPaint)+ } if (willStroke) { textStrokePaint.color = prim.strokeColor textStrokePaint.textSize = ts@@ -2943,12 +2961,6 @@ internal fun DrawScope.drawSafePage(page: SafePdfPage) { textStrokePaint.setBlend(prim.blend) nativeCanvas.drawText(prim.text, origin.x, origin.y, textStrokePaint) }- if (!isStrokeOnly) {- textPaint.color = prim.color- textPaint.textSize = ts- textPaint.setBlend(prim.blend)- nativeCanvas.drawText(prim.text, origin.x, origin.y, textPaint)- } } // Accumulate glyph outlines for text-clip render modes (Tr 4-7),
pdf/src/main/java/com/vayunmathur/pdf/util/SafePdfDocument.kt
diff --git a/pdf/src/main/java/com/vayunmathur/pdf/util/SafePdfDocument.kt b/pdf/src/main/java/com/vayunmathur/pdf/util/SafePdfDocument.ktindex 1a6386ae31..3fd48955b4 100644--- a/pdf/src/main/java/com/vayunmathur/pdf/util/SafePdfDocument.kt+++ b/pdf/src/main/java/com/vayunmathur/pdf/util/SafePdfDocument.kt@@ -122,21 +122,37 @@ class SafePdfDocument private constructor( } } + /**+ * Decode a listing buffer, degrading a malformed one to an empty list.+ *+ * [renderPage] already catches a wire-parse failure because a throw there becomes a null+ * page. These listings had no equivalent: the decoders throw on a truncated or desynced+ * buffer, none of the callers below caught, and every one of them is consumed from a+ * `produceState` in [com.vayunmathur.pdf.ui.SafePdfViewerScreen] — so the exception left+ * the coroutine and took the composition down. An empty overlay is a far better outcome+ * than losing the viewer, and it matches what a null buffer from the native side already+ * produces.+ */+ private fun <T> decodeListing(what: String, index: Int, bytes: ByteArray?, decode: (ByteArray) -> List<T>): List<T> {+ if (bytes == null) return emptyList()+ return runCatching { decode(bytes) }+ .onFailure { android.util.Log.w(TAG, "$what listing failed to decode for page $index", it) }+ .getOrDefault(emptyList())+ }+ /** Annotations on [index] for the editing overlay. */ suspend fun annotations(index: Int): List<SafeAnnotation> = withContext(Dispatchers.IO) {- PdfNative.listAnnotations(handle, index)- ?.let { SafePdfParser.parseAnnotations(it) } ?: emptyList()+ decodeListing("annotation", index, PdfNative.listAnnotations(handle, index), SafePdfParser::parseAnnotations) } /** AcroForm widget fields on [index]. */ suspend fun formFields(index: Int): List<SafeFormField> = withContext(Dispatchers.IO) {- PdfNative.listFormFields(handle, index)- ?.let { SafePdfParser.parseFormFields(it) } ?: emptyList()+ decodeListing("form field", index, PdfNative.listFormFields(handle, index), SafePdfParser::parseFormFields) } /** Link annotations on [index]. */ suspend fun links(index: Int): List<SafeLink> = withContext(Dispatchers.IO) {- PdfNative.listLinks(handle, index)?.let { SafePdfParser.parseLinks(it) } ?: emptyList()+ decodeListing("link", index, PdfNative.listLinks(handle, index), SafePdfParser::parseLinks) } suspend fun addText(@@ -295,7 +311,7 @@ class SafePdfDocument private constructor( /** The document outline (bookmarks), empty if none. */ suspend fun outline(): List<SafeOutlineItem> = withContext(Dispatchers.IO) {- PdfNative.listOutline(handle)?.let { SafePdfParser.parseOutline(it) } ?: emptyList()+ decodeListing("outline", -1, PdfNative.listOutline(handle), SafePdfParser::parseOutline) } /** Full-text search across all pages with case-sensitive toggle (Phase 7). Default case-insensitive for backward compat. */@@ -307,7 +323,7 @@ class SafePdfDocument private constructor( } else { PdfNative.searchDocument(handle, query) }- bytes?.let { SafePdfParser.parseSearchMatches(it) } ?: emptyList()+ decodeListing("search match", -1, bytes, SafePdfParser::parseSearchMatches) } }
pdf/src/main/java/com/vayunmathur/pdf/util/SafePdfParser.kt
diff --git a/pdf/src/main/java/com/vayunmathur/pdf/util/SafePdfParser.kt b/pdf/src/main/java/com/vayunmathur/pdf/util/SafePdfParser.ktindex 7820a7d36b..c68ef4f2b3 100644--- a/pdf/src/main/java/com/vayunmathur/pdf/util/SafePdfParser.kt+++ b/pdf/src/main/java/com/vayunmathur/pdf/util/SafePdfParser.kt@@ -130,10 +130,21 @@ object SafePdfParser { * content size from whichever cap is smaller rather than hard-coding one. */ const val MAX_PRIMITIVES = 1_000_000- const val MAX_ANNOTATIONS = 10000 /** A /TR transfer function is transmitted as this many u8 samples over the mask value. */ private const val TRANSFER_LUT_SIZE = 256+ /**+ * Largest raster payload this decoder will materialise for one image, in bytes.+ *+ * It is a LOCAL heap policy, not a wire invariant: Rust's own bound is looser in both+ * arms that reach it. `extract_image` downscales a decoded raster to 2048px on its long+ * side (16 MB of RGBA at worst, exactly this), but `extract_inline_image` only enforces+ * `MAX_IMAGE_PIXELS` (16 MP -> 64 MB of RGBA), and the format-1 JPEG passthrough hands+ * over the stream bytes with only a 64 MB ceiling on them. So a payload above this is a+ * legitimate stream we choose not to decode, NOT evidence that the buffer is corrupt —+ * which is why exceeding it skips the one primitive instead of ending the page.+ */+ private const val MAX_IMAGE_DATA_BYTES = 16 * 1024 * 1024 /** * Cap on a tiling pattern's lattice extent per axis. The extent only decides how large a * region the REPEAT shader is asked to cover, so a big count is not itself expensive, but@@ -440,8 +451,21 @@ object SafePdfParser { buf.get().toInt() != 0 } else true val len = buf.int- if (len < 0 || len > 16*1024*1024) throw IllegalArgumentException("Image data length out of bounds $len")+ if (len < 0) throw IllegalArgumentException("Negative image data length $len") if (buf.remaining() < len) throw IllegalArgumentException("Image data truncated")+ if (len > MAX_IMAGE_DATA_BYTES) {+ // The buffer is intact here — the length field is exactly how many+ // bytes to step over — so this resyncs. Throwing instead would break+ // out of the loop and discard every LATER primitive too, blanking the+ // rest of the page below a single over-sized JPEG or inline image.+ android.util.Log.w(+ TAG,+ "image payload $len exceeds $MAX_IMAGE_DATA_BYTES, dropping this " ++ "image and continuing the page",+ )+ buf.position(buf.position() + len)+ continue+ } val data = ByteArray(len) buf.get(data) val bmp = decodeBitmap(w, h, format, data)@@ -525,8 +549,17 @@ object SafePdfParser { val tileAlpha = buf.float.coerceIn(0f, 1f) val tileBlend = BlendMode.fromCode(buf.get().toInt() and 0xFF) val len = buf.int- if (len < 0 || len > 16*1024*1024) throw IllegalArgumentException("ImageTiled data length out of bounds $len")+ if (len < 0) throw IllegalArgumentException("Negative ImageTiled data length $len") if (buf.remaining() < len) throw IllegalArgumentException("ImageTiled data truncated")+ if (len > MAX_IMAGE_DATA_BYTES) {+ android.util.Log.w(+ TAG,+ "tiling cell payload $len exceeds $MAX_IMAGE_DATA_BYTES, dropping " ++ "this pattern and continuing the page",+ )+ buf.position(buf.position() + len)+ continue+ } val data = ByteArray(len) buf.get(data) // Format 0: the cell is always raw RGBA8888, so there is no format byte.@@ -545,7 +578,7 @@ object SafePdfParser { // The payload length of an unknown tag is unknowable, so the read // position is now inside a payload and every later tag byte would be // random data — which decodes into plausible-looking garbage primitives.- // Kotlin knows all 12 tags Rust emits, so an unknown tag means the stream+ // Kotlin knows all 14 tags Rust emits, so an unknown tag means the stream // has desynced: keep what decoded cleanly and stop. android.util.Log.w( TAG,@@ -588,7 +621,7 @@ object SafePdfParser { fun parseAnnotations(bytes: ByteArray): List<SafeAnnotation> { val buf = ByteBuffer.wrap(bytes).order(ByteOrder.LITTLE_ENDIAN) val count = buf.int- val out = ArrayList<SafeAnnotation>(count.coerceAtLeast(0))+ val out = ArrayList<SafeAnnotation>(buf.listCapacity(count, ANNOTATION_MIN_BYTES)) repeat(count) { val id = buf.long val subtype = buf.get().toInt()@@ -604,7 +637,7 @@ object SafePdfParser { fun parseFormFields(bytes: ByteArray): List<SafeFormField> { val buf = ByteBuffer.wrap(bytes).order(ByteOrder.LITTLE_ENDIAN) val count = buf.int- val out = ArrayList<SafeFormField>(count.coerceAtLeast(0))+ val out = ArrayList<SafeFormField>(buf.listCapacity(count, FORM_FIELD_MIN_BYTES)) repeat(count) { val id = buf.long val type = buf.get().toInt()@@ -621,7 +654,7 @@ object SafePdfParser { fun parseSearchMatches(bytes: ByteArray): List<SafeSearchMatch> { val buf = ByteBuffer.wrap(bytes).order(ByteOrder.LITTLE_ENDIAN) val count = buf.int- val out = ArrayList<SafeSearchMatch>(count.coerceAtLeast(0))+ val out = ArrayList<SafeSearchMatch>(buf.listCapacity(count, SEARCH_MATCH_BYTES)) repeat(count) { val page = buf.int out.add(SafeSearchMatch(page, buf.float, buf.float, buf.float, buf.float))@@ -633,7 +666,7 @@ object SafePdfParser { fun parseLinks(bytes: ByteArray): List<SafeLink> { val buf = ByteBuffer.wrap(bytes).order(ByteOrder.LITTLE_ENDIAN) val count = buf.int- val out = ArrayList<SafeLink>(count.coerceAtLeast(0))+ val out = ArrayList<SafeLink>(buf.listCapacity(count, LINK_MIN_BYTES)) repeat(count) { val x0 = buf.float; val y0 = buf.float; val x1 = buf.float; val y1 = buf.float val dest = buf.int@@ -643,10 +676,54 @@ object SafePdfParser { return out } + /**+ * Initial capacity for a listing whose header claims [count] records of at least+ * [minRecordBytes] each.+ *+ * The count is read straight off the wire, so a bare `ArrayList(count)` allocates an+ * `Object[count]` before a single record has been validated — a corrupt or truncated+ * header reading as ~2e9 raises OutOfMemoryError, which is an Error and so escapes+ * every `runCatching` between here and the composition rather than degrading to an+ * empty listing. The buffer cannot physically hold more than+ * `remaining / minRecordBytes` records, so cap on that: it can never clip a count a+ * well-formed buffer could justify, and it needs no invented constant. The `repeat`+ * loop still runs to `count` and stops on the underflow, so this only bounds the+ * pre-allocation, never the result.+ */+ private fun ByteBuffer.listCapacity(count: Int, minRecordBytes: Int): Int =+ count.coerceIn(0, remaining() / minRecordBytes)++ /** u64 id + u8 subtype + 4xf32 rect + u32 colour + the u16 /Contents length. */+ private const val ANNOTATION_MIN_BYTES = 8 + 1 + 16 + 4 + 2+ /** u64 id + u8 type + 4xf32 rect + two u16 string lengths + u8 checked. */+ private const val FORM_FIELD_MIN_BYTES = 8 + 1 + 16 + 2 + 2 + 1+ /** u32 page + 4xf32 rect, fixed width. */+ private const val SEARCH_MATCH_BYTES = 4 + 16+ /** 4xf32 rect + i32 destination page + the u16 URI length. */+ private const val LINK_MIN_BYTES = 16 + 4 + 2+ /** u16 level + i32 page + the u16 title length. */+ private const val OUTLINE_MIN_BYTES = 2 + 4 + 2++ /**+ * A u16-length-prefixed UTF-8 string, as every listing buffer writes them.+ *+ * No upper-bound rejection. Rust truncates each of these at `u16::MAX` — annotation+ * /Contents (annotations.rs:1980), form field /T and /V (forms.rs:452), a link URI+ * (forms.rs:351) and an outline title (forms.rs:1088) all use+ * `b.len().min(u16::MAX as usize)` — so any length the field can express is a length the+ * producer will legitimately send. The old 4096 cap sat below that and THREW on a longer+ * one, which is not survivable here the way it is inside [parse]: these parsers have no+ * per-record recovery, so a single 5 KB sticky-note comment or multi-line form value took+ * out the whole listing, and the throw propagates out of [SafePdfDocument.annotations] and+ * its siblings — none of which catch — into the composition. Exactly the reasoning already+ * applied to the Text primitive's length above.+ *+ * `len` is u16-bounded, so the allocation is capped at 64 KB regardless, and the remaining+ * check below is the real guard against a truncated buffer.+ */ private fun readString(buf: ByteBuffer): String { if (buf.remaining() < 2) throw IllegalArgumentException("readString header truncated") val len = buf.short.toInt() and 0xFFFF- if (len > 4096) throw IllegalArgumentException("readString length $len exceeds 4096 cap (v9 guard)") if (buf.remaining() < len) throw IllegalArgumentException("readString truncated len=$len remaining=${buf.remaining()}") val b = ByteArray(len) buf.get(b)@@ -657,7 +734,7 @@ object SafePdfParser { fun parseOutline(bytes: ByteArray): List<SafeOutlineItem> { val buf = ByteBuffer.wrap(bytes).order(ByteOrder.LITTLE_ENDIAN) val count = buf.int- val out = ArrayList<SafeOutlineItem>(count.coerceAtLeast(0))+ val out = ArrayList<SafeOutlineItem>(buf.listCapacity(count, OUTLINE_MIN_BYTES)) repeat(count) { val level = buf.short.toInt() and 0xFFFF val page = buf.int@@ -711,7 +788,7 @@ object SafePdfParser { return try { when (format) { 1 -> {- if (data.size > 16*1024*1024) {+ if (data.size > MAX_IMAGE_DATA_BYTES) { android.util.Log.w("SafePdfParser", "JPEG too large ${data.size}") null } else {
pdf/src/main/rust/src/annotations.rs
diff --git a/pdf/src/main/rust/src/annotations.rs b/pdf/src/main/rust/src/annotations.rsindex 954cc0ce45..1c221699a6 100644--- a/pdf/src/main/rust/src/annotations.rs+++ b/pdf/src/main/rust/src/annotations.rs@@ -1,8 +1,14 @@ use crate::*; -/// The matrix mapping an appearance stream's form space to page space, fitting-/// the (Matrix-transformed) `/BBox` into the annotation `/Rect` (PDF 12.5.5).-pub(crate) fn appearance_matrix(rect: [f64; 4], bbox: [f64; 4], matrix: Mat) -> Mat {+/// The §12.5.5 appearance algorithm's matrix **A**: it maps the `/Matrix`-+/// transformed `/BBox` onto the annotation `/Rect`, and does NOT itself include+/// `/Matrix`.+///+/// This is the matrix to concatenate before invoking the appearance with `Do`,+/// because §8.10.2 makes `Do` concatenate the form's own `/Matrix` with the CTM.+/// Using the full `AA` there applies `/Matrix` twice. Callers that play the+/// appearance's operators directly want `appearance_matrix` instead.+pub(crate) fn appearance_fit_matrix(rect: [f64; 4], bbox: [f64; 4], matrix: Mat) -> Mat { let corners = [ (bbox[0], bbox[1]), (bbox[2], bbox[1]),@@ -28,8 +34,17 @@ pub(crate) fn appearance_matrix(rect: [f64; 4], bbox: [f64; 4], matrix: Mat) -> let bh = ty1 - ty0; let sx = if bw.abs() > 1e-6 { (rx1 - rx0) / bw } else { 1.0 }; let sy = if bh.abs() > 1e-6 { (ry1 - ry0) / bh } else { 1.0 };- let fit = [sx, 0.0, 0.0, sy, rx0 - sx * tx0, ry0 - sy * ty0];- mat_mul(&matrix, &fit)+ [sx, 0.0, 0.0, sy, rx0 - sx * tx0, ry0 - sy * ty0]+}++/// The §12.5.5 appearance algorithm's matrix **AA** = `Matrix` × **A**: maps the+/// appearance stream's form space straight to page space.+///+/// For a caller that interprets the appearance's operator list itself (which+/// therefore never sees a `Do` to apply `/Matrix` for it). A caller that emits+/// `Do` must use `appearance_fit_matrix`.+pub(crate) fn appearance_matrix(rect: [f64; 4], bbox: [f64; 4], matrix: Mat) -> Mat {+ mat_mul(&matrix, &appearance_fit_matrix(rect, bbox, matrix)) } /// Whether an annotation should be painted on screen. Shared by the renderer and@@ -390,6 +405,18 @@ pub(crate) fn synthesize_annotation_appearance( let stroke = markup_color(doc, dict, b"C"); let fill = markup_color(doc, dict, b"IC"); let bw = annot_border_width(doc, dict);+ // §12.5.4 Table 166: "/W ... the border width in points. If this value is 0,+ // no border shall be drawn." `gs.line_width` floors at 0.5, so a shape whose+ // file says W=0 would otherwise come out ringed in a hairline it never asked+ // for — most visibly around a filled Square/Circle, which is exactly how+ // this codebase's own `set_shape_border` marks a filled shape.+ //+ // Applied only to the two shapes that have a spec-defined interior (/IC), so+ // suppressing the border still leaves the annotation's content. For Line,+ // PolyLine and Ink the stroke IS the whole annotation, and dropping it on a+ // producer that wrote W=0 by accident would erase the annotation outright,+ // which is the larger risk of the two.+ let has_border = bw > 0.0; let dev = |x: f64, y: f64| -> (f64, f64) { transform(base, x, y) }; // Device half-width for strokes (approx via base scale). let scale = ((base[0]*base[0]+base[1]*base[1]).sqrt() + (base[2]*base[2]+base[3]*base[3]).sqrt()) / 2.0;@@ -414,7 +441,7 @@ pub(crate) fn synthesize_annotation_appearance( b"Square" => { let poly = vec![dev(rect[0],rect[1]), dev(rect[2],rect[1]), dev(rect[2],rect[3]), dev(rect[0],rect[3])]; if let Some(f) = fill { emit_fill(prims, std::slice::from_ref(&poly), apply_alpha_to_argb(f, ca), false, 1.0, BlendMode::Normal); }- if let Some(s) = stroke {+ if let Some(s) = stroke.filter(|_| has_border) { let mut ring = poly.clone(); ring.push(poly[0]); let mut sgs = gs.clone(); sgs.stroke = s; let d = annot_border_dash(doc, dict);@@ -431,7 +458,7 @@ pub(crate) fn synthesize_annotation_appearance( dev(cx + rx*t.cos(), cy + ry*t.sin()) }).collect(); if let Some(f) = fill { emit_fill(prims, std::slice::from_ref(&poly), apply_alpha_to_argb(f, ca), false, 1.0, BlendMode::Normal); }- if let Some(s) = stroke {+ if let Some(s) = stroke.filter(|_| has_border) { let mut ring = poly.clone(); ring.push(poly[0]); let mut sgs = gs.clone(); sgs.stroke = s; let d = annot_border_dash(doc, dict);@@ -659,12 +686,16 @@ pub(crate) fn synthesize_annotation_appearance( b"Redact" => { // §12.5.6.24: a redaction is not applied until apply_redactions runs, // so before that the annotation only MARKS the region. Outline it in- // /C (default red) and fill only if /IC is present — a wash over the- // region would obscure the very text the user needs to read.+ // /C (default red) and draw no interior at all.+ //+ // /IC is deliberately NOT painted here. Table 187 defines it as "the+ // interior colour with which to fill the redacted region AFTER the+ // affected content has been removed" — it is the post-application+ // art, alongside /RO and /OverlayText. Filling with it while the+ // content is still there hides the very text the user has to read to+ // check the mark, which is the same "wash over the page" failure the+ // rest of this function exists to avoid. let poly = vec![dev(rect[0],rect[1]), dev(rect[2],rect[1]), dev(rect[2],rect[3]), dev(rect[0],rect[3])];- if let Some(f) = fill {- emit_fill(prims, std::slice::from_ref(&poly), apply_alpha_to_argb(f, ca), false, 1.0, BlendMode::Normal);- } let mut ring = poly.clone(); ring.push(poly[0]); let mut sgs = gs.clone(); sgs.stroke = stroke.unwrap_or(0xFFFF_0000);@@ -1666,9 +1697,46 @@ pub(crate) fn update_free_text(handle: i64, annot_id: i64, text: &str) -> bool { .unwrap_or(12.0); (rect, argb, size) };- let (w, h) = (rect[2] - rect[0], rect[3] - rect[1]);+ // The regenerated appearance must keep the orientation the annotation was+ // authored with. On a /Rotate 90/180/270 page `add_free_text` lays the text+ // out in DISPLAY orientation and carries it back into raw page space with+ // the form's `/Matrix` (§12.5.5, see `display_orientation`). Re-authoring+ // with an identity `/Matrix` and the raw `/Rect` extents put the edited text+ // sideways relative to the reader, and squashed it as well, because+ // §12.5.5 fits the /Matrix-transformed /BBox onto /Rect and a BBox whose+ // axes no longer line up with /Rect gets scaled to fit. Reusing the existing+ // stream's /BBox extents and /Matrix reproduces exactly what created it, and+ // is a strict no-op at /Rotate 0.+ let (w, h, apm) = {+ let existing = doc+ .get_dictionary(id)+ .ok()+ .and_then(|d| d.get(b"AP").ok())+ .and_then(|o| deref(doc, o))+ .and_then(|o| o.as_dict().ok())+ .and_then(|ap| ap.get(b"N").ok())+ .and_then(|o| deref(doc, o))+ .and_then(|o| o.as_stream().ok());+ let fallback = (rect[2] - rect[0], rect[3] - rect[1]);+ match existing {+ Some(s) => {+ let m = s.dict.get(b"Matrix").ok().and_then(read_matrix_obj).unwrap_or(IDENTITY);+ let (bw, bh) = s+ .dict+ .get(b"BBox")+ .ok()+ .and_then(|o| read_rect(doc, o))+ .map(normalize_rect)+ .filter(|b| b[2] - b[0] > 0.0 && b[3] - b[1] > 0.0)+ .map(|b| (b[2] - b[0], b[3] - b[1]))+ .unwrap_or(fallback);+ (bw, bh, m)+ }+ None => (fallback.0, fallback.1, IDENTITY),+ }+ }; let content = free_text_content(w, h, text, argb, size);- let ap_id = make_appearance(doc, w, h, content, helvetica_resources());+ let ap_id = make_appearance_oriented(doc, w, h, content, helvetica_resources(), apm); if let Ok(dict) = doc.get_dictionary_mut(id) { dict.set("Contents", Object::string_literal(text)); let mut ap = Dictionary::new();@@ -2292,6 +2360,173 @@ mod synthesis_tests { assert_eq!(display_orientation(0, dw, dh), (dw, dh, IDENTITY)); } + /// §12.5.5 computes the appearance placement as `AA = Matrix × A`, where+ /// `AA` maps form space straight to page space. A caller that emits+ /// `cm ... Do` must NOT use `AA`: §8.10.2 makes `Do` concatenate the form's+ /// own `/Matrix` for it, so `AA` there applies `/Matrix` twice. This pins+ /// `appearance_fit_matrix` as `A` and shows that the doubled form escapes the+ /// `/Rect` entirely, which is what `flatten_document` used to bake in.+ #[test]+ fn the_fit_matrix_omits_the_form_matrix_that_do_reapplies() {+ let (dw, dh) = (160.0_f64, 40.0_f64);+ let bbox = [0.0, 0.0, dw, dh];+ for rot in [0i64, 90, 180, 270] {+ let (_, _, apm) = display_orientation(rot, dw, dh);+ let rect = match rot {+ 90 | 270 => [10.0, 20.0, 10.0 + dh, 20.0 + dw],+ _ => [10.0, 20.0, 10.0 + dw, 20.0 + dh],+ };+ let aa = appearance_matrix(rect, bbox, apm);+ let a = appearance_fit_matrix(rect, bbox, apm);+ // What the interpreter's `Do` arm actually builds from a `cm A`.+ let via_do = mat_mul(&apm, &a);+ for i in 0..6 {+ assert!(+ (via_do[i] - aa[i]).abs() < 1e-9,+ "rot={rot}: `cm A ... Do` must land on AA, element {i}"+ );+ }+ if rot == 0 {+ assert_eq!(a, aa, "identity /Matrix: A and AA coincide");+ continue;+ }+ // Emitting AA in the `cm` instead: `Do` rotates a second time and the+ // appearance leaves its own /Rect.+ let doubled = mat_mul(&apm, &aa);+ let (px, py) = transform(&doubled, dw, dh);+ assert!(+ px < rect[0] - 1e-6 || px > rect[2] + 1e-6 || py < rect[1] - 1e-6 || py > rect[3] + 1e-6,+ "rot={rot}: doubling /Matrix should have escaped {rect:?}, got ({px},{py})"+ );+ }+ }++ /// §12.5.6.24 Table 187: `/IC` is "the interior colour with which to fill the+ /// redacted region AFTER the affected content has been removed". Painting it+ /// while the content is still there is a wash over the very text the user has+ /// to read to check the mark. Only the outline may be synthesized.+ #[test]+ fn a_pending_redaction_marks_the_region_without_covering_it() {+ let mut d = annot("Redact");+ d.set("IC", Object::Array(vec![0.into(), 0.into(), 0.into()]));+ d.set("C", Object::Array(vec![1.into(), 0.into(), 0.into()]));+ let prims = synth(&d, [0.0, 0.0, 60.0, 40.0]);+ assert!(+ !prims.iter().any(|p| matches!(p, Prim::Fill { .. })),+ "a pending redaction must not fill its region: {:?}",+ kinds(&prims)+ );+ assert_eq!(+ prims.iter().filter(|p| matches!(p, Prim::Stroke { .. })).count(),+ 1,+ "the region must still be outlined: {:?}",+ kinds(&prims)+ );+ }++ /// §12.5.4 Table 166: "/W ... If this value is 0, no border shall be drawn."+ /// The synthesized stroke floors its line width at 0.5, so without an explicit+ /// check a filled Square or Circle came out ringed in a hairline outline the+ /// file expressly asked not to have — and `set_shape_border` in this very file+ /// writes `W 0` for every filled shape it authors.+ #[test]+ fn a_zero_border_width_draws_no_border() {+ for subtype in ["Square", "Circle"] {+ let mut d = annot(subtype);+ d.set("C", Object::Array(vec![1.into(), 0.into(), 0.into()]));+ d.set("IC", Object::Array(vec![0.into(), 0.into(), 1.into()]));+ d.set("BS", dictionary! { "W" => 0 });+ let prims = synth(&d, [0.0, 0.0, 60.0, 40.0]);+ assert!(+ !prims.iter().any(|p| matches!(p, Prim::Stroke { .. })),+ "{subtype} with /BS /W 0 drew a border: {:?}",+ kinds(&prims)+ );+ assert!(+ prims.iter().any(|p| matches!(p, Prim::Fill { .. })),+ "{subtype}: the /IC interior must still paint"+ );+ // A width the file did not suppress still strokes.+ d.set("BS", dictionary! { "W" => 2 });+ assert!(+ synth(&d, [0.0, 0.0, 60.0, 40.0])+ .iter()+ .any(|p| matches!(p, Prim::Stroke { .. })),+ "{subtype}: a nonzero /W must still draw"+ );+ }+ }++ /// Editing a FreeText's text must not re-orient it. On a rotated page+ /// `add_free_text` authors the appearance in DISPLAY orientation and carries+ /// it back with the form's `/Matrix` (§12.5.5); regenerating with an identity+ /// `/Matrix` and the raw `/Rect` extents laid the edited text sideways, and+ /// squashed it because §12.5.5 scales the transformed /BBox to fit /Rect.+ #[test]+ fn editing_free_text_preserves_the_appearance_orientation() {+ for rot in [0i64, 90, 180, 270] {+ let mut doc = Document::with_version("1.7");+ let pages_id = doc.new_object_id();+ let page = doc.add_object(dictionary! {+ "Type" => name_obj("Page"),+ "Parent" => Object::Reference(pages_id),+ "MediaBox" => rect_obj([0.0, 0.0, 612.0, 792.0]),+ "Rotate" => Object::Integer(rot),+ });+ doc.objects.insert(+ pages_id,+ Object::Dictionary(dictionary! {+ "Type" => name_obj("Pages"),+ "Kids" => Object::Array(vec![Object::Reference(page)]),+ "Count" => 1,+ }),+ );+ let cat = doc.add_object(dictionary! {+ "Type" => name_obj("Catalog"),+ "Pages" => Object::Reference(pages_id),+ });+ doc.trailer.set("Root", cat);+ let handle = next_handle();+ registry().lock().unwrap_or_else(|e| e.into_inner()).insert(handle, doc);++ let aid = add_free_text(handle, 0, [40.0, 60.0, 200.0, 100.0], 0xFF00_0000, 12.0, "before")+ .expect("annotation added");+ let before = ap_box(handle, aid);+ assert!(update_free_text(handle, aid, "after"), "rot={rot}: update failed");+ let after = ap_box(handle, aid);+ assert_eq!(after, before, "rot={rot}: the appearance box/matrix changed");+ close_document(handle);+ }+ }++ /// The `/AP /N` stream's `/BBox` extents and `/Matrix`, rounded so the f32+ /// round-trip through `Object::Real` compares cleanly.+ fn ap_box(handle: i64, annot_id: i64) -> ([i64; 2], [i64; 6]) {+ let reg = registry().lock().unwrap_or_else(|e| e.into_inner());+ let doc = reg.get(&handle).expect("handle is registered");+ let dict = doc.get_dictionary(decode_id(annot_id)).expect("annot");+ let ap = dict+ .get(b"AP")+ .ok()+ .and_then(|o| deref(doc, o))+ .and_then(|o| o.as_dict().ok())+ .and_then(|d| d.get(b"N").ok())+ .and_then(|o| deref(doc, o))+ .and_then(|o| o.as_stream().ok())+ .expect("/AP /N stream");+ let bb = normalize_rect(+ ap.dict.get(b"BBox").ok().and_then(|o| read_rect(doc, o)).expect("/BBox"),+ );+ let m = ap.dict.get(b"Matrix").ok().and_then(read_matrix_obj).unwrap_or(IDENTITY);+ (+ [(bb[2] - bb[0]).round() as i64, (bb[3] - bb[1]).round() as i64],+ [+ m[0].round() as i64, m[1].round() as i64, m[2].round() as i64,+ m[3].round() as i64, m[4].round() as i64, m[5].round() as i64,+ ],+ )+ }+ #[test] fn stamp_names_split_into_words() { assert_eq!(stamp_label(b"Approved"), "APPROVED");
pdf/src/main/rust/src/color.rs
diff --git a/pdf/src/main/rust/src/color.rs b/pdf/src/main/rust/src/color.rsindex 5481431c11..bc4d6979a4 100644--- a/pdf/src/main/rust/src/color.rs+++ b/pdf/src/main/rust/src/color.rs@@ -202,7 +202,7 @@ fn parse_cs_array_at(doc: &Document, arr: &[Object], cs_resources: &HashMap<Vec< let dict = arr.get(1).and_then(|o| deref(doc, o)).and_then(|o| o.as_dict().ok()); if let Some(d) = dict { let white = read_white_point(d).unwrap_or([0.9505,1.0,1.0890]);- let gamma = d.get(b"Gamma").ok().and_then(num).unwrap_or(1.0);+ let gamma = d.get(b"Gamma").ok().and_then(num).filter(|g| g.is_finite()).unwrap_or(1.0); Some(CsKind::CalGray { white, gamma }) } else { Some(CsKind::DeviceGray)@@ -350,17 +350,36 @@ pub(crate) fn cs_kind_default_decode(kind: &CsKind) -> Vec<(f64, f64)> { } } +/// The Cal*/Lab dictionary readers below all feed `.unwrap_or(<spec default>)` at their+/// call sites, so rejecting a malformed entry makes it mean exactly what an ABSENT one+/// means. That matters for NON-FINITE values specifically: a real like 1e40 overflows+/// the f32 `Object::Real` holds, and an infinite /WhitePoint or /Matrix propagates+/// through `adapt_to_d65` (inf/inf) into NaN, which `rgb_to_argb` saturates to 0 — a+/// CalRGB image rendering as a solid black rectangle. Falling back to the default+/// renders the picture instead.+fn all_finite(v: &[f64]) -> bool {+ v.iter().all(|x| x.is_finite())+}+ pub(crate) fn read_white_point(dict: &lopdf::Dictionary) -> Option<[f64;3]> { let arr = dict.get(b"WhitePoint").ok().and_then(|o| o.as_array().ok())?; if arr.len()>=3 {- Some([num(&arr[0])?, num(&arr[1])?, num(&arr[2])?])+ let wp = [num(&arr[0])?, num(&arr[1])?, num(&arr[2])?];+ // A zero or negative Y also breaks the adaptation; §8.6.5.2 requires X and Z+ // positive and Y exactly 1.+ if all_finite(&wp) && wp[0] > 0.0 && wp[1] > 0.0 && wp[2] > 0.0 {+ Some(wp)+ } else {+ None+ } } else { None } } pub(crate) fn read_gamma_rgb(dict: &lopdf::Dictionary) -> Option<[f64;3]> { let arr = dict.get(b"Gamma").ok().and_then(|o| o.as_array().ok())?; if arr.len()>=3 {- Some([num(&arr[0])?, num(&arr[1])?, num(&arr[2])?])+ let g = [num(&arr[0])?, num(&arr[1])?, num(&arr[2])?];+ if all_finite(&g) { Some(g) } else { None } } else { None } } @@ -374,18 +393,22 @@ pub(crate) fn read_matrix_cal(dict: &lopdf::Dictionary) -> Option<[[f64;3];3]> { // [[XA XB XC],[YA YB YC],[ZA ZB ZC]] (i.e. transposed from the array // order). Storing it in raw array order transposes the transform and // turns e.g. CalRGB white into cyan (issue #321 colorrenderexample).- Some([+ let m = [ [num(&arr[0])?, num(&arr[3])?, num(&arr[6])?], [num(&arr[1])?, num(&arr[4])?, num(&arr[7])?], [num(&arr[2])?, num(&arr[5])?, num(&arr[8])?],- ])+ ];+ if m.iter().all(|row| all_finite(row)) { Some(m) } else { None } } else { None } } pub(crate) fn read_lab_range(dict: &lopdf::Dictionary) -> Option<[[f64;2];2]> { let arr = dict.get(b"Range").ok().and_then(|o| o.as_array().ok())?; if arr.len()>=4 {- Some([[num(&arr[0])?, num(&arr[1])?],[num(&arr[2])?, num(&arr[3])?]])+ let r = [num(&arr[0])?, num(&arr[1])?, num(&arr[2])?, num(&arr[3])?];+ // /Range also seeds the default /Decode for a Lab image (§8.9.5.2 Table 90),+ // so a non-finite bound would scale every sample to NaN.+ if all_finite(&r) { Some([[r[0], r[1]],[r[2], r[3]]]) } else { None } } else { None } } @@ -769,6 +792,7 @@ mod tests { alt: Box::new(CsKind::DeviceRGB), tint_fn: Some(PdfFunction::Exponential { domain: [0.0, 1.0],+ range: Vec::new(), c0: vec![0.0, 0.0, 0.0], c1: vec![1.0, 0.0, 0.0], n: 1.0,@@ -813,6 +837,7 @@ mod tests { alt: Box::new(CsKind::DeviceCMYK), tint_fn: Some(PdfFunction::Exponential { domain: [0.0, 1.0],+ range: Vec::new(), c0: vec![0.0], c1: vec![1.0], n: 1.0,@@ -1003,4 +1028,57 @@ mod tests { assert_eq!(base_n, 3); assert_eq!(palette, vec![0x00, 0x00, 0xFF], "palette must be decoded"); }++ // A malformed Cal*/Lab entry must mean exactly what an ABSENT one means — the spec+ // default — not propagate into the conversion. A real like 1e40 overflows the f32+ // `Object::Real` holds, and an infinite /WhitePoint reaches `adapt_to_d65` where+ // inf/inf is NaN; `rgb_to_argb` saturates NaN to 0, so a CalRGB image rendered as a+ // solid BLACK rectangle. (Same class as the non-finite path operands and shading+ // matrices found this round, on the colour side.)+ #[test]+ fn non_finite_cal_entries_fall_back_to_the_spec_defaults() {+ use lopdf::dictionary;+ let inf = Object::Real(f32::INFINITY);+ let bad_wp = dictionary! {+ "WhitePoint" => vec![inf.clone(), Object::Real(1.0), Object::Real(1.089)]+ };+ assert!(read_white_point(&bad_wp).is_none(), "non-finite /WhitePoint is refused");+ // A zero component breaks the adaptation just as badly.+ let zero_wp = dictionary! {+ "WhitePoint" => vec![Object::Real(0.0), Object::Real(1.0), Object::Real(1.089)]+ };+ assert!(read_white_point(&zero_wp).is_none(), "a zero /WhitePoint component is refused");+ let good_wp = dictionary! {+ "WhitePoint" => vec![Object::Real(0.9505), Object::Real(1.0), Object::Real(1.089)]+ };+ assert!(read_white_point(&good_wp).is_some(), "a sane /WhitePoint still reads");++ assert!(read_gamma_rgb(&dictionary! {+ "Gamma" => vec![inf.clone(), Object::Real(1.0), Object::Real(1.0)]+ }).is_none());+ assert!(read_lab_range(&dictionary! {+ "Range" => vec![Object::Real(-100.0), inf.clone(), Object::Real(-100.0), Object::Real(100.0)]+ }).is_none());+ let mut m: Vec<Object> = (0..9).map(|_| Object::Real(1.0)).collect();+ m[4] = inf;+ assert!(read_matrix_cal(&dictionary! { "Matrix" => m }).is_none());++ // End to end: a CalRGB space whose /WhitePoint overflowed must still render a+ // recognisable colour rather than collapsing to black.+ let doc = Document::with_version("1.7");+ let arr = vec![+ Object::Name(b"CalRGB".to_vec()),+ Object::Dictionary(dictionary! {+ "WhitePoint" => vec![Object::Real(f32::INFINITY), Object::Real(1.0), Object::Real(1.089)]+ }),+ ];+ let empty = HashMap::new();+ let kind = parse_cs_array_at(&doc, &arr, &empty, 0).expect("calrgb");+ let white = eval_cs_to_rgb(&doc, &kind, &[1.0, 1.0, 1.0], &empty).unwrap();+ assert!(+ (white & 0xFF) > 200,+ "CalRGB white must stay light, got {:#010X} - a NaN whitepoint renders black",+ white+ );+ } }
pdf/src/main/rust/src/crypto.rs
diff --git a/pdf/src/main/rust/src/crypto.rs b/pdf/src/main/rust/src/crypto.rsindex 6ae80a9b97..afdbb3e295 100644--- a/pdf/src/main/rust/src/crypto.rs+++ b/pdf/src/main/rust/src/crypto.rs@@ -388,6 +388,11 @@ pub fn authenticate_v5_owner(pw: &[u8], o: &[u8], oe: &[u8], u: &[u8], rev: u8) } let o_val_salt = &o[32..40]; let o_key_salt = &o[40..48];+ // ISO 32000-2 algorithm 12/13 concatenate the 48-BYTE /U string, not however many+ // bytes the file happened to put there. `u` is untrusted: algorithm 2.B repeats+ // (password || K || udata) 64 times per round for at least 64 rounds, so a 10 MB+ // /U turns one password check into tens of gigabytes of AES.+ let u = &u[..48]; // Owner validation hash: hash(owner_pw + oValSalt + U) let check = if rev >= 6 { hash_2b(pw, o_val_salt, u)?@@ -467,4 +472,33 @@ mod tests { let enc = aes_cbc_encrypt(&[7u8; 16], &iv, b"secret payload").expect("encrypt"); assert_eq!(aes_cbc_decrypt(&[8u8; 16], &enc), Err(CbcError::BadPadding)); }++ /// ISO 32000-2 algorithms 12/13 hash exactly the 48-byte /U string. A longer /U is+ /// untrusted input to algorithm 2.B, which repeats it 64 times per round for at+ /// least 64 rounds - so honouring the file's length turns one password check into+ /// tens of gigabytes of AES.+ #[test]+ fn owner_authentication_uses_only_the_48_byte_u_string() {+ let file_key = [0x5Au8; 32];+ let salts: [[u8; 8]; 4] = [[1; 8], [2; 8], [3; 8], [4; 8]];+ for rev in [5u8, 6u8] {+ let (u, _ue, o, oe) =+ compute_v5(b"user", b"owner", &file_key, &salts, rev).expect("entries");+ assert_eq!(u.len(), 48);+ assert_eq!(+ authenticate_v5_owner(b"owner", &o, &oe, &u, rev),+ Some(file_key.to_vec()),+ "R{rev} owner password must recover the file key"+ );+ // Trailing junk past the 48 bytes must be ignored, not hashed.+ let mut padded = u.clone();+ padded.extend(std::iter::repeat_n(0xAAu8, 4096));+ assert_eq!(+ authenticate_v5_owner(b"owner", &o, &oe, &padded, rev),+ Some(file_key.to_vec()),+ "only /U[0..48] is part of the hash"+ );+ assert!(authenticate_v5_owner(b"wrong", &o, &oe, &u, rev).is_none());+ }+ } }
pdf/src/main/rust/src/decrypt.rs
diff --git a/pdf/src/main/rust/src/decrypt.rs b/pdf/src/main/rust/src/decrypt.rsindex 07b4b346b4..69a106ea13 100644--- a/pdf/src/main/rust/src/decrypt.rs+++ b/pdf/src/main/rust/src/decrypt.rs@@ -36,18 +36,35 @@ pub(crate) enum DecryptStatus { /// Apply a cipher (`apply`) to every string and stream inside `obj`. pub(crate) fn crypt_object(obj: &mut Object, apply: &dyn Fn(&[u8]) -> Vec<u8>) {+ crypt_object_split(obj, Some(apply), Some(apply));+}++/// Apply `strings` to every string and `streams` to every stream body inside `obj`.+///+/// §7.6.5 gives streams and strings SEPARATE crypt filters (`/StmF`, `/StrF`), and+/// either may be `/Identity`, so the two cannot share one transform. `None` leaves+/// that class of data untouched.+fn crypt_object_split(+ obj: &mut Object,+ strings: Option<&dyn Fn(&[u8]) -> Vec<u8>>,+ streams: Option<&dyn Fn(&[u8]) -> Vec<u8>>,+) { match obj {- Object::String(s, _) => *s = apply(s),+ Object::String(s, _) => {+ if let Some(apply) = strings {+ *s = apply(s);+ }+ } Object::Array(a) => { for o in a.iter_mut() {- crypt_object(o, apply);+ crypt_object_split(o, strings, streams); } } Object::Dictionary(d) => { let keys: Vec<Vec<u8>> = d.iter().map(|(k, _)| k.clone()).collect(); for k in keys { if let Ok(v) = d.get_mut(&k) {- crypt_object(v, apply);+ crypt_object_split(v, strings, streams); } } }@@ -55,10 +72,12 @@ pub(crate) fn crypt_object(obj: &mut Object, apply: &dyn Fn(&[u8]) -> Vec<u8>) { let keys: Vec<Vec<u8>> = st.dict.iter().map(|(k, _)| k.clone()).collect(); for k in keys { if let Ok(v) = st.dict.get_mut(&k) {- crypt_object(v, apply);+ crypt_object_split(v, strings, streams); } }- st.content = apply(&st.content);+ if let Some(apply) = streams {+ st.content = apply(&st.content);+ } } _ => {} }@@ -104,6 +123,72 @@ pub(crate) enum CryptMethod { AesV3, } +/// §7.6.5: resolve a `/StmF` or `/StrF` crypt-filter NAME to the method it selects.+///+/// `None` means the data shall NOT be decrypted. `/Identity` is the reserved filter+/// name for exactly that (Table 20, and it is the DEFAULT for both keys), and+/// `/CFM /None` says the same at the filter itself (Table 25). Running the file's+/// cipher over data a crypt filter declared unencrypted turns plaintext into noise+/// for the whole document, which is why the two cases are worth separating.+///+/// A name that resolves to no readable `/CFM` falls back to `default`, so a file that+/// never mentions `/Identity` takes exactly the path it took before.+fn crypt_filter_method(+ cf: Option<&Dictionary>,+ name: &[u8],+ default: CryptMethod,+) -> Option<CryptMethod> {+ if name == b"Identity" {+ return None;+ }+ let cfm = cf+ .and_then(|d| d.get(name).ok())+ .and_then(|o| o.as_dict().ok())+ .and_then(|d| d.get(b"CFM").ok())+ .and_then(|o| o.as_name().ok());+ match cfm {+ Some(m) if m == b"None" => None,+ Some(m) if m == b"AESV3" => Some(CryptMethod::AesV3),+ Some(m) if m == b"AESV2" => Some(CryptMethod::AesV2),+ Some(m) if m == b"V2" => Some(CryptMethod::Rc4),+ _ => Some(default),+ }+}++/// The `/P` permission flags as the 32-BIT quantity §7.6.3.3 Algorithm 2 step (d)+/// feeds to the key hash.+///+/// Producers write the same bit pattern either signed (`-3904`) or unsigned+/// (`4294963392`); both are the same four bytes and Acrobat reads them identically.+/// Going through `f64 as i32` SATURATES the unsigned form to `2147483647`, which+/// hashes four wrong bytes and rejects a correct password on a file that opens+/// everywhere else. Truncating to 32 bits reads both forms the same.+fn permissions_p(enc: &Dictionary) -> i32 {+ enc.get(b"P")+ .ok()+ .and_then(|o| o.as_i64().ok().or_else(|| num(o).map(|v| v as i64)))+ .unwrap_or(0) as u32 as i32+}++/// The per-object transform for one object under `method`.+fn object_cipher(method: CryptMethod, key: &[u8], id: ObjectId, n: usize) -> CryptFn {+ match method {+ CryptMethod::Rc4 => {+ let okey = crypto::object_key(key, id.0, id.1, n);+ Box::new(move |d: &[u8]| crypto::rc4(&okey, d))+ }+ CryptMethod::AesV2 => {+ let okey = crypto::object_key_aes(key, id.0, id.1, n);+ Box::new(move |d: &[u8]| crypto::aes_cbc_decrypt(&okey, d).unwrap_or_default())+ }+ // §7.6.5.3: AESV3 uses the file encryption key directly, with no per-object key.+ CryptMethod::AesV3 => {+ let k = key.to_vec();+ Box::new(move |d: &[u8]| crypto::aes_cbc_decrypt(&k, d).unwrap_or_default())+ }+ }+}+ /// Decrypt a standard-encrypted document (RC4 or AES) in place with `password`. /// /// Tries lopdf's own standard-security-handler first. That matters for correctness, not@@ -146,7 +231,7 @@ fn decrypt_in_place_fallback(doc: &mut Document, password: &[u8]) -> DecryptStat Ok(id) => id, Err(_) => return DecryptStatus::Unsupported, };- let (o, u, ue, oe, p, r, length, method, encrypt_metadata, _cf_dict_opt) = {+ let (o, u, ue, oe, p, r, length, method, encrypt_metadata, stm_method, str_method) = { let enc = match doc.get_dictionary(enc_id) { Ok(d) => d, Err(_) => return DecryptStatus::Unsupported,@@ -224,13 +309,36 @@ fn decrypt_in_place_fallback(doc: &mut Document, password: &[u8]) -> DecryptStat let ue = enc.get(b"UE").ok().and_then(|o| o.as_str().ok()).map(|s| s.to_vec()).unwrap_or_default(); let oe = enc.get(b"OE").ok().and_then(|o| o.as_str().ok()).map(|s| s.to_vec()).unwrap_or_default(); // Preserve CF dict for later StmF/StrF handling? We already parsed method but for auth need OE for owner- let p = enc.get(b"P").ok().and_then(num).unwrap_or(0.0) as i32;+ // §7.6.3.3 Algorithm 2 step (d) hashes /P as a 32-BIT quantity.+ let p = permissions_p(enc); let default_len = if method == CryptMethod::AesV2 { 128.0 } else { 40.0 }; let length = enc.get(b"Length").ok().and_then(num).unwrap_or(default_len) as usize; // §7.6.3.3 Algorithm 2 step (f): with /EncryptMetadata false and R >= 4 the key // derivation takes four extra 0xFF bytes. Default true. let encrypt_metadata = !matches!(enc.get(b"EncryptMetadata"), Ok(Object::Boolean(false)));- (o, u, ue, oe, p, r, length, method, encrypt_metadata, cf_dict_opt)+ // §7.6.5 Table 20: /StmF and /StrF name the crypt filters for STREAMS and+ // STRINGS separately, and either may be /Identity. `method` above still drives+ // key derivation and authentication - only what gets transformed changes.+ let (stm_method, str_method) = if v >= 4 {+ let cf = cf_dict_opt.as_ref();+ let stm_name = enc+ .get(b"StmF")+ .ok()+ .and_then(|o| o.as_name().ok())+ .unwrap_or(b"StdCF");+ let str_name = enc+ .get(b"StrF")+ .ok()+ .and_then(|o| o.as_name().ok())+ .unwrap_or(b"StdCF");+ (+ crypt_filter_method(cf, stm_name, method),+ crypt_filter_method(cf, str_name, method),+ )+ } else {+ (Some(method), Some(method))+ };+ (o, u, ue, oe, p, r, length, method, encrypt_metadata, stm_method, str_method) }; let id0 = trailer_id0(doc);@@ -294,22 +402,14 @@ fn decrypt_in_place_fallback(doc: &mut Document, password: &[u8]) -> DecryptStat if is_xref_stream { continue; }- let apply: CryptFn = match method {- CryptMethod::Rc4 => {- let okey = crypto::object_key(&key, id.0, id.1, n);- Box::new(move |d: &[u8]| crypto::rc4(&okey, d))- }- CryptMethod::AesV2 => {- let okey = crypto::object_key_aes(&key, id.0, id.1, n);- Box::new(move |d: &[u8]| crypto::aes_cbc_decrypt(&okey, d).unwrap_or_default())- }- CryptMethod::AesV3 => {- let k = key.clone();- Box::new(move |d: &[u8]| crypto::aes_cbc_decrypt(&k, d).unwrap_or_default())- }- };+ let str_apply = str_method.map(|m| object_cipher(m, &key, id, n));+ let stm_apply = stm_method.map(|m| object_cipher(m, &key, id, n)); if let Some(obj) = doc.objects.get_mut(&id) {- crypt_object(obj, &apply);+ crypt_object_split(+ obj,+ str_apply.as_ref().map(|f| f.as_ref() as &dyn Fn(&[u8]) -> Vec<u8>),+ stm_apply.as_ref().map(|f| f.as_ref() as &dyn Fn(&[u8]) -> Vec<u8>),+ ); } } expand_object_streams(doc);@@ -527,3 +627,110 @@ pub(crate) fn encrypt_doc_bytes( doc.save_to(&mut out).ok()?; Some(out) }++#[cfg(test)]+mod tests {+ use super::*;++ /// §7.6.3.3 Algorithm 2 step (d): /P is hashed as 32 bits, so the signed and+ /// unsigned spellings of the same flags must derive the same file key.+ #[test]+ fn permissions_p_reads_both_spellings_of_the_same_flags() {+ let signed = dictionary! { "P" => Object::Integer(-3904) };+ let unsigned = dictionary! { "P" => Object::Integer(4_294_963_392) };+ assert_eq!(permissions_p(&signed), -3904);+ assert_eq!(+ permissions_p(&unsigned),+ -3904,+ "the unsigned spelling is the same 32 bits, not i32::MAX"+ );+ // The four bytes Algorithm 2 actually hashes.+ assert_eq!(+ (permissions_p(&unsigned) as u32).to_le_bytes(),+ (permissions_p(&signed) as u32).to_le_bytes()+ );+ // A missing /P still reads as zero rather than panicking.+ assert_eq!(permissions_p(&Dictionary::new()), 0);+ }++ /// §7.6.5 Table 20: /Identity is the reserved crypt-filter name for data that is+ /// NOT encrypted, and Table 25 gives /CFM /None the same meaning. Decrypting+ /// either turns plaintext into noise for the whole document.+ #[test]+ fn identity_crypt_filters_select_no_cipher() {+ let mut cf = Dictionary::new();+ cf.set("StdCF", dictionary! { "CFM" => name_obj("AESV2") });+ cf.set("NoneCF", dictionary! { "CFM" => name_obj("None") });+ cf.set("Rc4CF", dictionary! { "CFM" => name_obj("V2") });+ let cf = Some(&cf);++ assert!(crypt_filter_method(cf, b"Identity", CryptMethod::AesV2).is_none());+ assert!(crypt_filter_method(cf, b"NoneCF", CryptMethod::AesV2).is_none());+ assert!(matches!(+ crypt_filter_method(cf, b"StdCF", CryptMethod::Rc4),+ Some(CryptMethod::AesV2)+ ));+ // A crypt filter may differ from the default: /StmF and /StrF are independent.+ assert!(matches!(+ crypt_filter_method(cf, b"Rc4CF", CryptMethod::AesV2),+ Some(CryptMethod::Rc4)+ ));+ // An unresolvable name keeps the previous behaviour: fall back to the default,+ // so no file that never mentions /Identity changes path.+ assert!(matches!(+ crypt_filter_method(cf, b"MissingCF", CryptMethod::AesV3),+ Some(CryptMethod::AesV3)+ ));+ assert!(matches!(+ crypt_filter_method(None, b"StdCF", CryptMethod::Rc4),+ Some(CryptMethod::Rc4)+ ));+ }++ /// §7.6.5: streams and strings have SEPARATE crypt filters, so one of them being+ /// /Identity must not stop the other being decrypted - and must not decrypt it.+ #[test]+ fn a_stream_identity_filter_leaves_the_body_but_not_the_strings() {+ let flip = |d: &[u8]| d.iter().map(|b| b ^ 0xFF).collect::<Vec<u8>>();+ let mut obj = Object::Stream(Stream::new(+ dictionary! { "Author" => Object::String(b"abc".to_vec(), lopdf::StringFormat::Literal) },+ b"body".to_vec(),+ ));+ crypt_object_split(&mut obj, Some(&flip), None);+ let Object::Stream(s) = &obj else { panic!("expected a stream") };+ assert_eq!(s.content, b"body", "an /Identity /StmF must not touch the body");+ let Ok(Object::String(a, _)) = s.dict.get(b"Author") else {+ panic!("expected a string")+ };+ assert_eq!(a, &flip(b"abc"), "/StrF still applies to the dictionary strings");++ // And the mirror case: /StrF /Identity with a real /StmF.+ let mut obj = Object::Stream(Stream::new(+ dictionary! { "Author" => Object::String(b"abc".to_vec(), lopdf::StringFormat::Literal) },+ b"body".to_vec(),+ ));+ crypt_object_split(&mut obj, None, Some(&flip));+ let Object::Stream(s) = &obj else { panic!("expected a stream") };+ assert_eq!(s.content, flip(b"body"));+ let Ok(Object::String(a, _)) = s.dict.get(b"Author") else {+ panic!("expected a string")+ };+ assert_eq!(a, b"abc", "an /Identity /StrF must not touch the strings");+ }++ /// `crypt_object` (the encrypt-on-save path) must keep applying one transform to+ /// both, unchanged by the split above.+ #[test]+ fn crypt_object_still_applies_to_strings_and_streams_alike() {+ let flip = |d: &[u8]| d.iter().map(|b| b ^ 0xFF).collect::<Vec<u8>>();+ let mut obj = Object::Array(vec![+ Object::String(b"s".to_vec(), lopdf::StringFormat::Literal),+ Object::Stream(Stream::new(Dictionary::new(), b"c".to_vec())),+ ]);+ crypt_object(&mut obj, &flip);+ let Object::Array(a) = &obj else { panic!() };+ assert_eq!(a[0], Object::String(flip(b"s"), lopdf::StringFormat::Literal));+ let Object::Stream(s) = &a[1] else { panic!() };+ assert_eq!(s.content, flip(b"c"));+ }+}
pdf/src/main/rust/src/docedit.rs
diff --git a/pdf/src/main/rust/src/docedit.rs b/pdf/src/main/rust/src/docedit.rsindex b781a5f470..00476caeea 100644--- a/pdf/src/main/rust/src/docedit.rs+++ b/pdf/src/main/rust/src/docedit.rs@@ -553,7 +553,15 @@ pub(crate) fn flatten_document(handle: i64) -> bool { } None => continue, };- let m = appearance_matrix(rect, bbox, matrix);+ // §12.5.5 computes AA = Matrix x A, but AA is for a caller that plays+ // the appearance's operators itself. This bakes the appearance as a+ // `cm ... Do`, and §8.10.2 makes `Do` concatenate the form's own+ // /Matrix with the CTM — so emitting AA applies /Matrix TWICE. Only+ // the fit matrix A belongs in the `cm`. Every appearance this app+ // authors for a rotated page carries a /Matrix (see+ // `display_orientation`), so flattening one used to rotate it a+ // second time and translate it clean off its /Rect.+ let m = appearance_fit_matrix(rect, bbox, matrix); placements.push((format!("Fl{}_{}", page_id.0, i), ap_id, m)); } if placements.is_empty() {@@ -895,6 +903,96 @@ mod redaction_tests { doc.get_dictionary(annot_id).is_ok() } + /// §8.10.2: `Do` concatenates the invoked form's own `/Matrix` with the CTM.+ /// §12.5.5's `AA = Matrix × A` already contains `/Matrix`, so baking an+ /// appearance as `cm AA ... Do` applies it TWICE. Every appearance this app+ /// authors for a rotated page carries a `/Matrix` (`display_orientation`), so+ /// flattening one rotated it again and translated it clean off its `/Rect`.+ /// The emitted `cm` must be `A`, i.e. `Matrix × cm` must map the `/BBox` onto+ /// the `/Rect`.+ #[test]+ fn flatten_emits_the_fit_matrix_not_the_one_do_will_double() {+ let (dw, dh) = (160.0_f64, 40.0_f64);+ let bbox = [0.0, 0.0, dw, dh];+ for rot in [0i64, 90, 180, 270] {+ let (_, _, apm) = display_orientation(rot, dw, dh);+ let rect = match rot {+ 90 | 270 => [10.0, 20.0, 10.0 + dh, 20.0 + dw],+ _ => [10.0, 20.0, 10.0 + dw, 20.0 + dh],+ };+ let (handle, page_id) = flattenable_doc(rect, bbox, apm);+ assert!(flatten_document(handle), "rot={rot}: flatten failed");+ let cm = emitted_cm(handle, page_id);+ // What the renderer will build: the form's /Matrix on top of the `cm`.+ let effective = mat_mul(&apm, &cm);+ for (x, y) in [(0.0, 0.0), (dw, 0.0), (dw, dh), (0.0, dh)] {+ let (px, py) = transform(&effective, x, y);+ assert!(+ px >= rect[0] - 0.01 && px <= rect[2] + 0.01+ && py >= rect[1] - 0.01 && py <= rect[3] + 0.01,+ "rot={rot}: flattened BBox corner ({px},{py}) landed outside {rect:?}"+ );+ }+ close_document(handle);+ }+ }++ /// One-page document carrying a single annotation whose `/AP /N` has the+ /// given `/BBox` and `/Matrix`.+ fn flattenable_doc(rect: [f64; 4], bbox: [f64; 4], matrix: Mat) -> (i64, ObjectId) {+ let mut doc = Document::with_version("1.7");+ let ap_dict = dictionary! {+ "Type" => name_obj("XObject"),+ "Subtype" => name_obj("Form"),+ "BBox" => rect_obj(bbox),+ "Matrix" => Object::Array(matrix.iter().map(|v| Object::Real(*v as f32)).collect()),+ };+ let ap_id = doc.add_object(Stream::new(ap_dict, b"0 0 1 rg 0 0 1 1 re f".to_vec()));+ let annot_id = doc.add_object(dictionary! {+ "Type" => name_obj("Annot"),+ "Subtype" => name_obj("FreeText"),+ "Rect" => rect_obj(rect),+ "AP" => dictionary! { "N" => ap_id },+ });+ let pages_id = doc.new_object_id();+ let page_id = doc.add_object(dictionary! {+ "Type" => name_obj("Page"),+ "Parent" => Object::Reference(pages_id),+ "MediaBox" => rect_obj([0.0, 0.0, 612.0, 792.0]),+ "Annots" => Object::Array(vec![Object::Reference(annot_id)]),+ });+ doc.objects.insert(+ pages_id,+ Object::Dictionary(dictionary! {+ "Type" => name_obj("Pages"),+ "Kids" => Object::Array(vec![Object::Reference(page_id)]),+ "Count" => 1,+ }),+ );+ let cat = doc.add_object(dictionary! {+ "Type" => name_obj("Catalog"),+ "Pages" => Object::Reference(pages_id),+ });+ doc.trailer.set("Root", cat);+ let handle = next_handle();+ registry().lock().unwrap_or_else(|e| e.into_inner()).insert(handle, doc);+ (handle, page_id)+ }++ /// The six operands of the single `cm` the flatten overlay emitted.+ fn emitted_cm(handle: i64, page_id: ObjectId) -> Mat {+ let bytes = page_bytes(handle, page_id);+ let text = String::from_utf8_lossy(&bytes).into_owned();+ let toks: Vec<&str> = text.split_whitespace().collect();+ let at = toks.iter().position(|t| *t == "cm").expect("no `cm` in the flattened content");+ assert!(at >= 6, "malformed `cm`: {text}");+ let mut m = IDENTITY;+ for i in 0..6 {+ m[i] = toks[at - 6 + i].parse::<f64>().expect("cm operand");+ }+ m+ }+ /// An inline image makes lopdf reject the whole stream, and the lenient tokenizer /// cannot promise it saw every text-show operator. Redacting anyway would cover the /// text with black, drop the annotation and still ship the text inside the file, so
pdf/src/main/rust/src/draw.rs
diff --git a/pdf/src/main/rust/src/draw.rs b/pdf/src/main/rust/src/draw.rsindex 029632dbbe..d04093580b 100644--- a/pdf/src/main/rust/src/draw.rs+++ b/pdf/src/main/rust/src/draw.rs@@ -45,7 +45,32 @@ pub(crate) fn emit_stroke(prims: &mut Vec<Prim>, subpaths: &[Vec<(f64, f64)>], g // == dst` turned white knockout rectangles into no-ops and let content that // was meant to be covered show through. let blend = gs.blend_mode;+ // §8.5.3.2: "If a subpath is degenerate (consists of a single-point closed+ // subpath or of two or more points at the same coordinates), S shall paint it+ // only if round line caps have been specified, producing a filled circle+ // centred at the single point. If butt or projecting square line caps have+ // been specified, S shall paint nothing." A single-point subpath (`x y m S`,+ // or `x y m h S` once `h` drops the duplicate) never reached the renderer at+ // all, so the dot idiom used for stippled leader lines and map symbols+ // vanished. The circle is emitted directly rather than left to the renderer's+ // stroker, because what the spec asks for here is a fill, not a stroke.+ let dot_radius = (width as f64 / 2.0).max(0.05); for sp in subpaths {+ if sp.is_empty() { continue; }+ let (fx, fy) = sp[0];+ if sp.iter().all(|&(x, y)| (x - fx).abs() < 1e-9 && (y - fy).abs() < 1e-9) {+ if gs.line_cap == 1 {+ const DOT_SEGMENTS: usize = 16;+ let circle: Vec<(f32, f32)> = (0..DOT_SEGMENTS)+ .map(|i| {+ let a = i as f64 / DOT_SEGMENTS as f64 * std::f64::consts::TAU;+ ((fx + dot_radius * a.cos()) as f32, (fy + dot_radius * a.sin()) as f32)+ })+ .collect();+ prims.push(Prim::Fill { argb, even_odd: false, contours: vec![circle], blend });+ }+ continue;+ } if sp.len() >= 2 { prims.push(Prim::Stroke { argb,@@ -77,15 +102,38 @@ pub(crate) fn emit_fill(prims: &mut Vec<Prim>, subpaths: &[Vec<(f64, f64)>], arg } } -/// Emit a text primitive for `bytes` at the current text matrix (unless the-/// render mode is invisible/clip-only) and return the horizontal advance in-/// user-space units so the caller can step the text matrix.+/// Show `bytes` with no ambient resource dictionary — see [`show_string_in`],+/// which is what the interpreter calls.+///+/// `#[cfg(test)]` because the only remaining callers are test modules (here,+/// `golden_tests.rs` and `tests.rs`). It is kept rather than folded into them so+/// those files, which belong to other owners, did not have to change when+/// §9.6.5's Type 3 resource fallback added the `ambient_resources` parameter.+#[cfg(test)]+pub(crate) fn show_string(+ doc: &Document,+ prims: &mut Vec<Prim>,+ gs: &GraphicsState,+ fonts: &HashMap<Vec<u8>, FontInfo>,+ text_matrix: &Mat,+ bytes: &[u8],+ depth: u32,+) -> f64 {+ show_string_in(doc, prims, gs, fonts, text_matrix, bytes, depth, None)+}+ /// Emit one text primitive per glyph, each positioned at its exact device-space /// origin computed from the PDF glyph widths + text state. Drawing glyph-by-glyph /// (rather than one run) keeps kerned/justified text aligned even though a /// substitute system font renders the glyph shapes. Returns the total advance in /// text space so the caller can step the text matrix.-pub(crate) fn show_string(+///+/// `ambient_resources` is the resource dictionary in force at the showing+/// operator. Only Type 3 needs it: §9.6.5 makes a Type 3 font's own `/Resources`+/// optional and says the names "shall be looked up in the resource dictionary of+/// the page on which the font is used" when it is absent.+#[allow(clippy::too_many_arguments)]+pub(crate) fn show_string_in( doc: &Document, prims: &mut Vec<Prim>, gs: &GraphicsState,@@ -93,6 +141,7 @@ pub(crate) fn show_string( text_matrix: &Mat, bytes: &[u8], depth: u32,+ ambient_resources: Option<&lopdf::Dictionary>, ) -> f64 { let tfs = gs.font_size; let th = gs.h_scale;@@ -143,7 +192,7 @@ pub(crate) fn show_string( // Type 3 fonts: draw each glyph by interpreting its CharProc content stream. if let Some(t3) = &fi.t3 {- return show_string_type3(doc, prims, gs, fi, t3, text_matrix, bytes, depth);+ return show_string_type3(doc, prims, gs, fi, t3, text_matrix, bytes, depth, ambient_resources); } let mut pen = 0.0_f64;@@ -395,6 +444,7 @@ fn push_closers(prims: &mut Vec<Prim>, mut open: Vec<bool>) { /// Render a Type 3 text run by interpreting each glyph's CharProc content stream /// into the current graphics state. Returns the total text-space advance.+#[allow(clippy::too_many_arguments)] fn show_string_type3( doc: &Document, prims: &mut Vec<Prim>,@@ -404,6 +454,7 @@ fn show_string_type3( text_matrix: &Mat, bytes: &[u8], depth: u32,+ ambient_resources: Option<&lopdf::Dictionary>, ) -> f64 { let tfs = gs.font_size; let th = gs.h_scale;@@ -442,7 +493,15 @@ fn show_string_type3( interpret_content( doc, &glyph_ops,- t3.resources.as_ref(),+ // §9.6.5: the Type 3 `/Resources` entry is optional, and+ // "if any glyph descriptions refer to named resources but+ // this dictionary is absent, the names shall be looked up+ // in the resource dictionary of the page on which the font+ // is used". Passing `None` instead made a CharProc that+ // does `/Im0 Do`, `/GS0 gs` or `/Sh0 sh` against the page's+ // resources draw nothing at all — common in TeX/dvips+ // output, which routinely omits the font's own /Resources.+ t3.resources.as_ref().or(ambient_resources), glyph_gs, prims, depth + 1,@@ -586,6 +645,135 @@ fn show_string_type3( // Image XObjects // --------------------------------------------------------------------------- +#[cfg(test)]+mod type3_resource_fallback_tests {+ use crate::*;+ use lopdf::content::Operation;+ use lopdf::{dictionary, Stream};++ /// §9.6.5: a Type 3 font's `/Resources` is optional, and "if any glyph+ /// descriptions refer to named resources but this dictionary is absent, the+ /// names shall be looked up in the resource dictionary of the page on which+ /// the font is used". `show_string_type3` passed `t3.resources` straight+ /// through, so with no `/Resources` on the font the CharProc's resource+ /// lookups all missed and the glyph drew NOTHING — not even a fallback shape.+ /// TeX/dvips bitmap-font output routinely omits the entry. Reported by+ /// `a-text2`.+ #[test]+ fn a_type3_charproc_falls_back_to_the_page_resources() {+ let mut doc = Document::with_version("1.7");+ // The CharProc paints through an ExtGState it can only reach via the page.+ let egs = doc.add_object(dictionary! { "ca" => 0.5 });+ let proc_id = doc.add_object(Stream::new(+ dictionary! {},+ b"/GSP gs 0 0 700 700 re f".to_vec(),+ ));+ let font = dictionary! {+ "Type" => "Font", "Subtype" => "Type3",+ "FontMatrix" => vec![0.001.into(), 0.into(), 0.into(), 0.001.into(), 0.into(), 0.into()],+ "FontBBox" => vec![0.into(), 0.into(), 750.into(), 750.into()],+ "CharProcs" => doc.add_object(dictionary! { "a" => proc_id }),+ "Encoding" => doc.add_object(dictionary! {+ "Type" => "Encoding", "Differences" => vec![65.into(), "a".into()],+ }),+ "FirstChar" => 65, "LastChar" => 65, "Widths" => vec![700.into()],+ // Deliberately NO /Resources on the font: the whole point of the test.+ };+ let font_id = doc.add_object(font.clone());+ let res = dictionary! {+ "Font" => dictionary! { "F1" => Object::Reference(font_id) },+ "ExtGState" => dictionary! { "GSP" => Object::Reference(egs) },+ };+ let ops = vec![+ Operation::new("BT", vec![]),+ Operation::new("Tf", vec![Object::Name(b"F1".to_vec()), 100.into()]),+ Operation::new("Tj", vec![Object::string_literal("A")]),+ Operation::new("ET", vec![]),+ ];+ let mut prims = Vec::new();+ interpret_content(&doc, &ops, Some(&res), GraphicsState::default(), &mut prims, 0, false);++ let alpha = prims+ .iter()+ .find_map(|p| match p {+ Prim::Fill { argb, .. } => Some((argb >> 24) as u8),+ _ => None,+ })+ .expect("the Type 3 glyph must paint");+ assert_eq!(+ alpha, 0x80,+ "the CharProc's /GSP must resolve through the page resources"+ );+ }+}++#[cfg(test)]+mod degenerate_stroke_tests {+ use crate::*;++ fn stroke(subpaths: &[Vec<(f64, f64)>], cap: u8) -> Vec<Prim> {+ let gs = GraphicsState { line_cap: cap, line_width: 4.0, ..Default::default() };+ let mut prims = Vec::new();+ emit_stroke(&mut prims, subpaths, &gs);+ prims+ }++ /// §8.5.3.2: "If a subpath is degenerate (consists of a single-point closed+ /// subpath or of two or more points at the same coordinates), `S` shall paint+ /// it only if round line caps have been specified, producing a filled circle+ /// centred at the single point. If butt or projecting square line caps have+ /// been specified, `S` shall paint nothing."+ ///+ /// A single-point subpath — what `x y m S` and `x y m h S` produce — was+ /// dropped before it reached the renderer, so the round-cap dot idiom used for+ /// stipple patterns, leader-line dots and map symbols painted nothing at all.+ #[test]+ fn a_degenerate_subpath_paints_a_dot_only_with_round_caps() {+ for sp in [vec![(5.0, 7.0)], vec![(5.0, 7.0), (5.0, 7.0)]] {+ let round = stroke(std::slice::from_ref(&sp), 1);+ let contours = round+ .iter()+ .find_map(|p| match p {+ Prim::Fill { contours, .. } => Some(contours.clone()),+ _ => None,+ })+ .unwrap_or_else(|| panic!("round caps must paint a dot for {sp:?}"));+ assert_eq!(contours.len(), 1);+ // Centred on the point, radius = half the (device) line width.+ for &(x, y) in &contours[0] {+ let r = ((x as f64 - 5.0).hypot(y as f64 - 7.0) - 2.0).abs();+ assert!(r < 1e-3, "dot vertex ({x}, {y}) is not on the r=2 circle");+ }++ for butt_or_square in [0u8, 2] {+ let out = stroke(std::slice::from_ref(&sp), butt_or_square);+ assert!(+ out.is_empty(),+ "cap {butt_or_square} must paint nothing for a degenerate \+ subpath, got {} prims",+ out.len()+ );+ }+ }+ }++ /// The dot path must not swallow real strokes: a subpath with distinct points+ /// still strokes, round caps or not.+ #[test]+ fn a_non_degenerate_subpath_still_strokes() {+ let sp = vec![vec![(0.0, 0.0), (10.0, 0.0)]];+ for cap in [0u8, 1, 2] {+ let out = stroke(&sp, cap);+ assert_eq!(+ out.iter().filter(|p| matches!(p, Prim::Stroke { .. })).count(),+ 1,+ "cap {cap}"+ );+ assert!(!out.iter().any(|p| matches!(p, Prim::Fill { .. })));+ }+ }+}+ #[cfg(test)] mod type3_cap_tests { use crate::*;@@ -676,4 +864,4 @@ mod type3_cap_tests { } assert_eq!(depth, 0, "{depth} soft-mask level(s) left open by the cap"); }-}\ No newline at end of file+}
pdf/src/main/rust/src/filters.rs
diff --git a/pdf/src/main/rust/src/filters.rs b/pdf/src/main/rust/src/filters.rsindex 19ad77e0a5..9a139f9bb5 100644--- a/pdf/src/main/rust/src/filters.rs+++ b/pdf/src/main/rust/src/filters.rs@@ -232,9 +232,17 @@ pub fn decode_ascii85(data: &[u8]) -> Result<Vec<u8>, String> { /// RunLength per PDF spec EOD 128. pub fn decode_runlength(data: &[u8]) -> Vec<u8> {+ decode_runlength_limited(data, MAX_DECODED_BYTES as usize)+}++/// §7.4.5 expands by up to 128x, so a 200 MB stream (the `MAX_PDF_BYTES` ceiling)+/// can reach ~25 GB. Nothing else bounds this, and the bytes decoded so far are+/// still usable, so `limit` stops the expansion rather than the process being killed.+fn decode_runlength_limited(data: &[u8], limit: usize) -> Vec<u8> { let mut out = Vec::new(); let mut i=0; while i < data.len() {+ if out.len() >= limit { break; } let len = data[i] as i16; i+=1; if len==128 { break; } else if len<=127 {@@ -253,14 +261,14 @@ pub fn decode_runlength(data: &[u8]) -> Vec<u8> { pub fn decode_lzw(data: &[u8], early_change: bool) -> Option<Vec<u8>> { // weezl crate removed – pure std LZW decoder (single function we use, prefer stdlib)- lzw_decode_std(data, early_change)+ lzw_decode_std(data, early_change, MAX_DECODED_BYTES as usize) } /// Minimal std-only LZW decoder for PDF's LZWDecode (MSB-first, 8-bit symbols). /// Handles EarlyChange 1 (default, code size early bump) vs 0. /// This is the `single function we use, we can just write it ourselves` rewrite path. /// Returns None on malformed data.-fn lzw_decode_std(data: &[u8], early_change: bool) -> Option<Vec<u8>> {+fn lzw_decode_std(data: &[u8], early_change: bool, limit: usize) -> Option<Vec<u8>> { // Simplified version: common case – try via quick dict of 258+ entries. // If too complex, return None and let caller fail gracefully. // Real PDF LZW switches code size at 2^k - early. Standard TIFF variant uses clear code 256, eod 257.@@ -271,7 +279,10 @@ fn lzw_decode_std(data: &[u8], early_change: bool) -> Option<Vec<u8>> { for i in 0..256 { dict.push(vec![i as u8]); } dict.push(vec![]); // 256 clear dict.push(vec![]); // 257 eod- let mut out = Vec::with_capacity(data.len()*2);+ // Reserve a guess, not a file-controlled amount: `data.len() * 2` is a 400 MB+ // up-front allocation for a `MAX_PDF_BYTES`-sized stream, before a single code+ // has been shown to decode.+ let mut out = Vec::with_capacity(data.len().saturating_mul(2).min(1 << 20)); let mut code_bits = 9usize; let mut bit_buf: u32 = 0; let mut bits_in_buf = 0usize;@@ -323,6 +334,13 @@ fn lzw_decode_std(data: &[u8], early_change: bool) -> Option<Vec<u8>> { break; }; out.extend_from_slice(&entry);+ // §7.4.3 places no bound on the expansion ratio: a dictionary entry grows to+ // 4096 bytes, so a few-MB stream can decode to gigabytes. Flate is capped by+ // `MAX_DECODED_BYTES`; this was not, and nothing downstream bounds it either.+ // Everything decoded so far is kept, as for a truncated stream.+ if out.len() >= limit {+ break;+ } if let Some(p) = prev.take() { if dict.len() < 4096 { if let Some(&first) = entry.first() {@@ -411,10 +429,23 @@ pub fn parse_ccitt_params(doc: &Document, dict_opt: Option<&Dictionary>) -> Ccit pub fn decode_ccitt(data: &[u8], w: u32, h: u32, params: &CcittParams) -> Option<Vec<u8>> { // P0 fix: honor BlackIs1 (spec §7.4.6: true=>1=black, false default=>1=white inverted), estimate Rows when absent let columns = if params.columns > 0 { params.columns } else { w.max(1) };- let rows_est = if params.rows > 0 { params.rows } else {- // Estimate from data length: rows ≈ data_len*8 / cols (fax data may omit Rows)- let est = (data.len() * 8 / columns.max(1) as usize) as u32;- est.max(h).max(1)+ // §7.4.6 Table 11: /Rows gives the scan-line count; when it is absent or 0 the+ // height comes from the image dictionary's /Height, which is what `h` is.+ //+ // The data-length estimate below is the LAST resort, used only when neither is+ // available. It is not a spec-sanctioned reading of the row count at all: it+ // equates one row to `columns` BITS of payload, so it only exceeds `h` when the+ // encoded data is LARGER than the raster it encodes. For any normally-compressed+ // fax it comes out well below `h`, which is why deriving from it looks harmless.+ // On a padded, corrupt or mislabelled stream it does not, and past the 20000-row+ // guard below `decode_ccitt` then returns None and the image is dropped ENTIRELY+ // rather than merely mis-sized - total loss where a partial render was available.+ let rows_est = if params.rows > 0 {+ params.rows+ } else if h > 0 {+ h+ } else {+ ((data.len() * 8 / columns.max(1) as usize) as u32).max(1) }; let rows = rows_est; let rows_us = rows as usize;@@ -892,4 +923,134 @@ mod tests { assert_eq!(specs.len(), 1); assert_eq!(specs[0].0, FilterKind::Flate); }++ /// Writes MSB-first codes, which is the bit order §7.4.3 specifies for LZWDecode.+ struct BitWriter {+ out: Vec<u8>,+ acc: u32,+ bits: u32,+ }+ impl BitWriter {+ fn new() -> Self {+ BitWriter { out: Vec::new(), acc: 0, bits: 0 }+ }+ fn put(&mut self, code: u32, width: u32) {+ self.acc = (self.acc << width) | code;+ self.bits += width;+ while self.bits >= 8 {+ self.bits -= 8;+ self.out.push((self.acc >> self.bits) as u8);+ }+ }+ fn finish(mut self) -> Vec<u8> {+ if self.bits > 0 {+ self.out.push((self.acc << (8 - self.bits)) as u8);+ }+ self.out+ }+ }++ #[test]+ fn lzw_early_change_bumps_the_code_width_one_entry_early() {+ // §7.4.3 Table 8: /EarlyChange 1 (the DEFAULT) makes the code length grow one+ // code sooner than strictly necessary. Getting the boundary wrong desynchronizes+ // the bit stream from that point on, so everything after it is noise - the+ // classic "second half of the image is garbage" symptom.+ //+ // Codes 0..=253 are single-byte literals. The first adds no dictionary entry+ // (there is no previous string), each later one adds exactly one, so after code+ // 253 the dictionary holds 258 + 253 = 511 entries. With EarlyChange the width+ // must ALREADY be 10 bits for the next code; without it, it is still 9.+ let literals: Vec<u32> = (0..=253u32).collect();+ let mut early = BitWriter::new();+ for &c in &literals {+ early.put(c, 9);+ }+ early.put(100, 10);+ early.put(257, 10); // EOD+ let out = decode_lzw(&early.finish(), true).expect("decodes");+ let mut want: Vec<u8> = (0..=253u8).collect();+ want.push(100);+ assert_eq!(out, want, "EarlyChange 1 must switch to 10 bits at 511 entries");++ // /EarlyChange 0 keeps 9 bits until the 512th entry, so the same 254 literals+ // are followed by one more 9-bit code before the width changes.+ let mut late = BitWriter::new();+ for &c in &literals {+ late.put(c, 9);+ }+ late.put(100, 9);+ late.put(257, 10); // the 512th entry exists by now, so EOD is 10 bits+ let out = decode_lzw(&late.finish(), false).expect("decodes");+ assert_eq!(out, want, "EarlyChange 0 must switch to 10 bits at 512 entries");+ }++ #[test]+ fn lzw_kwkwk_case() {+ // §7.4.3: a code one past the end of the table means "previous string plus its+ // own first character". Emitting `A` then the not-yet-defined code 258 must+ // produce `AA`, not abandon the stream.+ let mut w = BitWriter::new();+ w.put(b'A' as u32, 9);+ w.put(258, 9);+ w.put(257, 9);+ assert_eq!(decode_lzw(&w.finish(), true).expect("decodes"), b"AAA");+ }++ #[test]+ fn lzw_output_is_bounded_by_the_decode_ceiling() {+ // §7.4.3 bounds neither the expansion ratio nor the output length, so the only+ // limit on a hostile stream is the one imposed here. Everything decoded up to+ // the ceiling is still returned.+ let mut w = BitWriter::new();+ for _ in 0..64 {+ w.put(b'A' as u32, 9);+ }+ let out = lzw_decode_std(&w.finish(), true, 4).expect("partial output");+ assert_eq!(out, b"AAAA", "decoding must stop at the ceiling, not at the data");+ }++ #[test]+ fn ccitt_row_count_comes_from_the_height_not_the_compressed_length() {+ // §7.4.6 Table 11: with /Rows absent the scan-line count is the image's /Height.+ // The old code used `max(data.len()*8/columns, h)`. That estimate exceeds `h`+ // only when the encoded payload is LARGER than the raster it encodes, so a+ // normally-compressed fax never reaches it and the two agree - which is why the+ // bug was invisible at fixture scale. On a padded or corrupt stream it does+ // exceed `h`, and past the 20000-row guard `decode_ccitt` returned None and the+ // image was dropped ENTIRELY rather than mis-sized.+ //+ // The numbers below are therefore deliberately pathological, not realistic: they+ // have to be, because that is the only shape of input the two expressions+ // disagree on. This witnesses spec conformance and the no-total-loss property,+ // NOT a scenario a well-formed file reaches.+ let params = CcittParams { k: -1, columns: 8, ..CcittParams::default() };+ // 8 columns, 4 rows => 1 byte per row. A payload far longer than the geometry+ // would previously have driven `rows` from its own length.+ let data = vec![0u8; 40_000];+ let packed = decode_ccitt(&data, 8, 4, ¶ms);+ if let Some(p) = packed {+ assert_eq!(p.len(), 4, "one byte per 8-column row, /Height rows");+ }+ // The case that used to disappear: columns * (len*8/columns) exceeds the 20000+ // row guard, so `decode_ccitt` returned None and the image vanished.+ let big = vec![0u8; 300_000];+ let params = CcittParams { k: -1, columns: 100, ..CcittParams::default() };+ assert!(+ decode_ccitt(&big, 100, 50, ¶ms).is_some(),+ "a 50-row image must not be refused because its data is long"+ );+ }++ #[test]+ fn runlength_output_is_bounded_by_the_decode_ceiling() {+ // §7.4.5 expands a 2-byte run record into up to 128 bytes, so a stream at the+ // 200 MB input ceiling reaches ~25 GB unbounded.+ let data = [0x81u8, 0xAA].repeat(64); // 64 runs of 128 bytes = 8192 bytes+ let out = decode_runlength_limited(&data, 5);+ assert_eq!(out.len(), 128, "one run past the ceiling, then stop");+ assert!(out.iter().all(|&b| b == 0xAA));+ // Unlimited decoding of the same input is unchanged.+ assert_eq!(decode_runlength(&data).len(), 8192);+ } }
pdf/src/main/rust/src/fonts.rs
diff --git a/pdf/src/main/rust/src/fonts.rs b/pdf/src/main/rust/src/fonts.rsindex 9587834280..498d1050c3 100644--- a/pdf/src/main/rust/src/fonts.rs+++ b/pdf/src/main/rust/src/fonts.rs@@ -366,6 +366,44 @@ fn font_identity(doc: &Document, dict: &Dictionary) -> u64 { h.finish() } +/// `code -> glyph name` from a simple font's NAMED base encoding, empty when the+/// font names none.+///+/// PDF 32000-1 9.6.6.2 orders a simple font's encoding: `/Differences` first,+/// then the base encoding named by `/Encoding` or `/Encoding /BaseEncoding`,+/// then the font program's own built-in encoding, then StandardEncoding. Only+/// the middle step needs a table here — an absent name is precisely the case+/// where the built-in encoding wins, and returning empty lets the caller fall+/// through to it.+///+/// MacRomanEncoding is deliberately not tabulated. PDF's MacRomanEncoding is not+/// Mac OS Roman (it leaves several codes undefined and differs at 0xDB), so a+/// half-remembered table would substitute one wrong glyph for another; leaving+/// it out keeps such fonts on the existing built-in-encoding path, which is the+/// spec's own next step.+fn named_base_encoding_names(doc: &Document, font: &lopdf::Dictionary) -> HashMap<u32, String> {+ let mut names = HashMap::new();+ let base = match font.get(b"Encoding").ok().and_then(|o| deref(doc, o)) {+ Some(Object::Name(n)) => Some(String::from_utf8_lossy(n).into_owned()),+ Some(Object::Dictionary(d)) => d+ .get(b"BaseEncoding")+ .ok()+ .and_then(|o| deref(doc, o))+ .and_then(|o| o.as_name().ok())+ .map(|n| String::from_utf8_lossy(n).into_owned()),+ _ => None,+ };+ let table: &[(u8, &str)] = match base.as_deref() {+ Some("WinAnsiEncoding") => encoding::WIN_ANSI_NAMES,+ Some("StandardEncoding") => crate::type1::STANDARD_ENCODING,+ _ => return names,+ };+ for (code, name) in table {+ names.insert(*code as u32, (*name).to_string());+ }+ names+}+ pub(crate) fn font_info(doc: &Document, font: &lopdf::Dictionary) -> FontInfo { let subtype = font.get(b"Subtype").ok().and_then(|o| o.as_name().ok()); let two_byte = matches!(subtype, Some(b"Type0"));@@ -512,7 +550,11 @@ pub(crate) fn font_info(doc: &Document, font: &lopdf::Dictionary) -> FontInfo { list.iter().filter_map(|o| deref(doc, o).and_then(num)).collect(); for (j, t) in vals.chunks(3).enumerate() { if t.len() < 3 { break; }- vm.insert(c0 + j as u32, (t[0] / 1000.0, t[1] / 1000.0));+ // Same file-controlled overflow as /W's array form.+ vm.insert(+ c0.saturating_add(j as u32).min(MAX_CID),+ (t[0] / 1000.0, t[1] / 1000.0),+ ); } i += 2; }@@ -646,7 +688,24 @@ pub(crate) fn font_info(doc: &Document, font: &lopdf::Dictionary) -> FontInfo { let glyph_names = if two_byte || is_type3 { HashMap::new() } else {- crate::outlines::encoding_differences(doc, font)+ // A Type 1 or bare-CFF program selects glyphs BY NAME, so a named base+ // encoding has to be resolved to names here or 9.6.6.2's priority is+ // silently inverted and the program's built-in encoding wins: a font+ // whose built-in encoding is Standard, used with /WinAnsiEncoding, then+ // draws Oslash for eacute, ae for ntilde and germandbls for ucircumflex+ // — wrong glyphs rather than missing ones.+ //+ // Sfnt programs are excluded on purpose. 9.6.6.4 routes those through the+ // cmap and treats `post`-table names as a fallback, so seeding a name for+ // every code would put a subset font's often-garbage `post` table ahead+ // of its cmap.+ let mut m = match glyph_program.as_ref() {+ Some(crate::outlines::GlyphProgram::Type1(_))+ | Some(crate::outlines::GlyphProgram::Cff { .. }) => named_base_encoding_names(doc, font),+ _ => HashMap::new(),+ };+ m.extend(crate::outlines::encoding_differences(doc, font));+ m }; // --- Standard-14 metrics fallback ---@@ -656,17 +715,50 @@ pub(crate) fn font_info(doc: &Document, font: &lopdf::Dictionary) -> FontInfo { // via /Differences, falling back to StandardEncoding. if !two_byte && !is_type3 && widths.is_empty() { if let Some(afm) = crate::afm::standard_14_widths(&base_font_name) {- for code in 0u32..=255 {- let name = glyph_names.get(&code).cloned().or_else(|| {- crate::type1::STANDARD_ENCODING.iter()- .find(|(c, _)| *c as u32 == code)- .map(|(_, n)| (*n).to_string())- });- if let Some(name) = name {- if let Some(w) = afm.get(&name) {- widths.insert(code, *w);+ // AFM metrics are keyed by GLYPH NAME, so the code -> name step has to+ // follow the font's real encoding (9.6.6.2), not StandardEncoding+ // unconditionally: for /WinAnsiEncoding, Standard names code 233+ // "Oslash" (611 units) where WinAnsi names it "eacute" (556), so every+ // accented character came out with another glyph's advance.+ let base_names = named_base_encoding_names(doc, font);+ // Symbol and ZapfDingbats have their own built-in encodings, whose AFM+ // names ("alpha", "a12") are in neither table. Their metrics are still+ // reachable by resolving the AFM name to Unicode and matching the+ // encoding's code -> Unicode map. Built in sorted-name order so a+ // Unicode collision resolves deterministically.+ let by_char: HashMap<char, f64> = {+ let mut names: Vec<&String> = afm.keys().collect();+ names.sort();+ let mut m = HashMap::new();+ for n in names {+ if let Some(c) = encoding::glyph_to_char(n) {+ m.entry(c).or_insert(afm[n]); } }+ m+ };+ for code in 0u32..=255 {+ let name = glyph_names+ .get(&code)+ .cloned()+ .or_else(|| base_names.get(&code).cloned())+ .or_else(|| {+ crate::type1::STANDARD_ENCODING+ .iter()+ .find(|(c, _)| *c as u32 == code)+ .map(|(_, n)| (*n).to_string())+ });+ if let Some(w) = name.as_deref().and_then(|n| afm.get(n)) {+ widths.insert(code, *w);+ continue;+ }+ // ZapfDingbats is the one face this cannot reach: its `aNNN` AFM+ // names carry no Unicode, so its codes stay on `default_width`.+ // Left as a known gap rather than approximated, because a wrong+ // advance for every dingbat is worse than one uniform one.+ if let Some(w) = encoding.get(&code).and_then(|c| by_char.get(c)) {+ widths.insert(code, *w);+ } } } }@@ -761,11 +853,19 @@ pub(crate) fn simple_widths(doc: &Document, font: &lopdf::Dictionary) -> (HashMa .and_then(|d| d.get(b"MissingWidth").ok()) .and_then(|o| deref(doc, o)) .and_then(num)- .unwrap_or(0.0)- / 1000.0;- // Simple fonts without a /Widths array (e.g. the standard 14) get a- // reasonable default so advances are non-degenerate.- let default_width = if widths.is_empty() { 0.5 } else { missing };+ .map(|v| v / 1000.0);+ // 9.6.2.1 Table 111: /MissingWidth is the width for codes the /Widths array+ // does not cover, and that includes every code when /Widths is absent. It is+ // only when the descriptor supplies no /MissingWidth either that a default is+ // invented — the spec default of 0 would stack a whole string on one point,+ // and the standard-14 AFM table fills in real metrics for the fonts where+ // this case is legitimate, so 0.5 applies to nothing but genuinely unknown+ // glyphs.+ let default_width = match missing {+ Some(w) => w,+ None if widths.is_empty() => 0.5,+ None => 0.0,+ }; (widths, default_width) } @@ -807,7 +907,11 @@ pub(crate) fn cid_widths(doc: &Document, font: &lopdf::Dictionary) -> (HashMap<u Some(Object::Array(list)) => { for (j, item) in list.iter().enumerate() { if let Some(v) = deref(doc, item).and_then(num) {- widths.insert(c + j as u32, v / 1000.0);+ // `c` is file-controlled and `num` saturates at+ // u32::MAX, so `c + j` wraps in release and panics in+ // debug. The range form is already clamped to MAX_CID;+ // this form was not.+ widths.insert(c.saturating_add(j as u32).min(MAX_CID), v / 1000.0); } } i += 2;@@ -1623,6 +1727,72 @@ pub(crate) mod encoding { m } + /// WinAnsiEncoding as `code -> glyph NAME` (PDF 32000-1 Annex D.2).+ ///+ /// Distinct from [`win_ansi`], which yields Unicode. Selecting an outline in a+ /// Type 1 or bare-CFF program is done by NAME, and 9.6.6.2 makes a named base+ /// encoding outrank the program's own built-in encoding — so a Unicode map+ /// cannot serve that lookup and StandardEncoding is the wrong table for it+ /// (Standard puts Oslash where WinAnsi puts eacute, ae where it puts ntilde,+ /// and so on across the whole 0xA0-0xFF range).+ pub static WIN_ANSI_NAMES: &[(u8, &str)] = &[+ (32, "space"), (33, "exclam"), (34, "quotedbl"), (35, "numbersign"),+ (36, "dollar"), (37, "percent"), (38, "ampersand"), (39, "quotesingle"),+ (40, "parenleft"), (41, "parenright"), (42, "asterisk"), (43, "plus"),+ (44, "comma"), (45, "hyphen"), (46, "period"), (47, "slash"),+ (48, "zero"), (49, "one"), (50, "two"), (51, "three"), (52, "four"),+ (53, "five"), (54, "six"), (55, "seven"), (56, "eight"), (57, "nine"),+ (58, "colon"), (59, "semicolon"), (60, "less"), (61, "equal"),+ (62, "greater"), (63, "question"), (64, "at"),+ (65, "A"), (66, "B"), (67, "C"), (68, "D"), (69, "E"), (70, "F"),+ (71, "G"), (72, "H"), (73, "I"), (74, "J"), (75, "K"), (76, "L"),+ (77, "M"), (78, "N"), (79, "O"), (80, "P"), (81, "Q"), (82, "R"),+ (83, "S"), (84, "T"), (85, "U"), (86, "V"), (87, "W"), (88, "X"),+ (89, "Y"), (90, "Z"),+ (91, "bracketleft"), (92, "backslash"), (93, "bracketright"),+ (94, "asciicircum"), (95, "underscore"), (96, "grave"),+ (97, "a"), (98, "b"), (99, "c"), (100, "d"), (101, "e"), (102, "f"),+ (103, "g"), (104, "h"), (105, "i"), (106, "j"), (107, "k"), (108, "l"),+ (109, "m"), (110, "n"), (111, "o"), (112, "p"), (113, "q"), (114, "r"),+ (115, "s"), (116, "t"), (117, "u"), (118, "v"), (119, "w"), (120, "x"),+ (121, "y"), (122, "z"),+ (123, "braceleft"), (124, "bar"), (125, "braceright"), (126, "asciitilde"),+ (128, "Euro"), (130, "quotesinglbase"), (131, "florin"),+ (132, "quotedblbase"), (133, "ellipsis"), (134, "dagger"),+ (135, "daggerdbl"), (136, "circumflex"), (137, "perthousand"),+ (138, "Scaron"), (139, "guilsinglleft"), (140, "OE"), (142, "Zcaron"),+ (145, "quoteleft"), (146, "quoteright"), (147, "quotedblleft"),+ (148, "quotedblright"), (149, "bullet"), (150, "endash"), (151, "emdash"),+ (152, "tilde"), (153, "trademark"), (154, "scaron"), (155, "guilsinglright"),+ (156, "oe"), (158, "zcaron"), (159, "Ydieresis"),+ (160, "space"), (161, "exclamdown"), (162, "cent"), (163, "sterling"),+ (164, "currency"), (165, "yen"), (166, "brokenbar"), (167, "section"),+ (168, "dieresis"), (169, "copyright"), (170, "ordfeminine"),+ (171, "guillemotleft"), (172, "logicalnot"), (173, "hyphen"),+ (174, "registered"), (175, "macron"), (176, "degree"), (177, "plusminus"),+ (178, "twosuperior"), (179, "threesuperior"), (180, "acute"), (181, "mu"),+ (182, "paragraph"), (183, "periodcentered"), (184, "cedilla"),+ (185, "onesuperior"), (186, "ordmasculine"), (187, "guillemotright"),+ (188, "onequarter"), (189, "onehalf"), (190, "threequarters"),+ (191, "questiondown"),+ (192, "Agrave"), (193, "Aacute"), (194, "Acircumflex"), (195, "Atilde"),+ (196, "Adieresis"), (197, "Aring"), (198, "AE"), (199, "Ccedilla"),+ (200, "Egrave"), (201, "Eacute"), (202, "Ecircumflex"), (203, "Edieresis"),+ (204, "Igrave"), (205, "Iacute"), (206, "Icircumflex"), (207, "Idieresis"),+ (208, "Eth"), (209, "Ntilde"), (210, "Ograve"), (211, "Oacute"),+ (212, "Ocircumflex"), (213, "Otilde"), (214, "Odieresis"), (215, "multiply"),+ (216, "Oslash"), (217, "Ugrave"), (218, "Uacute"), (219, "Ucircumflex"),+ (220, "Udieresis"), (221, "Yacute"), (222, "Thorn"), (223, "germandbls"),+ (224, "agrave"), (225, "aacute"), (226, "acircumflex"), (227, "atilde"),+ (228, "adieresis"), (229, "aring"), (230, "ae"), (231, "ccedilla"),+ (232, "egrave"), (233, "eacute"), (234, "ecircumflex"), (235, "edieresis"),+ (236, "igrave"), (237, "iacute"), (238, "icircumflex"), (239, "idieresis"),+ (240, "eth"), (241, "ntilde"), (242, "ograve"), (243, "oacute"),+ (244, "ocircumflex"), (245, "otilde"), (246, "odieresis"), (247, "divide"),+ (248, "oslash"), (249, "ugrave"), (250, "uacute"), (251, "ucircumflex"),+ (252, "udieresis"), (253, "yacute"), (254, "thorn"), (255, "ydieresis"),+ ];+ /// Adobe StandardEncoding: matches Latin-1 for the core ASCII letters/digits /// but differs across punctuation (0x27 quoteright, 0x60 quoteleft) and the /// whole 0x80–0xFF range, so it is built from the real name table rather than@@ -1744,6 +1914,217 @@ mod encrypt_tests { } } +#[cfg(test)]+mod encoding_priority_tests {+ use super::*;++ fn helvetica(encoding: Option<&str>) -> (Document, Dictionary) {+ let doc = Document::with_version("1.7");+ let mut f = dictionary! {+ "Type" => "Font",+ "Subtype" => "Type1",+ "BaseFont" => "Helvetica",+ };+ if let Some(e) = encoding {+ f.set("Encoding", Object::Name(e.as_bytes().to_vec()));+ }+ (doc, f)+ }++ // Builds a minimal but REAL Type 1 font program, so `font_info` takes the+ // `GlyphProgram::Type1` arm for real rather than being handed a pre-built+ // `glyph_names`. Mutation testing found that no test covered the wiring: with+ // the Type1/Cff arm reverted to an empty map, all 11 of the original tests+ // still passed, because each one either built `FontInfo` by hand or exercised+ // `named_base_encoding_names` directly. The production path that carries a+ // named base encoding into glyph selection was the one thing untested.+ fn type1_font_program(glyph: &str, charstring: &[u8]) -> Vec<u8> {+ fn crypt(seed: u16, lead: usize, plain: &[u8]) -> Vec<u8> {+ let (c1, c2) = (52845u16, 22719u16);+ let mut r = seed;+ let mut out = Vec::new();+ for &p in std::iter::repeat(&0u8).take(lead).chain(plain) {+ let c = p ^ (r >> 8) as u8;+ r = (c as u16).wrapping_add(r).wrapping_mul(c1).wrapping_add(c2);+ out.push(c);+ }+ out+ }+ let mut private = Vec::new();+ private.extend_from_slice(b"dup /Private 8 dict dup begin\n/lenIV 0 def\n");+ private.extend_from_slice(b"/CharStrings 1 dict dup begin\n");+ private.extend_from_slice(format!("/{glyph} {} RD ", charstring.len()).as_bytes());+ // `lenIV 0`, so the charstring is eexec-charstring encrypted with no skip.+ private.extend_from_slice(&crypt(4330, 0, charstring));+ private.extend_from_slice(b" ND\nend\nend\n");++ let mut font = Vec::new();+ font.extend_from_slice(b"%!PS-AdobeFont-1.0\n");+ font.extend_from_slice(b"/FontMatrix [0.001 0 0 0.001 0 0] readonly def\n");+ font.extend_from_slice(b"/Encoding StandardEncoding def\n");+ font.extend_from_slice(b"currentfile eexec\n");+ // Four lead plaintext bytes that `extract_eexec` discards. Zero bytes put+ // 0xD9 first in the ciphertext, which is not an ASCII hex digit, so the+ // section is correctly detected as binary rather than hex.+ font.extend_from_slice(&crypt(55665, 4, &private));+ font+ }++ /// A square: `0 500 hsbw 0 0 rmoveto 100 0 rlineto 0 100 rlineto -100 0 rlineto closepath endchar`+ fn square_charstring() -> Vec<u8> {+ vec![+ 139, 248, 136, 13, // 0 500 hsbw+ 139, 139, 21, // 0 0 rmoveto+ 239, 139, 5, // 100 0 rlineto+ 139, 239, 5, // 0 100 rlineto+ 39, 139, 5, // -100 0 rlineto+ 9, // closepath+ 14, // endchar+ ]+ }++ // §9.6.6.2 end to end, through `font_info` rather than a hand-built FontInfo.+ // The program's built-in encoding is StandardEncoding, which names code 233+ // "Oslash"; the PDF declares /WinAnsiEncoding, which names it "eacute". The+ // named base encoding must win, or an accented character silently draws a+ // different letter.+ #[test]+ fn font_info_carries_a_named_base_encoding_into_glyph_names() {+ let mut doc = Document::new();+ let ff = doc.add_object(Stream::new(+ dictionary! {},+ type1_font_program("eacute", &square_charstring()),+ ));+ let fd = doc.add_object(dictionary! {+ "Type" => "FontDescriptor", "FontName" => "Test", "FontFile" => ff,+ });+ let font = dictionary! {+ "Type" => "Font", "Subtype" => "Type1", "BaseFont" => "Test",+ "Encoding" => "WinAnsiEncoding",+ "FontDescriptor" => fd,+ };+ let fi = font_info(&doc, &font);+ assert!(fi.glyph_program.is_some(), "precondition: the Type 1 program must parse");+ assert_eq!(+ fi.glyph_names.get(&233).map(String::as_str),+ Some("eacute"),+ "WinAnsi must name code 233 eacute, not the program's built-in Oslash"+ );+ // And the whole path resolves to the real outline for that name.+ let (contours, upm) = crate::outlines::glyph_outline(&fi, 233).expect("outline");+ assert_eq!(upm, 1000.0);+ assert_eq!(contours.len(), 1);+ assert_eq!(contours[0].first(), contours[0].last(), "contour is closed");+ }++ // PDF 32000-1 9.6.6.2. The AFM metrics are keyed by GLYPH NAME, so resolving+ // the code through StandardEncoding regardless of the declared base encoding+ // charges every accented character another glyph's advance: Standard calls+ // code 233 "Oslash" (778/1000 in Helvetica) where WinAnsi calls it "eacute"+ // (556/1000). A whole line of accented text drifts right by ~40% of an em per+ // accent, so words overlap the following ones.+ #[test]+ fn standard14_widths_follow_the_declared_base_encoding() {+ let (doc, font) = helvetica(Some("WinAnsiEncoding"));+ let fi = font_info(&doc, &font);+ assert_eq!(fi.widths.get(&233).copied(), Some(0.556), "233 is eacute in WinAnsi");+ assert_eq!(fi.widths.get(&65).copied(), Some(0.667), "ASCII is unaffected");++ // With no /Encoding at all, StandardEncoding remains the right fallback.+ let (doc, font) = helvetica(None);+ let fi = font_info(&doc, &font);+ assert_eq!(fi.widths.get(&233).copied(), Some(0.778), "233 is Oslash in Standard");+ }++ // Symbol has its own built-in encoding, whose AFM names (alpha, Beta, …) are+ // in neither StandardEncoding nor WinAnsi. Resolving them through Unicode is+ // what keeps Greek and math text from falling back to a flat default advance.+ #[test]+ fn symbol_metrics_resolve_through_its_own_encoding() {+ let doc = Document::with_version("1.7");+ let font = dictionary! { "Type" => "Font", "Subtype" => "Type1", "BaseFont" => "Symbol" };+ let fi = font_info(&doc, &font);+ assert_eq!(fi.widths.get(&0x61).copied(), Some(0.631), "0x61 is alpha (631)");+ assert_eq!(fi.widths.get(&0x41).copied(), Some(0.722), "0x41 is Alpha (722)");+ assert_eq!(fi.widths.get(&0x2B).copied(), Some(0.549), "0x2B is plus (549)");+ }++ // An absent base-encoding NAME is the case where 9.6.6.2 gives the font+ // program's built-in encoding priority, so the table must stay empty and let+ // `outlines.rs` fall through to it rather than asserting Standard names.+ #[test]+ fn no_named_base_encoding_yields_no_names() {+ let (doc, font) = helvetica(None);+ assert!(named_base_encoding_names(&doc, &font).is_empty());++ let (doc, font) = helvetica(Some("WinAnsiEncoding"));+ let m = named_base_encoding_names(&doc, &font);+ assert_eq!(m.get(&233).map(String::as_str), Some("eacute"));+ assert_eq!(m.get(&39).map(String::as_str), Some("quotesingle"));+ assert_eq!(m.get(&96).map(String::as_str), Some("grave"));++ // /BaseEncoding inside an /Encoding dictionary is the same base encoding.+ let doc2 = Document::with_version("1.7");+ let font2 = dictionary! {+ "Type" => "Font", "Subtype" => "Type1", "BaseFont" => "Helvetica",+ "Encoding" => dictionary! { "BaseEncoding" => "WinAnsiEncoding" },+ };+ assert_eq!(+ named_base_encoding_names(&doc2, &font2).get(&233).map(String::as_str),+ Some("eacute")+ );+ }++ // 9.6.2.1 Table 111: /MissingWidth covers codes /Widths does not, which is all+ // of them when /Widths is absent. Discarding it there charged an invented+ // 0.5 em to every glyph of a font that had said what its default advance is.+ #[test]+ fn missing_width_applies_even_with_no_widths_array() {+ let mut doc = Document::new();+ let fd = doc.add_object(dictionary! { "Type" => "FontDescriptor", "MissingWidth" => 600 });+ let font = dictionary! {+ "Type" => "Font", "Subtype" => "TrueType", "BaseFont" => "NotAStandardFace",+ "FontDescriptor" => fd,+ };+ let (widths, default) = simple_widths(&doc, &font);+ assert!(widths.is_empty());+ assert_eq!(default, 0.6);++ // No descriptor at all still gets the non-degenerate invented default.+ let bare = dictionary! { "Type" => "Font", "Subtype" => "TrueType" };+ assert_eq!(simple_widths(&doc, &bare).1, 0.5);+ }++ // The array form of /W was the one width path with no bound on the start CID.+ // `num` saturates at u32::MAX, so `c + j` panics in debug and wraps in release.+ #[test]+ fn w_array_form_cannot_overflow_the_cid() {+ let mut doc = Document::new();+ let desc = doc.add_object(dictionary! {+ "Type" => "Font",+ "Subtype" => "CIDFontType2",+ "W" => vec![4_294_967_295u32.into(), Object::Array(vec![500.into(), 600.into()])],+ });+ let font = dictionary! {+ "Type" => "Font",+ "Subtype" => "Type0",+ "DescendantFonts" => vec![desc.into()],+ };+ let (widths, _) = cid_widths(&doc, &font);+ assert!(widths.keys().all(|c| *c <= MAX_CID));+ }++ // 9.10.3: a bfrange's array holds one destination per code in lo..=hi. A+ // longer array used to run past `hi` and, at the top of the code space, wrap.+ #[test]+ fn bfrange_array_form_stops_at_hi() {+ let map = cmap::parse(b"1 beginbfrange\n<0041> <0042> [<0061> <0062> <0063>]\nendbfrange");+ assert_eq!(map.get(&0x41).map(String::as_str), Some("a"));+ assert_eq!(map.get(&0x42).map(String::as_str), Some("b"));+ assert_eq!(map.get(&0x43), None, "the surplus entry is outside the range");+ }+}+ #[cfg(test)] mod type1_tests { use super::*;@@ -2122,8 +2503,12 @@ pub(crate) mod cmap { } i += 3; }- (Some(Token::Hex(lo)), Some(Token::Hex(_hi)), Some(Token::ArrayOpen)) => {+ (Some(Token::Hex(lo)), Some(Token::Hex(hi)), Some(Token::ArrayOpen)) => { let lo = code(lo);+ // 9.10.3: the array holds one destination per code in+ // lo..=hi. Clamped like the incrementing form so a+ // corrupt `hi` cannot be outrun by a longer array.+ let hi = code(hi).min(lo.saturating_add(super::MAX_CID)); i += 3; // skip lo, hi, '[' let mut n = 0u32; while i < tokens.len() {@@ -2133,7 +2518,16 @@ pub(crate) mod cmap { break; } Token::Hex(dst) => {- map.insert(lo + n, utf16be(dst));+ // `lo` comes from the file and the array+ // may be longer than hi-lo+1, so cap the+ // walk at `hi` instead of letting it run+ // past the range and wrap.+ let c = lo.saturating_add(n);+ if c > hi {+ i += 1;+ continue;+ }+ map.insert(c, utf16be(dst)); n += 1; i += 1; }
pdf/src/main/rust/src/forms.rs
diff --git a/pdf/src/main/rust/src/forms.rs b/pdf/src/main/rust/src/forms.rsindex 1c3f12c9fd..f61430beeb 100644--- a/pdf/src/main/rust/src/forms.rs+++ b/pdf/src/main/rust/src/forms.rs@@ -273,7 +273,14 @@ pub(crate) fn list_links(handle: i64, page_index: i32) -> Option<Vec<u8>> { } } else if s == Some(b"GoTo".as_ref()) { if let Ok(d) = action.get(b"D") {- dest_page = resolve_dest_page(doc, d, &page_of);+ // §12.6.4.2: a GoTo action's /D "shall be" a name, a byte+ // string or an array — the first two being named+ // destinations resolved through /Dests or the /Names+ // name tree (§12.3.2.3). Accepting only the array form+ // left dest_page at -1, and the record filter below then+ // dropped the link entirely, so every named-destination+ // link in the document was untappable.+ dest_page = resolve_dest(doc, deref(doc, d).unwrap_or(d), &page_of); } } else if s == Some(b"GoToR".as_ref()) { if let Ok(d) = action.get(b"D") {@@ -1177,6 +1184,70 @@ mod da_tests { assert_eq!(c.matches("Tj").count(), 2, "expected exactly two lines: {c}"); } + /// §12.6.4.2: a GoTo action's `/D` "shall be" a name, a byte string or an+ /// array — the first two naming a destination resolved through `/Dests` or+ /// the `/Names` name tree (§12.3.2.3). Accepting only the array form left+ /// `dest_page` at -1, and `list_links` drops any record with neither a page+ /// nor a URI, so every named-destination link was silently untappable.+ #[test]+ fn a_goto_link_to_a_named_destination_resolves() {+ for (name, dest) in [+ ("array", Object::Array(vec![])), // placeholder, replaced below+ ("name", name_obj("Chapter2")),+ ("string", Object::string_literal("Chapter2")),+ ] {+ let mut doc = Document::with_version("1.7");+ let pages_id = doc.new_object_id();+ let p0 = doc.add_object(dictionary! {+ "Type" => name_obj("Page"), "Parent" => Object::Reference(pages_id),+ "MediaBox" => rect_obj([0.0, 0.0, 612.0, 792.0]),+ });+ let p1 = doc.add_object(dictionary! {+ "Type" => name_obj("Page"), "Parent" => Object::Reference(pages_id),+ "MediaBox" => rect_obj([0.0, 0.0, 612.0, 792.0]),+ });+ let target = Object::Array(vec![Object::Reference(p1), name_obj("Fit")]);+ let dest = if name == "array" { target.clone() } else { dest };+ let action = doc.add_object(dictionary! { "S" => name_obj("GoTo"), "D" => dest });+ let link = doc.add_object(dictionary! {+ "Type" => name_obj("Annot"), "Subtype" => name_obj("Link"),+ "Rect" => rect_obj([10.0, 10.0, 100.0, 30.0]),+ "A" => Object::Reference(action),+ });+ if let Ok(Object::Dictionary(d)) = doc.get_object_mut(p0) {+ d.set("Annots", Object::Array(vec![Object::Reference(link)]));+ }+ doc.objects.insert(+ pages_id,+ Object::Dictionary(dictionary! {+ "Type" => name_obj("Pages"),+ "Kids" => Object::Array(vec![Object::Reference(p0), Object::Reference(p1)]),+ "Count" => 2,+ }),+ );+ let names = doc.add_object(dictionary! {+ "Dests" => dictionary! {+ "Names" => Object::Array(vec![Object::string_literal("Chapter2"), target]),+ },+ });+ let cat = doc.add_object(dictionary! {+ "Type" => name_obj("Catalog"),+ "Pages" => Object::Reference(pages_id),+ "Names" => Object::Reference(names),+ });+ doc.trailer.set("Root", cat);+ let handle = next_handle();+ registry().lock().unwrap_or_else(|e| e.into_inner()).insert(handle, doc);++ let buf = list_links(handle, 0).expect("links");+ let count = u32::from_le_bytes(buf[0..4].try_into().expect("count"));+ assert_eq!(count, 1, "/D as {name}: the link was dropped entirely");+ let dest_page = i32::from_le_bytes(buf[20..24].try_into().expect("dest"));+ assert_eq!(dest_page, 1, "/D as {name}: resolved to the wrong page");+ close_document(handle);+ }+ }+ /// A document with one AcroForm `/DR /Font /Fx` entry. fn doc_with_dr_font(font: Dictionary) -> Document { let mut doc = Document::with_version("1.7");
pdf/src/main/rust/src/functions.rs
diff --git a/pdf/src/main/rust/src/functions.rs b/pdf/src/main/rust/src/functions.rsindex f00ed375f8..529bf7a89e 100644--- a/pdf/src/main/rust/src/functions.rs+++ b/pdf/src/main/rust/src/functions.rs@@ -45,12 +45,18 @@ pub(crate) enum PdfFunction { }, Exponential { domain: [f64; 2],+ /// 7.10.1 Table 38 makes `/Range` optional for types 2 and 3, but when it IS+ /// present outputs shall be clipped to it — a Type 2 whose `/Domain` extends+ /// past 1 evaluates `C0 + t^N*(C1-C0)` outside the `C0..C1` interval, so the+ /// entry is not redundant.+ range: Vec<[f64; 2]>, c0: Vec<f64>, c1: Vec<f64>, n: f64, }, Stitching { domain: [f64; 2],+ range: Vec<[f64; 2]>, functions: Vec<PdfFunction>, bounds: Vec<f64>, encode: Vec<[f64; 2]>,@@ -103,6 +109,29 @@ fn read_floats(obj: Option<&Object>) -> Vec<f64> { } } +/// Clip `v` to the interval described by the pair `[a, b]` taken from a `/Domain`+/// or `/Range` entry (7.10.1: inputs are clipped to Domain, outputs to Range).+///+/// This exists instead of `f64::clamp` for two reasons, both reachable from a file:+///+/// * `f64::clamp` PANICS when its low bound exceeds its high bound, and nothing in+/// Table 38 stops a generator writing `[1 0]`. A reversed pair therefore aborted+/// the render of the whole page rather than clipping one component.+/// * `f64::clamp` PROPAGATES NaN. A NaN component survives every downstream+/// conversion and lands as an arbitrary (usually black) colour, so it has to be+/// removed at the boundary rather than clamped — the same reasoning the+/// `Exponential` arm already applies to `t^N`.+///+/// A non-finite bound is ignored rather than honoured, so `f64::max`/`min`'s+/// NaN-skipping behaviour is what makes the degenerate cases fall out.+fn clip(v: f64, a: f64, b: f64) -> f64 {+ if !v.is_finite() {+ let lo = a.min(b);+ return if lo.is_finite() { lo } else { 0.0 };+ }+ v.max(a.min(b)).min(a.max(b))+}+ impl PdfFunction { /// Parse a function object (reference, dict, stream, or array-of-functions). pub(crate) fn parse(doc: &Document, obj: &Object) -> Option<PdfFunction> {@@ -194,13 +223,13 @@ impl PdfFunction { // the target colour space too few components. The padding values are // the same per-index defaults `eval` already applied, so this is a // no-op for every well-formed function.- let range_j = read_pairs(dict.get(b"Range").ok()).len();- let j = c0.len().max(c1.len()).max(range_j).min(MAX_FN_OUTPUTS);+ let range = read_pairs(dict.get(b"Range").ok());+ let j = c0.len().max(c1.len()).max(range.len()).min(MAX_FN_OUTPUTS); c0.resize(j, 0.0); c1.resize(j, 1.0); let n = dict.get(b"N").ok().and_then(num).unwrap_or(1.0); let domain = domain_pairs.first().copied().unwrap_or([0.0, 1.0]);- Some(PdfFunction::Exponential { domain, c0, c1, n })+ Some(PdfFunction::Exponential { domain, range, c0, c1, n }) } 3 => { let funcs_obj = deref(doc, dict.get(b"Functions").ok()?)?;@@ -218,8 +247,9 @@ impl PdfFunction { } let bounds = read_floats(dict.get(b"Bounds").ok()); let encode = read_pairs(dict.get(b"Encode").ok());+ let range = read_pairs(dict.get(b"Range").ok()); let domain = domain_pairs.first().copied().unwrap_or([0.0, 1.0]);- Some(PdfFunction::Stitching { domain, functions, bounds, encode })+ Some(PdfFunction::Stitching { domain, range, functions, bounds, encode }) } 4 => { let bytes = stream_bytes?;@@ -234,8 +264,8 @@ impl PdfFunction { /// Evaluate the function, returning the output tuple. pub(crate) fn eval(&self, inputs: &[f64]) -> Vec<f64> { match self {- PdfFunction::Exponential { domain, c0, c1, n } => {- let t = inputs.first().copied().unwrap_or(0.0).clamp(domain[0], domain[1]);+ PdfFunction::Exponential { domain, range, c0, c1, n } => {+ let t = clip(inputs.first().copied().unwrap_or(0.0), domain[0], domain[1]); // 7.10.3 constrains Domain so that t^N is defined, but a malformed // file can still reach negative t with a non-integer N, which gives // NaN and would poison every output component.@@ -250,15 +280,19 @@ impl PdfFunction { .map(|i| { let a = c0.get(i).copied().unwrap_or(0.0); let b = c1.get(i).copied().unwrap_or(1.0);- a + (b - a) * tn+ let v = a + (b - a) * tn;+ match range.get(i) {+ Some(r) => clip(v, r[0], r[1]),+ None => v,+ } }) .collect() }- PdfFunction::Stitching { domain, functions, bounds, encode } => {+ PdfFunction::Stitching { domain, range, functions, bounds, encode } => { if functions.is_empty() { return Vec::new(); }- let x = inputs.first().copied().unwrap_or(0.0).clamp(domain[0], domain[1]);+ let x = clip(inputs.first().copied().unwrap_or(0.0), domain[0], domain[1]); // Select sub-function k. let mut k = 0usize; while k < bounds.len() && x >= bounds[k] {@@ -274,7 +308,13 @@ impl PdfFunction { } else { e0 + (x - lo) * (e1 - e0) / (hi - lo) };- functions[k].eval(&[xe])+ let mut out = functions[k].eval(&[xe]);+ for (i, v) in out.iter_mut().enumerate() {+ if let Some(r) = range.get(i) {+ *v = clip(*v, r[0], r[1]);+ }+ }+ out } PdfFunction::Sampled { .. } => self.eval_sampled(inputs), PdfFunction::PostScript { domain, range, program } => {@@ -283,7 +323,7 @@ impl PdfFunction { .enumerate() .map(|(i, v)| { if let Some(d) = domain.get(i) {- v.clamp(d[0], d[1])+ clip(*v, d[0], d[1]) } else { *v }@@ -298,7 +338,7 @@ impl PdfFunction { } for (i, v) in out.iter_mut().enumerate() { if let Some(r) = range.get(i) {- *v = v.clamp(r[0], r[1]);+ *v = clip(*v, r[0], r[1]); } } }@@ -352,13 +392,13 @@ impl PdfFunction { for (i, sz) in size.iter().enumerate().take(n_in) { let d = domain.get(i).copied().unwrap_or([0.0, 1.0]); let enc = encode.get(i).copied().unwrap_or([0.0, (*sz as f64 - 1.0).max(0.0)]);- let x = inputs.get(i).copied().unwrap_or(0.0).clamp(d[0], d[1]);+ let x = clip(inputs.get(i).copied().unwrap_or(0.0), d[0], d[1]); let ev = if (d[1] - d[0]).abs() < 1e-12 { enc[0] } else { enc[0] + (x - d[0]) * (enc[1] - enc[0]) / (d[1] - d[0]) };- e.push(ev.clamp(0.0, (*sz as f64 - 1.0).max(0.0)));+ e.push(clip(ev, 0.0, (*sz as f64 - 1.0).max(0.0))); } // Multilinear interpolation over the 2^n_in surrounding grid corners. let max_val = if bps >= 32 { u32::MAX as f64 } else { ((1u64 << bps) - 1) as f64 };@@ -414,7 +454,7 @@ impl PdfFunction { let dec = decode.get(j).copied().unwrap_or([0.0, 1.0]); *o = dec[0] + *o * (dec[1] - dec[0]); if let Some(r) = range.get(j) {- *o = o.clamp(r[0], r[1]);+ *o = clip(*o, r[0], r[1]); } } out@@ -605,7 +645,13 @@ fn exec_ps_op(op: PsOp, stack: &mut Vec<PsVal>, steps: &mut usize, depth: u32) - Log => { let a = pop_num(stack)?; stack.push(PsVal::Num(if a > 0.0 { a.log10() } else { 0.0 })); } Floor => { let a = pop_num(stack)?; stack.push(PsVal::Num(a.floor())); } Ceiling => { let a = pop_num(stack)?; stack.push(PsVal::Num(a.ceil())); }- Round => { let a = pop_num(stack)?; stack.push(PsVal::Num(a.round())); }+ Round => {+ // PLRM `round` returns the nearest integer and, for a value exactly+ // halfway, the GREATER of the two. `f64::round` breaks that tie away+ // from zero instead, so -1.5 came out -2 where PostScript gives -1.+ let a = pop_num(stack)?;+ stack.push(PsVal::Num((a + 0.5).floor()));+ } Truncate => { let a = pop_num(stack)?; stack.push(PsVal::Num(a.trunc())); } Cvi => { let a = pop_num(stack)?; stack.push(PsVal::Num(a.trunc())); } Cvr => { /* no-op: already real */ }@@ -633,7 +679,14 @@ fn exec_ps_op(op: PsOp, stack: &mut Vec<PsVal>, steps: &mut usize, depth: u32) - let b = pop_num(stack)? as i64; let a = pop_num(stack)? as i64; stack.push(PsVal::Num(if b != 0 { (a % b) as f64 } else { 0.0 })); }- Exp => { let b = pop_num(stack)?; let a = po
Diff truncated.