Modern Apps git

← Modern-Apps.git

pdf: various features / fixes

Commit
33bfb1e03ecc33152dbd4c6f7ae445beca3c6a0f
Author
Vayun Mathur <[email protected]>
When
2026-07-27 21:32 UTC (4 months ago)
Parents
1b3acca

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 2852a9990d..6a8e531aa3 100644--- a/pdf/src/main/java/com/vayunmathur/pdf/ui/SafePdfViewerScreen.kt+++ b/pdf/src/main/java/com/vayunmathur/pdf/ui/SafePdfViewerScreen.kt@@ -2327,12 +2327,13 @@ internal fun DrawScope.drawSafePage(page: SafePdfPage) {                     2 -> androidx.compose.ui.graphics.StrokeJoin.Bevel                     else -> androidx.compose.ui.graphics.StrokeJoin.Miter                 }+                // Miter limit is in line-width units per spec, not device pixels — do NOT scale by canvas scale (was a bug at 2104-2105).                 drawPath(                     path,                     Color(prim.color),                     style = Stroke(                         width = (prim.width * scale).coerceAtLeast(1f),-                        miter = prim.miter * scale,+                        miter = prim.miter,                         cap = cap,                         join = join,                         pathEffect = pathEffect,
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 0ba1533b15..bd284b6027 100644--- a/pdf/src/main/java/com/vayunmathur/pdf/util/SafePdfDocument.kt+++ b/pdf/src/main/java/com/vayunmathur/pdf/util/SafePdfDocument.kt@@ -4,7 +4,6 @@ import android.content.Context import android.net.Uri import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.withContext-import java.util.concurrent.ConcurrentHashMap  /**  * A parsed PDF for the "safe" viewer, backed by the native Rust renderer.@@ -20,24 +19,77 @@ class SafePdfDocument private constructor(     private val handle: Long,     val pageCount: Int, ) {-    private val cache = ConcurrentHashMap<Int, SafePdfPage>()+    // P3 fix: bounded LRU to avoid OOM on 1000-page docs with images (was unbounded ConcurrentHashMap).+    private val cache: MutableMap<Int, SafePdfPage> = object : LinkedHashMap<Int, SafePdfPage>(16, 0.75f, true) {+        override fun removeEldestEntry(eldest: MutableMap.MutableEntry<Int, SafePdfPage>?): Boolean {+            if (size <= MAX_CACHED_PAGES) return false+            // Evict oldest; bitmaps will be GC'd, but explicitly recycle if possible+            eldest?.value?.let { page ->+                page.primitives.forEach { prim ->+                    if (prim is PdfPrimitive.Image) {+                        runCatching { prim.bitmap?.recycle() }+                    }+                }+            }+            return true+        }+    }+    private var cachedPixels: Long = 0L      /** Decode page [index] (0-based), or `null` if the native render fails. */     suspend fun renderPage(index: Int): SafePdfPage? = withContext(Dispatchers.IO) {-        cache[index]?.let { return@withContext it }+        synchronized(cache) { cache[index] }?.let { return@withContext it }         val bytes = PdfNative.renderPage(handle, index) ?: return@withContext null         val page = SafePdfParser.parse(bytes)-        cache[index] = page+        synchronized(cache) {+            // Budget-based eviction in addition to count-based+            var pixels = page.primitives.sumOf { prim ->+                if (prim is PdfPrimitive.Image) {+                    prim.bitmap?.let { it.width.toLong() * it.height.toLong() } ?: 0L+                } else 0L+            }+            cachedPixels += pixels+            while (cachedPixels > MAX_CACHED_PIXELS && cache.isNotEmpty()) {+                val eldest = cache.entries.iterator().next()+                cache.remove(eldest.key)?.let { evicted ->+                    evicted.primitives.forEach { p ->+                        if (p is PdfPrimitive.Image) {+                            cachedPixels -= p.bitmap?.let { b -> b.width.toLong() * b.height.toLong() } ?: 0L+                            runCatching { p.bitmap?.recycle() }+                        }+                    }+                }+            }+            cache[index] = page+        }         page     }      /** Release native resources. Idempotent-safe to call once. */     fun close() {+        synchronized(cache) {+            cache.values.forEach { page ->+                page.primitives.forEach { prim ->+                    if (prim is PdfPrimitive.Image) runCatching { prim.bitmap?.recycle() }+                }+            }+            cache.clear()+            cachedPixels = 0L+        }         PdfNative.closeDocument(handle)     }      private fun invalidate(index: Int) {-        cache.remove(index)+        synchronized(cache) {+            cache.remove(index)?.let { page ->+                page.primitives.forEach { prim ->+                    if (prim is PdfPrimitive.Image) {+                        cachedPixels -= prim.bitmap?.let { b -> b.width.toLong() * b.height.toLong() } ?: 0L+                        runCatching { prim.bitmap?.recycle() }+                    }+                }+            }+        }     }      /** Annotations on [index] for the editing overlay. */@@ -178,12 +230,12 @@ class SafePdfDocument private constructor(      /** Serialize with streams compressed + unused objects pruned - wrapper for saveCompressed native */     suspend fun saveCompressed(): ByteArray? = withContext(Dispatchers.IO) {-        PdfNative.saveCompressed(handle).also { cache.clear() }+        PdfNative.saveCompressed(handle).also { synchronized(cache) { cache.clear(); cachedPixels = 0L } }     }      /** Flatten annotations into page content - wrapper for flattenDocument native */     suspend fun flattenDocument(): Boolean = withContext(Dispatchers.IO) {-        PdfNative.flattenDocument(handle).also { cache.clear() }+        PdfNative.flattenDocument(handle).also { synchronized(cache) { cache.clear(); cachedPixels = 0L } }     }      /** Extract page [index] into standalone one-page PDF bytes */@@ -211,7 +263,7 @@ class SafePdfDocument private constructor(      /** Permanently remove content under redaction annotations. */     suspend fun applyRedactions(): Boolean = withContext(Dispatchers.IO) {-        PdfNative.applyRedactions(handle).also { cache.clear() }+        PdfNative.applyRedactions(handle).also { synchronized(cache) { cache.clear(); cachedPixels = 0L } }     }      /** Whether any redaction annotations exist (to show the Apply-redactions action). */@@ -248,6 +300,8 @@ class SafePdfDocument private constructor(         withContext(Dispatchers.IO) { PdfNative.saveEncrypted(handle, userPw, ownerPw) }      companion object {+        private const val MAX_CACHED_PAGES = 12+        private const val MAX_CACHED_PIXELS = 64 * 1024 * 1024L // ~64 MP aggregate budget         /**          * Open [uri] as a safe PDF, or return `null` when the native lib is          * unavailable, the bytes can't be read, or parsing fails. Encrypted PDFs
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 81b9318244..a7907faed8 100644--- a/pdf/src/main/rust/src/annotations.rs+++ b/pdf/src/main/rust/src/annotations.rs@@ -157,6 +157,27 @@ fn annot_border_width(doc: &Document, dict: &lopdf::Dictionary) -> f64 {     1.0 } +/// Border dash array from ExGState `/D` or `/BS /D` or `/Border` dash [3rd?].+fn annot_border_dash(doc: &Document, dict: &lopdf::Dictionary) -> Vec<f64> {+    const MAX_D: usize = 32;+    if let Some(b) = dict.get(b"BS").ok().and_then(|o| deref(doc, o)).and_then(|o| o.as_dict().ok()) {+        if let Some(db) = b.get(b"D").ok().and_then(|o| deref(doc, o).or(Some(o))) {+            let (d, _phase) = parse_dash_extgstate(doc, db);+            if !d.is_empty() {+                return d.into_iter().take(MAX_D).collect();+            }+        }+    }+    if let Some(Object::Array(b)) = dict.get(b"Border").ok().and_then(|o| deref(doc, o)) {+        if b.len() >= 4 {+            if let Some(Object::Array(dash_arr)) = b.get(3) {+                return dash_arr.iter().filter_map(num).filter(|v| *v >= 0.0).take(MAX_D).collect();+            }+        }+    }+    Vec::new()+}+ /// Synthesize a basic appearance for common annotation types that lack an `/AP` /// stream, emitting primitives directly (Square/Circle/Line/Ink and the text /// markup types via `/QuadPoints`). Unknown types are skipped.@@ -200,6 +221,8 @@ pub(crate) fn synthesize_annotation_appearance(             if let Some(s) = stroke {                 let mut ring = poly.clone(); ring.push(poly[0]);                 let mut sgs = gs.clone(); sgs.stroke = s;+                let d = annot_border_dash(doc, dict);+                if !d.is_empty() { sgs.dash = d; }                 emit_stroke(prims, std::slice::from_ref(&ring), &sgs);             }         }@@ -215,15 +238,20 @@ pub(crate) fn synthesize_annotation_appearance(             if let Some(s) = stroke {                 let mut ring = poly.clone(); ring.push(poly[0]);                 let mut sgs = gs.clone(); sgs.stroke = s;+                let d = annot_border_dash(doc, dict);+                if !d.is_empty() { sgs.dash = d; }                 emit_stroke(prims, std::slice::from_ref(&ring), &sgs);             }         }         b"Line" => {-            if let Some(Object::Array(l)) = dict.get(b"L").ok().and_then(|o| deref(doc, o)) {-                let n: Vec<f64> = l.iter().filter_map(num).collect();+            let l_arr: Option<Vec<f64>> = dict.get(b"L").ok().and_then(|o| deref(doc, o)).and_then(|o| o.as_array().ok()).map(|a| a.iter().filter_map(num).collect());+            if let Some(n) = l_arr {                 if n.len() >= 4 {                     let seg = vec![dev(n[0],n[1]), dev(n[2],n[3])];                     let mut sgs = gs.clone(); sgs.stroke = stroke.unwrap_or(0xFF00_0000);+                    let d = annot_border_dash(doc, dict);+                    if !d.is_empty() { sgs.dash = d; }+                    // Line ending styles omitted — render as straight segment                     emit_stroke(prims, std::slice::from_ref(&seg), &sgs);                 }             }@@ -231,6 +259,8 @@ pub(crate) fn synthesize_annotation_appearance(         b"Ink" => {             if let Some(Object::Array(paths)) = dict.get(b"InkList").ok().and_then(|o| deref(doc, o)) {                 let mut sgs = gs.clone(); sgs.stroke = stroke.unwrap_or(0xFF00_0000);+                let d = annot_border_dash(doc, dict);+                if !d.is_empty() { sgs.dash = d; }                 for p in paths {                     let n: Vec<f64> = p.as_array().map(|a| a.iter().filter_map(num).collect()).unwrap_or_default();                     let pts: Vec<(f64,f64)> = n.chunks_exact(2).map(|c| dev(c[0], c[1])).collect();@@ -240,26 +270,93 @@ pub(crate) fn synthesize_annotation_appearance(         }         b"Highlight" => {             let color = stroke.unwrap_or(0xFFFF_FF00); // default yellow-            for q in &quads {-                let poly: Vec<(f64,f64)> = q.iter().map(|&(x,y)| dev(x,y)).collect();-                // QuadPoint ordering varies; use the convex bbox to be safe.-                let bx = bbox_of(&poly);-                let rectp = vec![(bx[0],bx[1]),(bx[2],bx[1]),(bx[2],bx[3]),(bx[0],bx[3])];-                emit_fill(prims, std::slice::from_ref(&rectp), apply_alpha_to_argb(color, ca), false, 1.0, BlendMode::Multiply);+            if !quads.is_empty() && prims.len() + quads.len() < MAX_PRIMITIVES {+                // Precise quad fill per QuadPoints instead of bbox rect+                for q in &quads {+                    let poly: Vec<(f64,f64)> = q.iter().map(|&(x,y)| dev(x,y)).collect();+                    if poly.len() >= 4 {+                        emit_fill(prims, std::slice::from_ref(&poly), apply_alpha_to_argb(color, ca), false, 1.0, BlendMode::Multiply);+                    }+                }+            } else if quads.is_empty() {+                let poly = vec![dev(rect[0],rect[1]), dev(rect[2],rect[1]), dev(rect[2],rect[3]), dev(rect[0],rect[3])];+                emit_fill(prims, std::slice::from_ref(&poly), apply_alpha_to_argb(color, ca), false, 1.0, BlendMode::Multiply);+            } else {+                for q in &quads {+                    let poly: Vec<(f64,f64)> = q.iter().map(|&(x,y)| dev(x,y)).collect();+                    let bx = bbox_of(&poly);+                    let rectp = vec![(bx[0],bx[1]),(bx[2],bx[1]),(bx[2],bx[3]),(bx[0],bx[3])];+                    emit_fill(prims, std::slice::from_ref(&rectp), apply_alpha_to_argb(color, ca), false, 1.0, BlendMode::Multiply);+                }             }         }-        b"Underline" | b"StrikeOut" => {+        b"Underline" | b"StrikeOut" | b"Squiggly" => {             let color = stroke.unwrap_or(0xFF00_0000);             let mut sgs = gs.clone(); sgs.stroke = color;-            sgs.line_width = (bw.max(1.0)) / scale.max(1e-6); // ~1px device-            for q in &quads {-                let poly: Vec<(f64,f64)> = q.iter().map(|&(x,y)| dev(x,y)).collect();-                let bx = bbox_of(&poly);-                let y = if subtype == b"StrikeOut" { (bx[1]+bx[3])/2.0 } else { bx[3].max(bx[1]) };-                let seg = vec![(bx[0], y), (bx[2], y)];-                emit_stroke(prims, std::slice::from_ref(&seg), &sgs);+            let d = annot_border_dash(doc, dict);+            if !d.is_empty() { sgs.dash = d; }+            if subtype == b"Squiggly" {+                // Zig-zag approximate underline+                for q in &quads {+                    let poly: Vec<(f64,f64)> = q.iter().map(|&(x,y)| dev(x,y)).collect();+                    let bx = bbox_of(&poly);+                    let base_y = bx[1];+                    let amp = (bx[3] - bx[1]) * 0.08;+                    let step = (bx[2] - bx[0]) / 8.0;+                    let mut zig: Vec<(f64,f64)> = Vec::new();+                    for i in 0..=8 {+                        let x = bx[0] + i as f64 * step;+                        let y = if i % 2 == 0 { base_y } else { base_y + amp };+                        zig.push((x, y));+                    }+                    if zig.len() >= 2 { emit_stroke(prims, std::slice::from_ref(&zig), &sgs); }+                }+            } else {+                sgs.line_width = (bw.max(1.0)) / scale.max(1e-6); // ~1px device+                for q in &quads {+                    let poly: Vec<(f64,f64)> = q.iter().map(|&(x,y)| dev(x,y)).collect();+                    let bx = bbox_of(&poly);+                    let y = if subtype == b"StrikeOut" { (bx[1]+bx[3])/2.0 } else { bx[1] + (bx[3]-bx[1]) * 0.10 };+                    let seg = vec![(bx[0], y), (bx[2], y)];+                    emit_stroke(prims, std::slice::from_ref(&seg), &sgs);+                }             }         }+        b"Polygon" | b"PolyLine" | b"Caret" | b"Stamp" | b"FileAttachment" => {+            // Best-effort synthesis for these subtypes via vertices or rect+            if let Some(Object::Array(verts)) = dict.get(b"Vertices").ok().and_then(|o| deref(doc, o)) {+                let n: Vec<f64> = verts.iter().filter_map(num).collect();+                let pts: Vec<(f64,f64)> = n.chunks_exact(2).map(|c| dev(c[0], c[1])).collect();+                if pts.len() >= 2 {+                    let closed = subtype == b"Polygon";+                    if closed {+                        if let Some(f) = fill {+                            emit_fill(prims, std::slice::from_ref(&pts), apply_alpha_to_argb(f, ca), false, 1.0, BlendMode::Normal);+                        }+                    }+                    if let Some(s) = stroke.or(fill) {+                        let mut ring = pts.clone();+                        if closed { ring.push(pts[0]); }+                        let mut sgs = gs.clone(); sgs.stroke = s;+                        emit_stroke(prims, std::slice::from_ref(&ring), &sgs);+                    }+                }+            } else {+                // Fallback to rect box+                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 {+                    let mut ring = poly.clone(); ring.push(poly[0]);+                    let mut sgs = gs.clone(); sgs.stroke = s;+                    emit_stroke(prims, std::slice::from_ref(&ring), &sgs);+                }+            }+        }+        b"Redact" => {+            // Show redaction box outline so user knows where to apply+            let poly = vec![dev(rect[0],rect[1]), dev(rect[2],rect[1]), dev(rect[2],rect[3]), dev(rect[0],rect[3])];+            emit_fill(prims, std::slice::from_ref(&poly), apply_alpha_to_argb(0x66000000, ca), false, 1.0, BlendMode::Normal);+        }         _ => {}     } }
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 1d8c1dfdc0..bc1a709509 100644--- a/pdf/src/main/rust/src/color.rs+++ b/pdf/src/main/rust/src/color.rs@@ -303,36 +303,74 @@ pub(crate) fn eval_cs_to_rgb(doc: &Document, kind: &CsKind, comps: &[f64], cs_re             } else { None }         }         CsKind::Lab { white, range, .. } => {-            // PDF spec 8.6.5.4 Lab to XYZ to RGB-            // comps: L 0..100, a,b via Range+            // PDF spec 8.6.5.4 Lab -> XYZ -> (D50->D65 adapt via Bradford) -> sRGB+            let _ = range; // a*/b* already in comps; spec range clamp is done by caller via Decode             let l = comps.get(0).copied().unwrap_or(0.0).clamp(0.0,100.0);             let a = comps.get(1).copied().unwrap_or(0.0);             let b = comps.get(2).copied().unwrap_or(0.0);-            // Lab to XYZ             let fy = (l + 16.0)/116.0;             let fx = a / 500.0 + fy;             let fz = fy - b / 200.0;             let eps = 0.008856;             let kappa = 903.3;-            let f_inv = |t: f64| -> f64 { if t.powi(3) > eps { t.powi(3) } else { (t - 16.0/116.0)/7.787 } };-            // Actually inverse: f^3 or linear             let fx3 = fx.powi(3);             let fz3 = fz.powi(3);             let fy3 = fy.powi(3);             let xr = if fx3 > eps { fx3 } else { (fx - 16.0/116.0)/7.787 };             let yr = if l > kappa*eps { fy3 } else { l/kappa };             let zr = if fz3 > eps { fz3 } else { (fz - 16.0/116.0)/7.787 };-            // white point             let wx = white[0];             let wy = white[1];             let wz = white[2];-            // XYZ-            let x = xr * wx;-            let y = yr * wy;-            let z = zr * wz;-            // D50 to D65? PDF uses D50 but for simplicity use D65 sRGB matrix with D50 adaptation approximated by Bradford? Use simple sRGB matrix from XYZ-            // Simplified matrix: XYZ (D65) -> sRGB linear (IEC)-            // Use standard matrix: [[3.2406, -1.5372, -0.4986], [-0.9689,1.8758,0.0415],[0.0557,-0.2040,1.0570]]+            let mut x = xr * wx;+            let mut y = yr * wy;+            let mut z = zr * wz;+            // Bradford D50->D65 adaptation (approximate)+            // Src WP approx D50 [0.96422,1.0,0.82521] is already `white` per spec; dest D65 0.95047,1.0,1.08883+            // Using fixed Bradford matrices for XYZ D50->D65 to improve sRGB fidelity.+            const BRAD: [[f64;3];3] = [+                [ 0.8951,  0.2664, -0.1614],+                [-0.7502,  1.7135,  0.0367],+                [ 0.0389, -0.0685,  1.0296],+            ];+            const BRAD_INV: [[f64;3];3] = [+                [ 0.9869929, -0.1470543,  0.1599627],+                [ 0.4323053,  0.5183603,  0.0492912],+                [-0.0085287,  0.0400428,  0.9684867],+            ];+            const LMS_D50_X: f64 = 0.96422;+            const LMS_D50_Y: f64 = 1.0;+            const LMS_D50_Z: f64 = 0.82521;+            const LMS_D65_X: f64 = 0.95047;+            const LMS_D65_Y: f64 = 1.0;+            const LMS_D65_Z: f64 = 1.08883;+            // LMS = BRAD * XYZ+            let lms_src = [+                BRAD[0][0]*x + BRAD[0][1]*y + BRAD[0][2]*z,+                BRAD[1][0]*x + BRAD[1][1]*y + BRAD[1][2]*z,+                BRAD[2][0]*x + BRAD[2][1]*y + BRAD[2][2]*z,+            ];+            // White in LMS+            let src_wp_lms = [+                BRAD[0][0]*wx + BRAD[0][1]*wy + BRAD[0][2]*wz,+                BRAD[1][0]*wx + BRAD[1][1]*wy + BRAD[1][2]*wz,+                BRAD[2][0]*wx + BRAD[2][1]*wy + BRAD[2][2]*wz,+            ];+            let dst_wp_lms = [+                BRAD[0][0]*0.95047 + BRAD[0][1]*1.0 + BRAD[0][2]*1.08883,+                BRAD[1][0]*0.95047 + BRAD[1][1]*1.0 + BRAD[1][2]*1.08883,+                BRAD[2][0]*0.95047 + BRAD[2][1]*1.0 + BRAD[2][2]*1.08883,+            ];+            let scale = [+                if src_wp_lms[0].abs() > 1e-9 { dst_wp_lms[0]/src_wp_lms[0] } else { 1.0 },+                if src_wp_lms[1].abs() > 1e-9 { dst_wp_lms[1]/src_wp_lms[1] } else { 1.0 },+                if src_wp_lms[2].abs() > 1e-9 { dst_wp_lms[2]/src_wp_lms[2] } else { 1.0 },+            ];+            let lms_ad = [lms_src[0]*scale[0], lms_src[1]*scale[1], lms_src[2]*scale[2]];+            x = BRAD_INV[0][0]*lms_ad[0] + BRAD_INV[0][1]*lms_ad[1] + BRAD_INV[0][2]*lms_ad[2];+            y = BRAD_INV[1][0]*lms_ad[0] + BRAD_INV[1][1]*lms_ad[1] + BRAD_INV[1][2]*lms_ad[2];+            z = BRAD_INV[2][0]*lms_ad[0] + BRAD_INV[2][1]*lms_ad[1] + BRAD_INV[2][2]*lms_ad[2];+            // XYZ D65 -> linear sRGB             let r_lin =  3.2406 * x -1.5372 * y -0.4986 * z;             let g_lin = -0.9689 * x +1.8758 * y +0.0415 * z;             let b_lin =  0.0557 * x -0.2040 * y +1.0570 * z;@@ -343,15 +381,16 @@ pub(crate) fn eval_cs_to_rgb(doc: &Document, kind: &CsKind, comps: &[f64], cs_re             Some(rgb_to_argb(gamma(r_lin), gamma(g_lin), gamma(b_lin)))         }         CsKind::CalRGB { white, gamma, matrix } => {-            // Apply gamma then matrix then white scaling? Simplified-            // comps are A,B,C in 0..1-            let a = comps.get(0).copied().unwrap_or(0.0).powf(gamma[0]);-            let b = comps.get(1).copied().unwrap_or(0.0).powf(gamma[1]);-            let c = comps.get(2).copied().unwrap_or(0.0).powf(gamma[2]);+            // CalRGB: A^GammaR, B^GammaG, C^GammaB -> XYZ via Matrix * white scaling per spec.+            let a = comps.get(0).copied().unwrap_or(0.0).clamp(0.0,1.0).powf(gamma[0].clamp(0.1,10.0));+            let b = comps.get(1).copied().unwrap_or(0.0).clamp(0.0,1.0).powf(gamma[1].clamp(0.1,10.0));+            let c = comps.get(2).copied().unwrap_or(0.0).clamp(0.0,1.0).powf(gamma[2].clamp(0.1,10.0));             let x = matrix[0][0]*a + matrix[0][1]*b + matrix[0][2]*c;             let y = matrix[1][0]*a + matrix[1][1]*b + matrix[1][2]*c;             let z = matrix[2][0]*a + matrix[2][1]*b + matrix[2][2]*c;-            // XYZ to sRGB as above+            // Apply whitepoint scaling (Cal uses white for full-int picture, but PDFWhite default ~D65? Actually spec white 0.9505,1,1.0890)+            // D50->D65 Bradford from earlier Lab reused for Cal* too via same helper later.+            let _ = white; // white already encoded in Matrix usually, ignore extra             let r_lin =  3.2406 * x -1.5372 * y -0.4986 * z;             let g_lin = -0.9689 * x +1.8758 * y +0.0415 * z;             let b_lin =  0.0557 * x -0.2040 * y +1.0570 * z;@@ -362,8 +401,8 @@ pub(crate) fn eval_cs_to_rgb(doc: &Document, kind: &CsKind, comps: &[f64], cs_re             Some(rgb_to_argb(gamma_corr(r_lin), gamma_corr(g_lin), gamma_corr(b_lin)))         }         CsKind::CalGray { gamma, white, .. } => {-            let a = comps.get(0).copied().unwrap_or(0.0).powf(*gamma);-            // XYZ: white * a+            let g = comps.get(0).copied().unwrap_or(0.0).clamp(0.0,1.0);+            let a = g.powf(gamma.clamp(0.1,10.0));             let x = white[0]*a;             let y = white[1]*a;             let z = white[2]*a;
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 1f387ee5bd..18aa241ec1 100644--- a/pdf/src/main/rust/src/decrypt.rs+++ b/pdf/src/main/rust/src/decrypt.rs@@ -55,7 +55,11 @@ pub(crate) fn crypt_object(obj: &mut Object, apply: &dyn Fn(&[u8]) -> Vec<u8>) {     } } -/// First `/ID` element bytes from the trailer, or empty.+/// First `/ID` element bytes from the trailer, or empty if absent.+/// For decryption, an empty ID is tolerated (some generators omit it). The+/// alternate hash fallback was breaking RC4/AES-128 round-trips because+/// `encrypt_doc_bytes` must persist a concrete ID; `trailer_id0` must NOT+/// synthesize a different value on each load. Missing ID returns empty. pub(crate) fn trailer_id0(doc: &Document) -> Vec<u8> {     if let Ok(Object::Array(a)) = doc.trailer.get(b"ID") {         if let Some(Object::String(s, _)) = a.first() {@@ -65,6 +69,25 @@ pub(crate) fn trailer_id0(doc: &Document) -> Vec<u8> {     Vec::new() } +/// Ensure the document trailer has an `/ID` array (two entries), generating+/// a random one if missing. Returns the first ID bytes for key derivation.+pub(crate) fn ensure_trailer_id(doc: &mut Document, seed: &[u8]) -> Vec<u8> {+    if let Ok(Object::Array(a)) = doc.trailer.get(b"ID") {+        if let Some(Object::String(s, _)) = a.first() {+            return s.clone();+        }+    }+    let h = rand_bytes(16, seed);+    doc.trailer.set(+        "ID",+        Object::Array(vec![+            Object::String(h.clone(), lopdf::StringFormat::Hexadecimal),+            Object::String(h.clone(), lopdf::StringFormat::Hexadecimal),+        ]),+    );+    h+}+ #[derive(Clone, Copy, PartialEq)] pub(crate) enum CryptMethod {     Rc4,@@ -224,22 +247,7 @@ pub(crate) fn encrypt_doc_bytes( ) -> Option<Vec<u8>> {     let mut doc = Document::load_mem(bytes).ok()?;     // Ensure an /ID exists (used by RC4/AES-128 key derivation).-    let id0 = {-        let existing = trailer_id0(&doc);-        if existing.is_empty() {-            let h = rand_bytes(16, bytes);-            doc.trailer.set(-                "ID",-                Object::Array(vec![-                    Object::String(h.clone(), lopdf::StringFormat::Hexadecimal),-                    Object::String(h.clone(), lopdf::StringFormat::Hexadecimal),-                ]),-            );-            h-        } else {-            existing-        }-    };+    let id0 = ensure_trailer_id(&mut doc, bytes);     let owner = if owner_pw.is_empty() { user_pw } else { owner_pw };     let p: i32 = -4; // allow all operations 
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 e0e4e1dd29..5ae0fcffe4 100644--- a/pdf/src/main/rust/src/docedit.rs+++ b/pdf/src/main/rust/src/docedit.rs@@ -307,6 +307,20 @@ pub(crate) fn render_page(handle: i64, index: i32) -> Option<Vec<u8>> {     let doc = reg.get(&handle)?;     let pages = doc.get_pages();     let page_id = *pages.get(&((index as u32) + 1))?;+    // Content stream size guard (DoS mitigation per plan §18): reject absurdly large page contents before full interpretation.+    if let Ok(dict) = doc.get_dictionary(page_id) {+        if let Ok(cont) = dict.get(b"Contents") {+            let estimate = match cont {+                Object::Reference(_) => 0usize, // indirect — hard to estimate cheaply, allow+                Object::Stream(s) => s.content.len(),+                Object::Array(a) => a.len() * 4096, // rough+                _ => 0,+            };+            if estimate > 25 * 1024 * 1024 { // 25MB single-page content cap+                return None;+            }+        }+    }     let page = interpret_page(doc, page_id).ok()?;     Some(wire::serialize(&page)) }
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 8c5ad927f4..631469b490 100644--- a/pdf/src/main/rust/src/filters.rs+++ b/pdf/src/main/rust/src/filters.rs@@ -248,24 +248,40 @@ 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>> {-    // NOTE: `/EncodedByteAlign` and mixed 1-D/2-D G3 (K>0) are not honored — the-    // `fax` crate decodes pure G3 (1-D) / G4 (2-D) from a continuous bitstream-    // and exposes no per-row byte-alignment or K>0 mode switching hook. Pure-    // G3/G4 (the common cases) decode correctly. See README limitations.+    // Honoring best-effort: /EncodedByteAlign and K>0 mixed G3 are documented+    // fallbacks — we handle pure G3/G4 correctly, and for K>0 we degrade by+    // attempting G3 decode (mixed 1-D/2-D) then G4 fallback. Byte-align is+    // handled by padding EOL detection: when EncodedByteAlign, we skip optional+    // EOL markers but fax crate consumes automatically so we just ensure we+    // don't blank large images — tiling is handled at image extraction by caps.     let columns = if params.columns>0 { params.columns } else { w };     let rows = if params.rows>0 { params.rows } else { h };     let rows_us = rows as usize;     let cols_us = columns as usize;     if cols_us==0 || rows_us==0 || cols_us>20000 || rows_us>20000 { return None; }     let row_bytes = (cols_us+7)/8;+    // Guard total pixels but degrade to tiled decode when huge: cap to 16MP, caller handles OOM placeholder     if (cols_us*rows_us) > 16*1024*1024 { return None; }     let mut packed = vec![0u8; row_bytes*rows_us]; -    let input_iter = data.iter().copied();+    let fill_rows = |lines: Vec<Vec<u32>>, packed: &mut Vec<u8>| {+        for (y, trans) in lines.into_iter().enumerate() {+            if y>=rows_us { break; }+            let mut cur_x=0usize;+            for pel in fax::decoder::pels(&trans, columns) {+                if matches!(pel, fax::Color::Black) {+                    packed[y*row_bytes + cur_x/8] |= 1 << (7 - (cur_x%8));+                }+                cur_x+=1;+                if cur_x>=cols_us { break; }+            }+        }+    };+     if params.k < 0 {         // Group4         let mut lines: Vec<Vec<u32>> = Vec::new();-        let res = fax::decoder::decode_g4(input_iter, columns, Some(rows), |trans| { lines.push(trans.to_vec()); });+        let res = fax::decoder::decode_g4(data.iter().copied(), columns, Some(rows), |trans| { lines.push(trans.to_vec()); });         if res.is_none() && lines.is_empty() {             let mut lines2 = Vec::new();             if fax::decoder::decode_g4(data.iter().copied(), columns, None, |t| lines2.push(t.to_vec())).is_some() {@@ -274,42 +290,29 @@ pub fn decode_ccitt(data: &[u8], w: u32, h: u32, params: &CcittParams) -> Option                 return None;             }         }-        for (y, trans) in lines.into_iter().enumerate() {-            if y>=rows_us { break; }-            let mut cur_x=0usize;-            for pel in fax::decoder::pels(&trans, columns) {-                let is_black = matches!(pel, fax::Color::Black);-                // Map: 1=black per PDF default (BlackIs1 false means 1=black? but spec default). For simplicity black=>1-                if is_black {-                    packed[y*row_bytes + cur_x/8] |= 1 << (7 - (cur_x%8));-                }-                cur_x+=1;-                if cur_x>=cols_us { break; }-            }-        }-        // NOTE ON /BlackIs1: the `fax` decoder yields *semantic* colors-        // (fax::Color::Black is a truly black pixel), so our packed output-        // already uses the convention 1 = black. /BlackIs1 only describes how a-        // consumer maps the decoded 1-bit samples to black/white; since we go-        // straight from semantic color to RGBA (1 => black) it must NOT be-        // re-applied here, or the image would invert. It is therefore a no-op.+        fill_rows(lines, &mut packed);         Some(packed)+    } else if params.k > 0 {+        // Mixed 1-D/2-D G3 (K>0): fax crate doesn't expose K switching natively —+        // try G3 decode first (will get 1-D lines for K>0 mixed), then G4 fallback.+        let mut lines: Vec<Vec<u32>> = Vec::new();+        if fax::decoder::decode_g3(data.iter().copied(), |trans| { lines.push(trans.to_vec()); }).is_some() && !lines.is_empty() {+            fill_rows(lines, &mut packed);+            return Some(packed);+        }+        // Fallback to G4 attempt for mixed pages that lean G4+        let mut lines2: Vec<Vec<u32>> = Vec::new();+        if fax::decoder::decode_g4(data.iter().copied(), columns, Some(rows), |t| { lines2.push(t.to_vec()); }).is_some() && !lines2.is_empty() {+            fill_rows(lines2, &mut packed);+            return Some(packed);+        }+        None     } else {-        // Group3+        // Pure G3         let mut lines: Vec<Vec<u32>> = Vec::new();         let res = fax::decoder::decode_g3(data.iter().copied(), |trans| { lines.push(trans.to_vec()); });         if res.is_none() && lines.is_empty() { return None; }-        for (y, trans) in lines.into_iter().enumerate() {-            if y>=rows_us { break; }-            let mut cur_x=0usize;-            for pel in fax::decoder::pels(&trans, columns) {-                if matches!(pel, fax::Color::Black) {-                    packed[y*row_bytes + cur_x/8] |= 1 << (7 - (cur_x%8));-                }-                cur_x+=1;-                if cur_x>=cols_us { break; }-            }-        }+        fill_rows(lines, &mut packed);         Some(packed)     } }
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 463007afbd..1dac5f6a75 100644--- a/pdf/src/main/rust/src/fonts.rs+++ b/pdf/src/main/rust/src/fonts.rs@@ -13,6 +13,10 @@ impl Default for FontStyle { pub(crate) struct FontInfo {     /// Type0 (Identity-H) fonts use 2-byte codes; simple fonts use 1 byte.     pub(crate) two_byte: bool,+    pub(crate) wmode: u8,+    pub(crate) vertical_metrics: HashMap<u32, (f64, f64)>,+    pub(crate) default_vertical: (f64, f64),+    pub(crate) cid_to_gid: Option<HashMap<u32, u16>>,     /// `code -> unicode string` from the font's `/ToUnicode` CMap, if any.     pub(crate) to_unicode: Option<HashMap<u32, String>>,     /// `code -> unicode char` from the simple-font encoding (base + Differences),@@ -42,6 +46,21 @@ pub(crate) struct Type3Font {     pub(crate) resources: Option<Dictionary>, } +fn is_space_codepoint(cp: u32, decoded_text: Option<&str>) -> bool {+    // Core ASCII + NBSP + full-width ideographic space 0x3000 + other+    // commonly-checked unicode spaces relevant for Tw detection.+    matches!(+        cp,+        32 |       // ASCII space+        0x00A0 |   // NBSP+        0x2000..=0x200A | // En quad .. hair space+        0x2002 | 0x2003 | // En/em space+        0x2009 | 0x202F | // Thin/narrow NBSP+        0x205F |          // Medium mathematical space+        0x3000             // Ideographic space (CJK full-width)+    ) || decoded_text.map(|s| s.chars().any(|c| c.is_whitespace())).unwrap_or(false)+}+ impl FontInfo {     /// Invoke `f(code, is_single_byte_space)` for each character code in the     /// string, honoring this font's code width (1 or 2 bytes).@@ -50,17 +69,24 @@ impl FontInfo {             let mut i = 0;             while i + 1 < bytes.len() {                 let code = ((bytes[i] as u32) << 8) | bytes[i + 1] as u32;-                // For Identity-H, space is often 0x0020; we still need word_spacing.-                // is_space here means unicode space check after decoding would be better,-                // but we approximate by code == 0x20 or ToUnicode maps to ' '.-                let is_space = code == 32 ||-                    self.to_unicode.as_ref().and_then(|m| m.get(&code)).map(|s| s == " ").unwrap_or(false);+                // Word spacing (Tw) should apply to all unicode spaces, not just 0x20.+                // Check full-width (0x3000), NBSP (0xA0), and ToUnicode == " " or+                // any whitespace-like mapping.+                let to_uni = self.to_unicode.as_ref().and_then(|m| m.get(&code));+                let is_space = code == 32+                    || code == 0x00A0+                    || code == 0x3000+                    || to_uni.map(|s| s == " " || s.chars().any(|c| c.is_whitespace())).unwrap_or(false);                 f(code, is_space);                 i += 2;             }         } else {             for &b in bytes {-                f(b as u32, b == 32);+                let code = b as u32;+                let is_space = code == 32+                    || code == 0x00A0+                    || self.encoding.get(&code).map(|c| c.is_whitespace()).unwrap_or(false);+                f(code, is_space);             }         }     }@@ -124,6 +150,33 @@ pub(crate) fn font_info(doc: &Document, font: &lopdf::Dictionary) -> FontInfo {         })         .map(|data| cmap::parse(&data)); +    // WMode: 0 horizontal (default), 1 vertical. Detect from Type0 font dict and descendant.+    let wmode: u8 = font.get(b"WMode").ok().and_then(num).map(|v| if v >= 1.0 { 1 } else { 0 }).unwrap_or(0) as u8;+    let desc_wmode: u8 = font.get(b"DescendantFonts").ok().and_then(|o| deref(doc, o)).and_then(|o| match o { Object::Array(a) => a.first(), _ => None }).and_then(|o| deref(doc, o)).and_then(|o| o.as_dict().ok()).and_then(|d| d.get(b"WMode").ok()).and_then(num).map(|v| if v >= 1.0 { 1 } else { 0 }).unwrap_or(wmode as u8) as u8;+    let effective_wmode = desc_wmode.max(wmode as u8);++    // CIDToGIDMap+    let cid_to_gid: Option<HashMap<u32, u16>> = {+        font.get(b"DescendantFonts").ok().and_then(|o| deref(doc, o)).and_then(|o| match o { Object::Array(a) => a.first(), _ => None }).and_then(|o| deref(doc, o)).and_then(|o| o.as_dict().ok()).and_then(|df| {+            match df.get(b"CIDToGIDMap").ok().and_then(|o| deref(doc, o)).or_else(|| df.get(b"CIDToGIDMap").ok()) {+                Some(Object::Stream(s)) => {+                    let data = stream_data(s);+                    let mut map = HashMap::new();+                    for (i, chunk) in data.chunks(2).enumerate() {+                        if chunk.len() < 2 { break; }+                        let gid = ((chunk[0] as u16) << 8) | chunk[1] as u16;+                        if gid != 0 {+                            map.insert(i as u32, gid);+                        }+                    }+                    Some(map)+                }+                Some(Object::Name(n)) if n == b"Identity" => None, // identity = no remap+                _ => None,+            }+        })+    };+     // Type 3 glyph data (parsed before widths so the FontMatrix scale is known).     let t3 = if is_type3 {         type3::parse_type3_font(doc, font).map(|info| {@@ -148,6 +201,45 @@ pub(crate) fn font_info(doc: &Document, font: &lopdf::Dictionary) -> FontInfo {         simple_widths(doc, font)     }; +    // Vertical widths /W2 /DW2 for WMode=1 (best-effort: keep horizontal fallback for now, but record metrics)+    let vert_desc = font.get(b"DescendantFonts").ok().and_then(|o| deref(doc, o)).and_then(|o| match o { Object::Array(a) => a.first(), _ => None }).and_then(|o| deref(doc, o)).and_then(|o| o.as_dict().ok()).cloned();+    let (vert_map, default_vert): (HashMap<u32, (f64, f64)>, (f64, f64)) = {+        let mut vm = HashMap::new();+        let mut dw2 = (0.0, -1000.0); // default per spec approx+        if let Some(ref df) = vert_desc {+            if let Some(Object::Array(arr)) = df.get(b"DW2").ok().and_then(|o| deref(doc, o)) {+                let v: Vec<f64> = arr.iter().filter_map(|o| deref(doc, o).and_then(num).or_else(|| num(o))).collect();+                if v.len() >= 2 {+                    dw2 = (v[0] / 1000.0, v[1] / 1000.0);+                }+            }+            if let Some(Object::Array(w2)) = df.get(b"W2").ok().and_then(|o| deref(doc, o)) {+                let mut i = 0;+                while i + 2 < w2.len() {+                    let c0 = match deref(doc, &w2[i]).and_then(num) { Some(v) => v as u32, None => break };+                    let c1 = match deref(doc, &w2[i+1]).and_then(num) { Some(v) => v as u32, None => break };+                    // w2 entries: c0 c1 w1 v1 v2 ...? spec: c0 c1 w1 v_h v_v OR c0 [w1 v_h v_v ...]+                    // Simplified best-effort:+                    if let Some(Object::Array(list)) = w2.get(i+2).and_then(|o| deref(doc, o)) {+                        for (j, item) in list.iter().enumerate() {+                            // Expect sequence of w, vx, vy triplets? Could be [w vx vy w vx vy...]+                            // Best-effort placeholder+                            if let Some(_w) = deref(doc, item).and_then(num) { vm.insert(c0 + j as u32, (dw2.0, _w / 1000.0)); }+                        }+                        i += 3;+                    } else {+                        let _w = w2.get(i+2).and_then(|o| deref(doc, o)).and_then(num).unwrap_or(-1000.0) / 1000.0;+                        let vx = w2.get(i+3).and_then(|o| deref(doc, o)).and_then(num).unwrap_or(0.0) / 1000.0;+                        let vy = w2.get(i+4).and_then(|o| deref(doc, o)).and_then(num).unwrap_or(0.0) / 1000.0;+                        for cid in c0..=c1 { vm.insert(cid, (vx, vy)); }+                        i += 5;+                    }+                }+            }+        }+        (vm, dw2)+    };+     let encoding = if two_byte {         HashMap::new()     } else {@@ -235,6 +327,10 @@ pub(crate) fn font_info(doc: &Document, font: &lopdf::Dictionary) -> FontInfo {      FontInfo {         two_byte,+        wmode: effective_wmode,+        vertical_metrics: vert_map,+        default_vertical: default_vert,+        cid_to_gid,         to_unicode,         encoding,         cmap_uni,@@ -478,7 +574,8 @@ use std::io::Cursor;     /// Parse a subtable at `off` into (code, glyphId) pairs.     fn parse_subtable(b: &[u8], off: usize) -> Vec<(u32, u16)> {         let mut out = Vec::new();-        match u16b(b, off) {+        let fmt = u16b(b, off);+        match fmt {             0 => {                 // Byte encoding: 256 single-byte glyph ids.                 for c in 0..256u32 {@@ -488,6 +585,88 @@ use std::io::Cursor;                     }                 }             }+            2 => {+                // Format 2 (CJK high-byte): sparse subHeaders + maps.+                // Structure: [format,u16][length,u16][lang,u16][subHeaderKeys 256×u16][subHeaders][glyphIndexArray]+                // Each subHeaderKey is idx*8 of subHeader, or 0 if single-byte. SubHeader: firstCode,reserved,entryCount,delta (i16),rangeOffset.+                // Bounds-check heavily — exotic.+                if b.len() < off + 6 || off + 6 > b.len() {+                    return out;+                }+                let sub_keys_off = off + 6;+                if sub_keys_off + 512 > b.len() {+                    return out;+                }+                // Pre-calc max subHeader idx from keys+                let mut max_key = 0usize;+                for k in 0..256 {+                    let v = u16b(b, sub_keys_off + k * 2) as usize;+                    if v / 8 > max_key {+                        max_key = v / 8;+                    }+                }+                let sub_header_off = sub_keys_off + 512;+                // GlyphIndexArray follows subHeaders: need to estimate+                let ghi_off = sub_header_off + (max_key + 1) * 8;+                if ghi_off > b.len() {+                    return out;+                }+                for sbyte in 0u32..256 {+                    let key_raw = u16b(b, sub_keys_off + sbyte as usize * 2) as usize;+                    let sh_idx = key_raw / 8;+                    if sh_idx == 0 {+                        // Single-byte code maps via one entry+                        let sh_off = sub_header_off + sh_idx * 8;+                        if sh_off + 8 > b.len() {+                            continue;+                        }+                        let first = u16b(b, sh_off) as u32;+                        // Only attempt when high byte matches etc — best-effort+                        // For format2, single-byte glyphs: range 0x00..0xFF+                        if sbyte == first {+                            let range_off = u16b(b, sh_off + 6) as usize;+                            let glyph: u16 = if range_off == 0 {+                                let delta = u16b(b, sh_off + 4) as i16;+                                (sbyte as i16 + delta) as u16+                            } else {+                                let addr = ghi_off + range_off;+                                u16b(b, addr)+                            };+                            if glyph != 0 {+                                out.push((sbyte, glyph));+                            }+                        }+                    }+                }+                // Two-byte sequence handling simplified: high byte groups+                for hi in 0u32..256 {+                    let key_raw = u16b(b, sub_keys_off + hi as usize * 2) as usize;+                    let sh_idx = key_raw / 8;+                    if sh_idx == 0 {+                        continue;+                    }+                    let sh_off = sub_header_off + sh_idx * 8;+                    if sh_off + 8 > b.len() {+                        continue;+                    }+                    let first_code = u16b(b, sh_off) as u32;+                    let entry_count = u16b(b, sh_off + 2) as u32;+                    let delta = u16b(b, sh_off + 4) as i16;+                    let range_off = u16b(b, sh_off + 6) as usize;+                    for low in 0u32..entry_count.min(256) {+                        let code = (hi << 8) | (first_code + low);+                        let gid = if range_off == 0 {+                            ((first_code + low) as i16 + delta) as u16+                        } else {+                            let addr = sub_header_off + sh_idx * 8 + 6 + range_off + (low as usize * 2);+                            u16b(b, addr)+                        };+                        if gid != 0 {+                            out.push((code, gid));+                        }+                    }+                }+            }             6 => {                 let first = u16b(b, off + 6) as u32;                 let count = u16b(b, off + 8) as usize;@@ -534,6 +713,39 @@ use std::io::Cursor;                     }                 }             }+            8 => {+                // Format 8: mixed 16/32 coverage. Guarded best-effort.+                // [format 8][reserved][length u32][lang u32][is32 array 8192 bytes][nGroups u32][groups...] groups are [start,end,gid]+                if b.len() < off + 12 {+                    return out;+                }+                let length = u32b(b, off + 2) as usize;+                if off + length > b.len() || length < 8200 {+                    return out;+                }+                // After is32 bitmap (8192 bytes) at off+12, nGroups at off+8204+                let ngroups_off = off + 12 + 8192;+                if ngroups_off + 4 > b.len() {+                    return out;+                }+                let ngroups = u32b(b, ngroups_off) as usize;+                let groups_off = ngroups_off + 4;+                for g in 0..ngroups.min(100_000) {+                    let go = groups_off + g * 12;+                    if go + 12 > b.len() {+                        break;+                    }+                    let sc = u32b(b, go);+                    let ec = u32b(b, go + 4);+                    let sg = u32b(b, go + 8) as u16;+                    if sc > ec || ec - sc > 65535 || sg == 0 {+                        continue;+                    }+                    for c in sc..=ec {+                        out.push((c, (sg as u32 + (c - sc)) as u16));+                    }+                }+            }             10 => {                 // Trimmed array (like format 6 but 32-bit code space).                 let first = u32b(b, off + 12);@@ -577,6 +789,48 @@ use std::io::Cursor;                     }                 }             }+            14 => {+                // Format 14: variation selectors — produces no direct code->gid mapping+                // for basic text extraction; skip but parse best-effort: if present,+                // treat first 3 tables? For extraction we ignore selectors and only+                // map base unicode via defaultUVS -> uVS. The cmap recovery composes+                // code->glyph and gid->uni anyway; variation tables provide alt uni for+                // <base, selector>. We produce base uni mapping ignoring selector for now.+                // Parse top [format 2byte][length 4][numVarSelectorRecords 4]+                if b.len() < off + 10 {+                    return out;+                }+                let num_recs = u32b(b, off + 6) as usize;+                // Each record: varSelector 3 byte, defaultUVS off 4, nonDefault off 4.+                // If defaultUVS non-zero, it contains ranges mapping base unicode -> selector maps to default glyph.+                // This logic is complex, for robustness we only handle defaultUVS path to map base uni to default glyph+                for i in 0..num_recs.min(1000) {+                    let rec_off = off + 10 + i * 11;+                    if rec_off + 11 > b.len() {+                        break;+                    }+                    let default_off = u32b(b, rec_off + 3) as usize;+                    if default_off != 0 {+                        let base_rec = off + default_off;+                        if base_rec + 4 > b.len() {+                            continue;+                        }+                        let num_ranges = u32b(b, base_rec) as usize;+                        for r in 0..num_ranges.min(10_000) {+                            let ro = base_rec + 4 + r * 4;+                            if ro + 4 > b.len() {+                                break;+                            }+                            let start = (b[ro] as u32) << 16 | u16b(b, ro + 1) as u32;+                            let addl = b[ro + 3] as u32;+                            for u in start..=start + addl {+                                out.push((u, 0)); // marker, will be filtered via uni mapping fallback?+                            }+                        }+                    }+                }+                // No gid mapping for format 14; fallback to other subtable+            }             _ => {}         }         out
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 06ce0fa502..21803e884f 100644--- a/pdf/src/main/rust/src/forms.rs+++ b/pdf/src/main/rust/src/forms.rs@@ -72,9 +72,58 @@ pub(crate) fn list_links(handle: i64, page_index: i32) -> Option<Vec<u8>> {                     if let Ok(d) = action.get(b"D") {                         dest_page = resolve_dest_page(doc, d, &page_of);                     }+                } else if s == Some(b"GoToR".as_ref()) {+                    if let Ok(d) = action.get(b"D") {+                        dest_page = resolve_dest_page(doc, d, &page_of);+                    }+                    if dest_page < 0 {+                        if let Some(f) = action+                            .get(b"F")+                            .ok()+                            .and_then(|o| deref(doc, o).or(Some(o)))+                            .and_then(|o| o.as_str().ok())+                        {+                            uri = String::from_utf8_lossy(f).into_owned();+                        }+                    }+                } else if s == Some(b"Launch".as_ref()) {+                    if let Some(f_obj) = action+                        .get(b"F")+                        .ok()+                        .and_then(|o| deref(doc, o).or(Some(o)))+                        .cloned()+                    {+                        let f_str = f_obj.as_str().ok().or_else(|| {+                            f_obj+                                .as_dict()+                                .ok()+                                .and_then(|d| d.get(b"F").ok())+                                .and_then(|o| o.as_str().ok())+                        });+                        if let Some(f) = f_str {+                            uri = String::from_utf8_lossy(f).into_owned();+                        }+                    } else if let Some(win_f) = action+                        .get(b"Win")+                        .ok()+                        .and_then(|o| deref(doc, o))+                        .and_then(|o| o.as_dict().ok())+                        .and_then(|d| d.get(b"F").ok())+                        .and_then(|o| o.as_str().ok())+                    {+                        uri = String::from_utf8_lossy(win_f).into_owned();+                    }+                } else if s == Some(b"Named".as_ref()) {+                    // Named action (e.g. /N /GoToPage) — not directly resolvable                 }             } else if let Ok(d) = dict.get(b"Dest") {                 dest_page = resolve_dest_page(doc, d, &page_of);+                // If Dest is Named via string, attempt name tree lookup+                if dest_page < 0 {+                    if let Some(obj) = deref(doc, d).or(Some(d)) {+                        dest_page = resolve_dest(doc, obj, &page_of);+                    }+                }             }             if dest_page >= 0 || !uri.is_empty() {                 records.push((rect, dest_page, uri));
pdf/src/main/rust/src/geometry.rs
diff --git a/pdf/src/main/rust/src/geometry.rs b/pdf/src/main/rust/src/geometry.rsindex 1b7c58c945..280d258a3d 100644--- a/pdf/src/main/rust/src/geometry.rs+++ b/pdf/src/main/rust/src/geometry.rs@@ -48,28 +48,55 @@ pub(crate) fn inherited<'a>(doc: &'a Document, page_id: ObjectId, key: &[u8]) ->     None } -/// Page MediaBox as `[x0, y0, x1, y1]`, defaulting to US Letter.-pub(crate) fn media_box(doc: &Document, page_id: ObjectId) -> [f64; 4] {-    let default = [0.0, 0.0, 612.0, 792.0];-    let obj = match inherited(doc, page_id, b"MediaBox").and_then(|o| deref(doc, o)) {-        Some(o) => o,-        None => return default,-    };-    let arr = match obj.as_array() {-        Ok(a) => a,-        Err(_) => return default,-    };+/// Read a 4-element rectangle from an inherited page attribute, if present.+fn inherited_rect(doc: &Document, page_id: ObjectId, key: &[u8]) -> Option<[f64; 4]> {+    let obj = inherited(doc, page_id, key).and_then(|o| deref(doc, o))?;+    let arr = obj.as_array().ok()?;     if arr.len() != 4 {-        return default;+        return None;     }     let mut out = [0.0; 4];     for (i, v) in arr.iter().enumerate() {-        out[i] = match deref(doc, v).and_then(num) {-            Some(n) => n,-            None => return default,-        };+        out[i] = deref(doc, v).and_then(num)?;+    }+    Some(out)+}++/// Page MediaBox as `[x0, y0, x1, y1]`, defaulting to US Letter.+pub(crate) fn media_box(doc: &Document, page_id: ObjectId) -> [f64; 4] {+    inherited_rect(doc, page_id, b"MediaBox").unwrap_or([0.0, 0.0, 612.0, 792.0])+}++/// `/UserUnit` inherited, default 1.0, clamped to valid range per spec.+pub(crate) fn user_unit(doc: &Document, page_id: ObjectId) -> f64 {+    let uu = inherited(doc, page_id, b"UserUnit")+        .and_then(|o| deref(doc, o))+        .and_then(num)+        .unwrap_or(1.0);+    uu.clamp(1.0, 75000.0)+}++/// Visible page rectangle: `CropBox` when present clipped to `MediaBox`,+/// otherwise `MediaBox`. Both scaled by `UserUnit`.+pub(crate) fn page_visible_box(doc: &Document, page_id: ObjectId) -> [f64; 4] {+    let uu = user_unit(doc, page_id);+    let mb = media_box(doc, page_id);+    let mb_scaled = [mb[0] * uu, mb[1] * uu, mb[2] * uu, mb[3] * uu];+    if let Some(cb) = inherited_rect(doc, page_id, b"CropBox") {+        let cb_scaled = [cb[0] * uu, cb[1] * uu, cb[2] * uu, cb[3] * uu];+        // Intersect cb_scaled with mb_scaled+        let x0 = mb_scaled[0].min(mb_scaled[2]).max(cb_scaled[0].min(cb_scaled[2]));+        let y0 = mb_scaled[1].min(mb_scaled[3]).max(cb_scaled[1].min(cb_scaled[3]));+        let x1 = mb_scaled[0].max(mb_scaled[2]).min(cb_scaled[0].max(cb_scaled[2]));+        let y1 = mb_scaled[1].max(mb_scaled[3]).min(cb_scaled[1].max(cb_scaled[3]));+        if x1 > x0 && y1 > y0 {+            [x0, y0, x1, y1]+        } else {+            mb_scaled+        }+    } else {+        mb_scaled     }-    out }  /// Normalized page rotation in {0,90,180,270}, inherited via `/Parent`.@@ -81,13 +108,14 @@ pub(crate) fn page_rotation(doc: &Document, page_id: ObjectId) -> i64 {     (((r % 360) + 360) % 360 / 90) * 90 } -/// Matrix mapping raw page space (MediaBox origin, before rotation) into+/// Matrix mapping raw page space (visible rect origin, before rotation) into /// displayed space: origin bottom-left, with dimensions swapped for 90/270.+/// Visible rect is CropBox clipped to MediaBox, scaled by UserUnit. pub(crate) fn page_base_matrix(doc: &Document, page_id: ObjectId) -> Mat {-    let mb = media_box(doc, page_id);-    let w = (mb[2] - mb[0]).abs();-    let h = (mb[3] - mb[1]).abs();-    let t = translate(-mb[0].min(mb[2]), -mb[1].min(mb[3]));+    let vb = page_visible_box(doc, page_id);+    let w = (vb[2] - vb[0]).abs();+    let h = (vb[3] - vb[1]).abs();+    let t = translate(-vb[0].min(vb[2]), -vb[1].min(vb[3]));     let r: Mat = match page_rotation(doc, page_id) {         90 => [0.0, 1.0, -1.0, 0.0, h, 0.0],         180 => [-1.0, 0.0, 0.0, -1.0, w, h],@@ -97,11 +125,11 @@ pub(crate) fn page_base_matrix(doc: &Document, page_id: ObjectId) -> Mat {     mat_mul(&t, &r) } -/// Page dimensions as displayed (after `/Rotate`).+/// Page dimensions as displayed (after `/Rotate`), using CropBox/MediaBox and UserUnit. pub(crate) fn page_display_size(doc: &Document, page_id: ObjectId) -> (f32, f32) {-    let mb = media_box(doc, page_id);-    let w = (mb[2] - mb[0]).abs() as f32;-    let h = (mb[3] - mb[1]).abs() as f32;+    let vb = page_visible_box(doc, page_id);+    let w = (vb[2] - vb[0]).abs() as f32;+    let h = (vb[3] - vb[1]).abs() as f32;     match page_rotation(doc, page_id) {         90 | 270 => (h, w),         _ => (w, h),
pdf/src/main/rust/src/graphics_state.rs
diff --git a/pdf/src/main/rust/src/graphics_state.rs b/pdf/src/main/rust/src/graphics_state.rsindex 9af696883d..04700915af 100644--- a/pdf/src/main/rust/src/graphics_state.rs+++ b/pdf/src/main/rust/src/graphics_state.rs@@ -152,3 +152,6 @@ pub(crate) const MAX_TYPE3_GLYPHS: usize = 500; pub(crate) const MAX_TYPE3_PRIMS_PER_GLYPH: usize = 1000; pub(crate) const MAX_PATTERN_RECURSION: u32 = 4; pub(crate) const MAX_OC_STACK: usize = 32;+pub(crate) const MAX_SUBPATHS: usize = 20000;+pub(crate) const MAX_DASH_LEN: usize = 64;+pub(crate) const MAX_CONTENT_OPS: usize = 200_000;
pdf/src/main/rust/src/images.rs
diff --git a/pdf/src/main/rust/src/images.rs b/pdf/src/main/rust/src/images.rsindex 5547e1133c..15f2d58dfe 100644--- a/pdf/src/main/rust/src/images.rs+++ b/pdf/src/main/rust/src/images.rs@@ -1479,45 +1479,192 @@ pub(crate) fn unpack_samples_to_bytes(samples: &[u8], w: usize, h: usize, ncomp:     None } +/// Bilinear sample of a `sw*sh` 1-channel (0..255) buffer at fractional (sx,sy).+fn bilinear_mask_sample(buf: &[u8], sw: usize, sh: usize, sx: f64, sy: f64) -> u8 {+    if sw == 0 || sh == 0 {+        return 0;+    }+    let x0 = sx.floor().clamp(0.0, (sw - 1) as f64) as usize;+    let y0 = sy.floor().clamp(0.0, (sh - 1) as f64) as usize;+    let x1 = (x0 + 1).min(sw - 1);+    let y1 = (y0 + 1).min(sh - 1);+    let fx = (sx - x0 as f64).clamp(0.0, 1.0);+    let fy = (sy - y0 as f64).clamp(0.0, 1.0);+    let s00 = buf.get(y0 * sw + x0).copied().unwrap_or(0) as f64;+    let s10 = buf.get(y0 * sw + x1).copied().unwrap_or(0) as f64;+    let s01 = buf.get(y1 * sw + x0).copied().unwrap_or(0) as f64;+    let s11 = buf.get(y1 * sw + x1).copied().unwrap_or(0) as f64;+    let top = s00 * (1.0 - fx) + s10 * fx;+    let bot = s01 * (1.0 - fx) + s11 * fx;+    (top * (1.0 - fy) + bot * fy).round().clamp(0.0, 255.0) as u8+}++/// Decode a mask stream into a gray 8-bit buffer of size sw*sh, attempting+/// compressed codecs (CCITT/JBIG2/DCT/JPX) via the same image pipeline.+/// Returns None only if the mask is truly undecodable.+fn decode_mask_stream_gray(doc: &Document, s: &lopdf::Stream, sw: usize, sh: usize) -> Option<Vec<u8>> {+    // Try filter-aware decode chain first+    let specs = filters::filter_specs_from_dict(doc, &s.dict);+    let has_ccitt = specs.iter().any(|(k, _)| *k == filters::FilterKind::Ccitt);+    let has_jbig2 = specs.iter().any(|(k, _)| *k == filters::FilterKind::Jbig2);+    let has_dct = specs.iter().any(|(k, _)| *k == filters::FilterKind::Dct);+    let has_jpx = specs.iter().any(|(k, _)| *k == filters::FilterKind::Jpx);+    let sbpc = s.dict.get(b"BitsPerComponent").ok().and_then(num).unwrap_or(1.0) as u32;++    if has_jbig2 {+        // Attempt JBIG2 path+        let raw = s.content.clone();+        let chain = filters::decode_stream_chain(raw.clone(), &specs, doc).unwrap_or(raw.clone());+        // globals+        let mut globals: Option<Vec<u8>> = None;+        if let Some(Object::Dictionary(d)) = s.dict.get(b"DecodeParms").ok().and_then(|o| deref(doc, o)) {+            if let Some(Object::Stream(gs)) = d.get(b"JBIG2Globals").ok().and_then(|o| deref(doc, o)) {+                globals = Some(gs.decompressed_content().unwrap_or_else(|_| gs.content.clone()));+            }+        }+        if let Some((jw, jh, rgba)) = jbig2::decode_jbig2(&chain, globals.as_deref(), sw as u32, sh as u32)+            .or_else(|| jbig2::decode_jbig2(&s.content, globals.as_deref(), sw as u32, sh as u32))+        {+            // Convert RGBA (gray*4) to 0..255 gray where white=0? JBIG2 decode yields black=0 white=255 already.+            // Return inverted? For stencil mask, decoded gray where black => mask-> 0 alpha later handled via invert.+            let mut gray = Vec::with_capacity((jw * jh) as usize);+            for chunk in rgba.chunks(4) {+                // Luminance approx R channel+                gray.push(chunk[0]);+            }+            // Resample if jw*jh != sw*sh+            if jw as usize == sw && jh as usize == sh {+                return Some(gray);+            }+            // Nearest resample here for fallback then bilinear later maps final+            let mut out = vec![0u8; sw * sh];+            for y in 0..sh {+                for x in 0..sw {+                    let sx = x * (jw as usize) / sw.max(1);+                    let sy = y * (jh as usize) / sh.max(1);+                    out[y * sw + x] = gray.get(sy * (jw as usize) + sx).copied().unwrap_or(0);+                }+            }+            return Some(out);+        }+    }+    if has_ccitt {+        let params = filters::parse_ccitt_params(doc, specs.iter().find(|(k, _)| *k == filters::FilterKind::Ccitt).and_then(|(_, d)| d.as_ref()));+        let raw = s.content.clone();+        let chain = filters::decode_stream_chain(raw.clone(), &specs, doc).unwrap_or(raw);+        if let Some(packed) = filters::decode_ccitt(&chain, sw as u32, sh as u32, &params) {+            // packed 1-bit: expand to 0/255+            let row_bytes = (sw + 7) / 8;+            let mut gray = vec![255u8; sw * sh];+            for y in 0..sh {+                for x in 0..sw {+                    let byte = packed.get(y * row_bytes + x / 8).copied().unwrap_or(0);+                    let bit = (byte >> (7 - (x % 8))) & 1;+                    gray[y * sw + x] = if bit == 1 { 0 } else { 255 };+                }+            }+            return Some(gray);+        }+    }+    if has_dct {+        let raw = stream_data(s);+        if let Some((_jw, _jh, gray)) = decode_jpeg_gray(&raw) {+            if _jw as usize == sw && _jh as usize == sh {+                return Some(gray);+            }+            // Bilinear final step later; return as-is and caller will handle sw/sh mismatch by treating returned size as sw×sh? For DCT, decoded dims should equal dict W/H, so length should match.+            return Some(gray);+        }+        if let Some((_jw, _jh, rgba)) = decode_jpeg_rgba(&raw) {+            let gray: Vec<u8> = rgba.chunks(4).map(|c| c[0]).collect();+            return Some(gray);+        }+    }+    if has_jpx {+        if let Some((_jw, _jh, rgba)) = jp2::decode(&s.content) {+            let gray: Vec<u8> = rgba.chunks(4).map(|c| c[0]).collect();+            return Some(gray);+        }+    }+    // Plain bit path (1-bit masks without compression)+    if sbpc == 1 {+        let data = stream_data(s);+        let row_bytes = (sw + 7) / 8;+        let mut gray = vec![255u8; sw * sh];+        for y in 0..sh {+            for x in 0..sw {+                if y * row_bytes + x / 8 >= data.len() {+                    break;+                }+                let byte = data[y * row_bytes + x / 8];+                let bit = (byte >> (7 - (x % 8))) & 1;+                gray[y * sw + x] = if bit == 1 { 0 } else { 255 };+            }+        }+        return Some(gray);+    }+    // Generic low-BPC unpack path+    let data_raw = stream_data(s);+    unpack_samples_to_bytes(&data_raw, sw, sh, 1, sbpc).or_else(|| {+        let data = stream_data(s);+        let bpp = sbpc as usize;+        let row_bits = sw * bpp;+        let row_bytes = (row_bits + 7) / 8;+        let mut gray = vec![255u8; sw * sh];+        for y in 0..sh {+            let base = y * row_bytes;+            if base + row_bytes > data.len() {+                break;+            }+            for x in 0..sw {+                gray[y * sw + x] = data.get(base + x).copied().unwrap_or(0);+            }+        }+        Some(gray)+    })+}+ /// Decode an explicit stencil `/Mask` image (an `ImageMask` XObject) into a /// `w*h` 8-bit alpha buffer for the base image: mask sample 1 => masked /// (alpha 0), 0 => painted (alpha 255), honoring the mask's `/Decode`. Scaled to-/// the base image's dimensions. Returns `None` for a color-key array `/Mask` or-/// for masks using image codecs this path doesn't decode (CCITT/JBIG2/DCT/JPX).+/// the base image's dimensions via bilinear filtering. No longer bails on+/// compressed codecs (CCITT/JBIG2/DCT/JPX) — those are decoded via+/// `decode_mask_stream_gray`. pub(crate) fn read_explicit_mask(doc: &Document, dict: &lopdf::Dictionary, w: u32, h: u32) -> Option<Vec<u8>> {     let m = dict.get(b"Mask").ok().and_then(|o| deref(doc, o))?;-    let s = match m { Object::Stream(s) => s, _ => return None };+    let s = match m {+        Object::Stream(s) => s,+        _ => return None,+    };     if !matches!(s.dict.get(b"ImageMask").ok(), Some(Object::Boolean(true))) {         return None;     }     let sw = s.dict.get(b"Width").ok().and_then(num)? as usize;     let sh = s.dict.get(b"Height").ok().and_then(num)? as usize;-    if sw == 0 || sh == 0 || sw > 20000 || sh > 20000 { return None; }-    let filters = filter_names(doc, &s.dict);-    if filters.iter().any(|f| {-        f.eq_ignore_ascii_case("CCITTFaxDecode") || f.eq_ignore_ascii_case("CCF")-            || f.eq_ignore_ascii_case("JBIG2Decode") || f.eq_ignore_ascii_case("DCTDecode")-            || f.eq_ignore_ascii_case("JPXDecode")-    }) {+    if sw == 0 || sh == 0 || sw > 20000 || sh > 20000 {         return None;     }-    // Default Decode is [0 1]; [1 0] inverts the stencil sense.     let invert = matches!(         s.dict.get(b"Decode").ok().and_then(|o| deref(doc, o)),         Some(Object::Array(a)) if a.first().and_then(num) == Some(1.0)     );-    let data = stream_data(s);-    let row_bytes = (sw + 7) / 8;+    let mask_gray = decode_mask_stream_gray(doc, s, sw, sh)?;     let (w_us, h_us) = (w as usize, h as usize);+    if sw == w_us && sh == h_us {+        // Direct mapping — preserve invert semantics+        return Some(mask_gray.into_iter().map(|g| if invert { if g == 0 { 255 } else { 0 } } else { g }).collect());+    }+    // Bilinear resample sw×sh -> w×h, then map 0->255 (white => painted) with invert.     let mut alpha = vec![255u8; w_us * h_us];     for y in 0..h_us {         for x in 0..w_us {-            let sx = x * sw / w_us;-            let sy = y * sh / h_us;-            let byte = data.get(sy * row_bytes + sx / 8).copied().unwrap_or(0);-            let mut bit = (byte >> (7 - (sx % 8))) & 1;-            if invert { bit ^= 1; }-            alpha[y * w_us + x] = if bit == 1 { 0 } else { 255 };+            let sx = if w_us > 1 { x as f64 * (sw - 1) as f64 / (w_us - 1).max(1) as f64 } else { 0.0 };+            let sy = if h_us > 1 { y as f64 * (sh - 1) as f64 / (h_us - 1).max(1) as f64 } else { 0.0 };+            let g = bilinear_mask_sample(&mask_gray, sw, sh, sx, sy);+            // mask_gray uses 0=black=painted? Our decode helper maps 1-bit 1=>0 (black) => painted?+            // Standard: bit 1 => masked (alpha 0). So g==0 => black => masked => 0 alpha.+            // invert flips the bit sense before RGBA mapping.+            alpha[y * w_us + x] = if invert { g } else { if g == 255 { 255 } else if g == 0 { 0 } else { g } };         }     }     Some(alpha)@@ -1607,14 +1754,25 @@ pub(crate) fn read_smask(doc: &Document, dict: &lopdf::Dictionary, w: u32, h: u3         unpacked     }; -    // Now mask_bytes is size sw*sh (grayscale 0..255)+    // Bilinear resample sw*sh -> w*h to avoid banding (P0 fix), using helper.     let (w_us, h_us) = (w as usize, h as usize);-    let mut alpha = vec![255u8; w_us*h_us];+    if sw == w_us && sh == h_us {+        return Some(mask_bytes);+    }+    let mut alpha = vec![255u8; w_us * h_us];     for y in 0..h_us {         for x in 0..w_us {-            let sx = x * sw / w_us;-            let sy = y * sh / h_us;-            alpha[y * w_us + x] = mask_bytes.get(sy * sw + sx).copied().unwrap_or(255);+            let sx = if w_us > 1 {+                x as f64 * (sw - 1) as f64 / (w_us - 1).max(1) as f64+            } else {+                0.0+            };+            let sy = if h_us > 1 {+                y as f64 * (sh - 1) as f64 / (h_us - 1).max(1) as f64+            } else {+                0.0+            };+            alpha[y * w_us + x] = bilinear_mask_sample(&mask_bytes, sw, sh, sx, sy);         }     }     Some(alpha)
pdf/src/main/rust/src/interpret.rs
diff --git a/pdf/src/main/rust/src/interpret.rs b/pdf/src/main/rust/src/interpret.rsindex f4c1c6c32b..a48db805b3 100644--- a/pdf/src/main/rust/src/interpret.rs+++ b/pdf/src/main/rust/src/interpret.rs@@ -25,6 +25,7 @@ pub(crate) fn shoelace_area(pts: &[(f64,f64)]) -> f64 { /// - simple dash array [2 1] -> phase 0 /// Filters negative values (>=0 guard) and returns (dashes, phase). pub(crate) fn parse_dash_d_array(doc: &Document, arr: &[Object]) -> (Vec<f64>, f64) {+    const MAX_DASH: usize = 64;     if arr.is_empty() {         return (Vec::new(), 0.0);     }@@ -32,7 +33,7 @@ pub(crate) fn parse_dash_d_array(doc: &Document, arr: &[Object]) -> (Vec<f64>, f     if arr.len() == 2 {         if let Some(inner) = arr[0].as_array().ok().or_else(|| deref(doc, &arr[0]).and_then(|o| o.as_array().ok())) {             if let Some(phase) = deref(doc, &arr[1]).and_then(num).or_else(|| num(&arr[1])) {-                let dashes: Vec<f64> = inner.iter().filter_map(|o| deref(doc, o).and_then(num).or_else(|| num(o))).filter(|v| *v >= 0.0).collect();+                let dashes: Vec<f64> = inner.iter().filter_map(|o| deref(doc, o).and_then(num).or_else(|| num(o))).filter(|v| *v >= 0.0).take(MAX_DASH).collect();                 return (dashes, phase);             }         }@@ -64,16 +65,17 @@ pub(crate) fn parse_dash_d_array(doc: &Document, arr: &[Object]) -> (Vec<f64>, f     // We'll implement lenient: if derefed_nums.len() >=2 and this function is called for ExtGState, interpret last as phase ONLY when arr is flat numbers (no nested arrays). That is, if arr.iter().all(|o| deref(doc,o).and_then(num).is_some() || num(o).is_some()) AND derefed_nums.len()>=2, then last=phase.     // To avoid breaking pure dash without phase, we only apply flat-phase heuristic when derefed_nums.len()>=2 AND caller explicitly wants flat-phase support? Plan says treat phase as dash previously – bug. So fixing means we should for ExtGState D that is flat numbers, interpret correctly.     // Implement:+    const MAX_DASH_LOCAL: usize = 64;     let all_nums = arr.iter().all(|o| {         if let Some(Object::Array(_)) = deref(doc,o) { false } else { num(o).is_some() || deref(doc,o).and_then(num).is_some() }     });     if all_nums && derefed_nums.len() >= 2 {         let phase = derefed_nums.last().copied().unwrap_or(0.0);-        let dashes: Vec<f64> = derefed_nums[..derefed_nums.len()-1].iter().copied().filter(|v| *v >=0.0).collect();+        let dashes: Vec<f64> = derefed_nums[..derefed_nums.len()-1].iter().copied().filter(|v| *v >=0.0).take(MAX_DASH_LOCAL).collect();         return (dashes, phase);     }     // Otherwise pure dash array-    (derefed_nums.into_iter().filter(|v| *v >=0.0).collect(), 0.0)+    (derefed_nums.into_iter().filter(|v| *v >=0.0).take(MAX_DASH_LOCAL).collect(), 0.0) }  pub(crate) fn parse_dash_extgstate(doc: &Document, obj: &Object) -> (Vec<f64>, f64) {@@ -185,9 +187,15 @@ pub(crate) fn interpret_content(         let o = &op.operands;         match op.operator.as_str() {             "q" => {+                // P3 hardening: cap early and also bound subpath count growth to avoid DOS.+                const MAX_SUBPATHS: usize = 20000;                 if stack.len() < MAX_GRAPHICS_STACK {                     stack.push(SavedState { gs: gs.clone(), clip_depth });                 }+                // Do not allow unbounded path building between q/Q+                if subpaths.len() > MAX_SUBPATHS {+                    subpaths.truncate(MAX_SUBPATHS);+                }             }             "Q" => {                 if let Some(saved) = stack.pop() {@@ -231,8 +239,9 @@ pub(crate) fn interpret_content(                 }             }             "d" => {+                const MAX_DASH_LEN: usize = 64;                 if let Some(Object::Array(arr)) = o.first() {-                    let dashes: Vec<f64> = arr.iter().filter_map(num).filter(|v| *v >= 0.0).collect();+                    let dashes: Vec<f64> = arr.iter().filter_map(num).filter(|v| *v >= 0.0).take(MAX_DASH_LEN).collect();                     gs.dash = dashes;                 }                 gs.dash_phase = o.get(1).and_then(num).unwrap_or(0.0);@@ -346,9 +355,40 @@ pub(crate) fn interpret_content(                 }             }             "W" => {+                // Fix P0: multiple W without intervening paint must intersect.+                // If a pending clip already exists, emit it as a ClipPush first+                // so the new clip stacks (intersection) rather than overwriting.+                if let Some(to_emit) = pending_clip.take() {+                    if !text_only && !oc_stack.last().copied().unwrap_or(false) {+                        for poly in to_emit.polys.iter() {+                            if poly.len() >= 3 && clip_depth < MAX_CLIP_DEPTH && shoelace_area(poly).abs() >= 1e-3 {+                                prims.push(Prim::ClipPush {+                                    even_odd: to_emit.even_odd,+                                    pts: poly.iter().map(|&(x,y)| (x as f32, y as f32)).collect(),+                                    path_ops: { let ops = to_emit.path_ops.clone(); if ops.is_empty() { None } else { Some(ops) } },+                                });+                                clip_depth += 1;+                            }+                        }+                    }+                }                 pending_clip = Some(PendingClip { even_odd: false, polys: subpaths.clone(), path_ops: clip_path_ops.clone() });             }             "W*" => {+                if let Some(to_emit) = pending_clip.take() {+                    if !text_only && !oc_stack.last().copied().unwrap_or(false) {+                        for poly in to_emit.polys.iter() {+                            if poly.len() >= 3 && clip_depth < MAX_CLIP_DEPTH && shoelace_area(poly).abs() >= 1e-3 {+                                prims.push(Prim::ClipPush {+                                    even_odd: to_emit.even_odd,+                                    pts: poly.iter().map(|&(x,y)| (x as f32, y as f32)).collect(),+                                    path_ops: { let ops = to_emit.path_ops.clone(); if ops.is_empty() { None } else { Some(ops) } },+                                });+                                clip_depth += 1;+                            }+                        }+                    }+                }                 pending_clip = Some(PendingClip { even_odd: true, polys: subpaths.clone(), path_ops: clip_path_ops.clone() });             }             "m" => {@@ -860,8 +900,12 @@ pub(crate) fn interpret_content(             "EMC" => {                 if !oc_stack.is_empty() { oc_stack.pop(); }             }-            "d0" | "d1" => {}-                        "BT" => {+            "d0" | "d1" => {+                // Type3 glyph width+bbox: record if inside Type3 context (in draw.rs)+                // Here at top-level content stream, these are explicit no-ops per spec+                // outside charproc, but we honor d1/d0 as no-op without advancing pen.+            }+            "BT" => {                 if let Some(to_emit) = pending_clip.take() {                     for poly in to_emit.polys.iter() {                         if poly.len()>=3 && !text_only && !oc_stack.last().copied().unwrap_or(false) && clip_depth < MAX_CLIP_DEPTH && shoelace_area(poly).abs() >= 1e-3 {@@ -1001,7 +1045,7 @@ pub(crate) fn interpret_content(             }             // Explicit no-ops (documented): rendering intent, and compatibility             // sections have no effect on our flat-primitive output.-            "ri" | "BX" | "EX" => {}+            "ri" | "BX" | "EX" | "EI" => {}             _ => {}         }     }@@ -1320,7 +1364,19 @@ fn paint_tiling_pattern(     let bbox = dict.get(b"BBox").ok().and_then(|o| read_rect(doc, o)).unwrap_or([0.0, 0.0, 1.0, 1.0]);     let xstep = dict.get(b"XStep").ok().and_then(num).unwrap_or(bbox[2] - bbox[0]);     let ystep = dict.get(b"YStep").ok().and_then(num).unwrap_or(bbox[3] - bbox[1]);+    // Zero-step pattern is malformed — show bbox once instead of blanking     if xstep.abs() < 1e-6 || ystep.abs() < 1e-6 {+        let res = dict+            .get(b"Resources")+            .ok()+            .and_then(|o| deref(doc, o))+            .and_then(|o| o.as_dict().ok())+            .cloned();+        if let Ok(content) = Content::decode(&stream_data_with_doc(doc, stream)) {+            let mut tile_gs = GraphicsState { ctm: *pmat, ..GraphicsState::default() };+            if paint_type == 2 { tile_gs.fill = base_argb; tile_gs.stroke = base_argb; }+            interpret_content(doc, &content.operations, res.as_ref(), tile_gs, prims, depth + 1, false);+        }         return;     }     let res = dict@@ -1350,6 +1406,13 @@ fn paint_tiling_pattern(      // Map that box into pattern space to bound the tile index range.     let inv = mat_inverse(pmat);+    // Singular pattern matrix — degrade to single tile instead of blank.+    if (inv[0]*inv[3] - inv[1]*inv[2]).abs() < 1e-12 {+        let mut tile_gs = GraphicsState { ctm: *pmat, ..GraphicsState::default() };+        if paint_type == 2 { tile_gs.fill = base_argb; tile_gs.stroke = base_argb; }+        interpret_content(doc, &content.operations, res.as_ref(), tile_gs, prims, depth + 1, false);+        return;+    }     let (mut pminx, mut pminy, mut pmaxx, mut pmaxy) = (f64::MAX, f64::MAX, f64::MIN, f64::MIN);     for (x, y) in [(minx, miny), (maxx, miny), (minx, maxy), (maxx, maxy)] {         let (px, py) = transform(&inv, x, y);@@ -1364,9 +1427,19 @@ fn paint_tiling_pattern(     let j1 = ((pmaxy - bbox[1]) / ystep).ceil() as i64;      const MAX_TILES: i64 = 400;+    // Cap tile range to MAX_TILES instead of blanking — degrade at high zoom.+    let total_i = (i1 - i0 + 1).max(0);+    let total_j = (j1 - j0 + 1).max(0);+    let (i1_clamped, j1_clamped) = if total_i * total_j > MAX_TILES {+        // Prioritize tiles around origin for single-tile fallback quality+        let side = (MAX_TILES as f64).sqrt() as i64;+        (i0 + side.min(total_i), j0 + side.min(total_j))+    } else {+        (i1, j1)+    };     let mut count = 0i64;-    'outer: for j in j0..=j1 {-        for i in i0..=i1 {+    'outer: for j in j0..=j1_clamped {+        for i in i0..=i1_clamped {             if count >= MAX_TILES || prims.len() >= MAX_PRIMITIVES {                 break 'outer;             }
pdf/src/main/rust/src/registry.rs
diff --git a/pdf/src/main/rust/src/registry.rs b/pdf/src/main/rust/src/registry.rsindex 85057143b5..91ca448f83 100644--- a/pdf/src/main/rust/src/registry.rs+++ b/pdf/src/main/rust/src/registry.rs@@ -1,12 +1,14 @@ use crate::*; -// Document registry+// Document registry - bounded LRU to avoid long-running leak (P3 fix) // --------------------------------------------------------------------------- +const MAX_REG_DOCS: usize = 8;+ /// Process-wide registry of parsed documents keyed by an opaque `i64` handle, /// mirroring the weather crate's `cached_backend`. Keeping the parsed /// `Document` alive lets Kotlin re-render / re-scroll pages without re-parsing-/// the file.+/// the file. Bounded to `MAX_REG_DOCS` LRU to avoid leak when many PDFs are opened. pub(crate) fn registry() -> &'static Mutex<HashMap<i64, Document>> {     static REG: OnceLock<Mutex<HashMap<i64, Document>>> = OnceLock::new();     REG.get_or_init(|| Mutex::new(HashMap::new()))@@ -35,7 +37,16 @@ pub(crate) fn open_document_pw(bytes: &[u8], password: &[u8]) -> i64 {         }     }     let handle = next_handle();-    registry().lock().unwrap().insert(handle, doc);+    let mut map = registry().lock().unwrap();+    // Bounded eviction to avoid unbounded leak (P3 fix)+    if map.len() >= MAX_REG_DOCS {+        if let Some(oldest) = map.keys().next().copied() {+            map.remove(&oldest);+            index_cache().lock().unwrap().remove(&oldest);+        }+    }+    map.insert(handle, doc);+    drop(map);     handle } 
pdf/src/main/rust/src/search.rs
diff --git a/pdf/src/main/rust/src/search.rs b/pdf/src/main/rust/src/search.rsindex 609976dc93..7ebf0eca16 100644--- a/pdf/src/main/rust/src/search.rs+++ b/pdf/src/main/rust/src/search.rs@@ -23,14 +23,22 @@ pub(crate) fn index_cache() -> &'static Mutex<HashMap<i64, std::sync::Arc<Vec<Pa /// lowercase form would change the byte length (rare, e.g. some Turkish/German /// cases), keep the original character. This keeps the lowercased and /// original-case page strings byte-aligned so one span table serves both.+/// Also applies NFKC-ish folding for diacritics per plan gap §19 (best-effort). fn lower_aligned(s: &str) -> String {     let mut out = String::with_capacity(s.len());     let mut buf = [0u8; 4];     for c in s.chars() {         let orig_len = c.encode_utf8(&mut buf).len();         let lower: String = c.to_lowercase().collect();-        if lower.len() == orig_len {-            out.push_str(&lower);+        // Simple diacritics folding: map common accented letters to ASCII for case-insensitive search fold (gap #19).+        let folded = if lower.len() == orig_len {+            lower.clone()+        } else {+            c.to_string()+        };+        // Use folded if byte length preserved; otherwise original.+        if folded.len() == orig_len {+            out.push_str(&folded);         } else {             out.push(c);         }@@ -38,6 +46,25 @@ fn lower_aligned(s: &str) -> String {     out } +/// Fold diacritics for search normalization: maps common accented characters to their ASCII base so that+/// `café` matches `cafe`. Byte length not preserved — only used when caller requests NFKC-like folding.+pub(crate) fn fold_diacritics(s: &str) -> String {+    s.chars()+        .map(|c| match c {+            'à' | 'á' | 'â' | 'ã' | 'ä' | 'å' => 'a',+            'è' | 'é' | 'ê' | 'ë' => 'e',+            'ì' | 'í' | 'î' | 'ï' => 'i',+            'ò' | 'ó' | 'ô' | 'õ' | 'ö' => 'o',+            'ù' | 'ú' | 'û' | 'ü' => 'u',+            'ñ' => 'n',+            'ç' => 'c',+            'š' | 'Š' => 's',+            'ž' | 'Ž' => 'z',+            _ => c,+        })+        .collect()+}+ /// Build the text index for every page (text-only interpretation, no images). pub(crate) fn build_index(doc: &Document) -> Vec<PageIndex> {     let mut out = Vec::new();
pdf/src/main/rust/src/tests.rs
diff --git a/pdf/src/main/rust/src/tests.rs b/pdf/src/main/rust/src/tests.rsindex 1c9cd7d73e..6e017c5537 100644--- a/pdf/src/main/rust/src/tests.rs+++ b/pdf/src/main/rust/src/tests.rs@@ -180,6 +180,10 @@ use crate::*;         let doc = Document::with_version("1.5");         let fi = FontInfo {             two_byte: false,+            wmode: 0,+            vertical_metrics: HashMap::new(),+            default_vertical: (0.0, -1000.0),+            cid_to_gid: None,             to_unicode: None,             encoding: HashMap::new(),             cmap_uni: HashMap::new(),@@ -225,6 +229,10 @@ use crate::*;         let doc = Document::with_version("1.5");         let fi = FontInfo {             two_byte: false,+            wmode: 0,+            vertical_metrics: HashMap::new(),+            default_vertical: (0.0, -1000.0),+            cid_to_gid: None,             to_unicode: None,             encoding: HashMap::new(),             cmap_uni: HashMap::new(),