From a9b5b3a7c6d5b8b63781ae40e4729ec5b86b3941 Mon Sep 17 00:00:00 2001 From: mavrick Date: Wed, 25 Nov 2026 16:37:10 -0600 Subject: [PATCH 01/14] fix(data): a zip and pasted text read workbooks, GeoRSS, LandXML and every layer of a KML or GPX file The route matrix (#2969) found a zip refused workbooks, GeoRSS and LandXML that the path and the browser read, text refused GeoRSS and LandXML, and both added only the first layer of a KML, KMZ or GPX file. A zip's members and pasted text are now read as those files are when added by themselves. A zip's .pbf members stay unread, since one can't be told from a vector tile by its name; that refusal stays listed. --- crates/data/src/io.rs | 7 ++ crates/engine/src/cmd/layer.rs | 4 +- .../engine/tests/integration/read_routes.rs | 73 ++++--------------- 3 files changed, 25 insertions(+), 59 deletions(-) diff --git a/crates/data/src/io.rs b/crates/data/src/io.rs index e5dd5d686d..d818360b74 100644 --- a/crates/data/src/io.rs +++ b/crates/data/src/io.rs @@ -3959,6 +3959,13 @@ fn read_zip_budget(file_name: &str, bytes: &[u8], crs: Option, budget: &mut read_city_member(leaf, &b, crs) } else if is_delimited_name(leaf) { read_delimited_bytes_budget(leaf, &b, &CsvOptions { crs, ..Default::default() }, budget).map(|r| vec![r]) + } else if crate::sheets::is_sheet_name(leaf) { + // A workbook's first sheet, as a workbook added by itself is read. + let name = Path::new(leaf).file_stem().and_then(|s| s.to_str()).unwrap_or("sheet"); + crate::sheets::read(&b, name, None, &CsvOptions { crs, ..Default::default() }).map(|r| vec![r]) + } else if is_multi_layer_name(leaf) && !leaf.to_ascii_lowercase().ends_with(".zip") { + // Every layer of a KML, GPX or other file of several, as when it is added by itself. + read_layers(leaf, &b).map(|layers| layers.into_iter().map(|l| (l.dataset, l.report)).collect()) } else { read_bytes(leaf, &b).map(|r| vec![r]) }; diff --git a/crates/engine/src/cmd/layer.rs b/crates/engine/src/cmd/layer.rs index 41b265a254..e4f046b26c 100644 --- a/crates/engine/src/cmd/layer.rs +++ b/crates/engine/src/cmd/layer.rs @@ -58,7 +58,7 @@ pub fn commands() -> Vec { C::new("layer.addEncodedPolyline", "Add Encoded Polyline", "Home › Add", add_encoded_polyline).roles(&[]).effects(crate::policy::Effects::NONE).params( r#"{"polyline": "encoded polyline text" | [texts] (one line each), "precision"?: 5 (Google) | 6 (OSRM, Valhalla), "name"?: text}"#, ), - C::new("layer.addDataText", "Add Data (from text)", "Home › Add", add_data_text).roles(&[]).effects(crate::policy::Effects::NONE).params(r#"{"fileName": "name.geojson|.csv|.tsv|.city.json|.gml|.dxf (CityJSON and CityGML: all their layers)", "text": string, "name"?: text, "x"?, "y"?, "wkt"?, "crs"?, "delimiter"? (as layer.addData, for delimited text; crs also for a CityJSON or CityGML model, and for a DXF), "layer"?, "paperSpace"?, "blocks"? (as layer.addData, for a DXF)}"#), + C::new("layer.addDataText", "Add Data (from text)", "Home › Add", add_data_text).roles(&[]).effects(crate::policy::Effects::NONE).params(r#"{"fileName": "name.geojson|.csv|.tsv|.city.json|.gml|.dxf|.kml|.gpx|.rss|.xml (LandXML, GeoRSS) (a file of several layers, such as a city model, KML or GPX: all its layers)", "text": string, "name"?: text, "x"?, "y"?, "wkt"?, "crs"?, "delimiter"? (as layer.addData, for delimited text; crs also for a CityJSON or CityGML model, and for a DXF), "layer"?, "paperSpace"?, "blocks"? (as layer.addData, for a DXF)}"#), C::new("layer.addSample", "Add Sample Data", "Home › Add › Add Data", add_sample).roles(&[]).effects(crate::policy::Effects::NONE).params(r#"{"name": "countries"|"cities"|"rivers"|"lakes"}"#), C::new("layer.remove", "Remove", "Layers", remove).roles(&[]).effects(crate::policy::Effects::NONE) .key("Delete") @@ -6995,7 +6995,9 @@ pub(crate) fn add_data_text_after(s: &mut Session, p: &Value, zoom: Option let text = s_req(p, "text")?; // A city model: all its layers, in the coordinate system given or with a layer picked. A DXF // drawing too, which takes its coordinate system and whether its blocks are drawn from here. + // Every other file of several layers too (KML, GPX, GeoRSS, LandXML), as its bytes are read. if rustgis_data::dxf::is_dxf_name(name) + || rustgis_data::io::is_multi_layer_name(name) || rustgis_data::cityjson::is_cityjson_name(name) || rustgis_data::io::is_citygml(name, text.as_bytes()) || (["crs", "layer"].iter().any(|k| ps(p, k).is_some_and(|c| !c.trim().is_empty())) diff --git a/crates/engine/tests/integration/read_routes.rs b/crates/engine/tests/integration/read_routes.rs index d72f4b5959..c354ef3a03 100644 --- a/crates/engine/tests/integration/read_routes.rs +++ b/crates/engine/tests/integration/read_routes.rs @@ -18,9 +18,9 @@ //! aren't zipped; text is read only when it is UTF-8. GDAL and DuckDB are not routes //! here yet. //! -//! Routes that read a format differently today are listed in [`DIFFERENT`] with how they differ; -//! any other difference still fails, and a route that starts agreeing fails until its entry is -//! removed, so the list only shrinks. +//! A route that refuses a file the path reads, on purpose, is listed in [`REFUSED`]; any other +//! difference still fails, and a listed route that starts reading the file fails until its entry +//! is removed, so the list only shrinks. use super::never_silent_reading::cases; use base64::Engine; use rustgis_engine::data::loss::LossCode; @@ -39,36 +39,10 @@ enum Route { Zip, } -/// How a route listed in [`DIFFERENT`] reads a file differently from its path; anything else -/// it does differently still fails. -#[derive(Clone, Copy)] -enum Differs { - /// Refuses it, saying why. - Refuses, - /// Adds only the first of its layers, says so, and says no code the path doesn't. - FirstLayer, -} - -/// Routes that read a corpus file differently from its path today: the file, the route, and -/// how. Each is said, not silent. -const DIFFERENT: &[(&str, Route, Differs)] = &[ - // A zip's feature-service page, workbook, GeoRSS feed and LandXML file aren't read. - ("a.feature.pbf", Route::Zip, Differs::Refuses), - ("a.xlsx", Route::Zip, Differs::Refuses), - ("a.xls", Route::Zip, Differs::Refuses), - ("a.xlsb", Route::Zip, Differs::Refuses), - ("a.ods", Route::Zip, Differs::Refuses), - ("a.rss", Route::Zip, Differs::Refuses), - ("a.xml", Route::Zip, Differs::Refuses), - // GeoRSS and LandXML aren't read from text. - ("a.rss", Route::Text, Differs::Refuses), - ("a.xml", Route::Text, Differs::Refuses), - // A KML document or GPX file of several layers adds them all by path, bytes or download. - ("a.kml", Route::Text, Differs::FirstLayer), - ("a.kml", Route::Zip, Differs::FirstLayer), - ("a.kmz", Route::Zip, Differs::FirstLayer), - ("a.gpx", Route::Text, Differs::FirstLayer), - ("a.gpx", Route::Zip, Differs::FirstLayer), +/// Routes that refuse a corpus file its path reads, saying why: the file and the route. +const REFUSED: &[(&str, Route)] = &[ + // A zip's `.pbf` members aren't read: one can't be told from a vector tile by its name. + ("a.feature.pbf", Route::Zip), ]; /// What one read gave: each layer and table as text, the loss codes said, and whether @@ -201,29 +175,13 @@ fn difference(path: &Result, other: &Result) -> Opti } } -/// Whether `other` differs from the path's read of `content` (named `file`) only as `how` says. -fn differs_as(how: Differs, file: &str, content: &[u8], path: &Result, other: &Result) -> bool { - match (how, path, other) { - // A crash `Session::run` caught is a bug, never the refusal listed. - (Differs::Refuses, Ok(_), Err(_)) => !crashed(other), - (Differs::FirstLayer, Ok(a), Ok(b)) => { - // The first in the file's own order: the map lists the path's layers in the order - // they were added, not read. - let first = - rustgis_engine::data::io::read_layers(file, content).ok().and_then(|l| l.into_iter().next()).map(|l| l.dataset.name); - let is_first = |layer: &String| first.as_ref().is_some_and(|name| layer.starts_with(&format!("{name} "))); - b.said - && b.codes.is_subset(&a.codes) - && a.layers.len() > 1 - && b.layers.len() == 1 - && a.layers.contains(&b.layers[0]) - && is_first(&b.layers[0]) - } - _ => false, - } +/// Whether `other` is a refusal, not a crash, of what the path reads. +fn refuses(path: &Result, other: &Result) -> bool { + // A crash `Session::run` caught is a bug, never the refusal listed. + path.is_ok() && other.is_err() && !crashed(other) } -/// Reads every corpus file by `route` and by path, and fails on a difference [`DIFFERENT`] +/// Reads every corpus file by `route` and by path, and fails on a difference [`REFUSED`] /// doesn't list, or an entry for `route` that no longer differs. fn route_reads_as_the_path_does(route: Route) { let root = std::env::temp_dir().join(format!("rustgis-read-routes-{route:?}-{}", std::process::id())); @@ -237,8 +195,7 @@ fn route_reads_as_the_path_does(route: Route) { let Some(by_path) = read(&dir, Route::Path, c.file, content, beside) else { continue }; compared += 1; let Some(what) = difference(&by_path, &other) else { continue }; - let listed = DIFFERENT.iter().find(|&&(file, r, _)| file == c.file && r == route); - if listed.is_some_and(|&(_, _, how)| differs_as(how, c.file, content, &by_path, &other)) { + if REFUSED.contains(&(c.file, route)) && refuses(&by_path, &other) { differing.insert(c.file); } else { failures.push(format!("{} [{}, {kind}]: {what}", c.name, c.file)); @@ -246,9 +203,9 @@ fn route_reads_as_the_path_does(route: Route) { } } let _ = std::fs::remove_dir_all(&root); - for &(file, r, _) in DIFFERENT { + for &(file, r) in REFUSED { if r == route && !differing.contains(file) { - failures.push(format!("{file} now reads as its path does: remove it from DIFFERENT")); + failures.push(format!("{file} now reads as its path does: remove it from REFUSED")); } } assert!(compared > 0, "no file travels by {route:?}"); From 951c11e242eac04726f8cd6c0dad614036859c0b Mon Sep 17 00:00:00 2001 From: mavrick Date: Wed, 25 Nov 2026 17:18:49 -0600 Subject: [PATCH 02/14] fix(data): a zipped KML keeps its styles, and a zip's workbooks share its memory allowance --- crates/data/src/io.rs | 120 +++++++++++++++++++++++++++------ crates/engine/src/cmd/layer.rs | 12 +--- 2 files changed, 100 insertions(+), 32 deletions(-) diff --git a/crates/data/src/io.rs b/crates/data/src/io.rs index d818360b74..a422b90f48 100644 --- a/crates/data/src/io.rs +++ b/crates/data/src/io.rs @@ -293,7 +293,7 @@ pub fn read_layers(file_name: &str, bytes: &[u8]) -> Result> { let plain = |v: Vec<(Dataset, ReadReport)>| v.into_iter().map(|(dataset, report)| LayerRead { dataset, report, styles: Vec::new() }).collect(); let mut out: Vec = match ext.as_str() { - "zip" => plain(read_zip(file_name, bytes)?), + "zip" => read_zip_layers(file_name, bytes, None)?, "kml" | "kmz" => crate::kml::read(file_name, bytes)? .into_iter() .map(|l| LayerRead { dataset: l.dataset, report: l.report, styles: l.styles }) @@ -3830,8 +3830,19 @@ pub fn read_zip_in(file_name: &str, bytes: &[u8], crs: Option) -> Result) -> Result> { + read_zip_layers_budget(file_name, bytes, crs, &mut csv_memory_budget()) +} + +/// [`read_zip_layers_budget`] without the styles. fn read_zip_budget(file_name: &str, bytes: &[u8], crs: Option, budget: &mut usize) -> Result> { + Ok(read_zip_layers_budget(file_name, bytes, crs, budget)?.into_iter().map(|l| (l.dataset, l.report)).collect()) +} + +/// Delimited, dBASE and workbook members share one allowance, including gzip members whose text +/// is nested in ZIP. +fn read_zip_layers_budget(file_name: &str, bytes: &[u8], crs: Option, budget: &mut usize) -> Result> { let max = max_bytes(); if bytes.len() as u64 > max { return Err(DataError::Format(file_size_error(file_name, max))); @@ -3891,9 +3902,9 @@ fn read_zip_budget(file_name: &str, bytes: &[u8], crs: Option, budget: &mut continue; }; match read_shapefile_parts(ShapefileParts { shp, shx, dbf, prj, cpg }, &name, crs) { - Ok(mut read) => { - read.0.source = Some(format!("{file_name}/{n}")); - out.push(read); + Ok((mut dataset, report)) => { + dataset.source = Some(format!("{file_name}/{n}")); + out.push(LayerRead { dataset, report, styles: Vec::new() }); } Err(DataError::Cancelled) => return Err(DataError::Cancelled), Err(e) => skipped.push(format!("{n} ({e})")), @@ -3913,9 +3924,9 @@ fn read_zip_budget(file_name: &str, bytes: &[u8], crs: Option, budget: &mut let mif = take(&mut entries, &base, "mif").map(|(_, b)| b).unwrap_or_default(); let mid = take(&mut entries, &base, "mid").map(|(_, b)| b); match crate::mapinfo::read_bytes(&mif, mid.as_deref(), &name) { - Ok(mut read) => { - read.0.source = Some(format!("{file_name}/{n}")); - out.push(read); + Ok((mut dataset, report)) => { + dataset.source = Some(format!("{file_name}/{n}")); + out.push(LayerRead { dataset, report, styles: Vec::new() }); } Err(DataError::Cancelled) => return Err(DataError::Cancelled), Err(e) => skipped.push(format!("{n} ({e})")), @@ -3950,34 +3961,39 @@ fn read_zip_budget(file_name: &str, bytes: &[u8], crs: Option, budget: &mut continue; } let leaf = n.rsplit('/').next().unwrap_or(&n); + let plain = |reads: Vec<(Dataset, ReadReport)>| { + reads.into_iter().map(|(dataset, report)| LayerRead { dataset, report, styles: Vec::new() }).collect::>() + }; // A city model has many layers. let read = if ext_of(&n) == "dbf" { let cpg = take(&mut entries, &stem(&n), "cpg").map(|(_, b)| b); let name = Path::new(leaf).file_stem().and_then(|s| s.to_str()).unwrap_or("table"); - read_dbf(b, cpg.as_deref(), name, budget).map(|r| vec![r]) + read_dbf(b, cpg.as_deref(), name, budget).map(|r| plain(vec![r])) } else if is_city_model(leaf, &b) { - read_city_member(leaf, &b, crs) + read_city_member(leaf, &b, crs).map(plain) } else if is_delimited_name(leaf) { - read_delimited_bytes_budget(leaf, &b, &CsvOptions { crs, ..Default::default() }, budget).map(|r| vec![r]) + read_delimited_bytes_budget(leaf, &b, &CsvOptions { crs, ..Default::default() }, budget).map(|r| plain(vec![r])) } else if crate::sheets::is_sheet_name(leaf) { - // A workbook's first sheet, as a workbook added by itself is read. + // A workbook's first sheet, as a workbook added by itself is read, within the allowance. let name = Path::new(leaf).file_stem().and_then(|s| s.to_str()).unwrap_or("sheet"); - crate::sheets::read(&b, name, None, &CsvOptions { crs, ..Default::default() }).map(|r| vec![r]) + crate::sheets::read(&b, name, None, &CsvOptions { crs, ..Default::default() }) + .and_then(|r| charge_retained(&r.0, leaf, budget).map(|()| plain(vec![r]))) } else if is_multi_layer_name(leaf) && !leaf.to_ascii_lowercase().ends_with(".zip") { - // Every layer of a KML, GPX or other file of several, as when it is added by itself. - read_layers(leaf, &b).map(|layers| layers.into_iter().map(|l| (l.dataset, l.report)).collect()) + // Every layer of a KML, GPX or other file of several, with its styles, as when it is + // added by itself. + read_layers(leaf, &b) } else { - read_bytes(leaf, &b).map(|r| vec![r]) + read_bytes(leaf, &b).map(|r| plain(vec![r])) }; match read { Ok(layers) => { - for (mut ds, report) in layers { + for mut layer in layers { if out.len() >= MAX_ZIP_LAYERS { - skipped.push(format!("{n}: {} (past the {MAX_ZIP_LAYERS}-layer limit)", ds.name)); + skipped.push(format!("{n}: {} (past the {MAX_ZIP_LAYERS}-layer limit)", layer.dataset.name)); continue; } - ds.source = Some(format!("{file_name}/{n}")); - out.push((ds, report)); + layer.dataset.source = Some(format!("{file_name}/{n}")); + out.push(layer); } } // A run cancelled while a member was read stops the archive, not just that member. @@ -4007,14 +4023,39 @@ fn read_zip_budget(file_name: &str, bytes: &[u8], crs: Option, budget: &mut }; return Err(DataError::Format(format!("{file_name}: no supported layers or tables in the archive could be read{why}{hint}"))); } - if let Some((_, report)) = out.first_mut() + if let Some(first) = out.first_mut() && !skipped.is_empty() { - report.messages.push(format!("{file_name}: skipped {}", skipped.join("; "))); + first.report.messages.push(format!("{file_name}: skipped {}", skipped.join("; "))); } Ok(out) } +/// Takes what a table read whole keeps (each row and its values, text twice for the copies made +/// on the way in, as dBASE members are charged) out of a zip's shared `budget`, refusing the +/// member `name` when it doesn't fit. Its read peaked within the reader's own per-file limit. +fn charge_retained(ds: &Dataset, name: &str, budget: &mut usize) -> Result<()> { + let cost = ds.features.iter().fold(0usize, |sum, f| { + let row = f.attrs.iter().fold( + std::mem::size_of::().saturating_add(f.attrs.capacity().saturating_mul(std::mem::size_of::())), + |row, value| { + row.saturating_add(match value { + Value::Text(s) => s.capacity(), + _ => 0, + }) + }, + ); + sum.saturating_add(row.saturating_mul(2)) + }); + let allowance = *budget; + *budget = budget.checked_sub(cost).ok_or_else(|| { + DataError::Format(format!( + "{name}: the sheet's retained table exceeds the {allowance}-byte remaining memory budget; import a smaller file" + )) + })?; + Ok(()) +} + /// The same schema, decoder and numeric declarations for loose tables and Shapefile attributes. struct DbfRead { reader: shapefile::dbase::Reader>>, @@ -8964,6 +9005,41 @@ mod tests { } } + /// Workbook members draw on the same allowance: two that each fit don't both fit in it. + #[test] + fn zip_workbook_members_share_retained_budget() { + let book = crate::sheets::xlsx(&[("Sheet1", &[&["id", "n"], &["A", "1"]])]); + let one = crate::zip::write(&[("a.xlsx".into(), book.clone())]).unwrap(); + let alone = read_zip_budget("books.zip", &one, None, &mut { usize::MAX }).unwrap(); + assert_eq!(alone.len(), 1); + let mut left = 1 << 20; + charge_retained(&alone[0].0, "a.xlsx", &mut left).unwrap(); + let cost = (1 << 20) - left; + assert!(cost > 0); + let zip = crate::zip::write(&[("a.xlsx".into(), book.clone()), ("b.xlsx".into(), book)]).unwrap(); + let limited = read_zip_budget("books.zip", &zip, None, &mut { cost }).unwrap(); + assert_eq!(limited.len(), 1); + assert!(limited[0].1.messages.iter().any(|m| m.contains("b.xlsx") && m.contains("memory budget")), "{:?}", limited[0].1.messages); + let clean = read_zip_budget("books.zip", &zip, None, &mut (cost * 2)).unwrap(); + assert_eq!(clean.len(), 2); + assert!(clean.iter().all(|(_, report)| report.messages.is_empty())); + } + + /// A zipped KML gives every layer with its styles, as the same file added by itself does. + #[test] + fn a_zipped_kml_keeps_its_layers_and_styles() { + let doc = br##"#red1,2#red0,0 1,1"##; + let alone = read_layers("a.kml", doc).unwrap(); + assert_eq!(alone.len(), 2); + assert!(alone.iter().all(|l| !l.styles.is_empty())); + let zipped = read_layers("a.zip", &crate::zip::write(&[("a.kml".into(), doc.to_vec())]).unwrap()).unwrap(); + assert_eq!(zipped.len(), alone.len()); + for (z, a) in zipped.iter().zip(&alone) { + assert_eq!(z.dataset.features, a.dataset.features); + assert_eq!(format!("{:?}", z.styles), format!("{:?}", a.styles)); + } + } + /// Cancellation while the CSV parser asks for more of a long DAT header stays cancellation. #[test] fn gzip_long_dat_header_preserves_cancellation() { diff --git a/crates/engine/src/cmd/layer.rs b/crates/engine/src/cmd/layer.rs index e4f046b26c..fa05102656 100644 --- a/crates/engine/src/cmd/layer.rs +++ b/crates/engine/src/cmd/layer.rs @@ -2348,11 +2348,7 @@ fn read_layers_file(p: &Value, path: &str) -> LayersRead { let crs = ps(p, "crs").map(str::trim).filter(|c| !c.is_empty()); let reads = match crs { Some(text) if full.to_ascii_lowercase().ends_with(".zip") => { - rustgis_data::io::read_zip_in(&full, &bytes, Some(rustgis_data::raster::Crs::parse(text)?)) - .map_err(|e| e.to_string())? - .into_iter() - .map(|(dataset, report)| rustgis_data::io::LayerRead { dataset, report, styles: Vec::new() }) - .collect() + rustgis_data::io::read_zip_layers(&full, &bytes, Some(rustgis_data::raster::Crs::parse(text)?)).map_err(|e| e.to_string())? } Some(text) if rustgis_data::io::is_city_model(&full, &bytes) => { city_reads(&full, &bytes, Some(rustgis_data::raster::Crs::parse(text)?))? @@ -2807,11 +2803,7 @@ pub(crate) fn add_layers(s: &mut Session, p: &Value, file_name: &str, bytes: &[u let reads = match crs.filter(|_| landxml) { _ if lower.ends_with(".zip") && crs.is_some() => { let crs = crs.map(|text| super::parse_crs(s, text)).transpose()?; - rustgis_data::io::read_zip_in(file_name, bytes, crs) - .map_err(|e| e.to_string())? - .into_iter() - .map(|(dataset, report)| rustgis_data::io::LayerRead { dataset, report, styles: Vec::new() }) - .collect() + rustgis_data::io::read_zip_layers(file_name, bytes, crs).map_err(|e| e.to_string())? } // A city model (CityJSON or CityGML) with a coordinate system given, which takes the place // of any it names. From 67fc75563b9ef0ca5056dd92d6975272ab14c1cb Mon Sep 17 00:00:00 2001 From: mavrick Date: Wed, 25 Nov 2026 17:43:13 -0600 Subject: [PATCH 03/14] fix(data): a zipped LandXML file takes the system the zip is given --- crates/data/src/io.rs | 25 ++++++++++++++++++++++++- 1 file changed, 24 insertions(+), 1 deletion(-) diff --git a/crates/data/src/io.rs b/crates/data/src/io.rs index a422b90f48..9fe2af6d8d 100644 --- a/crates/data/src/io.rs +++ b/crates/data/src/io.rs @@ -3822,7 +3822,7 @@ pub fn read_zip(file_name: &str, bytes: &[u8]) -> Result, budge let name = Path::new(leaf).file_stem().and_then(|s| s.to_str()).unwrap_or("sheet"); crate::sheets::read(&b, name, None, &CsvOptions { crs, ..Default::default() }) .and_then(|r| charge_retained(&r.0, leaf, budget).map(|()| plain(vec![r]))) + } else if let Some(crs) = crs.filter(|_| { + crate::landxml::is_landxml_name(leaf) + || (ext_of(&n) == "xml" + && crate::landxml::looks_like_landxml(&String::from_utf8_lossy(b.get(..b.len().min(4096)).unwrap_or(&b)))) + }) { + // A LandXML file in the system given, as when it is added by itself with one. + crate::landxml::read(leaf, &b, Some(crs)).map(plain) } else if is_multi_layer_name(leaf) && !leaf.to_ascii_lowercase().ends_with(".zip") { // Every layer of a KML, GPX or other file of several, with its styles, as when it is // added by itself. @@ -9025,6 +9032,22 @@ mod tests { assert!(clean.iter().all(|(_, report)| report.messages.is_empty())); } + /// A zipped LandXML file is read in the system the zip is given, as it is by itself. + #[test] + fn a_zipped_landxml_file_takes_the_zips_system() { + let xml = br#"4649776 500000"#; + let zip = crate::zip::write(&[("site.xml".into(), xml.to_vec())]).unwrap(); + let crs = Crs::from_epsg(32633); + let given = read_zip_in("site.zip", &zip, crs).unwrap(); + let alone = crate::landxml::read("site.xml", xml, crs).unwrap(); + assert_eq!(given.len(), alone.len()); + assert_eq!(given[0].0.held_in, alone[0].0.held_in); + assert_eq!(given[0].0.features, alone[0].0.features); + assert!(!given[0].1.messages.iter().any(|m| m.contains("\"crs\"")), "{:?}", given[0].1.messages); + let none = read_zip_in("site.zip", &zip, None).unwrap(); + assert!(none[0].1.messages.iter().any(|m| m.contains("\"crs\"")), "{:?}", none[0].1.messages); + } + /// A zipped KML gives every layer with its styles, as the same file added by itself does. #[test] fn a_zipped_kml_keeps_its_layers_and_styles() { From 3ad32ca2c07171ee851659d30b8800e209e3b1f7 Mon Sep 17 00:00:00 2001 From: mavrick Date: Wed, 25 Nov 2026 19:37:50 -0600 Subject: [PATCH 04/14] fix(data): a zip's KML and GPX layers share its allowance, with their coordinates and field names, and a zipped KML says the overlays it doesn't draw --- crates/data/src/io.rs | 65 +++++++++++++++++++++++++++++++++++-------- 1 file changed, 54 insertions(+), 11 deletions(-) diff --git a/crates/data/src/io.rs b/crates/data/src/io.rs index 9fe2af6d8d..ccc2c60591 100644 --- a/crates/data/src/io.rs +++ b/crates/data/src/io.rs @@ -3822,7 +3822,8 @@ pub fn read_zip(file_name: &str, bytes: &[u8]) -> Result, budge crate::landxml::read(leaf, &b, Some(crs)).map(plain) } else if is_multi_layer_name(leaf) && !leaf.to_ascii_lowercase().ends_with(".zip") { // Every layer of a KML, GPX or other file of several, with its styles, as when it is - // added by itself. - read_layers(leaf, &b) + // added by itself, within the allowance. + read_layers(leaf, &b).and_then(|mut layers| { + for l in &layers { + charge_retained(&l.dataset, leaf, budget)?; + } + // A KML's ground overlays are pictures drawn beside its file; from a zip, they aren't. + if let Some(first) = layers.first_mut() + && matches!(ext_of(&n).as_str(), "kml" | "kmz") + && let Ok((found, undrawn, over_budget)) = crate::kml::ground_overlays(leaf, &b) + { + let overlays = found.len() + undrawn + over_budget; + if overlays > 0 { + first.report.messages.push(format!( + "{leaf}: {overlays} ground overlays (pictures) aren't drawn from inside a zip; unzip it and add the KML to draw them" + )); + } + } + Ok(layers) + }) } else { read_bytes(leaf, &b).map(|r| plain(vec![r])) }; @@ -4038,13 +4056,18 @@ fn read_zip_layers_budget(file_name: &str, bytes: &[u8], crs: Option, budge Ok(out) } -/// Takes what a table read whole keeps (each row and its values, text twice for the copies made -/// on the way in, as dBASE members are charged) out of a zip's shared `budget`, refusing the -/// member `name` when it doesn't fit. Its read peaked within the reader's own per-file limit. +/// Takes what a layer read whole keeps (its field names, and each row, its coordinates and values, +/// twice for the copies made on the way in, as dBASE members are charged) out of a zip's shared `budget`, +/// refusing the member `name` when it doesn't fit. Its read peaked within the reader's own +/// per-file limit. fn charge_retained(ds: &Dataset, name: &str, budget: &mut usize) -> Result<()> { - let cost = ds.features.iter().fold(0usize, |sum, f| { + let fields = ds.fields.iter().fold(0usize, |sum, f| sum.saturating_add(std::mem::size_of::()).saturating_add(f.name.capacity())); + let cost = ds.features.iter().fold(fields.saturating_mul(2), |sum, f| { + let coords = f.geometry.as_ref().map_or(0, |g| g.coord_count().saturating_mul(std::mem::size_of::())); let row = f.attrs.iter().fold( - std::mem::size_of::().saturating_add(f.attrs.capacity().saturating_mul(std::mem::size_of::())), + std::mem::size_of::() + .saturating_add(coords) + .saturating_add(f.attrs.capacity().saturating_mul(std::mem::size_of::())), |row, value| { row.saturating_add(match value { Value::Text(s) => s.capacity(), @@ -4056,9 +4079,7 @@ fn charge_retained(ds: &Dataset, name: &str, budget: &mut usize) -> Result<()> { }); let allowance = *budget; *budget = budget.checked_sub(cost).ok_or_else(|| { - DataError::Format(format!( - "{name}: the sheet's retained table exceeds the {allowance}-byte remaining memory budget; import a smaller file" - )) + DataError::Format(format!("{name}: its retained layer exceeds the {allowance}-byte remaining memory budget; import a smaller file")) })?; Ok(()) } @@ -9032,6 +9053,28 @@ mod tests { assert!(clean.iter().all(|(_, report)| report.messages.is_empty())); } + /// A zipped KML says the ground overlays it doesn't draw, and its layers share the zip's + /// allowance: two that each fit don't both fit in it. + #[test] + fn zipped_kml_members_say_their_overlays_and_share_retained_budget() { + let doc = br##"1,2op.png1010"##; + let one = crate::zip::write(&[("a.kml".into(), doc.to_vec())]).unwrap(); + let alone = read_zip_budget("trips.zip", &one, None, &mut { usize::MAX }).unwrap(); + assert_eq!(alone.len(), 1); + assert!(alone[0].1.messages.iter().any(|m| m.contains("1 ground overlays (pictures) aren't drawn")), "{:?}", alone[0].1.messages); + let mut left = 1 << 20; + charge_retained(&alone[0].0, "a.kml", &mut left).unwrap(); + let cost = (1 << 20) - left; + let zip = crate::zip::write(&[("a.kml".into(), doc.to_vec()), ("b.kml".into(), doc.to_vec())]).unwrap(); + let limited = read_zip_budget("trips.zip", &zip, None, &mut { cost }).unwrap(); + assert_eq!(limited.len(), 1); + assert!(limited[0].1.messages.iter().any(|m| m.contains("b.kml") && m.contains("memory budget")), "{:?}", limited[0].1.messages); + assert_eq!(read_zip_budget("trips.zip", &zip, None, &mut (cost * 2)).unwrap().len(), 2); + // Without overlays, nothing is said. + let plain = crate::zip::write(&[("a.gpx".into(), br#""#.to_vec())]).unwrap(); + assert!(read_zip("p.zip", &plain).unwrap().iter().all(|(_, r)| r.messages.is_empty())); + } + /// A zipped LandXML file is read in the system the zip is given, as it is by itself. #[test] fn a_zipped_landxml_file_takes_the_zips_system() { From 6a5c0082a00d518cc9eb4ed2e26ec55cfb514183 Mon Sep 17 00:00:00 2001 From: mavrick Date: Wed, 25 Nov 2026 20:29:45 -0600 Subject: [PATCH 05/14] fix(data): a zip member's layers are charged all at once, LandXML too, and its KML overlays are said in one notice --- crates/data/src/io.rs | 108 ++++++++++++++++++++++++++++++------------ 1 file changed, 77 insertions(+), 31 deletions(-) diff --git a/crates/data/src/io.rs b/crates/data/src/io.rs index ccc2c60591..aafddded3f 100644 --- a/crates/data/src/io.rs +++ b/crates/data/src/io.rs @@ -3885,6 +3885,8 @@ fn read_zip_layers_budget(file_name: &str, bytes: &[u8], crs: Option, budge let mut out = Vec::new(); // Members that couldn't be read are skipped, and said in the first layer's report. let mut skipped: Vec = Vec::new(); + // KML and KMZ members with ground overlays, which aren't drawn from a zip: each, and how many. + let mut overlays_left: Vec<(String, usize)> = Vec::new(); for n in shps { if out.len() >= MAX_ZIP_LAYERS { skipped.push(format!("{n} (past the {MAX_ZIP_LAYERS}-layer limit)")); @@ -3978,32 +3980,27 @@ fn read_zip_layers_budget(file_name: &str, bytes: &[u8], crs: Option, budge // A workbook's first sheet, as a workbook added by itself is read, within the allowance. let name = Path::new(leaf).file_stem().and_then(|s| s.to_str()).unwrap_or("sheet"); crate::sheets::read(&b, name, None, &CsvOptions { crs, ..Default::default() }) - .and_then(|r| charge_retained(&r.0, leaf, budget).map(|()| plain(vec![r]))) + .and_then(|r| charge_retained([&r.0], leaf, budget).map(|()| plain(vec![r]))) } else if let Some(crs) = crs.filter(|_| { crate::landxml::is_landxml_name(leaf) || (ext_of(&n) == "xml" && crate::landxml::looks_like_landxml(&String::from_utf8_lossy(b.get(..b.len().min(4096)).unwrap_or(&b)))) }) { - // A LandXML file in the system given, as when it is added by itself with one. - crate::landxml::read(leaf, &b, Some(crs)).map(plain) + // A LandXML file in the system given, as when it is added by itself with one, within + // the allowance. + crate::landxml::read(leaf, &b, Some(crs)) + .and_then(|reads| charge_retained(reads.iter().map(|(ds, _)| ds), leaf, budget).map(|()| plain(reads))) } else if is_multi_layer_name(leaf) && !leaf.to_ascii_lowercase().ends_with(".zip") { // Every layer of a KML, GPX or other file of several, with its styles, as when it is // added by itself, within the allowance. - read_layers(leaf, &b).and_then(|mut layers| { - for l in &layers { - charge_retained(&l.dataset, leaf, budget)?; - } + read_layers(leaf, &b).and_then(|layers| { + charge_retained(layers.iter().map(|l| &l.dataset), leaf, budget)?; // A KML's ground overlays are pictures drawn beside its file; from a zip, they aren't. - if let Some(first) = layers.first_mut() - && matches!(ext_of(&n).as_str(), "kml" | "kmz") + if matches!(ext_of(&n).as_str(), "kml" | "kmz") && let Ok((found, undrawn, over_budget)) = crate::kml::ground_overlays(leaf, &b) + && found.len() + undrawn + over_budget > 0 { - let overlays = found.len() + undrawn + over_budget; - if overlays > 0 { - first.report.messages.push(format!( - "{leaf}: {overlays} ground overlays (pictures) aren't drawn from inside a zip; unzip it and add the KML to draw them" - )); - } + overlays_left.push((n.clone(), found.len() + undrawn + over_budget)); } Ok(layers) }) @@ -4048,6 +4045,17 @@ fn read_zip_layers_budget(file_name: &str, bytes: &[u8], crs: Option, budge }; return Err(DataError::Format(format!("{file_name}: no supported layers or tables in the archive could be read{why}{hint}"))); } + // One notice for every member's overlays. + if let Some(first) = out.first_mut() + && !overlays_left.is_empty() + { + let count: usize = overlays_left.iter().map(|(_, c)| c).sum(); + let names: Vec = overlays_left.iter().map(|(n, c)| format!("{n} ({c})")).collect(); + first.report.messages.push(format!( + "{file_name}: {count} ground overlays (pictures) aren't drawn from inside a zip, in {}; unzip it and add the KML to draw them", + names.join(", ") + )); + } if let Some(first) = out.first_mut() && !skipped.is_empty() { @@ -4056,13 +4064,23 @@ fn read_zip_layers_budget(file_name: &str, bytes: &[u8], crs: Option, budge Ok(out) } -/// Takes what a layer read whole keeps (its field names, and each row, its coordinates and values, -/// twice for the copies made on the way in, as dBASE members are charged) out of a zip's shared `budget`, -/// refusing the member `name` when it doesn't fit. Its read peaked within the reader's own -/// per-file limit. -fn charge_retained(ds: &Dataset, name: &str, budget: &mut usize) -> Result<()> { +/// Takes what a member's layers read whole keep (their field names, and each row, its coordinates +/// and values, twice for the copies made on the way in, as dBASE members are charged) out of a +/// zip's shared `budget` all at once, or refuses the member `name`, taking nothing, when they +/// don't fit. Its read peaked within the reader's own per-file limit. +fn charge_retained<'a>(layers: impl IntoIterator, name: &str, budget: &mut usize) -> Result<()> { + let cost = layers.into_iter().fold(0usize, |sum, ds| sum.saturating_add(retained_cost(ds))); + let allowance = *budget; + *budget = budget.checked_sub(cost).ok_or_else(|| { + DataError::Format(format!("{name}: its retained layers exceed the {allowance}-byte remaining memory budget; import a smaller file")) + })?; + Ok(()) +} + +/// What a layer read whole keeps, for [`charge_retained`]. +fn retained_cost(ds: &Dataset) -> usize { let fields = ds.fields.iter().fold(0usize, |sum, f| sum.saturating_add(std::mem::size_of::()).saturating_add(f.name.capacity())); - let cost = ds.features.iter().fold(fields.saturating_mul(2), |sum, f| { + ds.features.iter().fold(fields.saturating_mul(2), |sum, f| { let coords = f.geometry.as_ref().map_or(0, |g| g.coord_count().saturating_mul(std::mem::size_of::())); let row = f.attrs.iter().fold( std::mem::size_of::() @@ -4076,12 +4094,7 @@ fn charge_retained(ds: &Dataset, name: &str, budget: &mut usize) -> Result<()> { }, ); sum.saturating_add(row.saturating_mul(2)) - }); - let allowance = *budget; - *budget = budget.checked_sub(cost).ok_or_else(|| { - DataError::Format(format!("{name}: its retained layer exceeds the {allowance}-byte remaining memory budget; import a smaller file")) - })?; - Ok(()) + }) } /// The same schema, decoder and numeric declarations for loose tables and Shapefile attributes. @@ -9041,7 +9054,7 @@ mod tests { let alone = read_zip_budget("books.zip", &one, None, &mut { usize::MAX }).unwrap(); assert_eq!(alone.len(), 1); let mut left = 1 << 20; - charge_retained(&alone[0].0, "a.xlsx", &mut left).unwrap(); + charge_retained([&alone[0].0], "a.xlsx", &mut left).unwrap(); let cost = (1 << 20) - left; assert!(cost > 0); let zip = crate::zip::write(&[("a.xlsx".into(), book.clone()), ("b.xlsx".into(), book)]).unwrap(); @@ -9053,6 +9066,26 @@ mod tests { assert!(clean.iter().all(|(_, report)| report.messages.is_empty())); } + /// A workbook's geometry counts: a sheet whose rows fit without their coordinates is refused + /// once a large WKT polygon's coordinates are charged too. + #[test] + fn a_zipped_workbooks_coordinates_count_against_the_allowance() { + let ring: Vec = (0..2000).map(|i| format!("{} {}", i % 7, i / 7)).chain(["0 0".to_string()]).collect(); + let polygon = format!("POLYGON(({}))", ring.join(",")); + let book = crate::sheets::xlsx(&[("Sheet1", &[&["id", "wkt"], &["A", &polygon]])]); + let zip = crate::zip::write(&[("a.xlsx".into(), book)]).unwrap(); + let read = read_zip_budget("books.zip", &zip, None, &mut { usize::MAX }).unwrap(); + assert!(read[0].0.features[0].geometry.as_ref().is_some_and(|g| g.coord_count() > 2000)); + // The same rows without their geometry, and a little room: not enough for 2,000 coordinates. + let mut rows_only = read[0].0.clone(); + for f in &mut rows_only.features { + f.geometry = None; + } + let allowance = retained_cost(&rows_only) + 1024; + let e = read_zip_budget("books.zip", &zip, None, &mut { allowance }).unwrap_err().to_string(); + assert!(e.contains("a.xlsx") && e.contains("memory budget"), "{e}"); + } + /// A zipped KML says the ground overlays it doesn't draw, and its layers share the zip's /// allowance: two that each fit don't both fit in it. #[test] @@ -9061,15 +9094,28 @@ mod tests { let one = crate::zip::write(&[("a.kml".into(), doc.to_vec())]).unwrap(); let alone = read_zip_budget("trips.zip", &one, None, &mut { usize::MAX }).unwrap(); assert_eq!(alone.len(), 1); - assert!(alone[0].1.messages.iter().any(|m| m.contains("1 ground overlays (pictures) aren't drawn")), "{:?}", alone[0].1.messages); + assert!( + alone[0].1.messages.iter().any(|m| m.contains("1 ground overlays (pictures) aren't drawn") && m.contains("a.kml (1)")), + "{:?}", + alone[0].1.messages + ); let mut left = 1 << 20; - charge_retained(&alone[0].0, "a.kml", &mut left).unwrap(); + charge_retained([&alone[0].0], "a.kml", &mut left).unwrap(); let cost = (1 << 20) - left; let zip = crate::zip::write(&[("a.kml".into(), doc.to_vec()), ("b.kml".into(), doc.to_vec())]).unwrap(); let limited = read_zip_budget("trips.zip", &zip, None, &mut { cost }).unwrap(); assert_eq!(limited.len(), 1); assert!(limited[0].1.messages.iter().any(|m| m.contains("b.kml") && m.contains("memory budget")), "{:?}", limited[0].1.messages); - assert_eq!(read_zip_budget("trips.zip", &zip, None, &mut (cost * 2)).unwrap().len(), 2); + let both = read_zip_budget("trips.zip", &zip, None, &mut (cost * 2)).unwrap(); + assert_eq!(both.len(), 2); + // One notice for both members' overlays, with the count. + let said: Vec<&str> = both.iter().flat_map(|(_, r)| r.messages.texts()).filter(|m| m.contains("ground overlays")).collect(); + assert_eq!(said.len(), 1, "{said:?}"); + assert!(said[0].contains("2 ground overlays") && said[0].contains("a.kml (1)") && said[0].contains("b.kml (1)"), "{said:?}"); + // A member whose layers don't all fit takes nothing from the allowance. + let mut left = cost; + assert!(charge_retained([&alone[0].0, &alone[0].0], "two.kml", &mut left).is_err()); + assert_eq!(left, cost); // Without overlays, nothing is said. let plain = crate::zip::write(&[("a.gpx".into(), br#""#.to_vec())]).unwrap(); assert!(read_zip("p.zip", &plain).unwrap().iter().all(|(_, r)| r.messages.is_empty())); From 1e7483f8555caed72d5d22afd6e8441ccf442a48 Mon Sep 17 00:00:00 2001 From: mavrick Date: Wed, 25 Nov 2026 22:04:05 -0600 Subject: [PATCH 06/14] fix(data): a zipped KML's styles count against the zip's allowance --- crates/data/src/io.rs | 13 +++++++++++-- 1 file changed, 11 insertions(+), 2 deletions(-) diff --git a/crates/data/src/io.rs b/crates/data/src/io.rs index aafddded3f..bdd4cf336a 100644 --- a/crates/data/src/io.rs +++ b/crates/data/src/io.rs @@ -3994,7 +3994,11 @@ fn read_zip_layers_budget(file_name: &str, bytes: &[u8], crs: Option, budge // Every layer of a KML, GPX or other file of several, with its styles, as when it is // added by itself, within the allowance. read_layers(leaf, &b).and_then(|layers| { - charge_retained(layers.iter().map(|l| &l.dataset), leaf, budget)?; + // A KML's styles stay with its layers. + let styles = layers.iter().flat_map(|l| &l.styles).fold(0usize, |sum, (id, _)| { + sum.saturating_add(std::mem::size_of::<(String, crate::kml::Style)>()).saturating_add(id.capacity()) + }); + charge_retained_with(layers.iter().map(|l| &l.dataset), styles, leaf, budget)?; // A KML's ground overlays are pictures drawn beside its file; from a zip, they aren't. if matches!(ext_of(&n).as_str(), "kml" | "kmz") && let Ok((found, undrawn, over_budget)) = crate::kml::ground_overlays(leaf, &b) @@ -4069,7 +4073,12 @@ fn read_zip_layers_budget(file_name: &str, bytes: &[u8], crs: Option, budge /// zip's shared `budget` all at once, or refuses the member `name`, taking nothing, when they /// don't fit. Its read peaked within the reader's own per-file limit. fn charge_retained<'a>(layers: impl IntoIterator, name: &str, budget: &mut usize) -> Result<()> { - let cost = layers.into_iter().fold(0usize, |sum, ds| sum.saturating_add(retained_cost(ds))); + charge_retained_with(layers, 0, name, budget) +} + +/// [`charge_retained`] with `extra` bytes the layers keep besides their rows (a KML's styles). +fn charge_retained_with<'a>(layers: impl IntoIterator, extra: usize, name: &str, budget: &mut usize) -> Result<()> { + let cost = layers.into_iter().fold(extra, |sum, ds| sum.saturating_add(retained_cost(ds))); let allowance = *budget; *budget = budget.checked_sub(cost).ok_or_else(|| { DataError::Format(format!("{name}: its retained layers exceed the {allowance}-byte remaining memory budget; import a smaller file")) From f764d87a72c532c1b529a5eeed33e9aac07d461d Mon Sep 17 00:00:00 2001 From: mavrick Date: Wed, 25 Nov 2026 22:38:06 -0600 Subject: [PATCH 07/14] fix(data): a zipped KML of ground overlays only says them too --- crates/data/src/io.rs | 21 ++++++++++++++------- 1 file changed, 14 insertions(+), 7 deletions(-) diff --git a/crates/data/src/io.rs b/crates/data/src/io.rs index bdd4cf336a..68f205bc42 100644 --- a/crates/data/src/io.rs +++ b/crates/data/src/io.rs @@ -3993,19 +3993,20 @@ fn read_zip_layers_budget(file_name: &str, bytes: &[u8], crs: Option, budge } else if is_multi_layer_name(leaf) && !leaf.to_ascii_lowercase().ends_with(".zip") { // Every layer of a KML, GPX or other file of several, with its styles, as when it is // added by itself, within the allowance. + // A KML's ground overlays are pictures drawn beside its file; from a zip, they aren't, + // even in a document of overlays only, which gives no layer. + if matches!(ext_of(&n).as_str(), "kml" | "kmz") + && let Ok((found, undrawn, over_budget)) = crate::kml::ground_overlays(leaf, &b) + && found.len() + undrawn + over_budget > 0 + { + overlays_left.push((n.clone(), found.len() + undrawn + over_budget)); + } read_layers(leaf, &b).and_then(|layers| { // A KML's styles stay with its layers. let styles = layers.iter().flat_map(|l| &l.styles).fold(0usize, |sum, (id, _)| { sum.saturating_add(std::mem::size_of::<(String, crate::kml::Style)>()).saturating_add(id.capacity()) }); charge_retained_with(layers.iter().map(|l| &l.dataset), styles, leaf, budget)?; - // A KML's ground overlays are pictures drawn beside its file; from a zip, they aren't. - if matches!(ext_of(&n).as_str(), "kml" | "kmz") - && let Ok((found, undrawn, over_budget)) = crate::kml::ground_overlays(leaf, &b) - && found.len() + undrawn + over_budget > 0 - { - overlays_left.push((n.clone(), found.len() + undrawn + over_budget)); - } Ok(layers) }) } else { @@ -9125,6 +9126,12 @@ mod tests { let mut left = cost; assert!(charge_retained([&alone[0].0, &alone[0].0], "two.kml", &mut left).is_err()); assert_eq!(left, cost); + // A document of overlays only gives no layer, but its overlays are still said. + let only = br##"op.png1010"##; + let zip = crate::zip::write(&[("a.csv".into(), b"id,x,y\n1,1,2\n".to_vec()), ("o.kml".into(), only.to_vec())]).unwrap(); + let read = read_zip("mixed.zip", &zip).unwrap(); + assert_eq!(read.len(), 1); + assert!(read[0].1.messages.iter().any(|m| m.contains("1 ground overlays") && m.contains("o.kml (1)")), "{:?}", read[0].1.messages); // Without overlays, nothing is said. let plain = crate::zip::write(&[("a.gpx".into(), br#""#.to_vec())]).unwrap(); assert!(read_zip("p.zip", &plain).unwrap().iter().all(|(_, r)| r.messages.is_empty())); From 920bd50f2542672dc32125c10547ff1e3564798b Mon Sep 17 00:00:00 2001 From: mavrick Date: Wed, 25 Nov 2026 23:15:31 -0600 Subject: [PATCH 08/14] fix(data): a zipped KML whose ground overlays can't be counted says so --- crates/data/src/io.rs | 15 ++++++++++----- 1 file changed, 10 insertions(+), 5 deletions(-) diff --git a/crates/data/src/io.rs b/crates/data/src/io.rs index 68f205bc42..adb470c671 100644 --- a/crates/data/src/io.rs +++ b/crates/data/src/io.rs @@ -3995,11 +3995,16 @@ fn read_zip_layers_budget(file_name: &str, bytes: &[u8], crs: Option, budge // added by itself, within the allowance. // A KML's ground overlays are pictures drawn beside its file; from a zip, they aren't, // even in a document of overlays only, which gives no layer. - if matches!(ext_of(&n).as_str(), "kml" | "kmz") - && let Ok((found, undrawn, over_budget)) = crate::kml::ground_overlays(leaf, &b) - && found.len() + undrawn + over_budget > 0 - { - overlays_left.push((n.clone(), found.len() + undrawn + over_budget)); + if matches!(ext_of(&n).as_str(), "kml" | "kmz") { + match crate::kml::ground_overlays(leaf, &b) { + Ok((found, undrawn, over_budget)) if found.len() + undrawn + over_budget > 0 => { + overlays_left.push((n.clone(), found.len() + undrawn + over_budget)); + } + Ok(_) => {} + // Overlays that can't even be counted (a KMZ entry too large to expand) are + // said too. + Err(e) => skipped.push(format!("{n}'s ground overlays, which couldn't be counted ({e})")), + } } read_layers(leaf, &b).and_then(|layers| { // A KML's styles stay with its layers. From e75164ecb4088ef8e218961238440984164efc84 Mon Sep 17 00:00:00 2001 From: mavrick Date: Wed, 25 Nov 2026 23:33:51 -0600 Subject: [PATCH 09/14] fix(data): a zip of only ground overlays says them when it is refused --- crates/data/src/io.rs | 30 ++++++++++++++++++++---------- 1 file changed, 20 insertions(+), 10 deletions(-) diff --git a/crates/data/src/io.rs b/crates/data/src/io.rs index adb470c671..0f9ab7f3d9 100644 --- a/crates/data/src/io.rs +++ b/crates/data/src/io.rs @@ -4046,25 +4046,32 @@ fn read_zip_layers_budget(file_name: &str, bytes: &[u8], crs: Option, budge if geodatabase.get() { skipped.push("File Geodatabase contents (unzip the archive and add the .gdb folder on the desktop)".into()); } + // One notice for every member's overlays, said with the layers or, when there are none, with + // the refusal. + let overlays = (!overlays_left.is_empty()).then(|| { + let count: usize = overlays_left.iter().map(|(_, c)| c).sum(); + let names: Vec = overlays_left.iter().map(|(n, c)| format!("{n} ({c})")).collect(); + format!( + "{count} ground overlays (pictures) aren't drawn from inside a zip, in {}; unzip it and add the KML to draw them", + names.join(", ") + ) + }); if out.is_empty() { let why = if skipped.is_empty() { String::new() } else { format!(": {}", skipped.join("; ")) }; - let hint = if skipped.is_empty() { + let hint = if skipped.is_empty() && overlays.is_none() { "; unzip it and add a supported file (rename delimited text to .txt if it was not recognised)" } else { "" }; - return Err(DataError::Format(format!("{file_name}: no supported layers or tables in the archive could be read{why}{hint}"))); + let overlays = overlays.map(|o| format!("; {o}")).unwrap_or_default(); + return Err(DataError::Format(format!( + "{file_name}: no supported layers or tables in the archive could be read{why}{hint}{overlays}" + ))); } - // One notice for every member's overlays. if let Some(first) = out.first_mut() - && !overlays_left.is_empty() + && let Some(overlays) = overlays { - let count: usize = overlays_left.iter().map(|(_, c)| c).sum(); - let names: Vec = overlays_left.iter().map(|(n, c)| format!("{n} ({c})")).collect(); - first.report.messages.push(format!( - "{file_name}: {count} ground overlays (pictures) aren't drawn from inside a zip, in {}; unzip it and add the KML to draw them", - names.join(", ") - )); + first.report.messages.push(format!("{file_name}: {overlays}")); } if let Some(first) = out.first_mut() && !skipped.is_empty() @@ -9137,6 +9144,9 @@ mod tests { let read = read_zip("mixed.zip", &zip).unwrap(); assert_eq!(read.len(), 1); assert!(read[0].1.messages.iter().any(|m| m.contains("1 ground overlays") && m.contains("o.kml (1)")), "{:?}", read[0].1.messages); + // A zip of only that document is refused, saying its overlays and how to draw them. + let e = read_zip("only.zip", &crate::zip::write(&[("o.kml".into(), only.to_vec())]).unwrap()).unwrap_err().to_string(); + assert!(e.contains("1 ground overlays") && e.contains("o.kml (1)") && e.contains("unzip it and add the KML"), "{e}"); // Without overlays, nothing is said. let plain = crate::zip::write(&[("a.gpx".into(), br#""#.to_vec())]).unwrap(); assert!(read_zip("p.zip", &plain).unwrap().iter().all(|(_, r)| r.messages.is_empty())); From 1a481ec6b5a1cdc7af1918f8761b98590fb77b22 Mon Sep 17 00:00:00 2001 From: mavrick Date: Thu, 26 Nov 2026 00:07:15 -0600 Subject: [PATCH 10/14] fix(data): a KML past the size it is read within is refused before its overlays are scanned --- crates/data/src/io.rs | 3 ++- crates/engine/src/cmd/layer.rs | 7 ++++++- 2 files changed, 8 insertions(+), 2 deletions(-) diff --git a/crates/data/src/io.rs b/crates/data/src/io.rs index 0f9ab7f3d9..064dc1443b 100644 --- a/crates/data/src/io.rs +++ b/crates/data/src/io.rs @@ -3995,7 +3995,8 @@ fn read_zip_layers_budget(file_name: &str, bytes: &[u8], crs: Option, budge // added by itself, within the allowance. // A KML's ground overlays are pictures drawn beside its file; from a zip, they aren't, // even in a document of overlays only, which gives no layer. - if matches!(ext_of(&n).as_str(), "kml" | "kmz") { + // Past the size a KML is read within, `read_layers` refuses it below: not scanned first. + if matches!(ext_of(&n).as_str(), "kml" | "kmz") && b.len() as u64 <= BYTES_FLOOR { match crate::kml::ground_overlays(leaf, &b) { Ok((found, undrawn, over_budget)) if found.len() + undrawn + over_budget > 0 => { overlays_left.push((n.clone(), found.len() + undrawn + over_budget)); diff --git a/crates/engine/src/cmd/layer.rs b/crates/engine/src/cmd/layer.rs index fa05102656..f9bb86adde 100644 --- a/crates/engine/src/cmd/layer.rs +++ b/crates/engine/src/cmd/layer.rs @@ -2797,7 +2797,12 @@ pub(crate) fn add_layers(s: &mut Session, p: &Value, file_name: &str, bytes: &[u let lower = file_name.to_ascii_lowercase(); let kml = lower.ends_with(".kml") || lower.ends_with(".kmz"); // A KML's ground overlays (pictures) are raster layers, added after its placemarks. - let overlays = if kml && ps(p, "layer").is_none() { ground_overlays(s, file_name, bytes, local_file) } else { Vec::new() }; + // Past the size a KML is read within, it is refused below without being scanned first. + let overlays = if kml && ps(p, "layer").is_none() && bytes.len() as u64 <= rustgis_data::io::BYTES_FLOOR { + ground_overlays(s, file_name, bytes, local_file) + } else { + Vec::new() + }; // A DXF drawing: its coordinate system (it never says) and one of its own layers. let dxf = rustgis_data::dxf::is_dxf_name(file_name); let reads = match crs.filter(|_| landxml) { From e90b50992ec31512e7cddeb09b591196c5202ec5 Mon Sep 17 00:00:00 2001 From: mavrick Date: Thu, 26 Nov 2026 00:42:56 -0600 Subject: [PATCH 11/14] fix(engine): what a zip says of itself reaches the layer picked from it --- crates/engine/src/cmd/layer.rs | 12 ++++++++ .../engine/tests/integration/read_routes.rs | 28 +++++++++++++++++++ 2 files changed, 40 insertions(+) diff --git a/crates/engine/src/cmd/layer.rs b/crates/engine/src/cmd/layer.rs index f9bb86adde..08d91356a3 100644 --- a/crates/engine/src/cmd/layer.rs +++ b/crates/engine/src/cmd/layer.rs @@ -2878,10 +2878,22 @@ fn add_picked( (r.dataset.source.clone(), said) }) .collect(); + // What a zip says of itself (members skipped, overlays not drawn) sits on its first layer, + // named by the zip: it goes with whichever layer is picked. + let zip_wide: Vec = match reads.first() { + Some(first) if lower.ends_with(".zip") && !pick(&first.dataset.name) => { + let prefix = format!("{file_name}: "); + first.report.messages.iter().filter(|n| n.text.starts_with(&prefix)).cloned().collect() + } + _ => Vec::new(), + }; reads.retain(|r| pick(&r.dataset.name)); if reads.is_empty() { return Err(format!("{file_name}: no layer '{want}' (layers: {})", names.join(", "))); } + if let Some(kept) = reads.first_mut() { + kept.report.messages.extend(zip_wide); + } for (source, said) in file_wide { if let Some(kept) = reads.iter_mut().find(|r| r.dataset.source == source) { kept.report.messages.extend(said.messages); diff --git a/crates/engine/tests/integration/read_routes.rs b/crates/engine/tests/integration/read_routes.rs index c354ef3a03..e3f8843ad5 100644 --- a/crates/engine/tests/integration/read_routes.rs +++ b/crates/engine/tests/integration/read_routes.rs @@ -241,3 +241,31 @@ fn a_download_reads_as_its_path_does() { fn a_zipped_file_reads_as_its_path_does() { route_reads_as_the_path_does(Route::Zip); } + +/// What a zip says of itself (its KML's overlays not drawn, here) sits on its first layer; picking +/// another layer with `layer` still says it. +#[test] +fn a_zips_own_notices_reach_the_layer_picked() { + let dir = std::env::temp_dir().join(format!("rustgis-read-routes-picked-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + let kml = br##"1,2op.png1010"##; + let zip = rustgis_engine::data::zip::write(&[("a.csv".into(), b"id,x,y\n1,1,2\n".to_vec()), ("b.kml".into(), kml.to_vec())]).unwrap(); + let path = dir.join("trip.zip"); + std::fs::write(&path, zip).unwrap(); + for layer in [None, Some("b")] { + let mut s = Session::new(Project::default()); + let mark = s.notice_mark(); + let mut p = json!({"path": path}); + if let Some(l) = layer { + p["layer"] = json!(l); + } + s.run("layer.addData", &p).unwrap(); + let said: Vec = s.notices_since(mark).iter().map(|n| n.text.clone()).collect(); + assert!( + said.iter().any(|n| n.contains("ground overlays (pictures) aren't drawn") && n.contains("b.kml (1)")), + "{layer:?}: {said:?}" + ); + } + let _ = std::fs::remove_dir_all(&dir); +} From 8360d430996730f6627fad87a2549b255590a074 Mon Sep 17 00:00:00 2001 From: mavrick Date: Thu, 26 Nov 2026 01:10:51 -0600 Subject: [PATCH 12/14] fix(engine): what a zip says of itself is said once when a layer of its first member is picked --- crates/engine/src/cmd/layer.rs | 5 +++ .../engine/tests/integration/read_routes.rs | 35 +++++++++++-------- 2 files changed, 25 insertions(+), 15 deletions(-) diff --git a/crates/engine/src/cmd/layer.rs b/crates/engine/src/cmd/layer.rs index 08d91356a3..1d6ce4d040 100644 --- a/crates/engine/src/cmd/layer.rs +++ b/crates/engine/src/cmd/layer.rs @@ -2869,6 +2869,11 @@ fn add_picked( }) .map(|(_, r)| { let mut said = r.report.clone(); + // What the zip says of itself goes to the picked layer once, below. + if lower.ends_with(".zip") { + let prefix = format!("{file_name}: "); + said.messages.retain(|n| !n.text.starts_with(&prefix)); + } // The layer's own Z/M note, by its code: that layer says it. if r.dataset.zm_dropped && let Some(at) = said.messages.iter().position(|n| n.loss == Some(rustgis_data::loss::LossCode::DroppedZm)) diff --git a/crates/engine/tests/integration/read_routes.rs b/crates/engine/tests/integration/read_routes.rs index e3f8843ad5..656eef1f6f 100644 --- a/crates/engine/tests/integration/read_routes.rs +++ b/crates/engine/tests/integration/read_routes.rs @@ -250,22 +250,27 @@ fn a_zips_own_notices_reach_the_layer_picked() { let _ = std::fs::remove_dir_all(&dir); std::fs::create_dir_all(&dir).unwrap(); let kml = br##"1,2op.png1010"##; - let zip = rustgis_engine::data::zip::write(&[("a.csv".into(), b"id,x,y\n1,1,2\n".to_vec()), ("b.kml".into(), kml.to_vec())]).unwrap(); - let path = dir.join("trip.zip"); - std::fs::write(&path, zip).unwrap(); - for layer in [None, Some("b")] { - let mut s = Session::new(Project::default()); - let mark = s.notice_mark(); - let mut p = json!({"path": path}); - if let Some(l) = layer { - p["layer"] = json!(l); + // Its first layer from another member, then from the same member as the layer picked. + let two = br##"1,20,0 1,1op.png1010"##; + let cases: [(&[(&str, &[u8])], &str, &str); 2] = + [(&[("a.csv", b"id,x,y\n1,1,2\n"), ("b.kml", kml)], "b", "b.kml (1)"), (&[("a.kml", two)], "lines", "a.kml (1)")]; + for (i, (members, pick, named)) in cases.into_iter().enumerate() { + let entries: Vec<(String, Vec)> = members.iter().map(|(n, b)| (n.to_string(), b.to_vec())).collect(); + let path = dir.join(format!("trip{i}.zip")); + std::fs::write(&path, rustgis_engine::data::zip::write(&entries).unwrap()).unwrap(); + for layer in [None, Some(pick)] { + let mut s = Session::new(Project::default()); + let mark = s.notice_mark(); + let mut p = json!({"path": path}); + if let Some(l) = layer { + p["layer"] = json!(l); + } + s.run("layer.addData", &p).unwrap(); + let said: Vec = s.notices_since(mark).iter().map(|n| n.text.clone()).collect(); + // Said once, whichever layer is picked. + let overlays: Vec<&String> = said.iter().filter(|n| n.contains("ground overlays (pictures) aren't drawn")).collect(); + assert!(overlays.len() == 1 && overlays[0].contains(named), "{i} {layer:?}: {said:?}"); } - s.run("layer.addData", &p).unwrap(); - let said: Vec = s.notices_since(mark).iter().map(|n| n.text.clone()).collect(); - assert!( - said.iter().any(|n| n.contains("ground overlays (pictures) aren't drawn") && n.contains("b.kml (1)")), - "{layer:?}: {said:?}" - ); } let _ = std::fs::remove_dir_all(&dir); } From 82263b3f706ca7eff3e11e540e39999bef7a9e31 Mon Sep 17 00:00:00 2001 From: mavrick Date: Thu, 26 Nov 2026 01:40:34 -0600 Subject: [PATCH 13/14] fix(engine): a KML added with a layer picked says the ground overlays it leaves out --- crates/engine/src/cmd/layer.rs | 23 +++++++++++++++---- .../engine/tests/integration/read_routes.rs | 21 +++++++++++++++++ 2 files changed, 39 insertions(+), 5 deletions(-) diff --git a/crates/engine/src/cmd/layer.rs b/crates/engine/src/cmd/layer.rs index 1d6ce4d040..63153a5800 100644 --- a/crates/engine/src/cmd/layer.rs +++ b/crates/engine/src/cmd/layer.rs @@ -2798,11 +2798,24 @@ pub(crate) fn add_layers(s: &mut Session, p: &Value, file_name: &str, bytes: &[u let kml = lower.ends_with(".kml") || lower.ends_with(".kmz"); // A KML's ground overlays (pictures) are raster layers, added after its placemarks. // Past the size a KML is read within, it is refused below without being scanned first. - let overlays = if kml && ps(p, "layer").is_none() && bytes.len() as u64 <= rustgis_data::io::BYTES_FLOOR { - ground_overlays(s, file_name, bytes, local_file) - } else { - Vec::new() - }; + let within = bytes.len() as u64 <= rustgis_data::io::BYTES_FLOOR; + let picked = ps(p, "layer").is_some_and(|l| !l.trim().is_empty()); + let overlays = if kml && !picked && within { ground_overlays(s, file_name, bytes, local_file) } else { Vec::new() }; + // A layer picked leaves the document's ground overlays (pictures, not layers) out: said. + if kml + && picked + && within + && let Ok((found, undrawn, over_budget)) = rustgis_data::kml::ground_overlays(file_name, bytes) + && found.len() + undrawn + over_budget > 0 + { + s.notify( + format!( + "{file_name}: {} ground overlays (pictures) aren't added with a layer picked; add the file without \"layer\" to draw them", + found.len() + undrawn + over_budget + ), + false, + ); + } // A DXF drawing: its coordinate system (it never says) and one of its own layers. let dxf = rustgis_data::dxf::is_dxf_name(file_name); let reads = match crs.filter(|_| landxml) { diff --git a/crates/engine/tests/integration/read_routes.rs b/crates/engine/tests/integration/read_routes.rs index 656eef1f6f..f698e620cf 100644 --- a/crates/engine/tests/integration/read_routes.rs +++ b/crates/engine/tests/integration/read_routes.rs @@ -274,3 +274,24 @@ fn a_zips_own_notices_reach_the_layer_picked() { } let _ = std::fs::remove_dir_all(&dir); } + +/// A KML added with `layer` leaves its ground overlays out, and says how many. +#[test] +fn a_kml_layer_picked_says_the_overlays_left_out() { + let dir = std::env::temp_dir().join(format!("rustgis-read-routes-overlays-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + let kml = br##"1,2op.png1010"##; + let path = dir.join("trip.kml"); + std::fs::write(&path, kml).unwrap(); + for picked in [false, true] { + let mut s = Session::new(Project::default()); + let mark = s.notice_mark(); + let p = if picked { json!({"path": path, "layer": "trip"}) } else { json!({"path": path}) }; + s.run("layer.addData", &p).unwrap(); + let said: Vec = s.notices_since(mark).iter().map(|n| n.text.clone()).collect(); + let left_out = said.iter().filter(|n| n.contains("1 ground overlays (pictures) aren't added with a layer picked")).count(); + assert_eq!(left_out, usize::from(picked), "picked {picked}: {said:?}"); + } + let _ = std::fs::remove_dir_all(&dir); +} From c7b92d64bb9b4f1a5deab6e74cac1a897b242788 Mon Sep 17 00:00:00 2001 From: mavrick Date: Thu, 26 Nov 2026 02:14:43 -0600 Subject: [PATCH 14/14] fix(engine): a KML whose ground overlays can't be read says so --- crates/engine/src/cmd/layer.rs | 29 ++++++++++++++++------------- 1 file changed, 16 insertions(+), 13 deletions(-) diff --git a/crates/engine/src/cmd/layer.rs b/crates/engine/src/cmd/layer.rs index 63153a5800..46560e8326 100644 --- a/crates/engine/src/cmd/layer.rs +++ b/crates/engine/src/cmd/layer.rs @@ -2802,19 +2802,18 @@ pub(crate) fn add_layers(s: &mut Session, p: &Value, file_name: &str, bytes: &[u let picked = ps(p, "layer").is_some_and(|l| !l.trim().is_empty()); let overlays = if kml && !picked && within { ground_overlays(s, file_name, bytes, local_file) } else { Vec::new() }; // A layer picked leaves the document's ground overlays (pictures, not layers) out: said. - if kml - && picked - && within - && let Ok((found, undrawn, over_budget)) = rustgis_data::kml::ground_overlays(file_name, bytes) - && found.len() + undrawn + over_budget > 0 - { - s.notify( - format!( - "{file_name}: {} ground overlays (pictures) aren't added with a layer picked; add the file without \"layer\" to draw them", - found.len() + undrawn + over_budget + if kml && picked && within { + match rustgis_data::kml::ground_overlays(file_name, bytes) { + Ok((found, undrawn, over_budget)) if found.len() + undrawn + over_budget > 0 => s.notify( + format!( + "{file_name}: {} ground overlays (pictures) aren't added with a layer picked; add the file without \"layer\" to draw them", + found.len() + undrawn + over_budget + ), + false, ), - false, - ); + Ok(_) => {} + Err(e) => s.notify(format!("{file_name}: its ground overlays (pictures) couldn't be read, so none is added: {e}"), false), + } } // A DXF drawing: its coordinate system (it never says) and one of its own layers. let dxf = rustgis_data::dxf::is_dxf_name(file_name); @@ -3006,7 +3005,11 @@ fn add_reads( fn ground_overlays(s: &mut Session, file_name: &str, bytes: &[u8], local_file: bool) -> Vec<(String, rustgis_data::raster::Raster)> { match rustgis_data::kml::ground_overlays(file_name, bytes) { Ok(overlays) => overlays_drawn(s, file_name, overlays, local_file), - Err(_) => Vec::new(), + // Overlays that can't even be listed (a KMZ entry too large to expand) are said. + Err(e) => { + s.notify(format!("{file_name}: its ground overlays (pictures) couldn't be read, so none is added: {e}"), false); + Vec::new() + } } }