From c9d31c3ca73071e059eb163962c080ee67012de0 Mon Sep 17 00:00:00 2001 From: elpidioassinaturas Date: Tue, 1 Dec 2026 23:07:16 -0300 Subject: [PATCH 1/2] fix(engine): give a tool a layer's pixels, keep a turned GeoPDF's layers within the page's samples (#3442 part 5a) A raster layer with a subdataset (a PDF layer or page, a NetCDF variable) reaches a geoprocessing tool as its pixels, not as its whole file. Each layer of a turned GeoPDF is turned within its share of the samples. The layers are drawn from one copy of the file whose update is rewritten, and a shared embedded file is read back from the first layer of its id. Co-Authored-By: Claude Opus 5.5 --- crates/data/src/raster/mod.rs | 15 +++++- crates/data/src/raster/pdf.rs | 98 ++++++++++++++++++++++++++++------- crates/engine/src/cmd/gp.rs | 48 ++++++++++++++++- crates/map/src/raster.rs | 24 ++++++++- 4 files changed, 161 insertions(+), 24 deletions(-) diff --git a/crates/data/src/raster/mod.rs b/crates/data/src/raster/mod.rs index b2837bc0eb..e19bde27bb 100644 --- a/crates/data/src/raster/mod.rs +++ b/crates/data/src/raster/mod.rs @@ -1273,7 +1273,18 @@ impl Raster { /// larger. A rotated, skewed or mirrored one is resampled north up, as a rotated GeoTIFF is, /// keeping its bands' names, classes and wavelengths. When it can't be placed (it would lie /// nowhere it can be drawn, or be too large turned), the scan comes back unchanged with why. - pub fn placed_by_world_file(mut self, wf: &world::WorldFile, crs: Crs) -> std::result::Result, String)> { + pub fn placed_by_world_file(self, wf: &world::WorldFile, crs: Crs) -> std::result::Result, String)> { + self.placed_by_world_file_within(wf, crs, max_samples()) + } + + /// [`Raster::placed_by_world_file`], turned within `max` samples: a share of them, for one of + /// several rasters read together (a PDF's layers). + pub fn placed_by_world_file_within( + mut self, + wf: &world::WorldFile, + crs: Crs, + max: usize, + ) -> std::result::Result, String)> { if self.georeferenced { return Err((Box::new(self), "only a raster with no coordinates can be placed".into())); } @@ -1291,7 +1302,7 @@ impl Raster { } else { // The bands are only read, so a picture that can't be turned comes back as it was. let data: Vec<&[f32]> = self.bands.iter().map(|b| b.data.as_slice()).collect(); - let (data, ow, oh, t) = match north_up(&data, self.width, self.height, affine, max_samples()) { + let (data, ow, oh, t) = match north_up(&data, self.width, self.height, affine, max) { Ok(turned) => turned, Err(e) => return Err((Box::new(self), e.to_string())), }; diff --git a/crates/data/src/raster/pdf.rs b/crates/data/src/raster/pdf.rs index 297fa2453b..4b78e9c6af 100644 --- a/crates/data/src/raster/pdf.rs +++ b/crates/data/src/raster/pdf.rs @@ -110,7 +110,7 @@ fn picture(pdf: &Pdf, name: &str, (number, count): (usize, usize), place: bool, 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 }) + Ok(if place { place_by_viewport(r, page, scale, max) } else { r }) } /// That a PDF of `count` pages has others than page `number`, when it has. @@ -368,25 +368,31 @@ fn layers_limited(name: &str, bytes: PdfData, page: Option<&str>, place: bool, m 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. + // Every layer's four bands, and the content in none's, share what one page is drawn in, and + // each is turned north up (a map turned on the page) within its share. let (scale, note) = scale_for(page, max, 4.0 * (groups.len() + 1) as f64)?; + let share = max / (groups.len() + 1); 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: &[ObjectIdentifier]| -> Result { + // update at its end rewrites (hayro draws by the catalog's default configuration). The one copy + // is ours again once the drawing before is dropped; copied again only if it isn't. + let mut copy = std::sync::Arc::new(Vec::new()); + let mut draw_with = |on: &[ObjectIdentifier]| -> Result { crate::progress::check()?; 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))); + with_only(std::sync::Arc::make_mut(&mut copy), pdf.data().as_ref(), pdf.xref().root_id(), pages.into(), &ids, &on) + .map_err(DataError::Format)?; + let read = Pdf::new(PdfData::from(copy.clone())).ok(); + let drawn = read.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".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 }); + let (name, raster) = (r.name.clone(), if place { place_by_viewport(r, page, scale, share) } else { r }); out.layers.push(PdfLayer { name, visible, subdataset: format!("{number}{LAYER_MARK}{key}"), raster }); } else if !key.is_empty() { empty.push(format!("'{key}'")); @@ -448,31 +454,48 @@ fn layers_limited(name: &str, bytes: PdfData, page: Option<&str>, place: bool, m 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(); + // Where the page is placed is said once, for all its layers: each was placed alike, so the + // first's notes are kept and the others' cleared. + let mut said = None; + for l in &mut out.layers { + let notes = std::mem::take(&mut l.raster.lost); + said.get_or_insert(notes); + } 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). +/// `out` made `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`; why not +/// when what follows its last `startxref` isn't a number (the update's `/Prev` is only ever one), +/// or a copy doesn't fit in memory. `out` is empty, or such a copy of `bytes` made before: then +/// only its update is written again, the file not copied again for each drawing. fn with_only( + out: &mut Vec, bytes: &[u8], root: ObjectIdentifier, pages: ObjectIdentifier, all: &[ObjectIdentifier], on: &[ObjectIdentifier], -) -> Option> { +) -> std::result::Result<(), String> { let r = |id: &ObjectIdentifier| format!("{} {} R", id.obj_number, id.gen_number); + let cant = || "its PDF layers can't be drawn one by one".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()?) + Some(tail.split_whitespace().next().ok_or_else(cant)?.parse::().map_err(|_| cant())?) } None => None, }; - let mut out = bytes.to_vec(); + if out.is_empty() { + // Room for the longest update too (every layer named twice), so the copy stays where it is. + out.try_reserve_exact(bytes.len() + 256 + 48 * all.len()).map_err(|_| { + format!("its PDF layers can't be drawn one by one: a copy of its {} MB doesn't fit in memory", bytes.len() >> 20) + })?; + out.extend_from_slice(bytes); + } else { + out.truncate(bytes.len()); + } out.push(b'\n'); let at = out.len(); let all: Vec = all.iter().map(r).collect(); @@ -495,7 +518,7 @@ fn with_only( 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) + Ok(()) } /// Whether hayro reads the catalog [`with_only`] wrote (not one a broken file's repair found). @@ -694,8 +717,9 @@ fn viewport(vp: &Dict<'_>, measure: &Dict<'_>) -> std::result::Result, scale: f64) -> Raster { +/// left a scan when it has none, or none that can be used (said in `lost`). Turned north up, it +/// holds at most `max` samples. +fn place_by_viewport(mut r: Raster, page: &Page<'_>, scale: f64, max: usize) -> Raster { let (mut found, unread) = viewports(page); let unplaced = "it opens without coordinates"; if found.is_empty() { @@ -716,7 +740,7 @@ fn place_by_viewport(mut r: Raster, page: &Page<'_>, scale: f64) -> Raster { continue; } }; - r = match r.placed_by_world_file(&wf, v.crs) { + r = match r.placed_by_world_file_within(&wf, v.crs, max) { Ok(mut placed) => { let others = count - 1; if others > 0 { @@ -1252,4 +1276,40 @@ mod tests { assert!(longest <= MAX_NAME + 1 + " (30000)".len(), "{longest} characters"); assert!(names[0].starts_with("LLL") && names[0].ends_with('…'), "{}", &names[0][..40]); } + + /// Each drawing of a layer rewrites the update at the end of one copy of the file: the file + /// isn't copied again for each, and a copy holds one update, the last. + #[test] + fn each_drawing_rewrites_the_update_at_the_end_of_one_copy() { + let bytes = layered_pdf("<< >>"); + let id = |n| ObjectIdentifier::new(n, 0); + let all = [id(5), id(6), id(7), id(8)]; + let mut copy = Vec::new(); + with_only(&mut copy, &bytes, id(1), id(2), &all, &all).unwrap(); + let (at, longest) = (copy.as_ptr(), copy.len()); + with_only(&mut copy, &bytes, id(1), id(2), &all, &[id(6)]).unwrap(); + assert!(copy.starts_with(&bytes) && copy.len() < longest, "{} bytes", copy.len()); + assert_eq!(copy.as_ptr(), at, "copied again"); + assert_eq!(String::from_utf8_lossy(©).matches("/RustGISOnly").count(), 1); + let pdf = Pdf::new(copy).unwrap(); + assert!(only_on(&pdf)); + } + + /// A GeoPDF whose map is turned 45° on the page: each layer is turned north up within its + /// share of the samples a page has, not the whole of them, nor is the page as one picture. + #[test] + fn layers_of_a_turned_page_are_turned_within_the_samples_a_page_has() { + let wgs84 = "/Type /GEOGCS /EPSG 4326"; + let turned = vp(wgs84, "0 0 72 36").replace("/GPTS [41 10 41 12 40 12 40 10]", "/GPTS [41 10 42 11 41.5 11.5 40.5 10.5]"); + let mut objects = layered_objects(SQUARES, "<< >>"); + objects[2] = objects[2].replace("/Contents 4 0 R", &format!("/Contents 4 0 R /VP [{turned}]")); + let max = 30_000; + let all = read_layers_limited("m", build(&objects).into(), None, true, max).unwrap(); + assert_eq!(all.layers.len(), 4, "{:?}", all.lost); + let samples: u32 = all.layers.iter().map(|l| l.raster.width * l.raster.height * l.raster.bands.len() as u32).sum(); + assert!(all.layers.iter().all(|l| l.raster.georeferenced), "{:?}", all.lost); + assert!(samples as usize <= max, "{samples} samples"); + let one = read_limited("m", build(&objects).into(), None, true, max).unwrap(); + assert!(one.georeferenced && (one.width * one.height * 3) as usize <= max, "{} × {}", one.width, one.height); + } } diff --git a/crates/engine/src/cmd/gp.rs b/crates/engine/src/cmd/gp.rs index 0d42cd2771..7a101cdf8f 100644 --- a/crates/engine/src/cmd/gp.rs +++ b/crates/engine/src/cmd/gp.rs @@ -2601,10 +2601,13 @@ impl Inputs for MapInputs<'_> { let l = self.snap.map.layer_by_name(layer)?; let rl = l.raster.as_ref()?; let read = self.rasters.get(&l.name.to_ascii_lowercase()).map(std::sync::Arc::as_ref); + // A layer that is part of its file (its subdataset: a PDF's layer or page, a NetCDF + // variable) is given as its pixels: a tool given the file reads it whole (#3442). + let whole = rl.subdataset.is_none(); Some(RasterInput { raster: read.or(rl.data.as_deref())?, - path: rl.path.as_deref(), - embedded: rl.embedded.as_deref().map(|b| (rl.file_name.as_deref().unwrap_or("raster.tif"), b.as_slice())), + path: rl.path.as_deref().filter(|_| whole), + embedded: rl.embedded.as_deref().filter(|_| whole).map(|b| (rl.file_name.as_deref().unwrap_or("raster.tif"), b.as_slice())), }) } } @@ -8362,3 +8365,44 @@ mod replay_rollback_tests { assert_eq!(s.undo_depth(), history.0); } } + +#[cfg(test)] +mod raster_input_tests { + use super::*; + + /// A layer that is part of its file (a PDF's layer or page, a NetCDF variable: its subdataset) + /// reaches a tool as its pixels: given the file, a tool reads it whole, the PDF's page 1 drawn + /// whole instead of the layer (#3442). A layer that is the whole file is given as the file. + #[test] + fn a_layer_that_is_part_of_its_file_reaches_a_tool_as_its_pixels() { + let mut s = Session::new(crate::Project::default()); + let gt = rustgis_data::raster::GeoTransform { origin_x: 0.0, origin_y: 2.0, pixel_width: 1.0, pixel_height: -1.0 }; + let raster = || { + let gray = rustgis_data::raster::ColorHint::Gray; + rustgis_data::raster::Raster::new("r", 2, 2, vec![vec![1.0; 4]], gt, Crs::LonLat, None, gray, "Float32").unwrap() + }; + let bytes = Arc::new(b"%PDF-1.7".to_vec()); + let mut layers = Vec::new(); + for (id, sub) in [(0, None), (1, Some("1#Roads")), (2, Some("2"))] { + let mut file = rustgis_map::raster::RasterLayer::from_path(raster(), "/maps/atlas.pdf"); + let mut upload = rustgis_map::raster::RasterLayer::from_shared(raster(), "atlas.pdf", bytes.clone()); + (file.subdataset, upload.subdataset) = (sub.map(str::to_string), sub.map(str::to_string)); + s.map_mut().add_layer(rustgis_map::Layer::new_raster(id, format!("file {id}"), file)); + s.map_mut().add_layer(rustgis_map::Layer::new_raster(id + 10, format!("upload {id}"), upload)); + layers.push((id, sub.is_none())); + } + // A NetCDF variable alike: a tool given the file would read its first variable. + let mut variable = rustgis_map::raster::RasterLayer::from_path(raster(), "/data/clima.nc"); + variable.subdataset = Some("temperature".into()); + s.map_mut().add_layer(rustgis_map::Layer::new_raster(20, "temperature", variable)); + let inputs = map_inputs(&s, None, &json!({}), Tiled::File).unwrap(); + assert!(inputs.raster("temperature").unwrap().path.is_none(), "a NetCDF variable"); + for (id, whole) in layers { + let file = inputs.raster(&format!("file {id}")).unwrap(); + let upload = inputs.raster(&format!("upload {id}")).unwrap(); + assert_eq!(file.path.is_some(), whole, "file {id}"); + assert_eq!(upload.embedded.is_some(), whole, "upload {id}"); + assert_eq!((file.raster.width, upload.raster.width), (2, 2)); + } + } +} diff --git a/crates/map/src/raster.rs b/crates/map/src/raster.rs index 168170ea40..c45f9016d5 100644 --- a/crates/map/src/raster.rs +++ b/crates/map/src/raster.rs @@ -1922,7 +1922,12 @@ pub(crate) mod shared_files { pub fn deserialize<'de, D: Deserializer<'de>>(d: D) -> Result, D::Error> { let mut layers = Vec::::deserialize(d)?; - let files: HashMap>> = layers.iter().filter_map(|l| Some((l.id, l.raster.as_ref()?.embedded.clone()?))).collect(); + // The first layer of an id with a file, as written: a later one of the same id (a hand edit) + // doesn't take its place. + let mut files: HashMap>> = HashMap::new(); + for (id, file) in layers.iter().filter_map(|l| Some((l.id, l.raster.as_ref()?.embedded.as_ref()?))) { + files.entry(id).or_insert_with(|| file.clone()); + } for r in layers.iter_mut().filter_map(|l| l.raster.as_mut()) { // One naming a layer without a file (a hand edit) is left without data, as a corrupt // embedded file is. @@ -3492,6 +3497,23 @@ mod tests { Raster::new("dem", 4, 4, vec![data], gt, Crs::LonLat, None, ColorHint::Gray, "Float32").unwrap() } + /// A layer sharing an earlier one's file gets that file back when read, though another layer + /// after it has the same id (a project edited by hand or corrupted): the first's, as written. + #[test] + fn a_shared_file_is_read_back_from_the_first_layer_of_its_id() { + #[derive(Serialize, Deserialize)] + struct Saved { + #[serde(with = "shared_files")] + layers: Vec, + } + let (a, b) = (Arc::new(b"first".to_vec()), Arc::new(b"second".to_vec())); + let layer = |id, file: &Arc>| crate::Layer::new_raster(id, "pdf", RasterLayer::from_shared(dem(), "a.pdf", file.clone())); + let text = serde_json::to_string(&Saved { layers: vec![layer(1, &a), layer(1, &b), layer(2, &a)] }).unwrap(); + let read: Saved = serde_json::from_str(&text).unwrap(); + let files: Vec<&[u8]> = read.layers.iter().map(|l| l.raster.as_ref().unwrap().embedded.as_ref().unwrap().as_slice()).collect(); + assert_eq!(files, [b"first".as_slice(), b"second", b"first"]); + } + /// What reading the pixels lost is said once; a look applied after that (bands the file /// hasn't) says what it lost on its own, not the pixels' losses again. #[test] From 467546fcbd9b070c56c27444749937493906cd25 Mon Sep 17 00:00:00 2001 From: elpidioassinaturas Date: Wed, 2 Dec 2026 00:05:51 -0300 Subject: [PATCH 2/2] fix(map): share a saved file only through a layer whose id is its own Two layers with one id (a project edited by hand or corrupted) can't be told apart when read, so a file of theirs is written whole and a layer sharing it gets the right file in either order. Co-Authored-By: Claude Opus 5.5 --- crates/map/src/raster.rs | 36 ++++++++++++++++++++++-------------- 1 file changed, 22 insertions(+), 14 deletions(-) diff --git a/crates/map/src/raster.rs b/crates/map/src/raster.rs index c45f9016d5..c542355ed0 100644 --- a/crates/map/src/raster.rs +++ b/crates/map/src/raster.rs @@ -1897,6 +1897,13 @@ pub(crate) mod shared_files { use crate::Layer; pub fn serialize(layers: &[Layer], s: S) -> Result { + // A file is shared only through a layer whose id no other layer has: an id two layers have + // (a project edited by hand or corrupted) can't tell them apart when read, so a file of + // theirs is written whole. + let mut ids: HashMap = HashMap::new(); + for l in layers { + *ids.entry(l.id).or_default() += 1; + } let mut first = HashMap::new(); let mut seq = s.serialize_seq(Some(layers.len()))?; for layer in layers { @@ -1910,7 +1917,7 @@ pub(crate) mod shared_files { seq.serialize_element(&same)?; } None => { - if let Some(f) = file { + if let Some(f) = file.filter(|_| ids.get(&layer.id) == Some(&1)) { first.insert(Arc::as_ptr(f), layer.id); } seq.serialize_element(layer)?; @@ -1922,12 +1929,7 @@ pub(crate) mod shared_files { pub fn deserialize<'de, D: Deserializer<'de>>(d: D) -> Result, D::Error> { let mut layers = Vec::::deserialize(d)?; - // The first layer of an id with a file, as written: a later one of the same id (a hand edit) - // doesn't take its place. - let mut files: HashMap>> = HashMap::new(); - for (id, file) in layers.iter().filter_map(|l| Some((l.id, l.raster.as_ref()?.embedded.as_ref()?))) { - files.entry(id).or_insert_with(|| file.clone()); - } + let files: HashMap>> = layers.iter().filter_map(|l| Some((l.id, l.raster.as_ref()?.embedded.clone()?))).collect(); for r in layers.iter_mut().filter_map(|l| l.raster.as_mut()) { // One naming a layer without a file (a hand edit) is left without data, as a corrupt // embedded file is. @@ -3497,10 +3499,10 @@ mod tests { Raster::new("dem", 4, 4, vec![data], gt, Crs::LonLat, None, ColorHint::Gray, "Float32").unwrap() } - /// A layer sharing an earlier one's file gets that file back when read, though another layer - /// after it has the same id (a project edited by hand or corrupted): the first's, as written. + /// A layer sharing another's file gets that file back when read, though two layers have one id + /// (a project edited by hand or corrupted), whichever of theirs it shares. #[test] - fn a_shared_file_is_read_back_from_the_first_layer_of_its_id() { + fn a_shared_file_is_read_back_though_two_layers_have_one_id() { #[derive(Serialize, Deserialize)] struct Saved { #[serde(with = "shared_files")] @@ -3508,10 +3510,16 @@ mod tests { } let (a, b) = (Arc::new(b"first".to_vec()), Arc::new(b"second".to_vec())); let layer = |id, file: &Arc>| crate::Layer::new_raster(id, "pdf", RasterLayer::from_shared(dem(), "a.pdf", file.clone())); - let text = serde_json::to_string(&Saved { layers: vec![layer(1, &a), layer(1, &b), layer(2, &a)] }).unwrap(); - let read: Saved = serde_json::from_str(&text).unwrap(); - let files: Vec<&[u8]> = read.layers.iter().map(|l| l.raster.as_ref().unwrap().embedded.as_ref().unwrap().as_slice()).collect(); - assert_eq!(files, [b"first".as_slice(), b"second", b"first"]); + // Either order: an id two layers have can't tell them apart. + for (layers, want) in [ + (vec![layer(1, &a), layer(1, &b), layer(2, &a)], [b"first".as_slice(), b"second", b"first"]), + (vec![layer(1, &b), layer(1, &a), layer(2, &a)], [b"second".as_slice(), b"first", b"first"]), + ] { + let text = serde_json::to_string(&Saved { layers }).unwrap(); + let read: Saved = serde_json::from_str(&text).unwrap(); + let files: Vec<&[u8]> = read.layers.iter().map(|l| l.raster.as_ref().unwrap().embedded.as_ref().unwrap().as_slice()).collect(); + assert_eq!(files, want); + } } /// What reading the pixels lost is said once; a look applied after that (bands the file