From 6fc596f9472d765d74eccdfbcea693f5cb8c5ea3 Mon Sep 17 00:00:00 2001 From: elpidioassinaturas Date: Mon, 30 Nov 2026 09:14:00 -0300 Subject: [PATCH 1/6] feat(data): read a PDF page's optional content groups as separate rasters (#3442, part 1) pdf::read_layers draws page N once for each PDF layer (optional content group), on a transparent background, and once with every layer off for the content in none ("Not in a PDF layer"). Each group is drawn from an in-memory copy whose catalog an incremental update rewrites (/BaseState /OFF /ON [group]), since hayro 0.9 draws by the catalog's default configuration; a layer keeps the pixels that differ from the all-off drawing. - Names and order follow /OCProperties /D /Order (nested groups after their parent or label, "Mapa / Rios"), else /OCGs; a repeated name is numbered. - Visibility follows /D /BaseState, /ON and /OFF. - A group with nothing on the page is left out, and said. - The layers share the max_samples() budget one page has. - A layer reopens alone from its subdataset "#" through the existing read paths, at the same resolution. Co-Authored-By: Claude Opus 5.5 --- crates/data/src/raster/pdf.rs | 443 ++++++++++++++++++++++++++++++---- 1 file changed, 401 insertions(+), 42 deletions(-) diff --git a/crates/data/src/raster/pdf.rs b/crates/data/src/raster/pdf.rs index d75aa85750..e78229915c 100644 --- a/crates/data/src/raster/pdf.rs +++ b/crates/data/src/raster/pdf.rs @@ -9,11 +9,14 @@ use std::path::Path; use hayro::hayro_interpret::InterpreterSettings; use hayro::hayro_interpret::util::TransformExt; -use hayro::hayro_syntax::object::{Array, Dict, Name, String as PdfString}; +use hayro::hayro_syntax::object::{Array, Dict, MaybeRef, Name, ObjectIdentifier, String as PdfString}; use hayro::hayro_syntax::page::Page; +use hayro::hayro_syntax::xref::XRef; use hayro::hayro_syntax::{Pdf, PdfData}; use hayro::kurbo::{Affine, Point}; -use hayro::vello_cpu::color::palette::css::WHITE; +use hayro::vello_cpu::Pixmap; +use hayro::vello_cpu::color::palette::css::{TRANSPARENT, WHITE}; +use hayro::vello_cpu::color::{AlphaColor, Srgb}; use hayro::{PixmapSettings, RenderCache, RenderSettings}; use rustgis_geom::Coord; @@ -67,6 +70,33 @@ pub fn read_shared(name: &str, bytes: std::sync::Arc>, page: Option<&str /// [`read_bytes`], drawing the page in at most `max` samples (the tests' small limit exercises the /// reduction). fn read_limited(name: &str, bytes: PdfData, page: Option<&str>, place: bool, max: usize) -> Result { + // A layer of the page, saved as "#". + if let Some((page, layer)) = page.and_then(|p| p.split_once(LAYER_MARK)) { + let mut all = layers_limited(bytes, Some(page), place, max, Some(layer))?; + let mut one = all.layers.pop().ok_or_else(|| DataError::Format(format!("no PDF layer '{layer}' on page {page}")))?; + one.raster.lost = all.lost; + return Ok(one.raster); + } + let (pdf, number, count) = open(bytes, page)?; + let page = pdf.pages().get(number - 1).ok_or_else(|| DataError::Format(format!("no page {number}")))?; + let title = if count > 1 { format!("{name} page {number}") } else { name.to_string() }; + crate::progress::check()?; + let (mut r, scale) = draw(page, &title, max)?; + crate::progress::check()?; + if count > 1 { + // Only the pages named are written out, however many the file has. + let others = count - 1; + let shown: Vec = (1..=count).filter(|n| *n != number).take(NAMED_PAGES).map(|n| n.to_string()).collect(); + let more = others.saturating_sub(NAMED_PAGES); + let tail = if more > 0 { format!(", and {more} more") } else { String::new() }; + r.lost.push(format!("it has {others} more pages ({}{tail}): add one with \"layer\"", shown.join(", "))); + } + Ok(if place { place_by_viewport(r, page, scale) } else { r }) +} + +/// The PDF in `bytes`, the number of its page `page` (from 1; the first when `None`), and how +/// many pages it has. +fn open(bytes: PdfData, page: Option<&str>) -> Result<(Pdf, usize, usize)> { if bytes.as_ref().len() as u64 > MAX_BYTES { return Err(DataError::Format(format!("the PDF is larger than {} MB, too large to open", MAX_BYTES >> 20))); } @@ -77,8 +107,7 @@ fn read_limited(name: &str, bytes: PdfData, page: Option<&str>, place: bool, max hayro::hayro_syntax::LoadPdfError::Invalid => "not a PDF RustGIS can read".to_string(), }) })?; - let pages = pdf.pages(); - let count = pages.len(); + let count = pdf.pages().len(); if count == 0 { return Err(DataError::Format("the PDF has no pages".into())); } @@ -93,44 +122,265 @@ fn read_limited(name: &str, bytes: PdfData, page: Option<&str>, place: bool, max .filter(|n| (1..=count).contains(n)) .ok_or_else(|| DataError::Format(format!("no page '{p}': give a number from 1 to {count}")))?, }; - let Some(page) = pages.get(number - 1) else { - return Err(DataError::Format(format!("no page {number}"))); + Ok((pdf, number, count)) +} + +/// What a layer's subdataset puts between its page and its PDF layer's name ("1#Mapa / Rios"); +/// nothing follows it for the content in no layer. +pub const LAYER_MARK: char = '#'; +/// The name of the layer holding what a page draws whatever its PDF layers. +pub const OUTSIDE: &str = "Not in a PDF layer"; + +/// One of a page's PDF layers (optional content groups, #3442), drawn alone. +pub struct PdfLayer { + /// Its group's name, after the names of those it is nested in ("Mapa / Rios"). + pub name: String, + /// Whether the PDF shows it when opened. + pub visible: bool, + /// What reads it again ([`read_shared`]'s `page`). + pub subdataset: String, + /// Its drawing: red, green, blue and alpha, transparent where it has nothing. + pub raster: Raster, +} + +/// A page's PDF layers, the top first, and what is said of them all. +pub struct PdfLayers { + pub layers: Vec, + pub lost: crate::loss::Notes, +} + +/// Page `page` of a PDF as one layer for each of its PDF layers, and one for what is in none +/// ([`OUTSIDE`], left out when empty): none when it has no PDF layers, to read as a picture. +/// They share the memory one page is drawn in. +pub fn read_layers(bytes: std::sync::Arc>, page: Option<&str>, place: bool) -> Result { + read_layers_limited(bytes.into(), page, place, max_samples()) +} + +/// [`read_layers`] in at most `max` samples. +fn read_layers_limited(bytes: PdfData, page: Option<&str>, place: bool, max: usize) -> Result { + layers_limited(bytes, page, place, max, None) +} + +/// A PDF layer: its group, its name, and whether it is on when the PDF opens. +struct Group { + id: ObjectIdentifier, + name: String, + on: bool, +} + +/// The PDF's layers, in the order a reader lists them (the top first), with their names. +fn groups(pdf: &Pdf) -> Vec { + let xref = pdf.xref(); + let Some(props) = xref.get::(xref.root_id()).and_then(|c| c.get::(b"OCProperties".as_slice())) else { return Vec::new() }; + let refs = |d: &Dict, key: &[u8]| -> Vec { + d.get::(key).map(|a| a.raw_iter().filter_map(|i| i.as_obj_ref()).map(Into::into).collect()).unwrap_or_default() }; - let title = if count > 1 { format!("{name} page {number}") } else { name.to_string() }; - crate::progress::check()?; - let (mut r, scale) = draw(page, &title, max)?; - crate::progress::check()?; - if count > 1 { - // Only the pages named are written out, however many the file has. - let others = count - 1; - let shown: Vec = (1..=count).filter(|n| *n != number).take(NAMED_PAGES).map(|n| n.to_string()).collect(); - let more = others.saturating_sub(NAMED_PAGES); - let tail = if more > 0 { format!(", and {more} more") } else { String::new() }; - r.lost.push(format!("it has {others} more pages ({}{tail}): add one with \"layer\"", shown.join(", "))); + let all = refs(&props, b"OCGs"); + let d = props.get::(b"D"); + // As hayro draws them: all on, or all off with /BaseState /OFF, then /ON and /OFF. + let base = d.as_ref().and_then(|d| d.get::(b"BaseState".as_slice())).is_none_or(|n| n.as_str() != "OFF"); + let (on, off) = d.as_ref().map(|d| (refs(d, b"ON"), refs(d, b"OFF"))).unwrap_or_default(); + let mut named = Vec::new(); + if let Some(order) = d.as_ref().and_then(|d| d.get::(b"Order".as_slice())) { + walk(&order, xref, &all, "", &mut named, 0); + } + for id in &all { + if !named.iter().any(|(n, _)| n == id) + && let Some(name) = xref.get::(*id).and_then(|g| g.get::(b"Name".as_slice())) + { + named.push((*id, text(name.as_bytes()))); + } } - Ok(if place { place_by_viewport(r, page, scale) } else { r }) + // A name a group shares with one before it is numbered, so each layer opens again as itself. + let mut groups: Vec = Vec::with_capacity(named.len()); + for (id, first) in named { + let (mut name, mut n) = (first.clone(), 1); + while groups.iter().any(|g| g.name == name) { + n += 1; + name = format!("{first} ({n})"); + } + groups.push(Group { id, name, on: !off.contains(&id) && (base || on.contains(&id)) }); + } + groups } -/// The page drawn on white, as red, green and blue bands, and the pixels a point spans: at -/// [`DPI`], or less where its bands wouldn't fit in `max` samples or within the renderer's limit -/// (said in `lost`). -fn draw(page: &Page<'_>, name: &str, max: usize) -> Result<(Raster, f64)> { - let (w, h) = page.render_dimensions(); - let (w, h) = (f64::from(w), f64::from(h)); - if !(w >= 1.0 && h >= 1.0 && w.is_finite() && h.is_finite()) { - return Err(DataError::Format("the page has no area".into())); +/// The groups of `all` an `/Order` array lists, after `prefix` ("Mapa / "): a group followed by +/// an array has its children there, and an array whose first entry is text is a collection of +/// its own, labelled by it. +fn walk(order: &Array, xref: &XRef, all: &[ObjectIdentifier], prefix: &str, named: &mut Vec<(ObjectIdentifier, String)>, depth: usize) { + if depth > 32 { + return; + } + let (mut prefix, mut parent) = (prefix.to_string(), None); + for (i, item) in order.raw_iter().enumerate() { + match item { + MaybeRef::Ref(r) => { + let id = r.into(); + let name = xref.get::(id).and_then(|g| g.get::(b"Name".as_slice())); + if let Some(name) = name.filter(|_| all.contains(&id) && !named.iter().any(|(n, _)| *n == id)) { + let name = format!("{prefix}{}", text(name.as_bytes())); + parent = Some(format!("{name} / ")); + named.push((id, name)); + } + } + MaybeRef::NotRef(o) => { + if let Some(a) = o.clone().into_array() { + let labelled = + a.raw_iter().next().is_some_and(|i| matches!(i, MaybeRef::NotRef(o) if o.clone().into_string().is_some())); + let under = if labelled { None } else { parent.as_deref() }; + walk(&a, xref, all, under.unwrap_or(&prefix), named, depth + 1); + } else if let Some(label) = o.into_string().filter(|_| i == 0) { + prefix = format!("{prefix}{} / ", text(label.as_bytes())); + } + } + } } - let wanted = DPI / 72.0; - // Three samples a pixel kept (red, green, blue); the drawing's four bytes a pixel are a - // fraction of what they take as `f32`. - let fits = (max as f64 / 3.0 / (w * h)).sqrt(); - let largest = MAX_SIDE / w.max(h); - let scale = wanted.min(largest).min(fits); - if w * scale < 1.0 || h * scale < 1.0 { - return Err(DataError::Format("the page is too large to draw".into())); +} + +/// A PDF text string: UTF-16 after its byte order mark, else one character a byte. +fn text(b: &[u8]) -> String { + match b.strip_prefix(&[0xFE, 0xFF]) { + Some(utf16) => char::decode_utf16(utf16.chunks(2).map(|c| u16::from_be_bytes([c[0], *c.get(1).unwrap_or(&0)]))) + .map(|c| c.unwrap_or(char::REPLACEMENT_CHARACTER)) + .collect(), + None => b.iter().map(|&c| char::from(c)).collect(), + } +} + +/// [`read_layers`], or with `only` the layer of that name alone ("" for [`OUTSIDE`]), drawn as +/// when all are, and kept when empty. +fn layers_limited(bytes: PdfData, page: Option<&str>, place: bool, max: usize, only: Option<&str>) -> Result { + let (pdf, number, _) = open(bytes, page)?; + let groups = groups(&pdf); + let mut out = PdfLayers { layers: Vec::new(), lost: crate::loss::Notes::new() }; + if groups.is_empty() && only.is_none_or(|o| !o.is_empty()) { + return match only { + Some(o) => Err(DataError::Format(format!("no PDF layer '{o}' on page {number}"))), + None => Ok(out), + }; } - let settings = PixmapSettings { x_scale: scale as f32, y_scale: scale as f32, bg_color: WHITE }; - let pixmap = hayro::render(page, &RenderCache::new(), &InterpreterSettings::default(), &RenderSettings::default(), &settings); + let picked: Vec<&Group> = match only { + Some("") => Vec::new(), + Some(o) => { + vec![groups.iter().find(|g| g.name == o).ok_or_else(|| DataError::Format(format!("no PDF layer '{o}' on page {number}")))?] + } + None => groups.iter().collect(), + }; + let Some(page) = pdf.pages().get(number - 1) else { return Err(DataError::Format(format!("no page {number}"))) }; + // Every layer's four bands, and the content in none's, share what one page is drawn in. + let (scale, note) = scale_for(page, max, 4.0 * (groups.len() + 1) as f64)?; + out.lost.extend(note); + let ids: Vec = groups.iter().map(|g| g.id).collect(); + let catalog = pdf.xref().get::(pdf.xref().root_id()); + let pages = catalog.and_then(|c| c.get_ref(b"Pages".as_slice())).ok_or_else(|| DataError::Format("the PDF has no page tree".into()))?; + // The page drawn with only `on` of its layers on, from a copy of the file whose catalog an + // update at its end rewrites (hayro draws by the catalog's default configuration). + let draw_with = |on: Option| -> Result { + crate::progress::check()?; + let copy = Pdf::new(with_only(pdf.data().as_ref(), pdf.xref().root_id(), pages.into(), &ids, on)).ok(); + let drawn = copy.as_ref().filter(|c| only_on(c)).and_then(|c| c.pages().get(number - 1).map(|p| render(p, scale, TRANSPARENT))); + drawn.ok_or_else(|| DataError::Format("its PDF layers can't be drawn one by one: open it with \"pdfLayers\": false".into())) + }; + // A layer kept when it has something, or when asked for by name. + let add = |out: &mut PdfLayers, key: &str, visible: bool, (r, any): (Raster, bool)| { + if any || only.is_some() { + let (name, raster) = (r.name.clone(), if place { place_by_viewport(r, page, scale) } else { r }); + out.layers.push(PdfLayer { name, visible, subdataset: format!("{number}{LAYER_MARK}{key}"), raster }); + } else if !key.is_empty() { + out.lost.push(format!("its PDF layer '{key}' has nothing on this page: left out")); + } + }; + let none = draw_with(None)?; + for g in picked { + add(&mut out, &g.name, g.on, rgba(&draw_with(Some(g.id))?, Some(&none), &g.name)?); + } + if only.is_none_or(str::is_empty) { + add(&mut out, "", true, rgba(&none, None, OUTSIDE)?); + } + // Where the page is placed is said once, for all its layers. + let said = out.layers.iter_mut().map(|l| std::mem::take(&mut l.raster.lost)).last(); + out.lost.extend(said.into_iter().flatten()); + Ok(out) +} + +/// `bytes`, a PDF whose catalog is `root`, with an update at its end giving it a catalog of only +/// its page tree `pages` and its PDF layers `all`, all off but `on`. +fn with_only( + bytes: &[u8], + root: ObjectIdentifier, + pages: ObjectIdentifier, + all: &[ObjectIdentifier], + on: Option, +) -> Vec { + let r = |id: &ObjectIdentifier| format!("{} {} R", id.obj_number, id.gen_number); + let prev = bytes.windows(9).rposition(|w| w == b"startxref").map(|at| { + let tail = String::from_utf8_lossy(&bytes[at + 9..bytes.len().min(at + 40)]).into_owned(); + tail.split_whitespace().next().unwrap_or("0").to_string() + }); + let mut out = bytes.to_vec(); + out.push(b'\n'); + let at = out.len(); + let all: Vec = all.iter().map(r).collect(); + out.extend( + format!( + "{} {} obj\n<< /Type /Catalog /Pages {} /OCProperties << /OCGs [{}] /D << /BaseState /OFF /ON [{}] /RustGISOnly true >> >> >>\nendobj\n", + root.obj_number, + root.gen_number, + r(&pages), + all.join(" "), + on.as_ref().map(r).unwrap_or_default() + ) + .bytes(), + ); + let xref = out.len(); + let entry = format!("{at:010} {:05} n \n", root.gen_number); + let prev = prev.map(|p| format!(" /Prev {p}")).unwrap_or_default(); + let size = root.obj_number + 1; + out.extend( + format!("xref\n{} 1\n{entry}trailer\n<< /Size {size} /Root {}{prev} >>\nstartxref\n{xref}\n%%EOF\n", root.obj_number, r(&root)) + .bytes(), + ); + out +} + +/// Whether hayro reads the catalog [`with_only`] wrote (not one a broken file's repair found). +fn only_on(pdf: &Pdf) -> bool { + let xref = pdf.xref(); + let d = xref + .get::(xref.root_id()) + .and_then(|c| c.get::(b"OCProperties".as_slice())) + .and_then(|p| p.get::(b"D".as_slice())); + d.is_some_and(|d| d.contains_key(b"RustGISOnly".as_slice())) +} + +/// A drawing on a transparent background as red, green, blue and alpha bands, named `name`, +/// transparent where it is as `under` (drawn with no layer on) is, and whether anything is left. +fn rgba(drawn: &Pixmap, under: Option<&Pixmap>, name: &str) -> Result<(Raster, bool)> { + let (w, h) = (u32::from(drawn.width()), u32::from(drawn.height())); + let mut bands: Vec> = (0..4).map(|_| grid(w as usize, h as usize)).collect::>()?; + let under = under.map(|u| u.data_as_u8_slice().as_chunks::<4>().0); + let mut any = false; + for (i, px) in drawn.data_as_u8_slice().as_chunks::<4>().0.iter().take(w as usize * h as usize).enumerate() { + let keep = px[3] > 0 && under.is_none_or(|u| u.get(i) != Some(px)); + any |= keep; + // Premultiplied colours, divided by their alpha. + let a = u32::from(px[3]); + let colour = |c: u8| ((u32::from(c) * 255 + a / 2) / a.max(1)).min(255) as f32; + let v = if keep { [colour(px[0]), colour(px[1]), colour(px[2]), f32::from(px[3])] } else { [0.0; 4] }; + for (band, v) in bands.iter_mut().zip(v) { + band.push(v); + } + } + let mut r = Raster::new(name, w, h, bands, unreferenced(w, h), Crs::LonLat, None, ColorHint::Rgb { alpha: true }, "UInt8")?; + r.georeferenced = false; + Ok((r, any)) +} + +/// The page drawn on white, as red, green and blue bands, and the pixels a point spans +/// ([`scale_for`]'s, three samples a pixel). +fn draw(page: &Page<'_>, name: &str, max: usize) -> Result<(Raster, f64)> { + let (scale, note) = scale_for(page, max, 3.0)?; + let pixmap = render(page, scale, WHITE); let (pw, ph) = (u32::from(pixmap.width()), u32::from(pixmap.height())); // On an opaque background every pixel is opaque, so its premultiplied colour is its colour: // red, green and blue, the alpha left out. @@ -144,13 +394,37 @@ fn draw(page: &Page<'_>, name: &str, max: usize) -> Result<(Raster, f64)> { drop(pixmap); let mut r = Raster::new(name, pw, ph, bands, unreferenced(pw, ph), Crs::LonLat, None, ColorHint::Rgb { alpha: false }, "UInt8")?; r.georeferenced = false; - if scale < wanted * 0.999 { - let why = if fits <= largest { "to fit in memory" } else { "the largest size it can be drawn at" }; - r.lost.push(format!("its page is drawn at {:.0} dots an inch, not {DPI:.0}, {why}", scale * 72.0)); - } + r.lost.extend(note); Ok((r, scale)) } +/// The pixels a point spans when the page is drawn: at [`DPI`], or less where `per_pixel` +/// samples a pixel wouldn't fit in `max` or within the renderer's limit, and then why. +fn scale_for(page: &Page<'_>, max: usize, per_pixel: f64) -> Result<(f64, Option)> { + let (w, h) = page.render_dimensions(); + let (w, h) = (f64::from(w), f64::from(h)); + if !(w >= 1.0 && h >= 1.0 && w.is_finite() && h.is_finite()) { + return Err(DataError::Format("the page has no area".into())); + } + let wanted = DPI / 72.0; + // The drawing's four bytes a pixel are a fraction of what the samples take as `f32`. + let fits = (max as f64 / per_pixel / (w * h)).sqrt(); + let largest = MAX_SIDE / w.max(h); + let scale = wanted.min(largest).min(fits); + if w * scale < 1.0 || h * scale < 1.0 { + return Err(DataError::Format("the page is too large to draw".into())); + } + let why = if fits <= largest { "to fit in memory" } else { "the largest size it can be drawn at" }; + let note = (scale < wanted * 0.999).then(|| format!("its page is drawn at {:.0} dots an inch, not {DPI:.0}, {why}", scale * 72.0)); + Ok((scale, note)) +} + +/// The page drawn at `scale` pixels a point on `background`. +fn render(page: &Page<'_>, scale: f64, background: AlphaColor) -> Pixmap { + let settings = PixmapSettings { x_scale: scale as f32, y_scale: scale as f32, bg_color: background }; + hayro::render(page, &RenderCache::new(), &InterpreterSettings::default(), &RenderSettings::default(), &settings) +} + /// A GeoPDF viewport: its rectangle on the page, its control points (latitude, longitude) and /// where they lie in that rectangle (fractions of it), and its coordinate system with the PROJ /// definition whose datum the points are given on. @@ -422,12 +696,17 @@ mod tests { /// `extra` (a `/VP`, say), with a correct cross-reference table. fn tiny_pdf(media: &str, extra: &str) -> Vec { let content = "0 0 1 rg 0 0 10 10 re f"; - let objects = [ + build(&[ "<< /Type /Catalog /Pages 2 0 R >>".to_string(), "<< /Type /Pages /Kids [3 0 R] /Count 1 >>".to_string(), format!("<< /Type /Page /Parent 2 0 R /MediaBox [{media}] /Contents 4 0 R {extra} >>"), format!("<< /Length {} >>\nstream\n{content}\nendstream", content.len()), - ]; + ]) + } + + /// A PDF of these objects, numbered from 1 (the first its catalog), with a correct + /// cross-reference table. + fn build(objects: &[String]) -> Vec { let mut out = String::from("%PDF-1.7\n"); let mut at = Vec::new(); for (i, o) in objects.iter().enumerate() { @@ -558,4 +837,84 @@ mod tests { // A page box of no area: drawn at a size the renderer gives it, or refused, never a panic. let _ = read_bytes("flat", tiny_pdf("0 0 72 0", ""), None, true); } + + /// A 72 × 36 point page with four squares, 10 points a side, along its foot: red outside every + /// group, then green in "Relevo", blue in "Água" (its name in UTF-16) and yellow in "Quadro" + /// (objects 5 to 7), and a group "Vazio" (8) with nothing in it; `d` is the default + /// configuration's dictionary. + fn layered_pdf(d: &str) -> Vec { + let content = "1 0 0 rg 0 0 10 10 re f /OC /a BDC 0 1 0 rg 20 0 10 10 re f EMC \ + /OC /b BDC 0 0 1 rg 40 0 10 10 re f EMC /OC /c BDC 1 1 0 rg 60 0 10 10 re f EMC"; + build(&[ + format!("<< /Type /Catalog /Pages 2 0 R /OCProperties << /OCGs [5 0 R 6 0 R 7 0 R 8 0 R] /D {d} >> >>"), + "<< /Type /Pages /Kids [3 0 R] /Count 1 >>".to_string(), + "<< /Type /Page /Parent 2 0 R /MediaBox [0 0 72 36] /Contents 4 0 R \ + /Resources << /Properties << /a 5 0 R /b 6 0 R /c 7 0 R >> >> >>" + .to_string(), + format!("<< /Length {} >>\nstream\n{content}\nendstream", content.len()), + "<< /Type /OCG /Name (Relevo) >>".to_string(), + "<< /Type /OCG /Name >>".to_string(), + "<< /Type /OCG /Name (Quadro) >>".to_string(), + "<< /Type /OCG /Name (Vazio) >>".to_string(), + ]) + } + + /// Red, green, blue and alpha under the middle of the square `at` points from the page's + /// left edge, in a layer drawn at 150 dpi. + fn square(r: &Raster, at: f64) -> [f32; 4] { + let (col, row) = (((at + 5.0) * DPI / 72.0) as usize, 70); + std::array::from_fn(|b| r.bands[b].data[row * r.width as usize + col]) + } + + #[test] + fn a_page_with_layers_opens_one_raster_for_each_on_a_transparent_background() { + let d = "<< /Order [7 0 R [(Mapa) 6 0 R 5 0 R] 8 0 R] /OFF [7 0 R] >>"; + let all = read_layers(layered_pdf(d).into(), None, true).unwrap(); + let names: Vec<(&str, bool)> = all.layers.iter().map(|l| (l.name.as_str(), l.visible)).collect(); + assert_eq!(names, [("Quadro", false), ("Mapa / Água", true), ("Mapa / Relevo", true), (OUTSIDE, true)]); + assert_eq!(all.lost, ["its PDF layer 'Vazio' has nothing on this page: left out"]); + let none = [0.0; 4]; + let [red, green, blue, yellow] = + [[255.0, 0.0, 0.0], [0.0, 255.0, 0.0], [0.0, 0.0, 255.0], [255.0, 255.0, 0.0]].map(|[r, g, b]| [r, g, b, 255.0]); + let wanted = [[none, none, none, yellow], [none, none, blue, none], [none, green, none, none], [red, none, none, none]]; + for (layer, want) in all.layers.iter().zip(wanted) { + let r = &layer.raster; + assert_eq!((r.width, r.height, r.bands.len()), (150, 75, 4), "{}", layer.name); + assert_eq!([0.0, 20.0, 40.0, 60.0].map(|at| square(r, at)), want, "{}", layer.name); + assert!(r.lost.is_empty(), "{:?}", r.lost); + } + // Each layer opens again alone from its subdataset, as drawn with the others. + for layer in &all.layers { + let one = read_bytes("m", layered_pdf(d), Some(&layer.subdataset), true).unwrap(); + assert_eq!(one.name, layer.name); + assert!(one.bands.iter().zip(&layer.raster.bands).all(|(a, b)| a.data == b.data), "{}", layer.name); + } + let e = read_bytes("m", layered_pdf(d), Some("1#Lagos"), true).unwrap_err().to_string(); + assert!(e.contains("no PDF layer 'Lagos'"), "{e}"); + // A page without layers has none, and opens as one picture. + assert!(read_layers(tiny_pdf("0 0 72 36", "").into(), None, true).unwrap().layers.is_empty()); + } + + #[test] + fn layers_follow_the_groups_without_an_order_and_share_the_memory() { + // No /Order: the groups' own order; /BaseState /OFF with Água on. + let all = read_layers(layered_pdf("<< /BaseState /OFF /ON [6 0 R] >>").into(), None, true).unwrap(); + let names: Vec<(&str, bool)> = all.layers.iter().map(|l| (l.name.as_str(), l.visible)).collect(); + assert_eq!(names, [("Relevo", false), ("Água", true), ("Quadro", false), (OUTSIDE, true)]); + // Groups nested under another keep its name as a prefix. + let all = read_layers(layered_pdf("<< /Order [5 0 R [6 0 R 7 0 R]] >>").into(), None, true).unwrap(); + let names: Vec<&str> = all.layers.iter().map(|l| l.name.as_str()).collect(); + assert_eq!(names, ["Relevo", "Relevo / Água", "Relevo / Quadro", OUTSIDE]); + // Two groups of one name are told apart, and each opens again as itself. + let twice = String::from_utf8(layered_pdf("<< >>")).unwrap().replace("(Quadro)", "(Relevo)"); + let all = read_layers(twice.clone().into_bytes().into(), None, true).unwrap(); + let names: Vec<&str> = all.layers.iter().map(|l| l.name.as_str()).collect(); + assert_eq!(names, ["Relevo", "Água", "Relevo (2)", OUTSIDE]); + let yellow = read_bytes("m", twice.into_bytes(), Some(&all.layers[2].subdataset), true).unwrap(); + assert_eq!(square(&yellow, 60.0), [255.0, 255.0, 0.0, 255.0]); + // Four groups and the content outside them, four bands each, share the samples a page has. + let all = read_layers_limited(layered_pdf("<< >>").into(), None, true, 30_000).unwrap(); + assert!(all.layers.iter().all(|l| l.raster.width * l.raster.height * 4 * 5 <= 30_000), "{}", all.layers[0].raster.width); + assert_eq!(all.lost.iter().filter(|t| t.contains("dots an inch, not 150")).count(), 1, "{:?}", all.lost); + } } From 4684d8ec6671619cface46f8ac8cdff78e42837c Mon Sep 17 00:00:00 2001 From: elpidioassinaturas Date: Mon, 30 Nov 2026 09:21:10 -0300 Subject: [PATCH 2/6] test(data): a PDF layer over fixed content of its own colour (#3442, part 1) Pins down the limit of separating a group by what changes when it is turned on: where the group draws the colour the content in no group already has there, the pixel stays in "Not in a PDF layer". Co-Authored-By: Claude Opus 5.5 --- crates/data/src/raster/pdf.rs | 28 ++++++++++++++++++++++++++-- 1 file changed, 26 insertions(+), 2 deletions(-) diff --git a/crates/data/src/raster/pdf.rs b/crates/data/src/raster/pdf.rs index e78229915c..916f2176cd 100644 --- a/crates/data/src/raster/pdf.rs +++ b/crates/data/src/raster/pdf.rs @@ -843,8 +843,15 @@ mod tests { /// (objects 5 to 7), and a group "Vazio" (8) with nothing in it; `d` is the default /// configuration's dictionary. fn layered_pdf(d: &str) -> Vec { - let content = "1 0 0 rg 0 0 10 10 re f /OC /a BDC 0 1 0 rg 20 0 10 10 re f EMC \ - /OC /b BDC 0 0 1 rg 40 0 10 10 re f EMC /OC /c BDC 1 1 0 rg 60 0 10 10 re f EMC"; + layered( + "1 0 0 rg 0 0 10 10 re f /OC /a BDC 0 1 0 rg 20 0 10 10 re f EMC \ + /OC /b BDC 0 0 1 rg 40 0 10 10 re f EMC /OC /c BDC 1 1 0 rg 60 0 10 10 re f EMC", + d, + ) + } + + /// [`layered_pdf`]'s groups with this `content` drawn on the page. + fn layered(content: &str, d: &str) -> Vec { build(&[ format!("<< /Type /Catalog /Pages 2 0 R /OCProperties << /OCGs [5 0 R 6 0 R 7 0 R 8 0 R] /D {d} >> >>"), "<< /Type /Pages /Kids [3 0 R] /Count 1 >>".to_string(), @@ -859,6 +866,23 @@ mod tests { ]) } + #[test] + fn a_layer_over_content_of_its_own_colour_leaves_it_to_the_layer_under_it() { + // A black frame outside every group, and black text (a square) in "Relevo" lying half on + // it, half beside it. A layer is what changes when its group is turned on: where the + // group draws the colour already there, it is left to "Not in a PDF layer", so the + // layers stacked still give the page, but hiding that layer hides it too (a known limit: + // hayro always draws what is in no group, so a group can't be drawn alone). + let content = "0 0 0 rg 0 0 30 20 re f /OC /a BDC 0 0 0 rg 20 0 20 10 re f EMC"; + let all = read_layers(layered(content, "<< >>").into(), None, true).unwrap(); + let names: Vec<&str> = all.layers.iter().map(|l| l.name.as_str()).collect(); + assert_eq!(names, ["Relevo", OUTSIDE]); + let (black, none) = ([0.0, 0.0, 0.0, 255.0], [0.0; 4]); + // Its square beside the frame, at 30–40 points, is in the layer; on the frame, it is not. + assert_eq!([20.0, 30.0].map(|at| square(&all.layers[0].raster, at)), [none, black]); + assert_eq!([20.0, 30.0].map(|at| square(&all.layers[1].raster, at)), [black, none]); + } + /// Red, green, blue and alpha under the middle of the square `at` points from the page's /// left edge, in a layer drawn at 150 dpi. fn square(r: &Raster, at: f64) -> [f32; 4] { From bfabd195ac1f55636a92d18159bdafe9563a3dc3 Mon Sep 17 00:00:00 2001 From: elpidioassinaturas Date: Mon, 30 Nov 2026 10:47:38 -0300 Subject: [PATCH 3/6] fix(data): name unnamed PDF layers, decode PDFDocEncoding, cap the layers a page is read as (#3442, part 1) - A group with no /Name, or an empty one, is "Unnamed" (numbered when repeated), so its content keeps a layer and its subdataset is never the outside layer's. - Names without a UTF-16 mark are read as UTF-8 after its mark, else as PDFDocEncoding. - A page is read as at most 64 PDF layers; the others are left to the content in none, as the PDF opens them, and that is said. - The other pages are said in layer mode too. - Group membership checks use sets; a slice of the file uses get(). Co-Authored-By: Claude Opus 5.5 --- crates/data/src/raster/pdf.rs | 192 +++++++++++++++++++++++++--------- 1 file changed, 143 insertions(+), 49 deletions(-) diff --git a/crates/data/src/raster/pdf.rs b/crates/data/src/raster/pdf.rs index 916f2176cd..4b2505e6a0 100644 --- a/crates/data/src/raster/pdf.rs +++ b/crates/data/src/raster/pdf.rs @@ -5,6 +5,7 @@ //! The whole page is drawn, its title and legend too, and the map frame's coordinates run across //! it, as readers of GeoPDFs do. +use std::collections::HashSet; use std::path::Path; use hayro::hayro_interpret::InterpreterSettings; @@ -31,6 +32,8 @@ const MAX_SIDE: f64 = 65_535.0; pub const MAX_BYTES: u64 = 1 << 30; /// The most other pages a notice names. const NAMED_PAGES: usize = 20; +/// The most PDF layers a page is read as: the others are drawn with what is in none. +const MAX_LAYERS: usize = 64; /// Reads page `page` of the PDF at `path` (its number, from 1; the first when `None`), placed by /// its coordinates when `place` (else a scan, as `"as": "scan"` opens it). @@ -83,17 +86,20 @@ fn read_limited(name: &str, bytes: PdfData, page: Option<&str>, place: bool, max crate::progress::check()?; let (mut r, scale) = draw(page, &title, max)?; crate::progress::check()?; - if count > 1 { - // Only the pages named are written out, however many the file has. - let others = count - 1; - let shown: Vec = (1..=count).filter(|n| *n != number).take(NAMED_PAGES).map(|n| n.to_string()).collect(); - let more = others.saturating_sub(NAMED_PAGES); - let tail = if more > 0 { format!(", and {more} more") } else { String::new() }; - r.lost.push(format!("it has {others} more pages ({}{tail}): add one with \"layer\"", shown.join(", "))); - } + r.lost.extend(more_pages(number, count)); Ok(if place { place_by_viewport(r, page, scale) } else { r }) } +/// That a PDF of `count` pages has others than page `number`, when it has. +fn more_pages(number: usize, count: usize) -> Option { + // Only the pages named are written out, however many the file has. + let others = count.checked_sub(1).filter(|o| *o > 0)?; + let shown: Vec = (1..=count).filter(|n| *n != number).take(NAMED_PAGES).map(|n| n.to_string()).collect(); + let more = others.saturating_sub(NAMED_PAGES); + let tail = if more > 0 { format!(", and {more} more") } else { String::new() }; + Some(format!("it has {others} more pages ({}{tail}): add one with \"layer\"", shown.join(", "))) +} + /// The PDF in `bytes`, the number of its page `page` (from 1; the first when `None`), and how /// many pages it has. fn open(bytes: PdfData, page: Option<&str>) -> Result<(Pdf, usize, usize)> { @@ -179,23 +185,23 @@ fn groups(pdf: &Pdf) -> Vec { let d = props.get::(b"D"); // As hayro draws them: all on, or all off with /BaseState /OFF, then /ON and /OFF. let base = d.as_ref().and_then(|d| d.get::(b"BaseState".as_slice())).is_none_or(|n| n.as_str() != "OFF"); - let (on, off) = d.as_ref().map(|d| (refs(d, b"ON"), refs(d, b"OFF"))).unwrap_or_default(); + let set = |d: &Dict, key: &[u8]| -> HashSet { refs(d, key).into_iter().collect() }; + let (on, off) = d.as_ref().map(|d| (set(d, b"ON"), set(d, b"OFF"))).unwrap_or_default(); + let (member, mut seen): (HashSet<_>, HashSet<_>) = (all.iter().copied().collect(), HashSet::new()); let mut named = Vec::new(); if let Some(order) = d.as_ref().and_then(|d| d.get::(b"Order".as_slice())) { - walk(&order, xref, &all, "", &mut named, 0); + walk(&order, xref, &member, "", (&mut named, &mut seen), 0); } - for id in &all { - if !named.iter().any(|(n, _)| n == id) - && let Some(name) = xref.get::(*id).and_then(|g| g.get::(b"Name".as_slice())) - { - named.push((*id, text(name.as_bytes()))); + for id in all { + if seen.insert(id) { + named.push((id, group_name(xref, id))); } } // A name a group shares with one before it is numbered, so each layer opens again as itself. - let mut groups: Vec = Vec::with_capacity(named.len()); + let (mut groups, mut taken) = (Vec::with_capacity(named.len()), HashSet::new()); for (id, first) in named { let (mut name, mut n) = (first.clone(), 1); - while groups.iter().any(|g| g.name == name) { + while !taken.insert(name.clone()) { n += 1; name = format!("{first} ({n})"); } @@ -204,10 +210,24 @@ fn groups(pdf: &Pdf) -> Vec { groups } +/// A group's `/Name`, or "Unnamed" when it has none or an empty one (whose subdataset would be +/// [`OUTSIDE`]'s). +fn group_name(xref: &XRef, id: ObjectIdentifier) -> String { + let name = xref.get::(id).and_then(|g| g.get::(b"Name".as_slice())).map(|n| text(n.as_bytes())); + name.filter(|n| !n.is_empty()).unwrap_or_else(|| "Unnamed".into()) +} + /// The groups of `all` an `/Order` array lists, after `prefix` ("Mapa / "): a group followed by /// an array has its children there, and an array whose first entry is text is a collection of /// its own, labelled by it. -fn walk(order: &Array, xref: &XRef, all: &[ObjectIdentifier], prefix: &str, named: &mut Vec<(ObjectIdentifier, String)>, depth: usize) { +fn walk( + order: &Array, + xref: &XRef, + all: &HashSet, + prefix: &str, + (named, seen): (&mut Vec<(ObjectIdentifier, String)>, &mut HashSet), + depth: usize, +) { if depth > 32 { return; } @@ -216,9 +236,8 @@ fn walk(order: &Array, xref: &XRef, all: &[ObjectIdentifier], prefix: &str, name match item { MaybeRef::Ref(r) => { let id = r.into(); - let name = xref.get::(id).and_then(|g| g.get::(b"Name".as_slice())); - if let Some(name) = name.filter(|_| all.contains(&id) && !named.iter().any(|(n, _)| *n == id)) { - let name = format!("{prefix}{}", text(name.as_bytes())); + if all.contains(&id) && seen.insert(id) { + let name = format!("{prefix}{}", group_name(xref, id)); parent = Some(format!("{name} / ")); named.push((id, name)); } @@ -228,7 +247,7 @@ fn walk(order: &Array, xref: &XRef, all: &[ObjectIdentifier], prefix: &str, name let labelled = a.raw_iter().next().is_some_and(|i| matches!(i, MaybeRef::NotRef(o) if o.clone().into_string().is_some())); let under = if labelled { None } else { parent.as_deref() }; - walk(&a, xref, all, under.unwrap_or(&prefix), named, depth + 1); + walk(&a, xref, all, under.unwrap_or(&prefix), (&mut *named, &mut *seen), depth + 1); } else if let Some(label) = o.into_string().filter(|_| i == 0) { prefix = format!("{prefix}{} / ", text(label.as_bytes())); } @@ -237,22 +256,52 @@ fn walk(order: &Array, xref: &XRef, all: &[ObjectIdentifier], prefix: &str, name } } -/// A PDF text string: UTF-16 after its byte order mark, else one character a byte. +/// A PDF text string: UTF-16 or UTF-8 after its byte order mark, else PDFDocEncoding. fn text(b: &[u8]) -> String { - match b.strip_prefix(&[0xFE, 0xFF]) { - Some(utf16) => char::decode_utf16(utf16.chunks(2).map(|c| u16::from_be_bytes([c[0], *c.get(1).unwrap_or(&0)]))) - .map(|c| c.unwrap_or(char::REPLACEMENT_CHARACTER)) - .collect(), - None => b.iter().map(|&c| char::from(c)).collect(), + if let Some(utf16) = b.strip_prefix(&[0xFE, 0xFF]) { + let units = utf16.chunks(2).map(|c| u16::from_be_bytes([c.first().copied().unwrap_or(0), c.get(1).copied().unwrap_or(0)])); + return char::decode_utf16(units).map(|c| c.unwrap_or(char::REPLACEMENT_CHARACTER)).collect(); + } + if let Some(utf8) = b.strip_prefix(&[0xEF, 0xBB, 0xBF]) { + return String::from_utf8_lossy(utf8).into_owned(); } + b.iter().map(|&c| pdf_doc(c)).collect() +} + +/// A byte of PDFDocEncoding (ISO 32000-2 Annex D): Latin-1, but for 0x18-0x1F and 0x80-0xA0. +fn pdf_doc(c: u8) -> char { + const LOW: [u16; 8] = [0x02D8, 0x02C7, 0x02C6, 0x02D9, 0x02DD, 0x02DB, 0x02DA, 0x02DC]; + const HIGH: [u16; 33] = [ + 0x2022, 0x2020, 0x2021, 0x2026, 0x2014, 0x2013, 0x0192, 0x2044, 0x2039, 0x203A, 0x2212, 0x2030, 0x201E, 0x201C, 0x201D, 0x2018, + 0x2019, 0x201A, 0x2122, 0xFB01, 0xFB02, 0x0141, 0x0152, 0x0160, 0x0178, 0x017D, 0x0131, 0x0142, 0x0153, 0x0161, 0x017E, 0xFFFD, + 0x20AC, + ]; + let mapped = match c { + 0x18..=0x1F => LOW.get(usize::from(c - 0x18)), + 0x80..=0xA0 => HIGH.get(usize::from(c - 0x80)), + _ => None, + }; + mapped.and_then(|&u| char::from_u32(u32::from(u))).unwrap_or(char::from(c)) } /// [`read_layers`], or with `only` the layer of that name alone ("" for [`OUTSIDE`]), drawn as /// when all are, and kept when empty. fn layers_limited(bytes: PdfData, page: Option<&str>, place: bool, max: usize, only: Option<&str>) -> Result { - let (pdf, number, _) = open(bytes, page)?; - let groups = groups(&pdf); + let (pdf, number, count) = open(bytes, page)?; + let mut groups = groups(&pdf); let mut out = PdfLayers { layers: Vec::new(), lost: crate::loss::Notes::new() }; + out.lost.extend(more_pages(number, count)); + // Past the first MAX_LAYERS, groups are left to the content in none, as the PDF opens them. + let ids: Vec = groups.iter().map(|g| g.id).collect(); + let rest: Vec = groups.iter().skip(MAX_LAYERS).filter(|g| g.on).map(|g| g.id).collect(); + if groups.len() > MAX_LAYERS { + let other = groups.len() - MAX_LAYERS; + out.lost.push(format!( + "it has {} PDF layers: the first {MAX_LAYERS} are layers of their own, the other {other} are drawn in '{OUTSIDE}'", + groups.len() + )); + groups.truncate(MAX_LAYERS); + } if groups.is_empty() && only.is_none_or(|o| !o.is_empty()) { return match only { Some(o) => Err(DataError::Format(format!("no PDF layer '{o}' on page {number}"))), @@ -270,14 +319,14 @@ fn layers_limited(bytes: PdfData, page: Option<&str>, place: bool, max: usize, o // Every layer's four bands, and the content in none's, share what one page is drawn in. let (scale, note) = scale_for(page, max, 4.0 * (groups.len() + 1) as f64)?; out.lost.extend(note); - let ids: Vec = groups.iter().map(|g| g.id).collect(); let catalog = pdf.xref().get::(pdf.xref().root_id()); let pages = catalog.and_then(|c| c.get_ref(b"Pages".as_slice())).ok_or_else(|| DataError::Format("the PDF has no page tree".into()))?; // The page drawn with only `on` of its layers on, from a copy of the file whose catalog an // update at its end rewrites (hayro draws by the catalog's default configuration). let draw_with = |on: Option| -> Result { crate::progress::check()?; - let copy = Pdf::new(with_only(pdf.data().as_ref(), pdf.xref().root_id(), pages.into(), &ids, on)).ok(); + let on: Vec = on.into_iter().chain(rest.iter().copied()).collect(); + let copy = Pdf::new(with_only(pdf.data().as_ref(), pdf.xref().root_id(), pages.into(), &ids, &on)).ok(); let drawn = copy.as_ref().filter(|c| only_on(c)).and_then(|c| c.pages().get(number - 1).map(|p| render(p, scale, TRANSPARENT))); drawn.ok_or_else(|| DataError::Format("its PDF layers can't be drawn one by one: open it with \"pdfLayers\": false".into())) }; @@ -304,17 +353,11 @@ fn layers_limited(bytes: PdfData, page: Option<&str>, place: bool, max: usize, o } /// `bytes`, a PDF whose catalog is `root`, with an update at its end giving it a catalog of only -/// its page tree `pages` and its PDF layers `all`, all off but `on`. -fn with_only( - bytes: &[u8], - root: ObjectIdentifier, - pages: ObjectIdentifier, - all: &[ObjectIdentifier], - on: Option, -) -> Vec { +/// its page tree `pages` and its PDF layers `all`, all off but those `on`. +fn with_only(bytes: &[u8], root: ObjectIdentifier, pages: ObjectIdentifier, all: &[ObjectIdentifier], on: &[ObjectIdentifier]) -> Vec { let r = |id: &ObjectIdentifier| format!("{} {} R", id.obj_number, id.gen_number); let prev = bytes.windows(9).rposition(|w| w == b"startxref").map(|at| { - let tail = String::from_utf8_lossy(&bytes[at + 9..bytes.len().min(at + 40)]).into_owned(); + let tail = String::from_utf8_lossy(bytes.get(at + 9..bytes.len().min(at + 40)).unwrap_or_default()).into_owned(); tail.split_whitespace().next().unwrap_or("0").to_string() }); let mut out = bytes.to_vec(); @@ -328,7 +371,7 @@ fn with_only( root.gen_number, r(&pages), all.join(" "), - on.as_ref().map(r).unwrap_or_default() + on.iter().map(r).collect::>().join(" ") ) .bytes(), ); @@ -843,16 +886,21 @@ mod tests { /// (objects 5 to 7), and a group "Vazio" (8) with nothing in it; `d` is the default /// configuration's dictionary. fn layered_pdf(d: &str) -> Vec { - layered( - "1 0 0 rg 0 0 10 10 re f /OC /a BDC 0 1 0 rg 20 0 10 10 re f EMC \ - /OC /b BDC 0 0 1 rg 40 0 10 10 re f EMC /OC /c BDC 1 1 0 rg 60 0 10 10 re f EMC", - d, - ) + layered(SQUARES, d) } + /// [`layered_pdf`]'s four squares. + const SQUARES: &str = "1 0 0 rg 0 0 10 10 re f /OC /a BDC 0 1 0 rg 20 0 10 10 re f EMC \ + /OC /b BDC 0 0 1 rg 40 0 10 10 re f EMC /OC /c BDC 1 1 0 rg 60 0 10 10 re f EMC"; + /// [`layered_pdf`]'s groups with this `content` drawn on the page. fn layered(content: &str, d: &str) -> Vec { - build(&[ + build(&layered_objects(content, d)) + } + + /// [`layered`]'s objects, for a test to change before [`build`]. + fn layered_objects(content: &str, d: &str) -> Vec { + vec![ format!("<< /Type /Catalog /Pages 2 0 R /OCProperties << /OCGs [5 0 R 6 0 R 7 0 R 8 0 R] /D {d} >> >>"), "<< /Type /Pages /Kids [3 0 R] /Count 1 >>".to_string(), "<< /Type /Page /Parent 2 0 R /MediaBox [0 0 72 36] /Contents 4 0 R \ @@ -863,7 +911,53 @@ mod tests { "<< /Type /OCG /Name >>".to_string(), "<< /Type /OCG /Name (Quadro) >>".to_string(), "<< /Type /OCG /Name (Vazio) >>".to_string(), - ]) + ] + } + + /// The names of the layers read from these objects. + fn layer_names(objects: &[String]) -> Vec { + read_layers(build(objects).into(), None, true).unwrap().layers.into_iter().map(|l| l.name).collect() + } + + #[test] + fn groups_without_a_name_or_named_in_another_encoding_are_named_and_kept() { + let mut objects = layered_objects(SQUARES, "<< >>"); + // No /Name, and an empty one: named, so their squares stay in a layer that opens again. + objects[4] = "<< /Type /OCG >>".into(); + objects[6] = "<< /Type /OCG /Name () >>".into(); + assert_eq!(layer_names(&objects), ["Unnamed", "Água", "Unnamed (2)", OUTSIDE]); + let all = read_layers(build(&objects).into(), None, true).unwrap(); + let yellow = read_bytes("m", build(&objects), Some(&all.layers[2].subdataset), true).unwrap(); + assert_eq!(square(&yellow, 60.0), [255.0, 255.0, 0.0, 255.0]); + // PDFDocEncoding (0x8A is a minus sign), and UTF-8 after its byte order mark. + objects[4] = "<< /Type /OCG /Name <526F616473208A204D616A6F72> >>".into(); + objects[6] = "<< /Type /OCG /Name >>".into(); + assert_eq!(layer_names(&objects), ["Roads \u{2212} Major", "Água", "Água ", OUTSIDE]); + } + + #[test] + fn a_page_of_many_layers_draws_the_first_and_leaves_the_rest_to_the_page() { + // 70 groups, the last drawing a magenta square at the top left. + let mut objects = layered_objects("", "<< >>"); + let groups: Vec = (5..75).map(|n| format!("{n} 0 R")).collect(); + objects[0] = format!("<< /Type /Catalog /Pages 2 0 R /OCProperties << /OCGs [{}] /D << >> >> >>", groups.join(" ")); + objects[2] = objects[2].replace("/c 7 0 R", "/c 7 0 R /z 74 0 R"); + let content = "/OC /a BDC 0 1 0 rg 20 0 10 10 re f EMC /OC /z BDC 1 0 1 rg 0 20 10 10 re f EMC"; + objects[3] = format!("<< /Length {} >>\nstream\n{content}\nendstream", content.len()); + objects.extend((9..75).map(|n| format!("<< /Type /OCG /Name (G{n}) >>"))); + let all = read_layers(build(&objects).into(), None, true).unwrap(); + assert_eq!(all.layers.iter().map(|l| l.name.as_str()).collect::>(), ["Relevo", OUTSIDE]); + let said = format!("it has 70 PDF layers: the first {MAX_LAYERS} are layers of their own, the other 6 are drawn in '{OUTSIDE}'"); + assert!(all.lost.says(&said), "{:?}", all.lost); + assert_eq!(all.lost.iter().filter(|t| t.contains("has nothing on this page")).count(), MAX_LAYERS - 1); + let outside = &all.layers[1].raster; + let at = |b: usize| outside.bands[b].data[20 * outside.width as usize + 10]; + assert_eq!([at(0), at(1), at(2), at(3)], [255.0, 0.0, 255.0, 255.0]); + // A second page is said, as when the page is read as a picture. + objects[1] = format!("<< /Type /Pages /Kids [3 0 R {} 0 R] /Count 2 >>", objects.len() + 1); + objects.push("<< /Type /Page /Parent 2 0 R /MediaBox [0 0 72 36] >>".into()); + let all = read_layers(build(&objects).into(), None, true).unwrap(); + assert!(all.lost.iter().any(|t| t.starts_with("it has 1 more pages (2)")), "{:?}", all.lost); } #[test] From 0072ea413c19100c409b1b56bd0d04f76ad3b328 Mon Sep 17 00:00:00 2001 From: elpidioassinaturas Date: Mon, 30 Nov 2026 11:13:08 -0300 Subject: [PATCH 4/6] fix(data): number repeated PDF layer names in linear time, one notice for empty layers, say when none can be drawn (#3442, part 1) - Each name's count goes on from its last number, so 30,000 groups of one name are numbered at once instead of in minutes. - Empty layers are said in one notice with their count, the first 20 named. - A page with PDF layers of which none draws anything (a copy that can't be decrypted, say) says that it is read as one picture. Co-Authored-By: Claude Opus 5.5 --- crates/data/src/raster/pdf.rs | 56 ++++++++++++++++++++++++++++++----- 1 file changed, 49 insertions(+), 7 deletions(-) diff --git a/crates/data/src/raster/pdf.rs b/crates/data/src/raster/pdf.rs index 4b2505e6a0..81f82d3c31 100644 --- a/crates/data/src/raster/pdf.rs +++ b/crates/data/src/raster/pdf.rs @@ -5,7 +5,7 @@ //! The whole page is drawn, its title and legend too, and the map frame's coordinates run across //! it, as readers of GeoPDFs do. -use std::collections::HashSet; +use std::collections::{HashMap, HashSet}; use std::path::Path; use hayro::hayro_interpret::InterpreterSettings; @@ -198,13 +198,16 @@ fn groups(pdf: &Pdf) -> Vec { } } // A name a group shares with one before it is numbered, so each layer opens again as itself. - let (mut groups, mut taken) = (Vec::with_capacity(named.len()), HashSet::new()); + // Each name's count goes on from its last number, so a run of one name is numbered in linear time. + let (mut groups, mut taken, mut next) = (Vec::with_capacity(named.len()), HashSet::new(), HashMap::new()); for (id, first) in named { - let (mut name, mut n) = (first.clone(), 1); + let mut n = next.get(&first).copied().unwrap_or(1); + let mut name = first.clone(); while !taken.insert(name.clone()) { n += 1; name = format!("{first} ({n})"); } + next.insert(first, n); groups.push(Group { id, name, on: !off.contains(&id) && (base || on.contains(&id)) }); } groups @@ -330,13 +333,14 @@ fn layers_limited(bytes: PdfData, page: Option<&str>, place: bool, max: usize, o let drawn = copy.as_ref().filter(|c| only_on(c)).and_then(|c| c.pages().get(number - 1).map(|p| render(p, scale, TRANSPARENT))); drawn.ok_or_else(|| DataError::Format("its PDF layers can't be drawn one by one: open it with \"pdfLayers\": false".into())) }; - // A layer kept when it has something, or when asked for by name. - let add = |out: &mut PdfLayers, key: &str, visible: bool, (r, any): (Raster, bool)| { + // A layer kept when it has something, or when asked for by name; else its name kept in `empty`. + let mut empty = Vec::new(); + let mut add = |out: &mut PdfLayers, key: &str, visible: bool, (r, any): (Raster, bool)| { if any || only.is_some() { let (name, raster) = (r.name.clone(), if place { place_by_viewport(r, page, scale) } else { r }); out.layers.push(PdfLayer { name, visible, subdataset: format!("{number}{LAYER_MARK}{key}"), raster }); } else if !key.is_empty() { - out.lost.push(format!("its PDF layer '{key}' has nothing on this page: left out")); + empty.push(format!("'{key}'")); } }; let none = draw_with(None)?; @@ -346,6 +350,17 @@ fn layers_limited(bytes: PdfData, page: Option<&str>, place: bool, max: usize, o if only.is_none_or(str::is_empty) { add(&mut out, "", true, rgba(&none, None, OUTSIDE)?); } + // Nothing drawn at all (a copy that can't be decrypted, say): the caller reads a picture. + if out.layers.is_empty() && only.is_none() { + out.lost.push("its PDF layers couldn't be drawn; the page is read as one picture"); + } else if let [one] = empty.as_slice() { + out.lost.push(format!("its PDF layer {one} has nothing on this page: left out")); + } else if empty.len() > 1 { + let more = empty.len().saturating_sub(NAMED_PAGES); + let tail = if more > 0 { format!(", and {more} more") } else { String::new() }; + let shown = empty.iter().take(NAMED_PAGES).cloned().collect::>().join(", "); + out.lost.push(format!("{} of its PDF layers have nothing on this page, left out: {shown}{tail}", empty.len())); + } // Where the page is placed is said once, for all its layers. let said = out.layers.iter_mut().map(|l| std::mem::take(&mut l.raster.lost)).last(); out.lost.extend(said.into_iter().flatten()); @@ -949,7 +964,15 @@ mod tests { assert_eq!(all.layers.iter().map(|l| l.name.as_str()).collect::>(), ["Relevo", OUTSIDE]); let said = format!("it has 70 PDF layers: the first {MAX_LAYERS} are layers of their own, the other 6 are drawn in '{OUTSIDE}'"); assert!(all.lost.says(&said), "{:?}", all.lost); - assert_eq!(all.lost.iter().filter(|t| t.contains("has nothing on this page")).count(), MAX_LAYERS - 1); + // The 63 empty ones in one notice, the first 20 named. + let empty: Vec<&str> = all.lost.texts().filter(|t| t.contains("nothing on this page")).collect(); + assert_eq!(empty.len(), 1, "{empty:?}"); + assert!( + empty[0].starts_with("63 of its PDF layers have nothing on this page, left out: 'Água', 'Quadro', 'Vazio', 'G9', ") + && empty[0].ends_with("'G25', and 43 more"), + "{}", + empty[0] + ); let outside = &all.layers[1].raster; let at = |b: usize| outside.bands[b].data[20 * outside.width as usize + 10]; assert_eq!([at(0), at(1), at(2), at(3)], [255.0, 0.0, 255.0, 255.0]); @@ -1034,5 +1057,24 @@ mod tests { let all = read_layers_limited(layered_pdf("<< >>").into(), None, true, 30_000).unwrap(); assert!(all.layers.iter().all(|l| l.raster.width * l.raster.height * 4 * 5 <= 30_000), "{}", all.layers[0].raster.width); assert_eq!(all.lost.iter().filter(|t| t.contains("dots an inch, not 150")).count(), 1, "{:?}", all.lost); + // Groups, and nothing drawn (as when a copy can't be decrypted): said, and read as a picture. + let all = read_layers(layered("", "<< >>").into(), None, true).unwrap(); + assert!(all.layers.is_empty()); + assert_eq!(all.lost, ["its PDF layers couldn't be drawn; the page is read as one picture"]); + } + + #[test] + fn many_groups_of_one_name_are_numbered_in_linear_time() { + let n = 30_000; + let mut objects = layered_objects("", "<< >>"); + objects.truncate(4); + let refs: Vec = (5..5 + n).map(|i| format!("{i} 0 R")).collect(); + objects[0] = format!("<< /Type /Catalog /Pages 2 0 R /OCProperties << /OCGs [{}] /D << >> >> >>", refs.join(" ")); + objects.extend((0..n).map(|_| "<< /Type /OCG /Name (Rio) >>".to_string())); + let pdf = Pdf::new(build(&objects)).unwrap(); + let start = std::time::Instant::now(); + let names: Vec = groups(&pdf).into_iter().map(|g| g.name).collect(); + assert!(start.elapsed().as_secs() < 10, "{:?}", start.elapsed()); + assert_eq!((names.len(), names[0].as_str(), names[1].as_str(), names[n - 1].as_str()), (n, "Rio", "Rio (2)", "Rio (30000)")); } } From 4e1b87d21d8489959237e5a167012bcf689041d8 Mon Sep 17 00:00:00 2001 From: elpidioassinaturas Date: Mon, 30 Nov 2026 11:47:16 -0300 Subject: [PATCH 5/6] fix(data): bound the length of PDF layer names nested under long /Order labels (#3442, part 1) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A small file with 30 nested /Order collections, each labelled with 16 KiB of text, spelled every group's name out to about 480 KiB, so 30,000 groups under them took some 14 GiB before the layer cap. Each label, each name and each full name is now cut to 200 characters, with "…", before the next one is formed. Co-Authored-By: Claude Opus 5.5 --- crates/data/src/raster/pdf.rs | 40 ++++++++++++++++++++++++++++++++--- 1 file changed, 37 insertions(+), 3 deletions(-) diff --git a/crates/data/src/raster/pdf.rs b/crates/data/src/raster/pdf.rs index 81f82d3c31..f7ae5ed4da 100644 --- a/crates/data/src/raster/pdf.rs +++ b/crates/data/src/raster/pdf.rs @@ -34,6 +34,8 @@ pub const MAX_BYTES: u64 = 1 << 30; const NAMED_PAGES: usize = 20; /// The most PDF layers a page is read as: the others are drawn with what is in none. const MAX_LAYERS: usize = 64; +/// The longest a PDF layer's name is, in characters, with the names it is nested in. +const MAX_NAME: usize = 200; /// Reads page `page` of the PDF at `path` (its number, from 1; the first when `None`), placed by /// its coordinates when `place` (else a scan, as `"as": "scan"` opens it). @@ -217,7 +219,16 @@ fn groups(pdf: &Pdf) -> Vec { /// [`OUTSIDE`]'s). fn group_name(xref: &XRef, id: ObjectIdentifier) -> String { let name = xref.get::(id).and_then(|g| g.get::(b"Name".as_slice())).map(|n| text(n.as_bytes())); - name.filter(|n| !n.is_empty()).unwrap_or_else(|| "Unnamed".into()) + name.filter(|n| !n.is_empty()).map_or_else(|| "Unnamed".into(), |n| clip(&n)) +} + +/// `name` cut to [`MAX_NAME`] characters, with "…" where it is cut, so names nested under long +/// labels stay short however deep they are. +fn clip(name: &str) -> String { + match name.char_indices().nth(MAX_NAME) { + Some((at, _)) => format!("{}\u{2026}", name.get(..at).unwrap_or_default()), + None => name.to_string(), + } } /// The groups of `all` an `/Order` array lists, after `prefix` ("Mapa / "): a group followed by @@ -240,7 +251,7 @@ fn walk( MaybeRef::Ref(r) => { let id = r.into(); if all.contains(&id) && seen.insert(id) { - let name = format!("{prefix}{}", group_name(xref, id)); + let name = clip(&format!("{prefix}{}", group_name(xref, id))); parent = Some(format!("{name} / ")); named.push((id, name)); } @@ -252,7 +263,7 @@ fn walk( let under = if labelled { None } else { parent.as_deref() }; walk(&a, xref, all, under.unwrap_or(&prefix), (&mut *named, &mut *seen), depth + 1); } else if let Some(label) = o.into_string().filter(|_| i == 0) { - prefix = format!("{prefix}{} / ", text(label.as_bytes())); + prefix = format!("{} / ", clip(&format!("{prefix}{}", clip(&text(label.as_bytes()))))); } } } @@ -1077,4 +1088,27 @@ mod tests { assert!(start.elapsed().as_secs() < 10, "{:?}", start.elapsed()); assert_eq!((names.len(), names[0].as_str(), names[1].as_str(), names[n - 1].as_str()), (n, "Rio", "Rio (2)", "Rio (30000)")); } + + #[test] + fn long_labels_nested_in_the_order_give_names_of_a_bounded_length() { + // 30 collections, one in another, each labelled with 16 KiB of text, round 30,000 groups: + // a name spelled out in full would be 480 KiB long, for each of the groups. + let n = 30_000; + let label = "L".repeat(16 << 10); + let refs: Vec = (5..5 + n).map(|i| format!("{i} 0 R")).collect(); + let order = format!("{}{}{}", format!("[({label}) ").repeat(30), refs.join(" "), "]".repeat(30)); + let mut objects = layered_objects("", "<< >>"); + objects.truncate(4); + objects[0] = format!("<< /Type /Catalog /Pages 2 0 R /OCProperties << /OCGs [{}] /D << /Order {order} >> >> >>", refs.join(" ")); + objects.extend((0..n).map(|_| "<< /Type /OCG /Name (Rio) >>".to_string())); + let pdf = Pdf::new(build(&objects)).unwrap(); + let start = std::time::Instant::now(); + let names: Vec = groups(&pdf).into_iter().map(|g| g.name).collect(); + assert!(start.elapsed().as_secs() < 10, "{:?}", start.elapsed()); + assert_eq!(names.len(), n); + let longest = names.iter().map(|name| name.chars().count()).max().unwrap_or(0); + // The cut text, its "…", and the number a repeated name gets. + assert!(longest <= MAX_NAME + 1 + " (30000)".len(), "{longest} characters"); + assert!(names[0].starts_with("LLL") && names[0].ends_with('…'), "{}", &names[0][..40]); + } } From 50cec9870c93b85824f3792af5e66b48473e6d9c Mon Sep 17 00:00:00 2001 From: elpidioassinaturas Date: Mon, 30 Nov 2026 12:25:44 -0300 Subject: [PATCH 6/6] fix(data): say how many PDF layer names are cut, and take /Prev only as a number (#3442, part 1) - groups() counts the names it cuts to 200 characters, and the layers say it once: "N PDF layer names are cut to 200 characters". - The update's /Prev is the number after the file's last startxref; when that isn't a number, no copy is made, and the layers can't be drawn one by one, which is said. Co-Authored-By: Claude Opus 5.5 --- crates/data/src/raster/pdf.rs | 84 ++++++++++++++++++++++++----------- 1 file changed, 58 insertions(+), 26 deletions(-) diff --git a/crates/data/src/raster/pdf.rs b/crates/data/src/raster/pdf.rs index f7ae5ed4da..0729690647 100644 --- a/crates/data/src/raster/pdf.rs +++ b/crates/data/src/raster/pdf.rs @@ -177,9 +177,11 @@ struct Group { } /// The PDF's layers, in the order a reader lists them (the top first), with their names. -fn groups(pdf: &Pdf) -> Vec { +fn groups(pdf: &Pdf) -> (Vec, usize) { let xref = pdf.xref(); - let Some(props) = xref.get::(xref.root_id()).and_then(|c| c.get::(b"OCProperties".as_slice())) else { return Vec::new() }; + let Some(props) = xref.get::(xref.root_id()).and_then(|c| c.get::(b"OCProperties".as_slice())) else { + return (Vec::new(), 0); + }; let refs = |d: &Dict, key: &[u8]| -> Vec { d.get::(key).map(|a| a.raw_iter().filter_map(|i| i.as_obj_ref()).map(Into::into).collect()).unwrap_or_default() }; @@ -196,13 +198,15 @@ fn groups(pdf: &Pdf) -> Vec { } for id in all { if seen.insert(id) { - named.push((id, group_name(xref, id))); + let (name, cut) = group_name(xref, id); + named.push((id, name, cut)); } } // A name a group shares with one before it is numbered, so each layer opens again as itself. // Each name's count goes on from its last number, so a run of one name is numbered in linear time. let (mut groups, mut taken, mut next) = (Vec::with_capacity(named.len()), HashSet::new(), HashMap::new()); - for (id, first) in named { + let cut = named.iter().filter(|(_, _, cut)| *cut).count(); + for (id, first, _) in named { let mut n = next.get(&first).copied().unwrap_or(1); let mut name = first.clone(); while !taken.insert(name.clone()) { @@ -212,22 +216,24 @@ fn groups(pdf: &Pdf) -> Vec { next.insert(first, n); groups.push(Group { id, name, on: !off.contains(&id) && (base || on.contains(&id)) }); } - groups + (groups, cut) } /// A group's `/Name`, or "Unnamed" when it has none or an empty one (whose subdataset would be /// [`OUTSIDE`]'s). -fn group_name(xref: &XRef, id: ObjectIdentifier) -> String { +fn group_name(xref: &XRef, id: ObjectIdentifier) -> (String, bool) { let name = xref.get::(id).and_then(|g| g.get::(b"Name".as_slice())).map(|n| text(n.as_bytes())); - name.filter(|n| !n.is_empty()).map_or_else(|| "Unnamed".into(), |n| clip(&n)) + name.filter(|n| !n.is_empty()).map_or_else(|| ("Unnamed".into(), false), |n| clip(&n)) } /// `name` cut to [`MAX_NAME`] characters, with "…" where it is cut, so names nested under long /// labels stay short however deep they are. -fn clip(name: &str) -> String { +/// Whether it was cut is given too: a cut label or name always makes the full name it is in too +/// long, so the full name's cut tells it. +fn clip(name: &str) -> (String, bool) { match name.char_indices().nth(MAX_NAME) { - Some((at, _)) => format!("{}\u{2026}", name.get(..at).unwrap_or_default()), - None => name.to_string(), + Some((at, _)) => (format!("{}\u{2026}", name.get(..at).unwrap_or_default()), true), + None => (name.to_string(), false), } } @@ -239,7 +245,7 @@ fn walk( xref: &XRef, all: &HashSet, prefix: &str, - (named, seen): (&mut Vec<(ObjectIdentifier, String)>, &mut HashSet), + (named, seen): (&mut Vec<(ObjectIdentifier, String, bool)>, &mut HashSet), depth: usize, ) { if depth > 32 { @@ -251,9 +257,9 @@ fn walk( MaybeRef::Ref(r) => { let id = r.into(); if all.contains(&id) && seen.insert(id) { - let name = clip(&format!("{prefix}{}", group_name(xref, id))); + let (name, cut) = clip(&format!("{prefix}{}", group_name(xref, id).0)); parent = Some(format!("{name} / ")); - named.push((id, name)); + named.push((id, name, cut)); } } MaybeRef::NotRef(o) => { @@ -263,7 +269,7 @@ fn walk( let under = if labelled { None } else { parent.as_deref() }; walk(&a, xref, all, under.unwrap_or(&prefix), (&mut *named, &mut *seen), depth + 1); } else if let Some(label) = o.into_string().filter(|_| i == 0) { - prefix = format!("{} / ", clip(&format!("{prefix}{}", clip(&text(label.as_bytes()))))); + prefix = format!("{} / ", clip(&format!("{prefix}{}", clip(&text(label.as_bytes())).0)).0); } } } @@ -302,9 +308,12 @@ fn pdf_doc(c: u8) -> char { /// when all are, and kept when empty. fn layers_limited(bytes: PdfData, page: Option<&str>, place: bool, max: usize, only: Option<&str>) -> Result { let (pdf, number, count) = open(bytes, page)?; - let mut groups = groups(&pdf); + let (mut groups, cut) = groups(&pdf); let mut out = PdfLayers { layers: Vec::new(), lost: crate::loss::Notes::new() }; out.lost.extend(more_pages(number, count)); + if cut > 0 { + out.lost.push(format!("{cut} PDF layer names are cut to {MAX_NAME} characters")); + } // Past the first MAX_LAYERS, groups are left to the content in none, as the PDF opens them. let ids: Vec = groups.iter().map(|g| g.id).collect(); let rest: Vec = groups.iter().skip(MAX_LAYERS).filter(|g| g.on).map(|g| g.id).collect(); @@ -340,7 +349,7 @@ fn layers_limited(bytes: PdfData, page: Option<&str>, place: bool, max: usize, o let draw_with = |on: Option| -> Result { crate::progress::check()?; let on: Vec = on.into_iter().chain(rest.iter().copied()).collect(); - let copy = Pdf::new(with_only(pdf.data().as_ref(), pdf.xref().root_id(), pages.into(), &ids, &on)).ok(); + let copy = with_only(pdf.data().as_ref(), pdf.xref().root_id(), pages.into(), &ids, &on).and_then(|b| Pdf::new(b).ok()); let drawn = copy.as_ref().filter(|c| only_on(c)).and_then(|c| c.pages().get(number - 1).map(|p| render(p, scale, TRANSPARENT))); drawn.ok_or_else(|| DataError::Format("its PDF layers can't be drawn one by one: open it with \"pdfLayers\": false".into())) }; @@ -379,13 +388,23 @@ fn layers_limited(bytes: PdfData, page: Option<&str>, place: bool, max: usize, o } /// `bytes`, a PDF whose catalog is `root`, with an update at its end giving it a catalog of only -/// its page tree `pages` and its PDF layers `all`, all off but those `on`. -fn with_only(bytes: &[u8], root: ObjectIdentifier, pages: ObjectIdentifier, all: &[ObjectIdentifier], on: &[ObjectIdentifier]) -> Vec { +/// its page tree `pages` and its PDF layers `all`, all off but those `on`; none when what follows +/// its last `startxref` isn't a number (the update's `/Prev` is only ever one). +fn with_only( + bytes: &[u8], + root: ObjectIdentifier, + pages: ObjectIdentifier, + all: &[ObjectIdentifier], + on: &[ObjectIdentifier], +) -> Option> { let r = |id: &ObjectIdentifier| format!("{} {} R", id.obj_number, id.gen_number); - let prev = bytes.windows(9).rposition(|w| w == b"startxref").map(|at| { - let tail = String::from_utf8_lossy(bytes.get(at + 9..bytes.len().min(at + 40)).unwrap_or_default()).into_owned(); - tail.split_whitespace().next().unwrap_or("0").to_string() - }); + let prev = match bytes.windows(9).rposition(|w| w == b"startxref") { + Some(at) => { + let tail = String::from_utf8_lossy(bytes.get(at + 9..bytes.len().min(at + 40)).unwrap_or_default()).into_owned(); + Some(tail.split_whitespace().next()?.parse::().ok()?) + } + None => None, + }; let mut out = bytes.to_vec(); out.push(b'\n'); let at = out.len(); @@ -409,7 +428,7 @@ fn with_only(bytes: &[u8], root: ObjectIdentifier, pages: ObjectIdentifier, all: format!("xref\n{} 1\n{entry}trailer\n<< /Size {size} /Root {}{prev} >>\nstartxref\n{xref}\n%%EOF\n", root.obj_number, r(&root)) .bytes(), ); - out + Some(out) } /// Whether hayro reads the catalog [`with_only`] wrote (not one a broken file's repair found). @@ -893,6 +912,12 @@ mod tests { #[test] fn hostile_pdfs_are_refused_or_drawn_small_never_a_panic() { + // What follows the last `startxref` isn't a number: no copy is made from it, and that is said. + let good = String::from_utf8(layered_pdf("<< >>")).unwrap(); + let at = good.rfind("startxref\n").unwrap() + "startxref\n".len(); + let bad = format!("{}1>>/Root 9 0 R\n%%EOF\n", &good[..at]); + let e = read_layers(bad.into_bytes().into(), None, true).err().map(|e| e.to_string()).unwrap_or_default(); + assert!(e.contains("can't be drawn one by one"), "{e}"); assert!(read_bytes("x", b"not a pdf".to_vec(), None, true).unwrap_err().to_string().contains("not a PDF")); // Cut short: whatever it reads, it doesn't panic. let whole = tiny_pdf("0 0 72 36", ""); @@ -959,6 +984,12 @@ mod tests { objects[4] = "<< /Type /OCG /Name <526F616473208A204D616A6F72> >>".into(); objects[6] = "<< /Type /OCG /Name >>".into(); assert_eq!(layer_names(&objects), ["Roads \u{2212} Major", "Água", "Água ", OUTSIDE]); + // A name longer than MAX_NAME characters is cut, and said once with the count. + objects[4] = format!("<< /Type /OCG /Name ({}) >>", "A".repeat(300)); + let all = read_layers(build(&objects).into(), None, true).unwrap(); + assert_eq!(all.layers[0].name.chars().count(), MAX_NAME + 1); + let said = format!("1 PDF layer names are cut to {MAX_NAME} characters"); + assert!(all.lost.says(&said), "{:?}", all.lost); } #[test] @@ -1084,7 +1115,7 @@ mod tests { objects.extend((0..n).map(|_| "<< /Type /OCG /Name (Rio) >>".to_string())); let pdf = Pdf::new(build(&objects)).unwrap(); let start = std::time::Instant::now(); - let names: Vec = groups(&pdf).into_iter().map(|g| g.name).collect(); + let names: Vec = groups(&pdf).0.into_iter().map(|g| g.name).collect(); assert!(start.elapsed().as_secs() < 10, "{:?}", start.elapsed()); assert_eq!((names.len(), names[0].as_str(), names[1].as_str(), names[n - 1].as_str()), (n, "Rio", "Rio (2)", "Rio (30000)")); } @@ -1103,9 +1134,10 @@ mod tests { objects.extend((0..n).map(|_| "<< /Type /OCG /Name (Rio) >>".to_string())); let pdf = Pdf::new(build(&objects)).unwrap(); let start = std::time::Instant::now(); - let names: Vec = groups(&pdf).into_iter().map(|g| g.name).collect(); + let (groups, cut) = groups(&pdf); + let names: Vec = groups.into_iter().map(|g| g.name).collect(); assert!(start.elapsed().as_secs() < 10, "{:?}", start.elapsed()); - assert_eq!(names.len(), n); + assert_eq!((names.len(), cut), (n, n)); let longest = names.iter().map(|name| name.chars().count()).max().unwrap_or(0); // The cut text, its "…", and the number a repeated name gets. assert!(longest <= MAX_NAME + 1 + " (30000)".len(), "{longest} characters");