diff --git a/crates/data/src/raster/mod.rs b/crates/data/src/raster/mod.rs index 7e07700611..4a91e30699 100644 --- a/crates/data/src/raster/mod.rs +++ b/crates/data/src/raster/mod.rs @@ -185,6 +185,46 @@ pub fn is_pdf_name(name: &str) -> bool { /// Whether this build reads PDF pages (the `pdf` feature, #2336). pub const PDF_PAGES: bool = cfg!(feature = "pdf"); +/// What a PDF 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 (#3442). +pub const PDF_LAYER_MARK: char = '#'; +/// The name of the layer holding what a PDF page draws whatever its PDF layers. +pub const PDF_OUTSIDE: &str = "Not in a PDF layer"; + +/// One of a PDF page's 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, + /// The page and layer that read it again, as a PDF's subdataset ("1#Mapa / Rios"). + pub subdataset: String, + /// Its drawing: red, green, blue and alpha, transparent where it has nothing. + pub raster: Raster, +} + +/// A PDF page's layers, the top first, and what is said of them all. +#[derive(Default)] +pub struct PdfLayers { + pub layers: Vec, + pub lost: crate::loss::Notes, + /// The page as one picture, drawn from the same read of the file, when it has no layers or + /// none could be drawn. + pub picture: Option, +} + +/// Page `page` of the PDF at `path` as its PDF layers, placed by its coordinates: none when it +/// has none, and in a build without the `pdf` feature, where it isn't read as a picture either. +pub fn read_pdf_layers(path: &Path, page: Option<&str>) -> Result { + #[cfg(feature = "pdf")] + return pdf::read_layers_file(path, page); + #[cfg(not(feature = "pdf"))] + { + let _ = (path, page); + Ok(PdfLayers::default()) + } +} + /// Why a PDF isn't read in a build without the `pdf` feature (the browser, phones). pub const PDF_ELSEWHERE: &str = "PDFs are read in the desktop app, the command line and Python, not here: open it there"; diff --git a/crates/data/src/raster/pdf.rs b/crates/data/src/raster/pdf.rs index 0729690647..297fa2453b 100644 --- a/crates/data/src/raster/pdf.rs +++ b/crates/data/src/raster/pdf.rs @@ -40,6 +40,24 @@ 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). pub fn read_file(path: &Path, page: Option<&str>, place: bool) -> Result { + let name = path.file_stem().and_then(|s| s.to_str()).unwrap_or("raster"); + let mut r = read_bytes(name, file_bytes(path)?, page, place)?; + r.source = Some(path.display().to_string()); + Ok(r) +} + +/// Page `page` of the PDF at `path` as its PDF layers ([`read_layers`]), placed by its coordinates. +pub fn read_layers_file(path: &Path, page: Option<&str>) -> Result { + let name = path.file_stem().and_then(|s| s.to_str()).unwrap_or("raster"); + let mut all = read_layers(name, file_bytes(path)?.into(), page, true)?; + for r in all.layers.iter_mut().map(|l| &mut l.raster).chain(all.picture.as_mut()) { + r.source = Some(path.display().to_string()); + } + Ok(all) +} + +/// The PDF at `path`, read whole: a regular file no larger than [`MAX_BYTES`]. +fn file_bytes(path: &Path) -> Result> { let meta = std::fs::metadata(path)?; if !meta.is_file() { return Err(DataError::Format(format!("{} is not a regular file", path.display()))); @@ -47,10 +65,7 @@ pub fn read_file(path: &Path, page: Option<&str>, place: bool) -> Result if meta.len() > MAX_BYTES { return Err(DataError::Format(format!("the PDF is larger than {} MB, too large to open", MAX_BYTES >> 20))); } - let name = path.file_stem().and_then(|s| s.to_str()).unwrap_or("raster"); - let mut r = read_bytes(name, crate::provenance::read(path)?, page, place)?; - r.source = Some(path.display().to_string()); - Ok(r) + Ok(crate::provenance::read(path)?) } /// Reads page `page` (its number, from 1; the first when `None`) of a PDF's contents, named @@ -77,12 +92,18 @@ pub fn read_shared(name: &str, bytes: std::sync::Arc>, page: Option<&str 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 all = layers_limited(name, 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)?; + picture(&pdf, name, (number, count), place, max) +} + +/// Page `number` of the `count` of `pdf` drawn as one picture named `name` (with its number when +/// there are others), placed by its coordinates when `place`. +fn picture(pdf: &Pdf, name: &str, (number, count): (usize, usize), place: bool, max: usize) -> Result { 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()?; @@ -133,40 +154,20 @@ fn open(bytes: PdfData, page: Option<&str>) -> Result<(Pdf, usize, usize)> { 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, -} +pub use super::{PDF_LAYER_MARK as LAYER_MARK, PDF_OUTSIDE as OUTSIDE, PdfLayer, PdfLayers}; /// 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()) +/// When it has none, or none can be drawn, the page comes as one picture named `name`, drawn +/// from the same read of the file ([`PdfLayers::picture`]). +pub fn read_layers(name: &str, bytes: std::sync::Arc>, page: Option<&str>, place: bool) -> Result { + read_layers_limited(name, 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) +fn read_layers_limited(name: &str, bytes: PdfData, page: Option<&str>, place: bool, max: usize) -> Result { + layers_limited(name, bytes, page, place, max, None) } /// A PDF layer: its group, its name, and whether it is on when the PDF opens. @@ -174,8 +175,16 @@ struct Group { id: ObjectIdentifier, name: String, on: bool, + /// The groups it is nested in, in `/Order`, the outermost first: drawn on with it, as content + /// nested in theirs shows only when they are on. + ancestors: Vec, + /// Those of `ancestors` on as the PDF opens. + on_ancestors: Vec, } +/// A group named in [`groups`]: its id, its full name, whether that was cut, and its ancestors. +type Named = (ObjectIdentifier, String, bool, Vec); + /// 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(); @@ -194,19 +203,19 @@ fn groups(pdf: &Pdf) -> (Vec, usize) { 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); + walk(&order, xref, &member, ("", &[]), (&mut named, &mut seen), 0); } for id in all { if seen.insert(id) { let (name, cut) = group_name(xref, id); - named.push((id, name, cut)); + named.push((id, name, cut, Vec::new())); } } // 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 cut = named.iter().filter(|n| n.2).count(); + for (id, first, _, ancestors) in named { let mut n = next.get(&first).copied().unwrap_or(1); let mut name = first.clone(); while !taken.insert(name.clone()) { @@ -214,7 +223,11 @@ fn groups(pdf: &Pdf) -> (Vec, usize) { name = format!("{first} ({n})"); } next.insert(first, n); - groups.push(Group { id, name, on: !off.contains(&id) && (base || on.contains(&id)) }); + groups.push(Group { id, name, on: false, ancestors, on_ancestors: Vec::new() }); + } + let own = |id: &ObjectIdentifier| !off.contains(id) && (base || on.contains(id)); + for g in &mut groups { + (g.on, g.on_ancestors) = (own(&g.id), g.ancestors.iter().copied().filter(own).collect()); } (groups, cut) } @@ -237,37 +250,48 @@ fn clip(name: &str) -> (String, bool) { } } -/// 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. +/// The groups of `all` an `/Order` array lists, after `prefix` ("Mapa / ") and nested in +/// `ancestors`: a group followed by an array has its children there, listed before it (they lie +/// over it, as content nested in its own is drawn after it begins), 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), + (prefix, ancestors): (&str, &[ObjectIdentifier]), + (named, seen): (&mut Vec, &mut HashSet), depth: usize, ) { if depth > 32 { return; } - let (mut prefix, mut parent) = (prefix.to_string(), None); + // The last group listed: its name, id, and where it is in `named`. + let (mut prefix, mut parent): (String, Option<(String, ObjectIdentifier, usize)>) = (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)); + parent = Some((format!("{name} / "), id, named.len())); + named.push((id, name, cut, ancestors.to_vec())); } } 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); + match parent.as_mut().filter(|_| !labelled) { + Some((under, id, at)) => { + let nested: Vec = ancestors.iter().copied().chain([*id]).collect(); + let mut children = Vec::new(); + walk(&a, xref, all, (under, &nested), (&mut children, &mut *seen), depth + 1); + let n = children.len(); + named.splice(*at..*at, children); + *at += n; + } + None => walk(&a, xref, all, (&prefix, ancestors), (&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); } @@ -306,10 +330,15 @@ fn pdf_doc(c: u8) -> char { /// [`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 { +fn layers_limited(name: &str, 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() }; + let mut out = PdfLayers::default(); + // No layers to read: the page as one picture, from this read of the file. + if groups.is_empty() && only.is_none() { + out.picture = Some(picture(&pdf, name, (number, count), place, max)?); + return Ok(out); + } out.lost.extend(more_pages(number, count)); if cut > 0 { out.lost.push(format!("{cut} PDF layer names are cut to {MAX_NAME} characters")); @@ -320,7 +349,7 @@ fn layers_limited(bytes: PdfData, page: Option<&str>, place: bool, max: usize, o 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}'", + "it has {} PDF layers: the first {MAX_LAYERS} are layers of their own, the other {other} are left to '{OUTSIDE}' (where the PDF shows them)", groups.len() )); groups.truncate(MAX_LAYERS); @@ -346,12 +375,12 @@ fn layers_limited(bytes: PdfData, page: Option<&str>, place: bool, max: usize, o 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 { + let draw_with = |on: &[ObjectIdentifier]| -> Result { crate::progress::check()?; - let on: Vec = on.into_iter().chain(rest.iter().copied()).collect(); + let on: Vec = on.iter().chain(&rest).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())) + drawn.ok_or_else(|| DataError::Format("its PDF layers can't be drawn one by one".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(); @@ -363,16 +392,54 @@ fn layers_limited(bytes: PdfData, page: Option<&str>, place: bool, max: usize, o empty.push(format!("'{key}'")); } }; - let none = draw_with(None)?; + let none = draw_with(&[])?; + // A nested group is drawn with the groups it is in on, and kept where it changes their drawing. + // Theirs is kept while the next group (a sibling, listed next to it) is in the same ones: one + // drawing of them at a time, drawn once for each run of siblings; and so is the drawing of + // those of them on as the PDF opens, for the check below. With the one of no group on and the + // group's, at most four drawings of the page are held at once. + let mut under: Option<(Vec, Pixmap)> = None; + let mut on_under: Option<(Vec, Pixmap)> = None; + // Each layer drawn is counted, for the progress, and Cancel is looked at after each. + if !picked.is_empty() { + crate::progress::begin(picked.len()); + } for g in picked { - add(&mut out, &g.name, g.on, rgba(&draw_with(Some(g.id))?, Some(&none), &g.name)?); + if !g.ancestors.is_empty() && under.as_ref().is_none_or(|(chain, _)| *chain != g.ancestors) { + under = Some((g.ancestors.clone(), draw_with(&g.ancestors)?)); + } + let base = under.as_ref().filter(|(chain, _)| !g.ancestors.is_empty() && *chain == g.ancestors).map_or(&none, |(_, b)| b); + let on: Vec = g.ancestors.iter().copied().chain([g.id]).collect(); + let layer = rgba(&draw_with(&on)?, Some(base), &g.name)?; + // Shown as a reader shows it: when on, and the groups it is listed under are too, or it + // changes the page drawn with those of them that are on (`/Order` only lists; what hides + // content is the group whose content it is drawn in). + let visible = g.on + && (g.on_ancestors.len() == g.ancestors.len() || { + if !g.on_ancestors.is_empty() && on_under.as_ref().is_none_or(|(chain, _)| *chain != g.on_ancestors) { + on_under = Some((g.on_ancestors.clone(), draw_with(&g.on_ancestors)?)); + } + let without = + on_under.as_ref().filter(|(chain, _)| !g.on_ancestors.is_empty() && *chain == g.on_ancestors).map_or(&none, |(_, b)| b); + let with: Vec = g.on_ancestors.iter().copied().chain([g.id]).collect(); + draw_with(&with)?.data_as_u8_slice() != without.data_as_u8_slice() + }); + add(&mut out, &g.name, visible, layer); + crate::progress::step(1)?; } + // Cancel while the last was drawn: nothing is given back. + crate::progress::check()?; 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. + // Nothing drawn at all (a copy that can't be decrypted, or a blank page): the page as one + // picture, which says its other pages itself; what was said of its layers is kept. 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"); + if let Some(pages) = more_pages(number, count) { + out.lost.retain(|n| n.as_str() != pages); + } + out.lost.push("its PDF layers couldn't be drawn, or draw nothing on this page; the page is read as one picture"); + out.picture = Some(picture(&pdf, name, (number, count), place, max)?); } 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 { @@ -916,7 +983,7 @@ mod tests { 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(); + let e = read_layers("m", 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. @@ -967,7 +1034,7 @@ mod tests { /// 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() + read_layers("m", build(objects).into(), None, true).unwrap().layers.into_iter().map(|l| l.name).collect() } #[test] @@ -977,7 +1044,7 @@ mod tests { 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 all = read_layers("m", 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. @@ -986,7 +1053,7 @@ mod tests { 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(); + let all = read_layers("m", 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); @@ -1002,9 +1069,11 @@ mod tests { 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(); + let all = read_layers("m", 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}'"); + let said = format!( + "it has 70 PDF layers: the first {MAX_LAYERS} are layers of their own, the other 6 are left to '{OUTSIDE}' (where the PDF shows them)" + ); 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(); @@ -1021,10 +1090,41 @@ mod tests { // 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(); + let all = read_layers("m", 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_group_nested_in_another_is_drawn_with_it_on_and_lies_over_it() { + // Água's blue square is in Relevo's content, as a map frame holds its map's layers: drawn + // only with Relevo on, and a layer of its own over Relevo's, which keeps only its green. + let content = "/OC /a BDC 0 1 0 rg 20 0 10 10 re f /OC /b BDC 0 0 1 rg 40 0 10 10 re f EMC EMC"; + let all = read_layers("m", layered(content, "<< /Order [5 0 R [6 0 R]] >>").into(), None, true).unwrap(); + let names: Vec<&str> = all.layers.iter().map(|l| l.name.as_str()).collect(); + assert_eq!(names, ["Relevo / Água", "Relevo"]); + let (none, green, blue) = ([0.0; 4], [0.0, 255.0, 0.0, 255.0], [0.0, 0.0, 255.0, 255.0]); + assert_eq!([20.0, 40.0].map(|at| square(&all.layers[0].raster, at)), [none, blue]); + assert_eq!([20.0, 40.0].map(|at| square(&all.layers[1].raster, at)), [green, none]); + // Opened again alone, as drawn with the others. + let one = read_bytes("m", layered(content, "<< /Order [5 0 R [6 0 R]] >>"), Some(&all.layers[0].subdataset), true).unwrap(); + assert_eq!([20.0, 40.0].map(|at| square(&one, at)), [none, blue]); + // With its parent off, a group the PDF has on is hidden too, as a reader hides it. + let all = read_layers("m", layered(content, "<< /Order [5 0 R [6 0 R]] /OFF [5 0 R] >>").into(), None, true).unwrap(); + let shown: Vec<(&str, bool)> = all.layers.iter().map(|l| (l.name.as_str(), l.visible)).collect(); + assert_eq!(shown, [("Relevo / Água", false), ("Relevo", false)]); + // Listed under a group that is off, but drawn outside its content: a reader shows it. + let all = read_layers("m", layered(SQUARES, "<< /Order [5 0 R [6 0 R]] /OFF [5 0 R] >>").into(), None, true).unwrap(); + let shown: Vec<(&str, bool)> = all.layers.iter().take(2).map(|l| (l.name.as_str(), l.visible)).collect(); + assert_eq!(shown, [("Relevo / Água", true), ("Relevo", false)]); + // Three deep, the outermost off: Quadro's content is in Água's, which is on and drawn outside + // Relevo's, so a reader shows both. + let three = "/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 /OC /c BDC 1 1 0 rg 60 0 10 10 re f EMC EMC"; + let all = read_layers("m", layered(three, "<< /Order [5 0 R [6 0 R [7 0 R]]] /OFF [5 0 R] >>").into(), None, true).unwrap(); + let shown: Vec<(&str, bool)> = all.layers.iter().take(3).map(|l| (l.name.as_str(), l.visible)).collect(); + assert_eq!(shown, [("Relevo / Água / Quadro", true), ("Relevo / Água", true), ("Relevo", false)]); + } + #[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 @@ -1033,7 +1133,7 @@ mod tests { // 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 all = read_layers("m", 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]); @@ -1052,7 +1152,7 @@ mod tests { #[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 all = read_layers("m", 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"]); @@ -1074,35 +1174,44 @@ mod tests { } 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()); + // A page without layers has none, and comes as one picture from the same read. + let plain = read_layers("plain", tiny_pdf("0 0 72 36", "").into(), None, true).unwrap(); + let picture = plain.picture.as_ref().unwrap(); + assert!(plain.layers.is_empty() && plain.lost.is_empty()); + assert_eq!((picture.name.as_str(), picture.width, picture.bands.len()), ("plain", 150, 3)); } #[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 all = read_layers("m", 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(); + // Groups nested under another keep its name as a prefix, and lie over it. + let all = read_layers("m", 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]); + assert_eq!(names, ["Relevo / Água", "Relevo / Quadro", "Relevo", 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 all = read_layers("m", 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(); + let all = read_layers_limited("m", 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(); + let all = read_layers("m", 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"]); + let blank = "its PDF layers couldn't be drawn, or draw nothing on this page; the page is read as one picture"; + assert_eq!(all.lost, [blank]); + // What was said of the layers before is kept: a name cut, here. + let mut objects = layered_objects("", "<< >>"); + objects[4] = format!("<< /Type /OCG /Name ({}) >>", "A".repeat(300)); + let all = read_layers("m", build(&objects).into(), None, true).unwrap(); + assert_eq!(all.lost, [format!("1 PDF layer names are cut to {MAX_NAME} characters").as_str(), blank]); } #[test] diff --git a/crates/engine/command-surface.txt b/crates/engine/command-surface.txt index 01c6a4e3ea..c94018b294 100644 --- a/crates/engine/command-surface.txt +++ b/crates/engine/command-surface.txt @@ -213,7 +213,7 @@ labels.resetMoved layer? class? all? labels.scaleRange layer? class? min? max? clear? labels.style layer? class? size? color? halo? haloColor? haloWidth? spacing? stretch? bold? italic? font? background? wrapChar? wrapLength? lineAlign? labels.viewUnplaced on? -layer.addData path name? layer? paperSpace? blocks? stream? as? crs? x? y? wkt? delimiter? +layer.addData path name? layer? pdfLayers? paperSpace? blocks? stream? as? crs? x? y? wkt? delimiter? layer.addDataBytes fileName data zoom? layer? name? x? y? wkt? crs? delimiter? paperSpace? blocks? stream? as? layer.addDataText fileName text name? x? y? wkt? crs? delimiter? layer? paperSpace? blocks? layer.addDatabase database password? layer? crs? name? stream? diff --git a/crates/engine/src/cmd/layer.rs b/crates/engine/src/cmd/layer.rs index c57f71bdc3..11235b387e 100644 --- a/crates/engine/src/cmd/layer.rs +++ b/crates/engine/src/cmd/layer.rs @@ -21,7 +21,7 @@ pub const MAX_LAYER_NAME: usize = 200; pub fn commands() -> Vec { vec![ C::new("layer.addData", "Add Data", "Home › Add", add_data).roles(&[]).effects(crate::policy::Effects::NONE.with(crate::policy::Effect::Files)) - .params(r#"{"path": string, "name"?: string, "layer"?: "GeoPackage, GDAL, DuckDB or DXF layer, or a PDF's page number (the first when left out or blank)", "paperSpace"?: "bool: a DXF's layout entities too", "blocks"?: "bool: a DXF's block (图块) contents, true by default", "stream"?: "bool: true links the file instead of copying it (read in place, a view at a time; the project keeps its path, not its features), false copies it into the project; left out, decided by its size or feature count", "as"?: "scan" (a TIFF, PNG, JPEG or PDF page, even a photo, a GeoTIFF or a GeoPDF, as a picture with no coordinates), "crs"?: "EPSG:… (or WKT) for Shapefile coordinates (overrides .prj), a CSV, a DXF (which never says), a CityJSON or CityGML model (it replaces the system a model file names; in a zip, it is used for a model naming none RustGIS knows), or a GDAL or DuckDB file that doesn't say (GDAL takes an authority code such as EPSG:2263 or the exact names WGS84, WGS72, NAD27, NAD83, not WKT or a file)", "x"?: "CSV or workbook x/longitude column (in a zip, for each CSV and workbook member that has it)", "y"?: "CSV or workbook y/latitude column (as x)", "wkt"?: "CSV or workbook WKT geometry column (as x)", "delimiter"?: ","|";"|"\\t"|"|"}"#), + .params(r#"{"path": string, "name"?: string, "layer"?: "GeoPackage, GDAL, DuckDB or DXF layer, or a PDF's page number (the first when left out or blank)", "pdfLayers"?: "bool: a PDF page with layers (optional content groups) as a group of them, one raster each, true by default; false opens the page as one picture", "paperSpace"?: "bool: a DXF's layout entities too", "blocks"?: "bool: a DXF's block (图块) contents, true by default", "stream"?: "bool: true links the file instead of copying it (read in place, a view at a time; the project keeps its path, not its features), false copies it into the project; left out, decided by its size or feature count", "as"?: "scan" (a TIFF, PNG, JPEG or PDF page, even a photo, a GeoTIFF or a GeoPDF, as a picture with no coordinates), "crs"?: "EPSG:… (or WKT) for Shapefile coordinates (overrides .prj), a CSV, a DXF (which never says), a CityJSON or CityGML model (it replaces the system a model file names; in a zip, it is used for a model naming none RustGIS knows), or a GDAL or DuckDB file that doesn't say (GDAL takes an authority code such as EPSG:2263 or the exact names WGS84, WGS72, NAD27, NAD83, not WKT or a file)", "x"?: "CSV or workbook x/longitude column (in a zip, for each CSV and workbook member that has it)", "y"?: "CSV or workbook y/latitude column (as x)", "wkt"?: "CSV or workbook WKT geometry column (as x)", "delimiter"?: ","|";"|"\\t"|"|"}"#), C::new("layer.addPhotos", "Add Photos", "Home › Add", add_photos).roles(&[]).effects(crate::policy::Effects::NONE.with(crate::policy::Effect::Files)).params( r#"{"paths"?: [JPEG photo files], "folder"?: "a folder of photos (every JPEG in it)", "name"?: "the layer (default Photos; photos join it when it exists)"}"#, ), @@ -2084,6 +2084,10 @@ fn add_data(s: &mut Session, p: &Value) -> CmdResult { let page = super::raster::pdf_page(path, p)?; // An SRTM tile or DTED file has no subdataset or coordinate system to choose: said. let ignored = rustgis_data::raster::elevation_ignores(path, ps(p, "layer"), ps(p, "crs")); + // A PDF with layers: a group of them (#3442). + if super::raster::wants_pdf_layers(path, p, page.as_deref(), scan)? { + return super::raster::add_pdf(s, path, name, page.as_deref(), ignored); + } return super::raster::add_path(s, path, name, page.as_deref(), scan, ignored); } // A Zarr store's folder: its first variable, or the one "layer" names. @@ -2779,6 +2783,10 @@ pub(crate) fn add_data_ahead(p: &Value) -> Option { if rustgis_data::raster::is_raster_name(&path) { // A page that isn't one is refused when the command runs. let page = super::raster::pdf_page(&path, p).ok()?; + if super::raster::wants_pdf_layers(&path, p, page.as_deref(), scan).ok()? { + let key = super::raster::pdf_key(&path, page.as_deref()); + return Some(ahead(NAME, key, move || super::raster::read_pdf(&path, page.as_deref()))); + } let key = super::raster::read_key(&path, page.as_deref(), scan); return Some(ahead(NAME, key, move || super::raster::read_raster_as(&path, page.as_deref(), scan))); } diff --git a/crates/engine/src/cmd/raster.rs b/crates/engine/src/cmd/raster.rs index 4e27a13943..41c9d08500 100644 --- a/crates/engine/src/cmd/raster.rs +++ b/crates/engine/src/cmd/raster.rs @@ -355,8 +355,11 @@ pub fn add_raster(s: &mut Session, name: &str, layer: RasterLayer) -> CmdResult pub(crate) fn add_raster_after(s: &mut Session, name: &str, mut layer: RasterLayer, zoom: Option) -> CmdResult { // A scan has no coordinates: it is laid over what the view shows, and says so. let mut laid = None; + // A placement given (a PDF's layers) is said by the caller, once for them all. + let given = layer.placement.is_some(); if let Some(d) = layer.data.as_mut().filter(|d| !d.georeferenced) { - let bbox = scan_box(s, d.width, d.height); + // Where it is to lie when given (a PDF's layers all lie where the first does). + let bbox = layer.placement.unwrap_or_else(|| scan_box(s, d.width, d.height)); Arc::make_mut(d).place(bbox).map_err(|e| format!("{name}: {e}"))?; layer.placement = Some(bbox); laid = Some(bbox); @@ -386,7 +389,9 @@ pub(crate) fn add_raster_after(s: &mut Session, name: &str, mut layer: RasterLay let mut v = json!({"layer": id, "width": w, "height": h, "bands": n}); if let Some(bbox) = laid { let note = "it has no coordinates, so it is drawn over the current view until it is georeferenced"; - s.notify(format!("{unique}: {note}"), false); + if !given { + s.notify(format!("{unique}: {note}"), false); + } v["georeferenced"] = json!(false); v["placedOver"] = json!(bbox); v["note"] = json!(note); @@ -594,10 +599,24 @@ pub(crate) fn loss_lines(losses: Vec<(String, rustgis_data::loss::Note)>) -> Vec /// Opens a raster file by path; `ignored` is said with what reading it lost (options given that /// don't apply to it). pub fn add_path(s: &mut Session, path: &str, name: Option<&str>, page: Option<&str>, scan: bool, ignored: Option) -> CmdResult { - let (mut r, tiled) = match super::reads::take::(s, &read_key(path, page, scan)) { + let read = match super::reads::take::(s, &read_key(path, page, scan)) { Some(r) => r, None => read_raster_as(path, page, scan), - }?; + }; + add_path_read(s, path, name, page, scan, ignored, read) +} + +/// [`add_path`], with the file read. +fn add_path_read( + s: &mut Session, + path: &str, + name: Option<&str>, + page: Option<&str>, + scan: bool, + ignored: Option, + read: RasterRead, +) -> CmdResult { + let (mut r, tiled) = read?; r.lost.extend(ignored); if scan { r = r.into_scan().map_err(|e| format!("{path}: {e}"))?; @@ -613,6 +632,103 @@ pub fn add_path(s: &mut Session, path: &str, name: Option<&str>, page: Option<&s add_raster(s, &name, rl) } +/// Whether `layer.addData` opens the PDF at `path` as its PDF layers (#3442): a page placed by its +/// coordinates, unless `"pdfLayers": false`, or one of its layers is asked for ("1#Rios"). +pub(crate) fn wants_pdf_layers(path: &str, p: &Value, page: Option<&str>, scan: bool) -> Result { + if !raster::PDF_PAGES || !raster::is_pdf_name(path) { + return Ok(false); + } + let wanted = match p.get("pdfLayers") { + None | Some(Value::Null) => true, + Some(v) => v.as_bool().ok_or("\"pdfLayers\" must be true or false")?, + }; + Ok(wanted && !scan && !page.is_some_and(|p| p.contains(raster::PDF_LAYER_MARK))) +} + +/// A PDF's page read for [`add_pdf`]: its PDF layers, and the page as one picture when it has +/// none or they can't be read. +pub(crate) type PdfRead = (Result, Option); + +/// Reads the PDF at `path` for [`add_pdf`] (ahead, off the frame, in the app). +pub(crate) fn read_pdf(path: &str, page: Option<&str>) -> PdfRead { + let layers = raster::read_pdf_layers(Path::new(path), page); + // Cancel ends the read: the page isn't read again as one picture. + let cancelled = matches!(layers, Err(rustgis_data::DataError::Cancelled)); + let mut layers = layers.map_err(|e| e.to_string()); + // A page without layers comes as one picture from the same read of the file. + let picture = layers.as_mut().ok().and_then(|l| l.picture.take()).map(|r| Ok((r, false))); + let drawn = cancelled || layers.as_ref().is_ok_and(|l| !l.layers.is_empty()); + let picture = picture.or_else(|| (!drawn).then(|| read_raster_as(path, page, false))); + (layers, picture) +} + +/// The key [`read_pdf`]'s read ahead is kept by. +pub(crate) fn pdf_key(path: &str, page: Option<&str>) -> String { + format!("pdf-layers:{}", read_key(path, page, false)) +} + +/// Opens the PDF at `path` (its `page`) as a group of its PDF layers, or as one picture when it +/// has none, saying why when they couldn't be read. +pub(crate) fn add_pdf(s: &mut Session, path: &str, name: Option<&str>, page: Option<&str>, ignored: Option) -> CmdResult { + let (lost, picture) = match super::reads::take::(s, &pdf_key(path, page)).unwrap_or_else(|| read_pdf(path, page)) { + (Ok(all), None) => return add_pdf_layers(s, path, name, all), + (Ok(all), Some(picture)) => (all.lost, picture), + (Err(e), Some(picture)) => (vec![format!("{e}: the page is read as one picture")].into(), picture), + (Err(e), None) => return Err(format!("{path}: {e}")), + }; + let picture = picture.map(|(mut r, tiled)| { + r.lost.extend(lost); + (r, tiled) + }); + add_path_read(s, path, name, page, false, ignored, picture) +} + +/// Adds a PDF page's layers as a group named `name` or after the file: the PDF's first on top, +/// each shown or hidden as the PDF opens it, and what was read of them said. +fn add_pdf_layers(s: &mut Session, path: &str, name: Option<&str>, all: raster::PdfLayers) -> CmdResult { + if s.map().groups.len() >= rustgis_map::MAX_GROUPS { + return Err(format!("a map holds at most {} groups", rustgis_map::MAX_GROUPS)); + } + let stem = Path::new(path).file_stem().and_then(|s| s.to_str()).unwrap_or("PDF"); + let title = name.unwrap_or(stem).to_string(); + let full = std::path::absolute(path).map(|p| p.display().to_string()).unwrap_or_else(|_| path.to_string()); + let names: Vec = all.layers.iter().map(|l| l.name.clone()).collect(); + let mut ids = Vec::with_capacity(names.len()); + // A page without coordinates: its layers laid over one part of the view, though the first + // frames an empty map. + let laid = all.layers.first().filter(|l| !l.raster.georeferenced).map(|l| scan_box(s, l.raster.width, l.raster.height)); + // The bottom first, so that each lies over those under it, as in the PDF. + for l in all.layers.into_iter().rev() { + let mut rl = RasterLayer::from_path(l.raster, full.clone()); + rl.subdataset = Some(l.subdataset); + rl.placement = laid; + let id = add_raster(s, &l.name, rl)?["layer"].as_u64().and_then(|i| u32::try_from(i).ok()).ok_or("the layer wasn't added")?; + if let Some(layer) = s.map_mut().layer_mut(id) { + layer.visible = l.visible; + } + ids.push(id); + } + // Top first, as the map draws them. + ids.reverse(); + let mut group = rustgis_map::LayerGroup::new(title.as_str()); + group.children = ids.clone(); + let group_id = s.map_mut().add_group(group); + for note in all.lost { + s.say(note.prefixed(&title)); + } + let more = names.len().saturating_sub(20); + let tail = if more > 0 { format!(", and {more} more") } else { String::new() }; + let shown = names.iter().take(20).cloned().collect::>().join(", "); + s.notify(format!("{title}: added {} PDF layers ({shown}{tail})", names.len()), false); + if laid.is_some() { + s.notify( + format!("{title}: it has no coordinates, so its layers are drawn over the current view until they are georeferenced"), + false, + ); + } + Ok(json!({"group": group_id, "layers": ids})) +} + /// The page `"layer"` asks for when `path` is a PDF's: its number, given as text or as a whole /// number (a JSON number); `None` when not given, or for a raster that has no pages. Any other /// value is refused rather than read as the first page. diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index 364c19a4c1..46bc8e23e9 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -56481,9 +56481,11 @@ fn a_pdf_is_added_back_as_a_raster() { let dir = Dir(std::env::temp_dir().join(format!("rustgis-pdf-read-{}-{nanos}", std::process::id()))); std::fs::create_dir_all(&dir.0).unwrap(); let (series, single, plain) = (dir.0.join("series.pdf"), dir.0.join("single.pdf"), dir.0.join("plain.pdf")); - s.run("layout.export", &json!({"path": series, "dpi": 36})).unwrap(); - s.run("layout.export", &json!({"path": single, "dpi": 36, "allPages": false})).unwrap(); - s.run("layout.export", &json!({"path": plain, "dpi": 36, "allPages": false, "georeference": false})).unwrap(); + // Without PDF layers, which open as a group of their own (#3442). + let no_layers = json!({"layers": false}); + s.run("layout.export", &json!({"path": series, "dpi": 36, "pdf": no_layers})).unwrap(); + s.run("layout.export", &json!({"path": single, "dpi": 36, "allPages": false, "pdf": no_layers})).unwrap(); + s.run("layout.export", &json!({"path": plain, "dpi": 36, "allPages": false, "georeference": false, "pdf": no_layers})).unwrap(); let frame = s.project.layouts[0].elements.iter().find(|e| e.kind.code() == "mapFrame").unwrap().clone(); let added = |s: &mut Session, p: Value| { let mark = s.notice_mark(); @@ -56574,6 +56576,140 @@ fn a_pdf_is_added_back_as_a_raster() { } } +/// A GeoPDF with layers (optional content groups) opens as a group of them, named after the file: +/// one raster each, the PDF's first on top, all where the page lies. `"pdfLayers": false` opens +/// the page as one picture, and a project saved with the layers opens the same ones again (#3442). +#[test] +fn a_pdf_with_layers_is_added_as_a_group_of_them() { + let mut s = world(); + s.run("layout.new", &json!({"page": "a4", "orientation": "landscape", "template": "map"})).unwrap(); + let nanos = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map_or(0, |d| d.as_nanos()); + let dir = std::env::temp_dir().join(format!("rustgis-pdf-layers-{}-{nanos}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let path = dir.join("camadas.pdf"); + s.run("layout.export", &json!({"path": path, "dpi": 36})).unwrap(); + let mut t = Session::new(Project::default()); + let mark = t.notice_mark(); + let r = t.run("layer.addData", &json!({"path": path})).unwrap(); + let said: Vec = t.notices_since(mark).iter().map(|n| n.text.clone()).collect(); + let ids: Vec = r["layers"].as_array().unwrap().iter().map(|v| v.as_u64().unwrap() as u32).collect(); + assert!(ids.len() > 2, "{r}"); + let group = t.map().groups.iter().find(|g| Some(u64::from(g.id)) == r["group"].as_u64()).unwrap(); + let mut children = group.children.clone(); + children.sort_unstable(); + let mut sorted = ids.clone(); + sorted.sort_unstable(); + assert_eq!((group.name.as_str(), children), ("camadas", sorted)); + // Top first, as the PDF lists them: the first lies over the last. + let index = |id: u32| t.map().layer_index(id).unwrap(); + assert!(index(ids[0]) < index(ids[ids.len() - 1])); + // Each with its extent, bands, file and subdataset ("#"). + type Kept = (String, rustgis_geom::Extent, usize, Option, Option); + let kept = |l: &rustgis_map::Layer| -> Kept { + let r = l.raster.as_ref().unwrap(); + let d = r.data.as_ref().unwrap(); + assert!(d.georeferenced, "{}", l.name); + (l.name.clone(), d.extent(), d.band_count(), r.path.clone(), r.subdataset.clone()) + }; + let layers: Vec = ids.iter().map(|id| kept(t.map().layer(*id).unwrap())).collect(); + assert!(layers.iter().any(|(n, ..)| n.ends_with("Countries")), "{layers:?}"); + assert!(layers.iter().all(|(_, e, bands, ..)| *e == layers[0].1 && *bands == 4), "{layers:?}"); + let full = std::path::absolute(&path).unwrap().display().to_string(); + assert!( + layers.iter().all(|(n, .., file, sub)| file.as_deref() == Some(full.as_str()) + && sub.as_ref().is_some_and(|s| s.starts_with("1#") && (s.ends_with(n.as_str()) || s == "1#"))), + "{layers:?}" + ); + assert!(said.iter().any(|t| t.starts_with(&format!("camadas: added {} PDF layers (", ids.len()))), "{said:?}"); + // As one picture, when asked; anything but true or false is refused. + let r = t.run("layer.addData", &json!({"path": path, "pdfLayers": false})).unwrap(); + assert_eq!((r["bands"].as_u64(), r.get("group")), (Some(3), None)); + assert!(t.run("layer.addData", &json!({"path": path, "pdfLayers": "no"})).unwrap_err().contains("pdfLayers")); + // Saved and opened again: the same layers, where they were. + let rgis = dir.join("camadas.rgis"); + t.run("project.saveAs", &json!({"path": rgis.display().to_string()})).unwrap(); + let mut u = Session::new(Project::default()); + u.run("project.open", &json!({"path": rgis.display().to_string()})).unwrap(); + for before in &layers { + let l = u.map().layers.iter().find(|l| l.name == before.0).unwrap_or_else(|| panic!("no {}", before.0)); + assert_eq!(&kept(l), before); + } + // Without coordinates, on an empty map: every layer laid over the same part of the view. + let plain = dir.join("sem_coordenadas.pdf"); + s.run("layout.export", &json!({"path": plain, "dpi": 36, "georeference": false})).unwrap(); + let mut v = Session::new(Project::default()); + let mark = v.notice_mark(); + let r = v.run("layer.addData", &json!({"path": plain})).unwrap(); + // Said once, for the PDF, not for each of its layers. + let said: Vec = v.notices_since(mark).iter().map(|n| n.text.clone()).filter(|t| t.contains("no coordinates")).collect(); + assert!(said.len() == 1 && said[0].starts_with("sem_coordenadas: "), "{said:?}"); + let boxes: Vec> = r["layers"] + .as_array() + .unwrap() + .iter() + .map(|id| v.map().layer(id.as_u64().unwrap() as u32).unwrap().raster.as_ref().unwrap().placement) + .collect(); + assert!(boxes.len() > 2 && boxes[0].is_some() && boxes.iter().all(|b| *b == boxes[0]), "{boxes:?}"); + // Cancel while its layers are drawn: the read stops there, with nothing added, and the page + // isn't read again as one picture (which would look at Cancel only after reading the file). + struct Stopped(u32, std::sync::atomic::AtomicU32); + impl rustgis_data::progress::Probe for Stopped { + fn cancelled(&self) -> bool { + self.1.fetch_add(1, std::sync::atomic::Ordering::Relaxed) >= self.0 + } + fn begin(&self, _: u64) {} + fn advance(&self, _: u64) {} + } + for after in [2, 4] { + let mut w = Session::new(Project::default()); + let probe = std::sync::Arc::new(Stopped(after, 0.into())); + let stopped = rustgis_data::progress::install(Some(probe.clone())); + let e = w.run("layer.addData", &json!({"path": path})).unwrap_err(); + drop(stopped); + assert!(e.contains("cancel") && !e.contains("one picture"), "after {after}: {e}"); + assert!(w.map().layers.is_empty() && w.map().groups.is_empty(), "after {after}"); + // Looked at once more than it took to stop: not again by a picture's read. + assert_eq!(probe.1.load(std::sync::atomic::Ordering::Relaxed), after + 1, "after {after}"); + } + // Cancel once the last layer is drawn (the probe's count reaches the layers counted): seen + // after the drawing, so nothing is added. + struct AtTheEnd(std::sync::atomic::AtomicU64, std::sync::atomic::AtomicU64); + impl rustgis_data::progress::Probe for AtTheEnd { + fn cancelled(&self) -> bool { + self.1.load(std::sync::atomic::Ordering::Relaxed) >= self.0.load(std::sync::atomic::Ordering::Relaxed) + } + fn begin(&self, total: u64) { + self.0.store(total, std::sync::atomic::Ordering::Relaxed); + self.1.store(0, std::sync::atomic::Ordering::Relaxed); + } + fn advance(&self, n: u64) { + self.1.fetch_add(n, std::sync::atomic::Ordering::Relaxed); + } + } + let mut w = Session::new(Project::default()); + let probe = std::sync::Arc::new(AtTheEnd(u64::MAX.into(), 0.into())); + let stopped = rustgis_data::progress::install(Some(probe)); + let e = w.run("layer.addData", &json!({"path": path})).unwrap_err(); + drop(stopped); + assert!(e.contains("cancel"), "{e}"); + assert!(w.map().layers.is_empty() && w.map().groups.is_empty()); + // A PDF without layers is read and opened once: Cancel is looked at as often as when it is + // asked for as one picture, not again by a second read of the file. + let picture = dir.join("sem_camadas.pdf"); + s.run("layout.export", &json!({"path": picture, "dpi": 36, "pdf": {"layers": false}})).unwrap(); + let looks = |p: Value| { + let mut w = Session::new(Project::default()); + let probe = std::sync::Arc::new(Stopped(u32::MAX, 0.into())); + let counting = rustgis_data::progress::install(Some(probe.clone())); + let r = w.run("layer.addData", &p).unwrap(); + drop(counting); + assert_eq!(r["bands"].as_u64(), Some(3), "{r}"); + probe.1.load(std::sync::atomic::Ordering::Relaxed) + }; + assert_eq!(looks(json!({"path": picture})), looks(json!({"path": picture, "pdfLayers": false}))); + let _ = std::fs::remove_dir_all(&dir); +} + /// A frame drawn over another (an inset on the main map) is cut out of the other's viewport, so /// that a reader shows the main map's coordinates around the inset and not in it: none there when /// the inset is left out of georeferencing (tilted), the inset's own when it isn't (#1191). No two