diff --git a/crates/data/src/raster/pdf.rs b/crates/data/src/raster/pdf.rs index d75aa85750..0729690647 100644 --- a/crates/data/src/raster/pdf.rs +++ b/crates/data/src/raster/pdf.rs @@ -5,15 +5,19 @@ //! 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::{HashMap, HashSet}; 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; @@ -28,6 +32,10 @@ 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; +/// 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). @@ -67,6 +75,36 @@ 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()?; + 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)> { 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 +115,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 +130,345 @@ 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, 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(), 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() }; - 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 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, &member, "", (&mut named, &mut seen), 0); } - Ok(if place { place_by_viewport(r, page, scale) } else { r }) + for id in all { + if seen.insert(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()); + 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()) { + n += 1; + name = format!("{first} ({n})"); + } + next.insert(first, n); + groups.push(Group { id, name, on: !off.contains(&id) && (base || on.contains(&id)) }); + } + (groups, cut) } -/// 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())); +/// 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, 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(), 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. +/// 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()), true), + None => (name.to_string(), false), } - 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())); +} + +/// 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: &HashSet, + prefix: &str, + (named, seen): (&mut Vec<(ObjectIdentifier, String, bool)>, &mut HashSet), + 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(); + if all.contains(&id) && seen.insert(id) { + let (name, cut) = clip(&format!("{prefix}{}", group_name(xref, id).0)); + parent = Some(format!("{name} / ")); + named.push((id, name, cut)); + } + } + 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), (&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())).0)).0); + } + } + } + } +} + +/// A PDF text string: UTF-16 or UTF-8 after its byte order mark, else PDFDocEncoding. +fn text(b: &[u8]) -> String { + 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, count) = open(bytes, page)?; + 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(); + 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}"))), + None => Ok(out), + }; + } + 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 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 on: Vec = on.into_iter().chain(rest.iter().copied()).collect(); + 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())) + }; + // 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() { + empty.push(format!("'{key}'")); + } + }; + 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)?); } - 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); + // 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()); + 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 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 = 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(); + 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.iter().map(r).collect::>().join(" ") + ) + .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(), + ); + Some(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 +482,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 +784,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() { @@ -545,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", ""); @@ -558,4 +931,216 @@ 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 { + 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(&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 \ + /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(), + ] + } + + /// 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]); + // 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] + 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); + // 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]); + // 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] + 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] { + 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); + // 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).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)")); + } + + #[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 (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(), 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"); + assert!(names[0].starts_with("LLL") && names[0].ends_with('…'), "{}", &names[0][..40]); + } }