Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 13 additions & 2 deletions crates/data/src/raster/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<Raster, (Box<Raster>, String)> {
pub fn placed_by_world_file(self, wf: &world::WorldFile, crs: Crs) -> std::result::Result<Raster, (Box<Raster>, 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<Raster, (Box<Raster>, String)> {
if self.georeferenced {
return Err((Box::new(self), "only a raster with no coordinates can be placed".into()));
}
Expand All @@ -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())),
};
Expand Down
98 changes: 79 additions & 19 deletions crates/data/src/raster/pdf.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down Expand Up @@ -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::<Dict>(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<Pixmap> {
// 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());
Comment thread
elpidioassinaturas marked this conversation as resolved.
Resolved
Comment thread
elpidioassinaturas marked this conversation as resolved.
Resolved
let mut draw_with = |on: &[ObjectIdentifier]| -> Result<Pixmap> {
crate::progress::check()?;
let on: Vec<ObjectIdentifier> = 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}'"));
Expand Down Expand Up @@ -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::<Vec<_>>().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<u8>,
bytes: &[u8],
root: ObjectIdentifier,
pages: ObjectIdentifier,
all: &[ObjectIdentifier],
on: &[ObjectIdentifier],
) -> Option<Vec<u8>> {
) -> 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::<u64>().ok()?)
Some(tail.split_whitespace().next().ok_or_else(cant)?.parse::<u64>().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<String> = all.iter().map(r).collect();
Expand All @@ -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).
Expand Down Expand Up @@ -694,8 +717,9 @@ fn viewport(vp: &Dict<'_>, measure: &Dict<'_>) -> std::result::Result<Viewport,
}

/// `r`, the drawn page at `scale` pixels a point, placed by the largest of its GeoPDF viewports:
/// left a scan when it has none, or none that can be used (said in `lost`).
fn place_by_viewport(mut r: Raster, page: &Page<'_>, 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() {
Expand All @@ -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 {
Expand Down Expand Up @@ -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(&copy).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);
}
}
48 changes: 46 additions & 2 deletions crates/engine/src/cmd/gp.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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())),
})
}
}
Expand Down Expand Up @@ -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));
}
}
}
32 changes: 31 additions & 1 deletion crates/map/src/raster.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1897,6 +1897,13 @@ pub(crate) mod shared_files {
use crate::Layer;

pub fn serialize<S: Serializer>(layers: &[Layer], s: S) -> Result<S::Ok, S::Error> {
// 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<u32, usize> = 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 {
Expand All @@ -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)?;
Expand Down Expand Up @@ -3492,6 +3499,29 @@ mod tests {
Raster::new("dem", 4, 4, vec![data], gt, Crs::LonLat, None, ColorHint::Gray, "Float32").unwrap()
}

/// 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_though_two_layers_have_one_id() {
#[derive(Serialize, Deserialize)]
struct Saved {
#[serde(with = "shared_files")]
layers: Vec<crate::Layer>,
}
let (a, b) = (Arc::new(b"first".to_vec()), Arc::new(b"second".to_vec()));
let layer = |id, file: &Arc<Vec<u8>>| crate::Layer::new_raster(id, "pdf", RasterLayer::from_shared(dem(), "a.pdf", file.clone()));
// 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
/// hasn't) says what it lost on its own, not the pixels' losses again.
#[test]
Expand Down
Loading