diff --git a/crates/data/src/capped.rs b/crates/data/src/capped.rs index 966e7c7782..af40209177 100644 --- a/crates/data/src/capped.rs +++ b/crates/data/src/capped.rs @@ -160,12 +160,13 @@ impl Buffer<'_> { Ok(()) } - /// The file made, its spare room given back, no longer counted against the limit. + /// The file made, no longer counted against the limit; a file held to a limit gives back its + /// spare room, one to be written keeps it until dropped (up to about twice its length). pub fn into_inner(mut self) -> Vec { let mut file = std::mem::take(&mut self.file); // Only a file held to a limit (a download, which waits counted by what it holds) gives // back its spare room: a file to be written isn't reallocated for it. - if self.limit.max != usize::MAX { + if self.limit.bounded() { file.shrink_to_fit(); } self.release(); diff --git a/crates/data/src/dbf.rs b/crates/data/src/dbf.rs index 6d88b75efd..959b8212c8 100644 --- a/crates/data/src/dbf.rs +++ b/crates/data/src/dbf.rs @@ -153,7 +153,7 @@ pub(crate) fn encoding(cpg: Option<&[u8]>, ldid: u8, notes: &mut crate::loss::No let page = (ldid != 0).then(|| ldid_code_page(ldid)).flatten(); let resolved = page.and_then(DbfEncoding::from_number); if cpg.is_some() { - let text = "Shapefile: unsupported or empty .cpg; using the .dbf code page, or UTF-8 if unavailable"; + let text = "unsupported or empty .cpg; using the .dbf code page, or UTF-8 if unavailable"; notes.push(if ldid == 0 { crate::loss::Note::loss(crate::loss::LossCode::AssumedEncoding, text) } else { @@ -173,7 +173,7 @@ pub(crate) fn encoding(cpg: Option<&[u8]>, ldid: u8, notes: &mut crate::loss::No }); notes.push(crate::loss::Note::loss( crate::loss::LossCode::AssumedEncoding, - format!("Shapefile: unsupported .dbf code page 0x{ldid:02X}{named}; using UTF-8"), + format!("unsupported .dbf code page 0x{ldid:02X}{named}; using UTF-8"), )); DbfEncoding::Utf8 } @@ -215,7 +215,7 @@ pub(crate) fn not_utf8_names_note(columns: &[usize], encoding: &str) -> Option = columns.iter().take(5).map(usize::to_string).collect(); let more = if columns.len() > 5 { format!(" and {} more", columns.len() - 5) } else { String::new() }; let text = format!( - "Shapefile: {what} read with U+FFFD in place of the bytes that can't be read, in {label} {}{more}; {}", + "{what} read with U+FFFD in place of the bytes that can't be read, in {label} {}{more}; {}", named.join(", "), cause(encoding) ); @@ -433,7 +433,7 @@ pub(crate) fn date(field: &[u8]) -> std::result::Result, ldid: u8, present: impl FnOnce() -> bool, notes: &mut crate::loss::Notes) { if cpg_encoding(cpg).is_none() && ldid_code_page(ldid).and_then(DbfEncoding::from_number).is_none() && present() { - notes.push(crate::loss::Note::plain("Shapefile: an unused .cst sidecar exists; RustGIS does not read .cst encoding declarations. If its encoding label is trusted, write that label to a same-basename .cpg (replacing an unusable declaration if present) and reopen the data; otherwise confirm the encoding with the provider")); + notes.push(crate::loss::Note::plain("an unused .cst sidecar exists; RustGIS does not read .cst encoding declarations. If its encoding label is trusted, write that label to a same-basename .cpg (replacing an unusable declaration if present) and reopen the data; otherwise confirm the encoding with the provider")); } } @@ -452,20 +452,25 @@ pub(crate) fn has_cst(path: &std::path::Path) -> bool { /// Every ASCII case of the optional CST hint's extension. const CST_SPELLINGS: [&str; 8] = ["cst", "CST", "Cst", "cSt", "csT", "CSt", "CsT", "cST"]; -/// A code-page label should be a few bytes. Bound reads even for a hostile sidecar. -pub(crate) fn read_cpg(path: &std::path::Path, notes: &mut crate::loss::Notes) -> crate::Result>> { - cpg_result(try_read_cpg(path), notes) +/// A code-page label should be a few bytes. Bound reads even for a hostile sidecar. A `.cpg` that +/// can't be read is said once, with what is used instead: the `.dbf`'s code page (its language +/// driver `ldid`), or UTF-8, assumed, when it names none. +pub(crate) fn read_cpg(path: &std::path::Path, ldid: u8, notes: &mut crate::loss::Notes) -> crate::Result>> { + cpg_result(try_read_cpg(path), ldid, notes) } /// An optional declaration can fall back after an I/O failure, but Cancel must end the read. -fn cpg_result(result: std::io::Result>>, notes: &mut crate::loss::Notes) -> crate::Result>> { +fn cpg_result(result: std::io::Result>>, ldid: u8, notes: &mut crate::loss::Notes) -> crate::Result>> { match result.map_err(crate::DataError::from) { Ok(bytes) => Ok(bytes), Err(crate::DataError::Io(e)) => { - // Why it can't be used; what the encoding falls back to, and whether that is assumed, - // is said with the `.dbf`'s code page in hand ([`encoding`]), as for one that can't be. - notes.push(crate::loss::Note::plain(format!("could not read the .cpg ({e})"))); - Ok(Some(Vec::new())) + let text = format!("could not read the .cpg ({e}); using the .dbf code page if RustGIS reads it, otherwise UTF-8"); + notes.push(if ldid == 0 { + crate::loss::Note::loss(crate::loss::LossCode::AssumedEncoding, text) + } else { + crate::loss::Note::plain(text) + }); + Ok(None) } Err(e) => Err(e), } @@ -541,14 +546,17 @@ mod tests { fn cpg_cancellation_is_not_an_encoding_fallback() { let mut notes = crate::loss::Notes::new(); let cancelled = std::io::Error::other(crate::DataError::Cancelled); - assert!(matches!(cpg_result(Err(cancelled), &mut notes), Err(crate::DataError::Cancelled))); + assert!(matches!(cpg_result(Err(cancelled), 0, &mut notes), Err(crate::DataError::Cancelled))); assert!(notes.is_empty()); let unreadable = std::io::Error::new(std::io::ErrorKind::PermissionDenied, "permission denied"); - assert_eq!(cpg_result(Err(unreadable), &mut notes).unwrap(), Some(Vec::new())); + assert_eq!(cpg_result(Err(unreadable), 0, &mut notes).unwrap(), None); assert_eq!(notes.len(), 1); - assert_eq!(notes[0].text, "could not read the .cpg (permission denied)"); + assert_eq!( + notes[0].text, + "could not read the .cpg (permission denied); using the .dbf code page if RustGIS reads it, otherwise UTF-8" + ); notes.clear(); - assert_eq!(cpg_result(Ok(None), &mut notes).unwrap(), None); + assert_eq!(cpg_result(Ok(None), 0, &mut notes).unwrap(), None); assert!(notes.is_empty()); } @@ -584,28 +592,35 @@ mod tests { let path = dir.path().join("places.dbf"); let cpg = path.with_extension("cpg"); assert!(Command::new("mkfifo").arg(&cpg).status().unwrap().success()); - assert_eq!(read_cpg(&path, &mut crate::loss::Notes::new()).unwrap(), Some(Vec::new())); + // No label, and one note saying so. + let unusable = |path: &std::path::Path| { + let mut notes = crate::loss::Notes::new(); + let read = read_cpg(path, 0, &mut notes).unwrap(); + assert_eq!(notes.len(), 1, "{notes:?}"); + read + }; + assert_eq!(unusable(&path), None); // A rejected spelling must not hide a later regular one. // A case-insensitive filesystem gives this spelling to the FIFO itself. if !path.with_extension("CpG").exists() { std::fs::write(path.with_extension("CpG"), b"1252").unwrap(); - assert_eq!(read_cpg(&path, &mut crate::loss::Notes::new()).unwrap(), Some(b"1252".to_vec())); + assert_eq!(read_cpg(&path, 0, &mut crate::loss::Notes::new()).unwrap(), Some(b"1252".to_vec())); std::fs::remove_file(path.with_extension("CpG")).unwrap(); } std::fs::remove_file(&cpg).unwrap(); let socket = std::os::unix::net::UnixListener::bind(&cpg).unwrap(); - assert_eq!(read_cpg(&path, &mut crate::loss::Notes::new()).unwrap(), Some(Vec::new())); + assert_eq!(unusable(&path), None); drop(socket); std::fs::remove_file(&cpg).unwrap(); std::fs::create_dir(&cpg).unwrap(); - assert_eq!(read_cpg(&path, &mut crate::loss::Notes::new()).unwrap(), Some(Vec::new())); + assert_eq!(unusable(&path), None); std::fs::remove_dir(&cpg).unwrap(); std::os::unix::fs::symlink("/dev/zero", &cpg).unwrap(); - assert_eq!(read_cpg(&path, &mut crate::loss::Notes::new()).unwrap(), Some(Vec::new())); + assert_eq!(unusable(&path), None); std::fs::remove_file(&cpg).unwrap(); std::fs::write(dir.path().join("label"), b"1252").unwrap(); std::os::unix::fs::symlink("label", &cpg).unwrap(); - assert_eq!(read_cpg(&path, &mut crate::loss::Notes::new()).unwrap(), Some(b"1252".to_vec())); + assert_eq!(read_cpg(&path, 0, &mut crate::loss::Notes::new()).unwrap(), Some(b"1252".to_vec())); return; } let mut child = Command::new(std::env::current_exe().unwrap()) @@ -762,12 +777,12 @@ mod tests { assert!(matches!(encoding(None, 0x6C, &mut notes), DbfEncoding::Utf8)); assert_eq!( notes.texts().collect::>(), - ["Shapefile: unsupported .dbf code page 0x6C (code page 863, DOS French Canadian); using UTF-8"] + ["unsupported .dbf code page 0x6C (code page 863, DOS French Canadian); using UTF-8"] ); assert_eq!(notes[0].loss, Some(crate::loss::LossCode::AssumedEncoding)); let mut notes = crate::loss::Notes::new(); encoding(None, 0xFF, &mut notes); - assert_eq!(notes.texts().collect::>(), ["Shapefile: unsupported .dbf code page 0xFF; using UTF-8"]); + assert_eq!(notes.texts().collect::>(), ["unsupported .dbf code page 0xFF; using UTF-8"]); assert_eq!(notes[0].loss, Some(crate::loss::LossCode::AssumedEncoding)); } @@ -853,11 +868,11 @@ mod tests { let one = not_utf8_names_note(&[3], "UTF-8").unwrap(); assert_eq!(one.loss, Some(crate::loss::LossCode::ChangedEncoding)); let one = one.as_str(); - assert!(one.starts_with("Shapefile: 1 field name isn't valid UTF-8 and was read with U+FFFD"), "{one}"); + assert!(one.starts_with("1 field name isn't valid UTF-8 and was read with U+FFFD"), "{one}"); assert!(one.contains("in field 3;"), "{one}"); let two = not_utf8_names_note(&[3, 7], "UTF-8").unwrap(); let two = two.as_str(); - assert!(two.starts_with("Shapefile: 2 field names aren't valid UTF-8 and were read with U+FFFD"), "{two}"); + assert!(two.starts_with("2 field names aren't valid UTF-8 and were read with U+FFFD"), "{two}"); assert!(two.contains("in fields 3, 7;"), "{two}"); assert!(two.ends_with(NO_OTHER_ENCODING), "{two}"); let many = not_utf8_names_note(&[1, 2, 3, 4, 5, 6, 7], "UTF-8").unwrap(); @@ -867,7 +882,7 @@ mod tests { assert_eq!( not_utf8_names_note(&[1], "Big5").as_ref().map(crate::loss::Note::as_str), Some( - "Shapefile: 1 field name isn't valid Big5 and was read with U+FFFD in place of the bytes that can't be read, in field 1; the .cpg or the .dbf's language driver declares Big5" + "1 field name isn't valid Big5 and was read with U+FFFD in place of the bytes that can't be read, in field 1; the .cpg or the .dbf's language driver declares Big5" ) ); } diff --git a/crates/data/src/filegdb.rs b/crates/data/src/filegdb.rs index 38d5841277..4f02e8abe9 100644 --- a/crates/data/src/filegdb.rs +++ b/crates/data/src/filegdb.rs @@ -390,6 +390,8 @@ fn read_table(name: &str, t: &[u8], x: &[u8], wkid: Option) -> Result) -> Result beyond += usize::from(e.beyond_lonlat()), + Some(e) => { + placed += 1; + beyond += usize::from(e.beyond_lonlat()); + } None => unprojected += 1, } } @@ -475,14 +480,8 @@ fn read_table(name: &str, t: &[u8], x: &[u8], wkid: Option) -> Result 0 { - report - .messages - .push(if unprojected == 1 { - "one feature has a place that can't be given in longitude/latitude (coordinates outside its coordinate system): it is kept as the file holds it, but doesn't draw".to_string() - } else { - format!("{unprojected} features have a place that can't be given in longitude/latitude (coordinates outside their coordinate system): they are kept as the file holds them, but don't draw") - }); + if let Some(c) = crs.filter(|_| to_lonlat.is_some()) { + report.messages.extend(crate::io::kept_unplaced_note("features", unprojected, placed == 0, c)); } if zm { // The table declares them for every shape. diff --git a/crates/data/src/filegdb/tests.rs b/crates/data/src/filegdb/tests.rs index 77ebc8323a..28448df7ed 100644 --- a/crates/data/src/filegdb/tests.rs +++ b/crates/data/src/filegdb/tests.rs @@ -571,9 +571,25 @@ fn coordinates_that_cant_be_converted_are_said() { assert!(rows[0].geometry.is_some() && rows[1].geometry.is_some(), "{:?}", rows[1].geometry); assert!(!ds.crs_incomplete); assert!( - report.messages.iter().any(|m| m.starts_with("one feature has a place that can't be given in longitude/latitude")), + report + .messages + .iter() + .any(|m| m.starts_with("one of the features has a place in EPSG:3035 that can't be given in longitude/latitude")), "{report:?}" ); + // None of them placed: the system doesn't seem to be theirs, which Define Projection can set. + let all_out = vec![vec![V::Blob(polygon(&square(9e8, 9e8, 10.0))), V::Text(Some("out"))]]; + let files = geodatabase(vec![("T", table(4, &fields, &all_out))]); + let layers = read_files(&files).unwrap(); + assert!( + layers[0] + .1 + .messages + .iter() + .any(|m| m.starts_with("none of the features has a place") && m.contains("Define Projection can set the right one")), + "{:?}", + layers[0].1 + ); } #[test] diff --git a/crates/data/src/gml.rs b/crates/data/src/gml.rs index 811096f99e..0f632a577c 100644 --- a/crates/data/src/gml.rs +++ b/crates/data/src/gml.rs @@ -778,7 +778,7 @@ pub(crate) fn read_with_members(file_name: &str, bytes: &[u8], application_membe let unread_names = kind.unread_names.said(); let (mut outside, mut null_text) = (false, Vec::new()); // Features with a place the file's system can't give in longitude/latitude, kept missing. - let (mut unplaced, mut beyond) = (0usize, 0usize); + let (mut unplaced, mut beyond, mut placed) = (0usize, 0usize, 0usize); // Held as the file holds its coordinates, in its own system (in the axis order RustGIS // gives every system's), when RustGIS converts it. if let Some((Some(_), _)) = &transform @@ -814,6 +814,7 @@ pub(crate) fn read_with_members(file_name: &str, bytes: &[u8], application_membe } }); unplaced += usize::from(missing.get()); + placed += usize::from(!missing.get()); e = lonlat.get(); // Converted, but beyond longitude/latitude: it draws out of place. beyond += usize::from(!missing.get() && e.beyond_lonlat()); @@ -847,7 +848,8 @@ pub(crate) fn read_with_members(file_name: &str, bytes: &[u8], application_membe ds.geometry_type = crate::io::dominant_type(&ds); // The file's notices go with its first layer only. let mut rep = if out.is_empty() { report.clone() } else { ReadReport::default() }; - // Features whose shape couldn't be read are said with their own feature type. + // Features whose shape couldn't be read are said with their own feature type. These rows + // are kept, without their geometry: `skipped` counts them as the reading corpus compares. rep.skipped = kind.skipped; if kind.skipped > 0 { let what = if kind.skipped == 1 { "feature" } else { "features" }; @@ -857,13 +859,8 @@ pub(crate) fn read_with_members(file_name: &str, bytes: &[u8], application_membe format!("{}: {} {what} had geometry that couldn't be read", ds.name, kind.skipped), )); } - if unplaced > 0 { - let what = if unplaced == 1 { "feature has" } else { "features have" }; - let system = file_srs.map_or_else(String::new, |(c, _)| format!(" in {}", c.label())); - rep.messages.push(format!( - "{}: {unplaced} {what} places{system} that can't be given in longitude/latitude; they are kept as the file holds them, but don't draw", - ds.name - )); + if let Some((c, _)) = file_srs { + rep.messages.extend(crate::io::kept_unplaced_note("features", unplaced, placed == 0, c).map(|n| format!("{}: {n}", ds.name))); } if let Some((c, _)) = file_srs { rep.messages.extend(crate::io::beyond_lonlat_note("features", beyond, c).map(|n| format!("{}: {n}", ds.name))); @@ -1216,9 +1213,19 @@ mod tests { assert_eq!(parts[0][0], Coord::new(500000.0, 4649776.0), "the file's numbers"); assert_eq!(parts[0][1], Coord::new(1e15, 4649776.0), "the file's numbers"); assert!(serde_json::to_string(ds).is_ok(), "saves"); + // None of its features has a place: the system doesn't seem to be theirs, which Define + // Projection can set. let said = &layers[0].1.messages; - assert!(said.iter().any(|m| m.contains("1 feature has places") && m.contains("kept as the file holds them")), "{said:?}"); + let all = ": none of the features has a place in longitude/latitude from"; + assert!(said.iter().any(|m| m.contains(all) && m.contains("Define Projection can set the right one")), "{said:?}"); assert_eq!(ds.in_lonlat_leaving_out().unwrap().1, 1); + // Beside one with a place, it is counted alone. + let two = gml.replace("", r#"500000,4649776 500100,4649776 +"#); + let said = read("r.gml", two.as_bytes()).unwrap()[0].1.messages.clone(); + let one = ": one of the features has a place in"; + assert!(said.iter().any(|m| m.contains(one) && m.contains("it is kept as the file holds it, but doesn't draw")), "{said:?}"); + assert!(said.iter().all(|m| !m.contains("Define Projection")), "{said:?}"); } /// A place a file's system converts to beyond longitude/latitude (Web Mercator a billion diff --git a/crates/data/src/io.rs b/crates/data/src/io.rs index d92e38ddd5..078460e495 100644 --- a/crates/data/src/io.rs +++ b/crates/data/src/io.rs @@ -531,9 +531,10 @@ pub fn read_path(path: &Path) -> Result<(Dataset, ReadReport)> { "dbf" => { check_size(path)?; let mut notes = crate::loss::Notes::new(); - let cpg = crate::dbf::read_cpg(path, &mut notes)?; let bytes = std::fs::read(path)?; - crate::dbf::unused_cst(cpg.as_deref(), bytes.get(29).copied().unwrap_or(0), || crate::dbf::has_cst(path), &mut notes); + let ldid = bytes.get(29).copied().unwrap_or(0); + let cpg = crate::dbf::read_cpg(path, ldid, &mut notes)?; + crate::dbf::unused_cst(cpg.as_deref(), ldid, || crate::dbf::has_cst(path), &mut notes); let (ds, mut report) = read_dbf(bytes, cpg.as_deref(), &name, &mut csv_memory_budget())?; report.messages.extend(notes.prefixed(&name)); (ds, report) @@ -879,11 +880,14 @@ fn project_pieces_leaving_out( } } match done.lock() { - Ok(mut d) => { - if let Some(slot) = d.get_mut(k) { - *slot = (unplaced, placed); + Ok(mut d) => match d.get_mut(k) { + Some(slot) => *slot = (unplaced, placed), + // Never so (a slot for each piece); said rather than dropping its count. + None => { + stop(DataError::Format("a piece of the features had no place to record its count".into())); + break; } - } + }, Err(_) => { stop(poisoned()); break; @@ -2240,7 +2244,7 @@ pub(crate) fn places_lonlat_extent(g: &Geometry, t: &crate::raster::Transformer) /// host's layers) (#2032 C2f-4b). `all` when none of the file's has a place there: then its system /// doesn't seem to match its coordinates, and Define Projection can set the one that does, as /// nothing was lost. `None` for none. -pub(crate) fn kept_unplaced_note(what: &str, n: usize, all: bool, crs: Crs) -> Option { +pub fn kept_unplaced_note(what: &str, n: usize, all: bool, crs: Crs) -> Option { (n > 0).then(|| { if all { format!( @@ -4118,7 +4122,7 @@ impl CsvWriter { } } -/// The error of a CSV writer used after a write of its failed. +/// The error of a CSV writer used after one of its writes failed. fn csv_stopped() -> DataError { DataError::Format("CSV: writing stopped at an earlier error".into()) } @@ -4155,14 +4159,14 @@ pub fn read_shapefile_in(path: &Path, name: &str, crs: Option) -> Result<(D check_size_with(&shx, shapefile_size_error)?; } let mut notes = crate::loss::Notes::new(); - let parts = ShapefileParts { - shp: crate::provenance::read(path)?, - shx: if shx.is_file() { Some(crate::provenance::read(shx)?) } else { None }, - dbf: crate::provenance::read(dbf)?, - prj: crate::raster::read_prj(path), - cpg: crate::dbf::read_cpg(path, &mut notes)?, - }; - crate::dbf::unused_cst(parts.cpg.as_deref(), parts.dbf.get(29).copied().unwrap_or(0), || crate::dbf::has_cst(path), &mut notes); + let shp = crate::provenance::read(path)?; + let shx = if shx.is_file() { Some(crate::provenance::read(shx)?) } else { None }; + let dbf = crate::provenance::read(dbf)?; + // The `.dbf`'s language driver, for what an unreadable `.cpg` falls back to. + let ldid = dbf.get(29).copied().unwrap_or(0); + let cpg = crate::dbf::read_cpg(path, ldid, &mut notes)?; + crate::dbf::unused_cst(cpg.as_deref(), ldid, || crate::dbf::has_cst(path), &mut notes); + let parts = ShapefileParts { shp, shx, dbf, prj: crate::raster::read_prj(path), cpg }; let (ds, mut report) = read_shapefile_parts(parts, name, crs)?; report.messages.extend(notes.prefixed(name)); Ok((ds, report)) @@ -4402,6 +4406,14 @@ pub fn read_zip_layers(file_name: &str, bytes: &[u8], opts: &CsvOptions) -> Resu read_zip_layers_budget(file_name, bytes, opts, &mut csv_memory_budget()) } +/// Whether a zip member's path ends as a vector tile set's do, `…///.pbf`. +fn is_tile_path(n: &str) -> bool { + let digits = |p: &str| !p.is_empty() && p.bytes().all(|b| b.is_ascii_digit()); + let mut parts = n.rsplit('/'); + let y = parts.next().and_then(|leaf| leaf.get(..leaf.len().saturating_sub(4)).filter(|_| leaf.to_ascii_lowercase().ends_with(".pbf"))); + y.is_some_and(digits) && parts.next().is_some_and(digits) && parts.next().is_some_and(digits) +} + /// [`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, &CsvOptions { crs, ..Default::default() }, budget)? @@ -4410,8 +4422,8 @@ fn read_zip_budget(file_name: &str, bytes: &[u8], crs: Option, budget: &mut .collect()) } -/// Delimited, dBASE and workbook members share one allowance, including gzip members whose text -/// is nested in ZIP. +/// Delimited, dBASE, workbook, LandXML and multi-layer members (KML, GPX and the like) share one +/// allowance, including gzip members whose text is nested in ZIP. fn read_zip_layers_budget(file_name: &str, bytes: &[u8], opts: &CsvOptions, budget: &mut usize) -> Result> { let crs = opts.crs; // The tables' options: not every member holds the columns given. @@ -4432,6 +4444,10 @@ fn read_zip_layers_budget(file_name: &str, bytes: &[u8], opts: &CsvOptions, budg // A `.pbf` is read only as an OpenStreetMap extract (`.osm.pbf`): a vector tile set's // `z/x/y.pbf` files aren't extracted at all. let geodatabase = std::cell::Cell::new(false); + // Members of formats read when added by themselves that aren't read from a zip, said: a zip + // inside the zip, and a `.pbf` that isn't an extract (a service's page). A tile set's + // `z/x/y.pbf` files are left out without a word. Names only. + let left_inside: std::cell::RefCell> = std::cell::RefCell::new(Vec::new()); let cst_names = std::cell::RefCell::new(std::collections::BTreeSet::new()); let wanted = |n: &str| { if crate::progress::check().is_err() { @@ -4446,6 +4462,13 @@ fn read_zip_layers_budget(file_name: &str, bytes: &[u8], opts: &CsvOptions, budg cst_names.borrow_mut().insert(lower(n)); return false; // Presence only: never inflate or validate this optional member. } + if !is_resource_fork(n) { + if e == "zip" { + left_inside.borrow_mut().push(format!("{n} (a zip inside the zip: extract it and add it by itself)")); + } else if e == "pbf" && !lower(n).ends_with(".osm.pbf") && !is_tile_path(n) { + left_inside.borrow_mut().push(format!("{n} (a .pbf that isn't an OpenStreetMap extract: extract it and add it by itself)")); + } + } !is_resource_fork(n) && (matches!(e.as_str(), "shp" | "shx" | "dbf" | "prj" | "cpg" | "mid") || (e == "pbf" && lower(n).ends_with(".osm.pbf")) @@ -4466,7 +4489,7 @@ fn read_zip_layers_budget(file_name: &str, bytes: &[u8], opts: &CsvOptions, budg let cst_names = cst_names.into_inner(); 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(); + let mut skipped: Vec = left_inside.into_inner(); // 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 { @@ -4558,6 +4581,8 @@ fn read_zip_layers_budget(file_name: &str, bytes: &[u8], opts: &CsvOptions, budg reads.into_iter().map(|(dataset, report)| LayerRead { dataset, report, styles: Vec::new() }).collect::>() }; let mut table = false; + // The ground overlays of a KML member, said once the member is read. + let mut member_overlays = None; // A city model has many layers. let read = if ext_of(&n) == "dbf" { let cpg = take(&mut entries, &stem(&n), "cpg").map(|(_, b)| b); @@ -4582,7 +4607,11 @@ fn read_zip_layers_budget(file_name: &str, bytes: &[u8], opts: &CsvOptions, budg table = true; // 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, &member).and_then(|r| charge_retained([&r.0], leaf, budget).map(|()| plain(vec![r]))) + // Its note of the other sheets names the member, and "layer" picks among the zip's + // layers, not its sheets. + let hint = "unzip it and add the workbook by itself to pick one with \"layer\""; + crate::sheets::read_with_hint(&b, name, None, &member, &format!("{n}: "), hint) + .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" @@ -4601,7 +4630,7 @@ fn read_zip_layers_budget(file_name: &str, bytes: &[u8], opts: &CsvOptions, budg 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)); + member_overlays = Some(found.len() + undrawn + over_budget); } Ok(_) => {} // Overlays that can't even be counted (a KMZ entry too large to expand) are @@ -4614,12 +4643,17 @@ fn read_zip_layers_budget(file_name: &str, bytes: &[u8], opts: &CsvOptions, budg 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 member the allowance refuses isn't named for its overlays, only as skipped. + charge_retained_with(layers.iter().map(|l| &l.dataset), styles, leaf, budget).inspect_err(|_| member_overlays = None)?; Ok(layers) }) } else { read_bytes(leaf, &b).map(|r| plain(vec![r])) }; + // A document of overlays alone gives no layer (an error), and its overlays are said. + if let Some(count) = member_overlays { + overlays_left.push((n.clone(), count)); + } match read { Ok(layers) => { for mut layer in layers { @@ -4663,10 +4697,8 @@ fn read_zip_layers_budget(file_name: &str, bytes: &[u8], opts: &CsvOptions, budg 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(", ") - ) + let what = if count == 1 { "ground overlay (picture) isn't" } else { "ground overlays (pictures) aren't" }; + format!("{count} {what} 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("; ")) }; @@ -4798,7 +4830,8 @@ fn dbf_reader(mut bytes: Vec, cpg: Option<&[u8]>, name: &str) -> Result "csv" => { // Of the coordinates the file is written in: longitude/latitude, or another // geographic system's, whose points alone are converted to be checked (no copy of the - // layer); a projected system's aren't degrees, so aren't checked as such. + // layer). A projected system's, and the layer's own geographic one, are counted as + // they are held; for a projected one the degree count isn't read + // (`coordinates_note_in`). let losses = if crs == Crs::LonLat { let to = ds.lonlat_conversion().map_err(DataError::of_conversion)?; match csv_losses_in_lonlat(ds, &to)? { @@ -6461,8 +6496,8 @@ fn run_of(features: &[crate::Feature], most: usize, vertices: usize) -> Result`, which reading drops, so the column and its values are gone -/// (#2415). A field with no value written is said by [`kml_empty_fields_note`]. +/// written with its name as it is (``, or spaces or a tab), which reading drops, so +/// the column and its values are gone (#2415). A field with no value written is said by [`kml_empty_fields_note`]. fn kml_blank_names_note(ds: &Dataset, placed: &[bool], target: &str) -> Result> { let blank: Vec = ds.fields.iter().enumerate().filter(|(_, f)| f.name.trim().is_empty()).map(|(k, _)| k).collect(); if blank.is_empty() { @@ -7043,9 +7078,9 @@ const SHAPEFILE_HEADER: usize = 100; const SHX_RECORD: usize = 8; /// The bytes `g`'s record adds to a `.shp` in a layer of type `gt` (its `.shx` entry is -/// [`SHX_RECORD`] more), counted from -/// the vertices [`shapefile_parts_within`] keeps, without copying them; `None` for one it leaves -/// out. `multi_points` says the layer's points are written as multipoints. +/// [`SHX_RECORD`] more), counted from the vertices [`shapefile_parts_within`] keeps, without +/// copying them; `None` for one it leaves out. `multi_points` says the layer's points are written +/// as multipoints. fn shapefile_record_bytes(g: &Geometry, gt: GeometryType, multi_points: bool) -> Option { if !shapefile_keeps(Some(g), gt) { return None; @@ -10394,6 +10429,22 @@ mod tests { assert!(e.contains("a.xlsx") && e.contains("memory budget"), "{e}"); } + /// A zipped workbook of several sheets names the member and says how to pick another sheet + /// (unzipped: `"layer"` inside a zip picks among its layers); added by itself, the advice is + /// `"layer"`. + #[test] + fn a_zipped_workbook_names_itself_and_how_to_pick_a_sheet() { + let book = crate::sheets::xlsx(&[("First", &[&["id", "x", "y"], &["1", "1", "2"]]), ("Second", &[&["id"], &["2"]])]); + let zip = crate::zip::write(&[("book.xlsx".into(), book.clone())]).unwrap(); + let read = read_zip_budget("books.zip", &zip, None, &mut { usize::MAX }).unwrap(); + let said: Vec<&str> = read[0].1.messages.texts().filter(|m| m.contains("more sheets")).collect(); + assert_eq!(said.len(), 1, "{:?}", read[0].1.messages); + assert!(said[0].starts_with("book.xlsx: ") && said[0].contains("Second"), "{said:?}"); + assert!(said[0].ends_with("unzip it and add the workbook by itself to pick one with \"layer\""), "{said:?}"); + let (_, alone) = crate::sheets::read(&book, "book", None, &CsvOptions::default()).unwrap(); + assert!(alone.messages.says("the workbook has more sheets (Second): add one with \"layer\""), "{:?}", alone.messages); + } + /// 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] @@ -10403,7 +10454,7 @@ mod tests { 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") && m.contains("a.kml (1)")), + alone[0].1.messages.iter().any(|m| m.contains("1 ground overlay (picture) isn't drawn") && m.contains("a.kml (1)")), "{:?}", alone[0].1.messages ); @@ -10414,6 +10465,10 @@ mod tests { 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); + // The member refused isn't named for its overlays: only the one read is. + let overlays: Vec<&str> = limited[0].1.messages.texts().filter(|m| m.contains("ground overlay")).collect(); + assert!(overlays.len() == 1 && overlays[0].contains("1 ground overlay (picture) isn't drawn"), "{overlays:?}"); + assert!(overlays[0].contains("a.kml (1)") && !overlays[0].contains("b.kml"), "{overlays:?}"); 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. @@ -10429,10 +10484,14 @@ mod tests { 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); + assert!( + read[0].1.messages.iter().any(|m| m.contains("1 ground overlay (picture) isn't") && 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}"); + assert!(e.contains("1 ground overlay (picture) isn't") && 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())); @@ -10958,6 +11017,17 @@ mod tests { let layers = read_zip("x.zip", &crate::zip::write(&with_tiles).unwrap()).unwrap(); assert_eq!(layers.len(), 2); assert!(layers[0].1.messages.iter().all(|m| !m.contains(".pbf")), "{:?}", layers[0].1.messages); + // A zip inside the zip and a .pbf that isn't an extract (a service's page) are named, not + // left out without a word. + let mut with_inner = entries.clone(); + with_inner.push(("inner.zip".to_string(), crate::zip::write(&[("a.csv".to_string(), b"x,y\n1,2\n".to_vec())]).unwrap())); + with_inner.push(("page.pbf".to_string(), vec![0x1a, 2, 0, 0])); + let layers = read_zip("x.zip", &crate::zip::write(&with_inner).unwrap()).unwrap(); + assert_eq!(layers.len(), 2); + let said = layers[0].1.messages.texts().collect::>().join(" | "); + assert!(said.contains("inner.zip (a zip inside the zip: extract it and add it by itself)"), "{said}"); + assert!(said.contains("page.pbf (a .pbf that isn't an OpenStreetMap extract: extract it and add it by itself)"), "{said}"); + assert!(is_tile_path("tiles/3/1/2.pbf") && !is_tile_path("page.pbf") && !is_tile_path("a/b/1.pbf")); // Nothing readable at all is an error. let only_shp: Vec<_> = entries.iter().filter(|(n, _)| n.ends_with(".SHP")).cloned().collect(); assert!(read_zip("x.zip", &crate::zip::write(&only_shp).unwrap()).is_err()); diff --git a/crates/data/src/kml.rs b/crates/data/src/kml.rs index 1a5030c4eb..561e1b52da 100644 --- a/crates/data/src/kml.rs +++ b/crates/data/src/kml.rs @@ -373,7 +373,12 @@ impl GeometryLosses { // Each is a part left out of a kept placemark's geometry. for (count, one, many, code) in [ (self.unreadable.get(), "unreadable KML coordinate tuple", "unreadable KML coordinate tuples", DroppedGeometry), - (self.holes, "unreadable KML polygon hole", "unreadable KML polygon holes", DroppedRing), + ( + self.holes, + "KML polygon hole with fewer than three usable coordinates", + "KML polygon holes with fewer than three usable coordinates", + DroppedRing, + ), ( self.short_lines, "KML line part with fewer than two usable coordinates", @@ -884,7 +889,7 @@ mod tests { layers[0].report.messages.texts().collect::>(), [ "a: 2 unreadable KML coordinate tuples were left out", - "a: 1 unreadable KML polygon hole was left out", + "a: 1 KML polygon hole with fewer than three usable coordinates was left out", "a: 2 KML polygons without a usable outer ring were left out" ] ); @@ -982,7 +987,7 @@ mod tests { messages, [ "a: 2 unreadable KML coordinate tuples were left out", - "a: 1 unreadable KML polygon hole was left out", + "a: 1 KML polygon hole with fewer than three usable coordinates was left out", "a: 1 KML line part with fewer than two usable coordinates was left out", "a: 2 excess KML Point coordinate tuples were left out" ] diff --git a/crates/data/src/landxml.rs b/crates/data/src/landxml.rs index 9f695caa6a..b26f9a29db 100644 --- a/crates/data/src/landxml.rs +++ b/crates/data/src/landxml.rs @@ -87,6 +87,11 @@ pub fn read(file_name: &str, bytes: &[u8], crs: Option) -> Result, max_faces: usize) -> Result> { + // Read as added, on the desktop's UI thread: within [`crate::io::BYTES_FLOOR`] by every route + // (a coordinate system given, or a zip member), as `read_layers` holds it. + if bytes.len() as u64 > crate::io::BYTES_FLOOR { + return Err(DataError::Format(crate::io::file_size_error(file_name, crate::io::BYTES_FLOOR))); + } let name = std::path::Path::new(file_name).file_stem().and_then(|s| s.to_str()).unwrap_or("landxml").to_string(); let text = std::str::from_utf8(bytes).map_err(|_| DataError::Format(format!("{file_name} is not UTF-8 text")))?; let opts = ParsingOptions { allow_dtd: false, nodes_limit: crate::io::XML_NODES, ..ParsingOptions::default() }; @@ -375,6 +380,15 @@ fn read_with_max_faces(file_name: &str, bytes: &[u8], crs: Option, max_face mod tests { use super::*; + /// A LandXML file past the limit of files read as added is refused with a coordinate system + /// given too, as `read_layers` refuses it without one. + #[test] + fn landxml_past_the_floor_is_refused_with_a_crs_given() { + let past_floor = vec![b' '; crate::io::BYTES_FLOOR as usize + 1]; + let e = read("site.landxml", &past_floor, Crs::from_epsg(2056)).err().map(|e| e.to_string()); + assert_eq!(e, Some(crate::io::file_size_error("site.landxml", crate::io::BYTES_FLOOR))); + } + #[test] fn xml_loss_parcels_without_coordgeom_are_counted() { let xml = br#"1 2"#; diff --git a/crates/data/src/lib.rs b/crates/data/src/lib.rs index 7c37513a9f..16ec9201ce 100644 --- a/crates/data/src/lib.rs +++ b/crates/data/src/lib.rs @@ -818,6 +818,8 @@ impl Serialize for Dataset { /// What a reader skipped. #[derive(Clone, Debug, Default, PartialEq)] pub struct ReadReport { + /// Features left out, or kept without the geometry that couldn't be read (as GML keeps + /// them); the messages say which. pub skipped: usize, /// What the read says, each loss with its code ([`loss::Note`]). pub messages: loss::Notes, diff --git a/crates/data/src/loss.rs b/crates/data/src/loss.rs index 62a4a050f4..105a73fbcc 100644 --- a/crates/data/src/loss.rs +++ b/crates/data/src/loss.rs @@ -87,7 +87,7 @@ loss_codes! { "dropped.value", Dropped, "A value could not be kept and was read or written as empty (null). Examples are spreadsheet error cells, text in a date or yes/no column, and a result that is not a number.", - "Correct the value or use a destination field that can hold it.", + "Correct the value in the source, or, on export, use a destination field that can hold it.", ), DroppedCalculationResult => ( "dropped.calculation-result", @@ -105,7 +105,7 @@ loss_codes! { "dropped.crs-name", Dropped, "A coordinate system's name or definition could not be written with the data, so the file holds the coordinates without it.", - "Keep the source file's coordinate system definition with the export, or export in WGS 84, which every format can name." + "On reading, give the coordinate system in a form RustGIS reads (\"crs\" when adding the data, or Define Projection); on export, keep the source's coordinate system definition with it, or export in WGS 84, which every format can name." ), DroppedFeature => ( "dropped.feature", @@ -117,13 +117,13 @@ loss_codes! { "dropped.geometry", Dropped, "A feature's geometry could not be read or written. The feature was kept without its place, or the place was left out.", - "Correct the geometry in the source, or give the coordinate system its coordinates are in." + "Correct the geometry in the source; when the notice names a coordinate system, give the one its coordinates are in." ), DroppedOverLimit => ( "dropped.over-limit", Dropped, "RustGIS read only part of the data because it is past a size limit.", - "Read less at once, such as by filtering or clipping the source first." + "Read less at once, such as by filtering or clipping the source first, or keep fewer fields (columns) in it." ), ChangedTruncated => ( "changed.truncated", @@ -141,7 +141,7 @@ loss_codes! { "changed.cut", Changed, "Text was cut short to fit a format or a limit.", - "Shorten the text to what the format holds (254 bytes for a Shapefile; nothing past a NUL character), or write to a format without the limit, such as GeoPackage." + "Shorten the text or name in the source; on export, to what the format holds (254 bytes for a Shapefile; nothing past a NUL character), or write to a format without the limit, such as GeoPackage." ), ChangedBody => ( "changed.body", @@ -153,7 +153,7 @@ loss_codes! { "changed.encoding", Changed, "Text that is not valid in the encoding it was read with was read with a replacement character in its place.", - "Put a .cpg file naming the file's own encoding beside it." + "Give the source's encoding in a form RustGIS reads: a .cpg beside a Shapefile or dBASE file, a DXF saved as UTF-8 or with its $DWGCODEPAGE, or a service that sends UTF-8." ), ChangedRounded => ( "changed.rounded", @@ -171,7 +171,7 @@ loss_codes! { "approximated.datum", Approximated, "A datum RustGIS does not shift was treated as WGS 84, so places may be a little off.", - "Export in the layer's own coordinate system, or give that system with a known transformation to WGS 84." + "On reading, give the coordinate system with a known transformation to WGS 84; on export, export in the layer's own coordinate system." ), ApproximatedCurve => ( "approximated.curve", diff --git a/crates/data/src/osm.rs b/crates/data/src/osm.rs index 7a68ca1354..eda1b0d86c 100644 --- a/crates/data/src/osm.rs +++ b/crates/data/src/osm.rs @@ -842,6 +842,8 @@ fn read_with_text_limit(file_name: &str, bytes: &[u8], text_limit: usize) -> Res let mut unsupported_members = 0u64; let mut short_ways = 0usize; let mut no_closed_outer = 0usize; + // Relations whose outer geometry is only in nested relations, which aren't read. + let mut nested_only = 0usize; // Ways in a multipolygon are drawn as its parts, not again on their own when their tags are // the relation's (as old-style multipolygons repeat them): only a way saying more is a // feature of its own. @@ -883,12 +885,15 @@ fn read_with_text_limit(file_name: &str, bytes: &[u8], text_limit: usize) -> Res let mut inner_ways = Vec::new(); let (mut relation_missing_members, mut relation_missing_rings, mut relation_unclosed) = (0usize, 0usize, 0usize); let mut relation_subrelations = 0usize; + // Sub-relation members that may hold the outer rings (any role but `inner`). + let mut outer_subrelations = 0usize; let mut unavailable_outer = false; // Places the member ways store themselves (LocationsOnWays), by node id. let mut local: HashMap = HashMap::new(); for (ty, m, role) in members { if *ty == 2 { relation_subrelations += 1; + outer_subrelations += usize::from(role != "inner"); continue; } if *ty != 1 { @@ -916,6 +921,8 @@ fn read_with_text_limit(file_name: &str, bytes: &[u8], text_limit: usize) -> Res }) .collect() }; + // Outer ways of its own, closed or not: then its outer isn't only in sub-relations. + let own_outer_ways = !outer_ways.is_empty(); let outer_rings = join_rings(outer_ways, &mut relation_unclosed); // Closed outer rings with no usable coordinates refer to unavailable nodes. unavailable_outer |= !outer_rings.is_empty(); @@ -924,6 +931,8 @@ fn read_with_text_limit(file_name: &str, bytes: &[u8], text_limit: usize) -> Res if outers.is_empty() { if unavailable_outer { missing += 1; + } else if outer_subrelations > 0 && !own_outer_ways { + nested_only += 1; } else { no_closed_outer += 1; } @@ -962,7 +971,7 @@ fn read_with_text_limit(file_name: &str, bytes: &[u8], text_limit: usize) -> Res } polys.push_next(Some(Geometry::Polygon(parts)), attrs(*id, t)); } - let mut report = ReadReport { skipped: missing + short_ways + no_closed_outer, ..ReadReport::default() }; + let mut report = ReadReport { skipped: missing + short_ways + no_closed_outer + nested_only, ..ReadReport::default() }; if osm.omitted_members > 0 { let members = if osm.omitted_members == 1 { "relation member" } else { "relation members" }; report.messages.push(crate::loss::Note::loss( @@ -983,6 +992,17 @@ fn read_with_text_limit(file_name: &str, bytes: &[u8], text_limit: usize) -> Res format!("{no_closed_outer} {subject} no usable closed outer ring"), )); } + if nested_only > 0 { + let subject = if nested_only == 1 { + "relation left out because its outer rings are" + } else { + "relations left out because their outer rings are" + }; + report.messages.push(crate::loss::Note::loss( + crate::loss::LossCode::DroppedFeature, + format!("{nested_only} {subject} in nested relations, which aren't read"), + )); + } if osm.capped { report .messages @@ -1003,7 +1023,7 @@ fn read_with_text_limit(file_name: &str, bytes: &[u8], text_limit: usize) -> Res parts.push(format!("{n} {} (omitted from multipolygons)", if n == 1 { "relation" } else { "relations" })); } format!( - "OSM tag/role text reached the {}-byte limit: {} ({} bytes of text and per-entry overhead left out)", + "OSM tag/role text reached its per-kind share (a third each for nodes, ways and relations) of the {}-byte limit: {} ({} bytes of text and per-entry overhead left out)", osm.text_limit, parts.join(", "), osm.text_capped_bytes, @@ -1021,8 +1041,8 @@ fn read_with_text_limit(file_name: &str, bytes: &[u8], text_limit: usize) -> Res for (count, one, many) in [ ( unsupported_members, - "OSM sub-relation member was omitted because nested relations are not supported", - "OSM sub-relation members were omitted because nested relations are not supported", + "OSM sub-relation member not merged into its parent (nested relations aren't supported; a multipolygon or boundary member the extract holds is drawn on its own)", + "OSM sub-relation members not merged into their parent (nested relations aren't supported; a multipolygon or boundary member the extract holds is drawn on its own)", ), ( missing_members, @@ -1397,13 +1417,30 @@ pub(crate) mod tests { assert_eq!(lossy[0].1.skipped, 0); assert_eq!( lossy[0].1.messages.texts().collect::>(), - ["1 OSM sub-relation member was omitted because nested relations are not supported"] + [ + "1 OSM sub-relation member not merged into its parent (nested relations aren't supported; a multipolygon or boundary member the extract holds is drawn on its own)" + ] ); assert!(lossy[1].1.messages.is_empty()); + // Its outer only in a sub-relation (role outer): said as nested. let omitted = - read("nested.pbf", &finite_member_arrays_file(ways, &[(200, &[8], &[201], &[2]), (201, &[7], &[101], &[1])])).unwrap(); + read("nested.pbf", &finite_member_arrays_file(ways, &[(200, &[7], &[201], &[2]), (201, &[7], &[101], &[1])])).unwrap(); assert_eq!(omitted[0].1.skipped, 1); - assert_eq!(omitted[0].1.messages.texts().collect::>(), ["1 relation left out because it has no usable closed outer ring"]); + assert_eq!( + omitted[0].1.messages.texts().collect::>(), + ["1 relation left out because its outer rings are in nested relations, which aren't read"] + ); + // An inner sub-relation, or an outer way of its own that never closes, doesn't show its + // outer is nested: said as having no usable closed outer ring. + let no_outer = "1 relation left out because it has no usable closed outer ring"; + let open: &[(u64, &[i64], bool)] = &[(100, &[1, 2, 3], false), (101, &[5, 6, 7, 5], false)]; + for (ways, relations) in [ + (ways, vec![(200u64, &[8u64][..], &[201i64][..], &[2u64][..]), (201, &[7], &[101], &[1])]), + (open, vec![(200, &[7, 7][..], &[100, 201][..], &[1, 2][..]), (201, &[7], &[101], &[1])]), + ] { + let read = read("nested.pbf", &finite_member_arrays_file(ways, &relations)).unwrap(); + assert!(read[0].1.messages.says(no_outer), "{:?}", read[0].1.messages); + } } /// Parallel member arrays must agree; valid geometry must not hide an unmatched tail. @@ -1764,7 +1801,7 @@ pub(crate) mod tests { assert_eq!( note.as_str(), format!( - "OSM tag/role text reached the 1800-byte limit: 9 tagged nodes (left out of points), 1 tagged way (omitted from lines/multipolygons), 1 relation (omitted from multipolygons) ({expected_bytes} bytes of text and per-entry overhead left out)" + "OSM tag/role text reached its per-kind share (a third each for nodes, ways and relations) of the 1800-byte limit: 9 tagged nodes (left out of points), 1 tagged way (omitted from lines/multipolygons), 1 relation (omitted from multipolygons) ({expected_bytes} bytes of text and per-entry overhead left out)" ) ); @@ -1846,7 +1883,7 @@ pub(crate) mod tests { assert_eq!( note.as_str(), format!( - "OSM tag/role text reached the 3000-byte limit: 1 tagged way (omitted from lines/multipolygons) ({expected} bytes of text and per-entry overhead left out)" + "OSM tag/role text reached its per-kind share (a third each for nodes, ways and relations) of the 3000-byte limit: 1 tagged way (omitted from lines/multipolygons) ({expected} bytes of text and per-entry overhead left out)" ) ); } @@ -1925,7 +1962,7 @@ pub(crate) mod tests { .find(|m| m.loss == Some(crate::loss::LossCode::DroppedOverLimit)) .expect("node cap notice must be emitted"); assert!(note.contains("9 tagged nodes (left out of points)"), "{note:?}"); - assert!(!note.contains("tagged way") && !note.contains("relation"), "{note:?}"); + assert!(!note.contains("tagged way") && !note.contains("(omitted from multipolygons)"), "{note:?}"); } /// The text budget follows the file's size between its floor and ceiling, so an ordinary diff --git a/crates/data/src/provenance.rs b/crates/data/src/provenance.rs index 08f76ec87c..a895e28983 100644 --- a/crates/data/src/provenance.rs +++ b/crates/data/src/provenance.rs @@ -146,7 +146,9 @@ fn folder(root: &Path) { let mut entries = match std::fs::read_dir(&dir) { Ok(entries) => entries, Err(e) => { - gap(format!("a folder inside couldn't be listed ({e}); its files aren't named")); + // The input itself, or a folder inside it. + let which = if depth == 0 { "the folder" } else { "a folder inside" }; + gap(format!("{which} couldn't be listed ({e}); its files aren't named")); continue; } }; @@ -477,6 +479,18 @@ mod tests { assert!(other.inputs().is_empty()); } + /// A folder input that can't be listed itself is marked as the folder, not a folder inside. + #[test] + fn a_folder_input_that_cant_be_listed_says_it_is_the_folder() { + let dir = tempfile::tempdir().unwrap(); + let scope = Capture::start(); + // Gone by the time it is walked: the folder given, not one inside, couldn't be listed. + folder(&dir.path().join("gone.gdb")); + let inputs = scope.inputs(); + let mark = inputs.iter().find_map(|i| i.incomplete.as_deref()).unwrap_or_default().to_string(); + assert!(mark.starts_with("the folder couldn't be listed ("), "{inputs:?}"); + } + /// A folder another program opens lists the files inside it, in name order and without a /// mark; one past the limits keeps what it lists and says why the rest aren't (#2639). #[test] diff --git a/crates/data/src/publish.rs b/crates/data/src/publish.rs index 79b5410ea5..4c0081e879 100644 --- a/crates/data/src/publish.rs +++ b/crates/data/src/publish.rs @@ -555,6 +555,9 @@ fn retain_source_numbers(parts: &mut [(&str, Vec)], original: &RawTable<'_>, }; let le16 = |at| bytes.get(at..at + 2).and_then(|v| <[u8; 2]>::try_from(v).ok()).map(u16::from_le_bytes).map(usize::from); let (Some(header), Some(stride)) = (le16(8), le16(10)) else { return Ok(()) }; + // Each numeric column's place in the original table, found once rather than for every row. + let source_of: Vec> = + columns.iter().map(|c| if matches!(c.ty, b'N' | b'F') { original.columns.iter().position(|old| old == c) } else { None }).collect(); let mut by_shape = std::collections::HashMap::>::new(); for (i, row) in source.features.iter().enumerate() { crate::progress::check()?; @@ -569,10 +572,7 @@ fn retain_source_numbers(parts: &mut [(&str, Vec)], original: &RawTable<'_>, for (column_index, column) in columns.iter().enumerate() { let start = header.checked_add(row_index.saturating_mul(stride)).and_then(|v| v.checked_add(offset)); offset = offset.saturating_add(usize::from(column.len)); - if !matches!(column.ty, b'N' | b'F') { - continue; - } - let Some(source_column) = original.columns.iter().position(|old| old == column) else { continue }; + let Some(Some(source_column)) = source_of.get(column_index).copied() else { continue }; let Some(old) = before.attrs.get(source_column) else { continue }; let Some(current) = row.attrs.get(column_index) else { continue }; if old != current || !matches!(old, Value::Int(_) | Value::Float(_)) { diff --git a/crates/data/src/query.rs b/crates/data/src/query.rs index f0e904ddde..2467369045 100644 --- a/crates/data/src/query.rs +++ b/crates/data/src/query.rs @@ -835,12 +835,11 @@ fn lex_first(s: &str, tolerant: bool, most: usize) -> Result { /// The token of a number literal, refusing one that can't be held exactly rather than rounding it. /// A literal of digits only is an exact `i64`; past `i64::MAX`, a decimal that holds it exactly, or -/// refused. Any other literal is a -/// decimal (`f64`), refused only when the decimal read would have other whole-number digits than -/// written (`9007199254740993.0`, `1.2345678901234567891e19`, `2.99999999999999999`); its -/// fraction digits round as any do. One that merely has no -/// exact binary form (`0.1`) or many fraction digits (`0.12345678901234567891`) is read as the -/// nearest decimal, as every number written in decimal is. +/// refused. Any other literal is a decimal (`f64`), refused only when the decimal read would have +/// other whole-number digits than written (`9007199254740993.0`, `1.2345678901234567891e19`, +/// `2.99999999999999999`); its fraction digits round as any do. One that merely has no exact +/// binary form (`0.1`) or many fraction digits (`0.12345678901234567891`) is read as the nearest +/// decimal, as every number written in decimal is. fn number_token(t: &str) -> Result { if t.bytes().all(|b| b.is_ascii_digit()) { if let Ok(i) = t.parse::() { diff --git a/crates/data/src/query/legacy.rs b/crates/data/src/query/legacy.rs index 36d96f1b03..dbd495dcad 100644 --- a/crates/data/src/query/legacy.rs +++ b/crates/data/src/query/legacy.rs @@ -1,7 +1,11 @@ //! The WHERE clause parser and evaluator as they were before the expression language, kept //! verbatim as the oracle of the differential tests (every clause it accepts must select the -//! same rows through the new one) but for the one rule the expression language changes: a NULL -//! in an IN list matches nothing, where the text `` once matched it. +//! same rows through the new one). Among the rules the expression language changes: a NULL in an +//! IN list matches nothing, where the text `` once matched it; a whole number within the +//! `i64` range is exact there, where this parser reads every number as `f64` and rounds it; and a +//! decimal literal (or a whole number past `i64`) whose whole-number digits a decimal read would +//! change (`9007199254740993.0`) is refused there, where this one rounds it (#3155). The +//! generated clauses of the differential tests use no literal where the two differ. use crate::{Dataset, Value}; diff --git a/crates/data/src/raster/cogwrite.rs b/crates/data/src/raster/cogwrite.rs index 75434d3487..7251976f81 100644 --- a/crates/data/src/raster/cogwrite.rs +++ b/crates/data/src/raster/cogwrite.rs @@ -283,13 +283,15 @@ fn block(r: &Raster, plan: &Plan, factor: usize, ox: usize, oy: usize, out: &mut let (x1, y1) = ((x0 + factor).min(w), (y0 + factor).min(h)); // With an alpha band, alpha says which pixels have no value: a colour channel that equals the // no-data value (a black red channel, with no-data 0) is a real colour. - let valid = |v: f32| if plan.alpha.is_some() { v.is_finite() } else { r.is_valid(v) }; + // The alpha sample itself is valid as the raster says: an alpha equal to the no-data value + // is drawn see-through on the map, so it becomes NaN here and is written as 0. + let valid_in = |s: usize, v: f32| if plan.alpha.is_some_and(|a| a != s) { v.is_finite() } else { r.is_valid(v) }; if factor == 1 || plan.categorical { // Classes are never averaged: an overview takes the pixel in the middle of its block. let (x, y) = (x0 + (x1 - x0) / 2, y0 + (y1 - y0) / 2); - for (o, &b) in out.iter_mut().zip(&plan.bands) { + for (s, (o, &b)) in out.iter_mut().zip(&plan.bands).enumerate() { let v = r.bands.get(b).and_then(|band| band.data.get(y * w + x)).copied().unwrap_or(f32::NAN); - *o = if valid(v) { v } else { f32::NAN }; + *o = if valid_in(s, v) { v } else { f32::NAN }; } return; } @@ -306,11 +308,15 @@ fn block(r: &Raster, plan: &Plan, factor: usize, ox: usize, oy: usize, out: &mut continue; }; for (i, &v) in row.iter().enumerate() { - if !valid(v) { + // An alpha with no value is see-through: it counts as 0 and stays in the mean, so + // a block half of it comes out half opaque, not opaque. + let is_alpha = plan.alpha == Some(s); + let v = if is_alpha && !r.is_valid(v) { 0.0 } else { v }; + if !is_alpha && !valid_in(s, v) { continue; } let k = match arow { - Some(a) => a.get(i).copied().filter(|a| valid(*a)).map_or(0.0, f64::from), + Some(a) => a.get(i).copied().filter(|a| r.is_valid(*a)).map_or(0.0, f64::from), None => 1.0, }; sum += f64::from(v) * k; @@ -341,15 +347,15 @@ fn tile_samples(r: &Raster, plan: &Plan, lv: &Level, tx: u32, ty: u32) -> Vec 250.0); + } + + /// An overview's alpha counts a cell whose alpha is the no-data value as see-through (0): a + /// block half of them is half opaque, not opaque. + #[test] + fn an_overview_counts_a_no_data_alpha_as_see_through() { + let bands = vec![vec![10.0; 4], vec![20.0; 4], vec![30.0; 4], vec![0.0, 255.0, 0.0, 255.0]]; + let r = utm(2, 2, bands, ColorHint::Rgb { alpha: true }, "UInt8", Some(0.0)); + let p = plan(&r, 0).unwrap(); + assert_eq!(p.alpha, Some(3)); + let mut out = vec![0.0; p.bands.len()]; + block(&r, &p, 2, 0, 0, &mut out); + assert!((out[3] - 127.5).abs() < 1.0, "{out:?}"); + } + /// An overview's pixel is the mean of the pixels with a value it covers: none, NaN or infinite /// left out, an odd last row or column covering itself alone, and no-data where it covers /// none with one. diff --git a/crates/data/src/raster/dted.rs b/crates/data/src/raster/dted.rs index 7278f0e105..94fed473af 100644 --- a/crates/data/src/raster/dted.rs +++ b/crates/data/src/raster/dted.rs @@ -86,17 +86,18 @@ fn digits(bytes: &[u8], at: usize, len: usize) -> Option { if s.bytes().all(|b| b.is_ascii_digit()) { s.parse().ok() } else { None } } -/// An angle written `DDDMMSSH` (3.12 c) as signed degrees: `H` is `N` or `E` for positive, `S` -/// or `W` for negative. -fn angle(bytes: &[u8], at: usize) -> Option { +/// An angle written `DDDMMSSH` (3.12 c) as signed degrees: `H` is `positive` (`N` for a latitude, +/// `E` for a longitude) or `negative` (`S` or `W`); any other letter, such as a latitude's `E`, +/// can't be read. +fn angle(bytes: &[u8], at: usize, positive: u8, negative: u8) -> Option { let (d, m, s) = (digits(bytes, at, 3)?, digits(bytes, at + 3, 2)?, digits(bytes, at + 5, 2)?); if m >= 60 || s >= 60 { return None; } let v = f64::from(d) + f64::from(m) / 60.0 + f64::from(s) / 3600.0; match bytes.get(at + 7)?.to_ascii_uppercase() { - b'N' | b'E' => Some(v), - b'S' | b'W' => Some(-v), + h if h == positive => Some(v), + h if h == negative => Some(-v), _ => None, } } @@ -244,9 +245,12 @@ fn read_from_limited(file_name: &str, mut source: impl std::io::Read, max: usize return Err(bad("the DSI and ACC records aren't where the UHL ends")); } // The UHL: origin, intervals and counts (3.12 c). - let west = - angle(bytes, 4).filter(|v| (-180.0..=180.0).contains(v)).ok_or_else(|| bad("the UHL's longitude of origin can't be read"))?; - let south = angle(bytes, 12).filter(|v| (-90.0..=90.0).contains(v)).ok_or_else(|| bad("the UHL's latitude of origin can't be read"))?; + let west = angle(bytes, 4, b'E', b'W') + .filter(|v| (-180.0..=180.0).contains(v)) + .ok_or_else(|| bad("the UHL's longitude of origin can't be read"))?; + let south = angle(bytes, 12, b'N', b'S') + .filter(|v| (-90.0..=90.0).contains(v)) + .ok_or_else(|| bad("the UHL's latitude of origin can't be read"))?; let lon_tenths = digits(bytes, 20, 4).filter(|v| *v > 0).ok_or_else(|| bad("the UHL's longitude interval can't be read"))?; let lat_tenths = digits(bytes, 24, 4).filter(|v| *v > 0).ok_or_else(|| bad("the UHL's latitude interval can't be read"))?; let posts = |v: Option| v.map(|v| v as usize).filter(|v| (2..=MAX_POSTS).contains(v)); @@ -970,6 +974,9 @@ mod tests { (with(4, "0006000E"), "longitude of origin"), (with(12, "0910000N"), "latitude of origin"), (with(12, "0000000Q"), "latitude of origin"), + // Each axis takes only its own hemisphere letters. + (with(12, "0000000E"), "latitude of origin"), + (with(4, "0000000N"), "longitude of origin"), (with(20, "9999"), "more than the one-degree cell"), (with(12, "0895959N"), "more than the one-degree cell"), ] { diff --git a/crates/data/src/raster/geotiff.rs b/crates/data/src/raster/geotiff.rs index 9d7d18b1c4..8778abf7fb 100644 --- a/crates/data/src/raster/geotiff.rs +++ b/crates/data/src/raster/geotiff.rs @@ -1484,7 +1484,14 @@ pub fn read_asked_in(r: R, name: &str, asked: Crs) -> Result Result> { + unpack_rgba_within(grey, bytes, max_samples()) +} + +/// [`unpack_rgba`] holding at most `limit` samples. +fn unpack_rgba_within(grey: &Raster, bytes: &[u8], limit: usize) -> Result> { let [band] = &grey.bands[..] else { return Ok(None) }; if grey.data_type != "UInt32" { return Ok(None); @@ -1499,26 +1506,39 @@ pub fn unpack_rgba(grey: &Raster, bytes: &[u8]) -> Result> { } let mut dec = Decoder::new(reader(std::io::Cursor::new(bytes)).map_err(err)?).map_err(err)?.with_limits(limits()); let (w, h) = dec.dimensions().map_err(err)?; - if geo_tags(&mut dec)?.affine.is_some() { - return Err(err("it is rotated or skewed, which packed colours aren't split for")); - } + let rotated = geo_tags(&mut dec)?.affine.is_some(); let n = (w as usize).saturating_mul(h as usize); - // An overview's pixels aren't the image's: its colours come from the whole image, as four bands. - if grey.overview.is_some() || (grey.width, grey.height) != (w, h) || n.saturating_mul(4) > max_samples() { - return Err(err(format!( - "its {w} × {h} pixels are too many to hold as four bands: clip the tool's inputs to a smaller area first" + let too_many = + || err(format!("its {w} × {h} pixels are too many to hold as four bands: clip the tool's inputs to a smaller area first")); + // Whether the band is packed colour is decided from the raw values first, so a band that + // isn't (IDs whose no-data value reads past every colour) is never refused as one. An image + // too large to decode at all can't be told apart. + // Said as unchecked, not as a loss: the band may not be colour at all. + if n > limit { + return Err(DataError::Unsupported(format!( + "its {w} × {h} pixels are too many to check for packed colours: clip the tool's inputs to a smaller area first" ))); } let DecodingResult::U32(packed) = dec.read_image().map_err(err)? else { return Ok(None) }; - if packed.len() != n || band.data.len() != n { + if packed.len() != n { return Err(err(format!("its image holds {} values, not {w} × {h}", packed.len()))); } + // The band read holds the image's pixels in order, unless it was read resampled (rotated) or + // as an overview: then only the no-data value says which pixels are holes. + let same_grid = !rotated && grey.overview.is_none() && (grey.width, grey.height) == (w, h) && band.data.len() == n; // No-data, exactly, or hidden by the file's transparency mask (NaN as read). - let hole = |i: usize, p: u32| grey.nodata == Some(f64::from(p)) || band.data.get(i).is_some_and(|v| v.is_nan()); + let hole = |i: usize, p: u32| grey.nodata == Some(f64::from(p)) || (same_grid && band.data.get(i).is_some_and(|v| v.is_nan())); let shown = || packed.iter().enumerate().filter(|(i, p)| !hole(*i, **p)).map(|(_, p)| p >> 24); if !shown().all(|a| a == 0 || a == 255) || !shown().any(|a| a == 255) { return Ok(None); } + if rotated { + return Err(err("it is rotated or skewed, which packed colours aren't split for")); + } + // An overview's pixels aren't the image's: its colours come from the whole image, as four bands. + if !same_grid || n.saturating_mul(4) > limit { + return Err(too_many()); + } // A file with no GeoTIFF tags has only a stand-in place, which the rebuilt raster would // hold, and be written with, as coordinates. if !grey.georeferenced { @@ -1894,7 +1914,6 @@ fn read_image( other => return Err(err(format!("{other:?} images aren't supported"))), }; let planar = dec.find_tag_unsigned::(Tag::PlanarConfiguration).ok().flatten() == Some(2); - // The pixels kept of the grid read (`w` × `h`): a part's, else all of them. // The image's extent in the grid's pixels: every k-th pixel's grid passes its edge when k // doesn't divide its size. let extent = if decimate_by > 1 { @@ -1902,6 +1921,7 @@ fn read_image( } else { (f64::from(w), f64::from(h)) }; + // The pixels kept of the grid read (`w` × `h`): a part's, else all of them. let span = part.map(|p| p.span((w, h), extent)); let (ow, oh) = span.map_or((w, h), Span::size); let n = (ow as usize) * (oh as usize); @@ -2379,23 +2399,34 @@ fn encode(r: &Raster, band: usize, every: bool, out: &mut (impl std::io::Write + // Without alpha or a no-data marker, byte samples cannot keep NaN holes (for example the // cells outside a reprojected RGBI image). Keep those samples as floats instead. With alpha, // a hole its alpha hides is fine (the cell is see-through), but one under an opaque alpha - // would be written as an opaque 0. A pass over the bands: the byte branch asks it last. - let byte_holes = || { + // would be written as an opaque 0. A pass over the bands, listening for Cancel: the byte + // branch asks it once the bands fit bytes, before it copies them. + let byte_holes = || -> Result { let counted = || written_bands(r, band).iter().any(|b| r.bands.get(*b).is_some_and(|b| b.stats.count < (w as usize) * (h as usize))); - r.nodata.is_none() - && match (&r.color, r.color.alpha(r.bands.len())) { - (ColorHint::Rgb { alpha: false }, _) => counted(), - (ColorHint::Rgb { alpha: true }, Some((_, colour))) => colour.into_iter().any(|b| { - r.bands - .get(b) - .zip(r.see_through_cells(b)) - .is_some_and(|(band, hidden)| band.data.iter().enumerate().any(|(i, v)| !v.is_finite() && !hidden(i))) - }), - // No alpha band to hide a hole (alpha declared on three bands). - (ColorHint::Rgb { alpha: true }, None) => counted(), - _ => false, + if r.nodata.is_some() { + return Ok(false); + } + Ok(match (&r.color, r.color.alpha(r.bands.len())) { + (ColorHint::Rgb { alpha: false }, _) => counted(), + (ColorHint::Rgb { alpha: true }, Some((_, colour))) => { + for b in colour { + let (Some(band), Some(hidden)) = (r.bands.get(b), r.see_through_cells(b)) else { continue }; + for (i, v) in band.data.iter().enumerate() { + if i % (1 << 20) == 0 { + crate::progress::check()?; + } + if !v.is_finite() && !hidden(i) { + return Ok(true); + } + } + } + false } + // No alpha band to hide a hole (alpha declared on three bands). + (ColorHint::Rgb { alpha: true }, None) => counted(), + _ => false, + }) }; let all: Vec = (0..r.bands.len()).collect(); if every && written_bands(r, band).len() < all.len() { @@ -2445,8 +2476,9 @@ fn encode(r: &Raster, band: usize, every: bool, out: &mut (impl std::io::Write + } } else if rgb && (!written_bands(r, band).contains(&3) || fits_bytes(r, 3)) + && (0..3).all(|b| fits_bytes(r, b)) + && !byte_holes()? && let (Some(red), Some(green), Some(blue)) = (bytes(0), bytes(1), bytes(2)) - && !byte_holes() { let alpha = if written_bands(r, band).contains(&3) { bytes(3) } else { None }; let n = (w as usize) * (h as usize); @@ -2475,15 +2507,23 @@ fn encode(r: &Raster, band: usize, every: bool, out: &mut (impl std::io::Write + let nan_cells = alpha_hits_no_data(r, opaque, &alpha.data); nan_tag.set(nan_cells); let cell = |is_alpha: bool, v: f32| float_cell(r, opaque, nan_cells, is_alpha, v); - let mut data = Vec::with_capacity(n * 4); + // Reserved first, so a raster this machine can't hold again is an error, and a + // cancel is heard while the samples are copied. + let mut data = super::room(n.saturating_mul(4), w as usize, h as usize)?; for i in 0..n { + if i % (1 << 20) == 0 { + crate::progress::check()?; + } data.extend([cell(false, at(red, i)), cell(false, at(green, i)), cell(false, at(blue, i)), cell(true, at(alpha, i))]); } put(image(&[0, 1, 2, 3], Sample::Float, fourth())?, &data, f32::to_le_bytes, out)?; } None => { - let mut data = Vec::with_capacity(n * 3); + let mut data = super::room(n.saturating_mul(3), w as usize, h as usize)?; for i in 0..n { + if i % (1 << 20) == 0 { + crate::progress::check()?; + } data.extend([at(red, i), at(green, i), at(blue, i)]); } put(image(&[0, 1, 2], Sample::Float, Vec::new())?, &data, f32::to_le_bytes, out)?; @@ -3201,6 +3241,11 @@ mod tests { ("RGBA, NaN under an opaque alpha", rgba([1.0, nan, 2.0], [6.0, 6.0, nan], [255.0; 3]), true), ("RGBA, NaN under a clear alpha", rgba([1.0, nan, 2.0], [6.0, nan, 6.0], [255.0, 0.0, 255.0]), false), ("RGBA, no NaN", rgba([1.0, 4.0, 2.0], [6.0; 3], [255.0; 3]), false), + // Alpha declared on three bands: no alpha band hides a hole. + ("three bands hinted RGBA, NaN", raster(rgb([1.0, nan, 2.0], [6.0; 3]), ColorHint::Rgb { alpha: true }), true), + ("three bands hinted RGBA, no NaN", raster(rgb([1.0, 4.0, 2.0], [6.0; 3]), ColorHint::Rgb { alpha: true }), false), + ("one band, NaN", raster(vec![vec![1.0, nan, 2.0]], ColorHint::Gray), true), + ("one band, no NaN", raster(vec![vec![1.0, 4.0, 2.0]], ColorHint::Gray), false), ]; for (case, r, floats) in &cases { for (writer, bytes) in [("write", write(r, 0).unwrap()), ("write_all", write_all(r).unwrap())] { @@ -3211,7 +3256,10 @@ mod tests { let back = read(std::io::Cursor::new(bytes), "back").unwrap(); let at = format!("{case}, {writer}"); assert_eq!(back.data_type, if *floats { "Float32" } else { "UInt8" }, "{at}"); - assert_eq!((back.band_count(), &back.color), (r.band_count(), &r.color), "{at}"); + // Three bands hold no alpha, so alpha declared on them doesn't come back. + let three = r.band_count() == 3 && matches!(r.color, ColorHint::Rgb { .. }); + let color = if three { ColorHint::Rgb { alpha: false } } else { r.color.clone() }; + assert_eq!((back.band_count(), &back.color), (r.band_count(), &color), "{at}"); if *floats { // An alpha band is on the float scale: `rgba_written_as_floats_keeps_its_opacity`. let alpha = if r.color == (ColorHint::Rgb { alpha: true }) { Some(3) } else { None }; @@ -3221,9 +3269,27 @@ mod tests { } } } + // The COG writer keeps a grey band's hole too. + if r.bands.len() == 1 { + let back = read(std::io::Cursor::new(super::super::cogwrite::write(r, 0).unwrap()), "back").unwrap(); + assert_eq!(back.data_type, if *floats { "Float32" } else { "UInt8" }, "{case}, cog"); + assert_eq!(back.bands[0].data.get(1).is_some_and(|v| !back.is_valid(*v)), *floats, "{case}, cog"); + } } } + /// A band of IDs too large to decode can't be told from packed colour: it is undecided + /// (`Unsupported`), which the caller says without claiming a colour loss. + #[test] + fn a_band_too_large_to_check_for_packed_colour_is_undecided() { + use tiff::encoder::{TiffEncoder, colortype}; + let mut out = std::io::Cursor::new(Vec::new()); + TiffEncoder::new(&mut out).unwrap().write_image::(2, 2, &[1, 2, 3, 0xFFFF_FFFF]).unwrap(); + let bytes = out.into_inner(); + let grey = read(std::io::Cursor::new(bytes.clone()), "ids").unwrap(); + assert!(matches!(unpack_rgba_within(&grey, &bytes, 1), Err(DataError::Unsupported(_)))); + } + /// An RGBA raster written as floats keeps how see-through each pixel is: its alpha is on the /// float scale (1 is opaque) once read back, whatever scale the integer raster had. The /// colours stay as they are (a float raster is stretched by its own range when drawn). diff --git a/crates/data/src/raster/mod.rs b/crates/data/src/raster/mod.rs index d55135e149..43babe5221 100644 --- a/crates/data/src/raster/mod.rs +++ b/crates/data/src/raster/mod.rs @@ -1690,7 +1690,7 @@ pub fn apply_world_file(path: &Path, mut r: Raster) -> Raster { }; match r.placed_by_world_file(&wf, crs) { Ok(mut r) => { - r.lost.extend(note.map(|n| format!("the .prj file: {n}"))); + r.lost.extend(note.map(|n| wkt::approximated_note(format!("the .prj file: {n}")))); r } Err((r, why)) => { @@ -2128,7 +2128,7 @@ fn read_ascii(path: &Path, text: &str, name: &str, nodata: Option) -> Resul // missing. A readable system keeps its other notes, without repeating the planetary body. let mut r = ascii::read_with_nodata(text, name, crs, nodata, note.as_deref().filter(|_| crs.is_none()))?; if crs.is_some() { - r.lost.extend(note); + r.lost.extend(note.map(wkt::approximated_note)); } Ok(r) } @@ -2940,6 +2940,12 @@ pub(crate) mod tests { std::fs::write(dir.join("g.prj"), wkt::to_wkt(Crs::LonLat).unwrap()).unwrap(); let r = read_path(&asc).unwrap(); assert!(r.lost.is_empty(), "{:?}", r.lost); + // A datum with no shift to WGS 84 is read as it, and said with its code. + let unshifted = r#"GEOGCS["g",DATUM["Somewhere",SPHEROID["Clarke 1880",6378249.145,293.465]],PRIMEM["Greenwich",0],UNIT["degree",0.0174532925199433]]"#; + std::fs::write(dir.join("g.prj"), unshifted).unwrap(); + let r = read_path(&asc).unwrap(); + let datum: Vec<_> = r.lost.iter().filter(|n| n.loss == Some(crate::loss::LossCode::ApproximatedDatum)).collect(); + assert!(datum.len() == 1 && datum[0].contains("has no conversion to WGS 84"), "{:?}", r.lost); std::fs::write(dir.join("g.prj"), "not a coordinate system").unwrap(); let r = read_path(&asc).unwrap(); assert_eq!(r.lost.len(), 1, "{:?}", r.lost); diff --git a/crates/data/src/raster/wkt.rs b/crates/data/src/raster/wkt.rs index 4d8dbae263..8f98e80701 100644 --- a/crates/data/src/raster/wkt.rs +++ b/crates/data/src/raster/wkt.rs @@ -358,10 +358,7 @@ fn read_tree(root: &Node, code: Option, text: &str) -> Result<(Crs, Option< let note = match geogcs(root).filter(|g| (crs.custom_def().is_some() || (crs == Crs::LonLat && !by_code)) && g.child("DATUM").is_none()) { Some(_) => { - let said = format!( - "the coordinate system {} has no datum and is read on WGS 84, so positions may be off by up to a few hundred metres", - clip(root.title()) - ); + let said = format!("the coordinate system {} has no datum and is read on WGS 84, {OFF_BY}", clip(root.title())); Some(note.map_or(said.clone(), |n| format!("{n}; {said}"))) } None => note, @@ -2257,6 +2254,22 @@ fn unapplied(datum: Option<&Node>) -> Option { }) } +/// How every note of a datum read as WGS 84 for want of a conversion ends: what +/// [`approximated_note`] codes `approximated.datum`. +pub(crate) const OFF_BY: &str = "so positions may be off by up to a few hundred metres"; + +/// A note of reading a coordinate system (from [`read_wkt`], or a PROJ definition), coded +/// `approximated.datum` when it says the datum was read as WGS 84 ([`OFF_BY`]), so `--strict`, +/// Python's warnings and the Assistant see it; plain otherwise. +pub fn approximated_note(text: impl Into) -> crate::loss::Note { + let text = text.into(); + if text.contains(OFF_BY) { + crate::loss::Note::loss(crate::loss::LossCode::ApproximatedDatum, text) + } else { + crate::loss::Note::plain(text) + } +} + /// A note when the datum (of a `GEOGCS`) is neither WGS 84-like nor shifted to it by `TOWGS84`. /// A datum whose file gives a shift that can't be applied has [`read_wkt`] say that instead. fn datum_note(geog: Option<&Node>) -> Option { @@ -2268,10 +2281,7 @@ fn datum_note(geog: Option<&Node>) -> Option { { return None; } - Some(format!( - "the datum {} has no conversion to WGS 84 in the file, so positions may be off by up to a few hundred metres", - clip(datum.title()) - )) + Some(format!("the datum {} has no conversion to WGS 84 in the file, {OFF_BY}", clip(datum.title()))) } /// [`datum_note`] for a system terrio-crs finds no transformation of: said unless the file names @@ -2281,10 +2291,7 @@ fn unshifted_datum_note(geog: Option<&Node>) -> Option { if wgs84_like(Some(datum)).is_some() || towgs84(Some(datum)).is_some() || unapplied(Some(datum)).is_some() { return None; } - Some(format!( - "the datum {} has no conversion to WGS 84 in the file, so positions may be off by up to a few hundred metres", - clip(datum.title()) - )) + Some(format!("the datum {} has no conversion to WGS 84 in the file, {OFF_BY}", clip(datum.title()))) } /// The datum of a `GEOGCS`, by name for the common ones, else by its spheroid's axes; and its diff --git a/crates/data/src/raster/zarr.rs b/crates/data/src/raster/zarr.rs index a414a670b4..5cee1c9aa2 100644 --- a/crates/data/src/raster/zarr.rs +++ b/crates/data/src/raster/zarr.rs @@ -2079,11 +2079,11 @@ pub fn assemble(store: &Store, plan: &Plan, chunks: &HashMap>, n let assumed = assumed.map(|a| crate::loss::Note::loss(crate::loss::LossCode::AssumedCrs, a)); ( Some(if actual.is_geographic() { actual } else { Crs::LonLat }), - note.into_iter().map(crate::loss::Note::plain).chain(assumed).collect(), + note.into_iter().map(super::wkt::approximated_note).chain(assumed).collect(), ) } else { match found { - Some((crs, note)) => (Some(crs), note.into_iter().map(crate::loss::Note::plain).collect()), + Some((crs, note)) => (Some(crs), note.into_iter().map(super::wkt::approximated_note).collect()), None => (crs, crs.and_then(super::planetary::note_of).into_iter().map(crate::loss::Note::plain).collect()), } }; @@ -3606,7 +3606,9 @@ mod tests { let want = Crs::parse(def).unwrap(); let r = read(serde_json::json!({"proj4": def}), &lons); assert!(r.crs == want && want.is_geographic(), "{def}: {:?}", r.crs); - assert_eq!(r.lost, if said { vec![NO_DATUM_SHIFT.to_string()] } else { Vec::new() }, "{def}"); + assert_eq!(r.lost.texts().collect::>(), if said { vec![NO_DATUM_SHIFT] } else { Vec::new() }, "{def}"); + // Coded, so `--strict` and the Assistant see it. + assert!(r.lost.iter().all(|n| n.loss == Some(crate::loss::LossCode::ApproximatedDatum)), "{def}: {:?}", r.lost); } // An EPSG code is the system itself, and says what the same system's WKT says: nothing for // WGS 84 or ED50. diff --git a/crates/data/src/row_access.rs b/crates/data/src/row_access.rs index db74a4a6ea..659d9ada13 100644 --- a/crates/data/src/row_access.rs +++ b/crates/data/src/row_access.rs @@ -144,10 +144,17 @@ impl Features { } return Ok(()); } + // The first row's check comes before the hook that frees older Undo steps, so a cancel + // there leaves them, as an edit that fails before writing does; the loop skips it. + if !self.rows.is_empty() { + step()?; + } self.before_copy(); let mut copy = Vec::with_capacity(self.rows.len()); - for f in self.rows.iter() { - step()?; + for (i, f) in self.rows.iter().enumerate() { + if i > 0 { + step()?; + } let mut attrs = Vec::with_capacity(f.attrs.len().saturating_add(n)); attrs.extend_from_slice(&f.attrs); attrs.extend(added.clone()); @@ -377,6 +384,25 @@ mod tests { assert_eq!(ds.features.row(2).map(|r| r.values().cloned().collect::>()), Some(vec![Value::Int(9), Value::Null])); } + /// A cancel at the first check of shared rows leaves the hook unfired (older Undo steps + /// kept) and the rows as they were; one at the second fires it, the copy under way. + #[test] + fn a_column_cancelled_at_once_keeps_older_undo_steps() { + let ds = layer(); + for (cancel_at, fires) in [(1, false), (2, true)] { + let mut copy = ds.features.clone(); + let mut asked = 0; + let step = || { + asked += 1; + if asked == cancel_at { Err("cancelled") } else { Ok(()) } + }; + let (done, fired) = crate::before_rows_copy(Box::new(|| {}), || copy.try_add_columns(1, Value::Int(0), step)); + assert_eq!(done, Err("cancelled")); + assert_eq!(fired, fires, "cancelled at check {cancel_at}"); + assert!(copy.shares(&ds.features)); + } + } + #[test] fn a_column_stopped_part_way_leaves_shared_rows_as_they_were() { let ds = layer(); diff --git a/crates/data/src/sheets.rs b/crates/data/src/sheets.rs index 4ed4563b6b..e43e3c84cb 100644 --- a/crates/data/src/sheets.rs +++ b/crates/data/src/sheets.rs @@ -49,6 +49,20 @@ fn guarded(f: impl FnOnce() -> Result) -> Result { /// named `` (or ` ` when the workbook has several). The report names the other /// sheets. pub fn read(bytes: &[u8], name: &str, sheet: Option<&str>, opts: &CsvOptions) -> Result<(Dataset, ReadReport)> { + read_with_hint(bytes, name, sheet, opts, "", "add one with \"layer\"") +} + +/// [`read`], its note of the other sheets after `prefix` (a zip member's path) and ending with +/// `hint`, the way to pick one: a workbook inside a zip can't be picked from with `"layer"`, which +/// picks among the zip's own layers. +pub(crate) fn read_with_hint( + bytes: &[u8], + name: &str, + sheet: Option<&str>, + opts: &CsvOptions, + prefix: &str, + hint: &str, +) -> Result<(Dataset, ReadReport)> { let g = grid(bytes, sheet)?; let title = if g.names.len() > 1 { format!("{name} {}", g.pick) } else { name.to_string() }; let (ds, mut report) = read_rows(&g.headers, &g.rows, 0, &title, opts, Some((&g.dates, &g.phantom_dates)))?; @@ -103,7 +117,7 @@ pub fn read(bytes: &[u8], name: &str, sheet: Option<&str>, opts: &CsvOptions) -> } let others: Vec<&str> = g.names.iter().filter(|n| **n != g.pick).map(String::as_str).take(20).collect(); if !others.is_empty() { - report.messages.push(format!("the workbook has more sheets ({}): add one with \"layer\"", others.join(", "))); + report.messages.push(format!("{prefix}the workbook has more sheets ({}): {hint}", others.join(", "))); } Ok((ds, report)) } diff --git a/crates/data/src/source/fgb.rs b/crates/data/src/source/fgb.rs index 1b9825c880..7700859dcb 100644 --- a/crates/data/src/source/fgb.rs +++ b/crates/data/src/source/fgb.rs @@ -83,7 +83,8 @@ pub(crate) fn header_says_wgs84(path: &Path) -> bool { let Ok(reader) = std::fs::File::open(path).map_err(DataError::from).and_then(|f| open_reader(BufReader::new(f))) else { return false }; let Some(crs) = reader.header().crs() else { return true }; let org = crs.org().unwrap_or("EPSG"); - (org.eq_ignore_ascii_case("epsg") && crs.code() == 4326) + // WGS 84 3D (EPSG:4979) holds the same longitude/latitude, with heights. + (org.eq_ignore_ascii_case("epsg") && matches!(crs.code(), 4326 | 4979)) || (org.eq_ignore_ascii_case("ogc") && crs.code_string().is_some_and(|c| c.eq_ignore_ascii_case("CRS84"))) || crs.wkt().is_some_and(|w| crate::raster::wkt::read_wkt(w).is_ok_and(|(c, _)| c == Crs::LonLat)) } @@ -976,7 +977,8 @@ fn geometry_part_fits(g: &flatgeobuf::Geometry<'_>, kind: GeometryKind, depth: u ); if !from_parts { let values = g.xy().map_or(0, |xy| xy.len()); - // A point is read from its own first coordinate. + // Read in pairs. A point the reader would take its first pair of, past a stray value, is + // refused too: keeping it would drop that value without a word; refused, it is counted. if !values.is_multiple_of(2) || (kind == K::Point && values < 2) { return false; } @@ -1371,12 +1373,130 @@ mod geometry_fits_tests { assert!(!with_ends(GeometryKind::MultiLineString, &[3, 2])); assert!(with_ends(GeometryKind::Polygon, &[2, 4])); } + + /// A point or a line whose `xy` holds a stray third value is refused (and counted), not read + /// with the value dropped unsaid (#3017). + #[test] + fn a_point_or_a_line_with_an_odd_xy_is_refused() { + let odd = |kind| { + fits( + |fbb| { + let xy = fbb.create_vector(&[1.0, 2.0, 3.0]); + Geometry::create(fbb, &GeometryArgs { xy: Some(xy), type_: kind, ..Default::default() }) + }, + kind, + ) + }; + assert!(!odd(GeometryKind::Point)); + assert!(!odd(GeometryKind::LineString)); + } + + /// A file whose point holds a third `xy` value reads through the layer reader without a + /// panic: the feature is skipped and counted (`skipped`, which the add says), its stray value + /// never dropped unsaid (#3017). + #[test] + fn a_point_with_an_odd_xy_is_skipped_and_said() { + use flatgeobuf::{Feature, FeatureArgs, Header, HeaderArgs}; + let mut fbb = FlatBufferBuilder::new(); + let name = fbb.create_string("p"); + let header = Header::create( + &mut fbb, + &HeaderArgs { + name: Some(name), + geometry_type: GeometryKind::Point, + features_count: 1, + index_node_size: 0, + ..Default::default() + }, + ); + fbb.finish_size_prefixed(header, None); + let header = fbb.finished_data().to_vec(); + let mut fbb = FlatBufferBuilder::new(); + let xy = fbb.create_vector(&[1.0, 2.0, 3.0]); + let g = Geometry::create(&mut fbb, &GeometryArgs { xy: Some(xy), ..Default::default() }); + let f = Feature::create(&mut fbb, &FeatureArgs { geometry: Some(g), ..Default::default() }); + fbb.finish_size_prefixed(f, None); + let file = [&[b'f', b'g', b'b', flatgeobuf::VERSION, b'f', b'g', b'b', 0][..], &header, fbb.finished_data()].concat(); + let (ds, report) = crate::io::read_bytes("p.fgb", &file).unwrap(); + let kept = ds.features.iter().filter(|f| f.geometry.is_some()).count(); + assert_eq!((kept, report.skipped), (0, 1), "{report:?}"); + } + + /// Collections nested around a point are followed 32 levels deep and refused past that, so a + /// file can't make the reader recurse without end (#3017). + #[test] + fn collections_nest_no_deeper_than_the_limit() { + let nested = |levels: usize| { + fits( + |fbb| { + let xy = fbb.create_vector(&[1.0, 2.0]); + let mut g = Geometry::create(fbb, &GeometryArgs { xy: Some(xy), type_: GeometryKind::Point, ..Default::default() }); + for _ in 0..levels { + let parts = fbb.create_vector(&[g]); + g = Geometry::create( + fbb, + &GeometryArgs { parts: Some(parts), type_: GeometryKind::GeometryCollection, ..Default::default() }, + ); + } + g + }, + GeometryKind::GeometryCollection, + ) + }; + assert!(nested(32)); + assert!(!nested(33)); + } + + /// A multi-polygon's parts are read as polygons, so a part's ring end past its coordinates + /// refuses the whole feature (#3017). + #[test] + fn a_multi_polygon_part_with_a_bad_ring_end_is_refused() { + let multi = |ends: &'static [u32]| { + fits( + |fbb| { + let first = square(fbb); + let xy = fbb.create_vector(&[0.0, 0.0, 1.0, 0.0, 1.0, 1.0, 0.0, 0.0]); + let ends = fbb.create_vector(ends); + let second = Geometry::create( + fbb, + &GeometryArgs { xy: Some(xy), ends: Some(ends), type_: GeometryKind::Polygon, ..Default::default() }, + ); + let parts = fbb.create_vector(&[first, second]); + Geometry::create(fbb, &GeometryArgs { parts: Some(parts), type_: GeometryKind::MultiPolygon, ..Default::default() }) + }, + GeometryKind::MultiPolygon, + ) + }; + assert!(!multi(&[2, 9])); + assert!(multi(&[2, 4])); + } } #[cfg(test)] mod write_tests { use super::*; + /// A header naming WGS 84 3D (EPSG:4979) with no definition says longitude/latitude, so GDAL's + /// copy of it isn't said to be converted; another system's code doesn't. + #[cfg(not(target_arch = "wasm32"))] + #[test] + fn a_wgs84_3d_header_says_wgs84() { + use flatgeobuf::{FgbCrs, FgbWriter, FgbWriterOptions}; + let dir = tempfile::tempdir().unwrap(); + let header = |code: i32| { + let options = FgbWriterOptions { crs: FgbCrs { org: Some("EPSG"), code, ..Default::default() }, ..Default::default() }; + let w = FgbWriter::create_with_options("h", flatgeobuf::GeometryType::Point, options).unwrap(); + let path = dir.path().join(format!("{code}.fgb")); + let mut out = Vec::new(); + w.write(&mut out).unwrap(); + std::fs::write(&path, out).unwrap(); + header_says_wgs84(&path) + }; + assert!(header(4979)); + assert!(header(4326)); + assert!(!header(32611)); + } + /// The browser refuses FlatGeobuf before the writer, whose temporary file aborted the web /// app, is made; the desktop writes it. #[test] diff --git a/crates/data/src/source/gpkg.rs b/crates/data/src/source/gpkg.rs index b8a77305d0..9fe1b6926b 100644 --- a/crates/data/src/source/gpkg.rs +++ b/crates/data/src/source/gpkg.rs @@ -448,13 +448,15 @@ impl GpkgSource { cols.join(", ") } - /// The order a scan of the table gives, written out (` ORDER BY …`) so that SQLite can't read - /// it another way, such as down a covering index: the order a view read through the R-tree - /// fetches in. + /// The order a scan of the table gives, written out (` ORDER BY …`) by its key or rowid so + /// that SQLite can't read it another way, such as down a covering index: the order a view read + /// through the R-tree fetches in. A table read by a scan (no usable rowid, or no key) writes no + /// ORDER BY, so it keeps SQLite's own scan order, the same for the whole read and a view read. fn order_by(&self) -> String { match (self.row_order, &self.pk) { - // The rowid itself, or a name of it no column has taken: no sort. + // The key, which is the rowid: written out so SQLite reads the table in this order too. (RowOrder::Key, Some(pk)) => format!(" ORDER BY {}", quote(pk)), + // The rowid itself, or a name of it no column has taken, where the key is apart. (RowOrder::Rowid(rowid), _) => format!(" ORDER BY {rowid}"), // Without a key no view is read through the R-tree, so there's no order to match. (RowOrder::Key, None) | (RowOrder::Scan, _) => String::new(), diff --git a/crates/data/src/source/gpkg/edit.rs b/crates/data/src/source/gpkg/edit.rs index 64ba8e863e..bed2c21a40 100644 --- a/crates/data/src/source/gpkg/edit.rs +++ b/crates/data/src/source/gpkg/edit.rs @@ -179,7 +179,7 @@ impl EditTable { let mut rows = st.query([limit.clamp(1, MAX_EDITABLE) as i64]).map_err(err)?; while let Some(row) = rows.next().map_err(err)? { let id = row.get::<_, i64>(key).map_err(err)?.cast_unsigned(); - let Some(geometry) = self.geometry(row.get_ref(geom).map_err(err)?, &Held::Own) else { + let Ok(geometry) = self.geometry(row.get_ref(geom).map_err(err)?, &Held::Own) else { out.skipped += 1; continue; }; @@ -328,7 +328,7 @@ impl EditTable { } } let old = ValueRef::from(row.get(geom).ok_or_else(|| self.shape_error())?); - let stored = self.geometry(old, how).ok_or_else(|| self.unread(f.id, how))?; + let stored = self.geometry(old, how).map_err(|why| self.unread(f.id, how, why))?; let geometry_changed = stored != f.geometry; spatial_changed |= geometry_changed; if geometry_changed { @@ -464,8 +464,8 @@ impl EditTable { for (original, k) in originals { let row = rows.get(&k).ok_or_else(|| DataError::Format(format!("row {k}: it was removed while saving")))?; let geometry = - self.geometry(ValueRef::from(row.get(geom).ok_or_else(|| self.shape_error())?), how).ok_or_else(|| match how { - Held::Other { crs, .. } => DataError::Format(format!( + self.geometry(ValueRef::from(row.get(geom).ok_or_else(|| self.shape_error())?), how).map_err(|why| match (how, why) { + (Held::Other { crs, .. }, Unread::Unconverted) => DataError::Format(format!( "row {k}: its stored geometry can't be converted to {}, so nothing was saved", crs.label() )), @@ -597,33 +597,34 @@ impl EditTable { }) } - /// A stored geometry that can't be read, or given in `how`'s system. - fn unread(&self, id: u64, how: &Held) -> DataError { - match how { - Held::Other { crs, .. } => { + /// A stored geometry that can't be read, or (in another system) given in `how`'s system. + fn unread(&self, id: u64, how: &Held, why: Unread) -> DataError { + match (how, why) { + (Held::Other { crs, .. }, Unread::Unconverted) => { DataError::Format(format!("row {}: its stored geometry can't be converted to {}", id.cast_signed(), crs.label())) } _ => self.shape_error(), } } - // Outer None is unreadable (or, in another system, can't be converted); inner None is a valid - // NULL or empty geometry. As the table holds it, in longitude/latitude (for a layer a project - // saved before RustGIS kept a table's own coordinates), or in another system. - fn geometry(&self, v: ValueRef<'_>, how: &Held) -> Option> { + // `Err` says why a geometry isn't there: unreadable, or (in another system) not converted; + // `Ok(None)` is a valid NULL or empty geometry. As the table holds it, in longitude/latitude + // (for a layer a project saved before RustGIS kept a table's own coordinates), or in another + // system. + fn geometry(&self, v: ValueRef<'_>, how: &Held) -> std::result::Result, Unread> { match v { - ValueRef::Null => Some(None), - ValueRef::Blob(b) if is_empty_blob(b) => Some(None), + ValueRef::Null => Ok(None), + ValueRef::Blob(b) if is_empty_blob(b) => Ok(None), ValueRef::Blob(b) => { - let (_, body) = split_blob(b)?; - let g = wkb::decode(body)?; - match how { - Held::Own => Some(Some(g)), - Held::LonLat => self.src.reproject.to_lonlat_geometry(g).map(Some), - Held::Other { to_held, .. } => to_held.whole_geometry(&g).map(Some), - } + let g = split_blob(b).and_then(|(_, body)| wkb::decode(body)).ok_or(Unread::Unreadable)?; + let placed = match how { + Held::Own => Some(g), + Held::LonLat => self.src.reproject.to_lonlat_geometry(g), + Held::Other { to_held, .. } => to_held.whole_geometry(&g), + }; + placed.map(Some).ok_or(Unread::Unconverted) } - _ => None, + _ => Err(Unread::Unreadable), } } @@ -649,16 +650,17 @@ impl EditTable { let Some(g) = g else { return Ok(Sql::Null); }; - let id = || row.map(|(k, _)| k.cast_signed().to_string()).unwrap_or_else(|| "new".into()); - let unconverted = || DataError::Format(format!("row {}: its geometry can't be converted to {}", id(), self.src.reproject.label())); + // An update's row by its key; an insert is a new feature, which has none yet. + let subject = || row.map(|(k, _)| format!("row {}", k.cast_signed())).unwrap_or_else(|| "a new feature".into()); + let unconverted = || DataError::Format(format!("{}: its geometry can't be converted to {}", subject(), self.src.reproject.label())); // A coordinate that isn't a number can't be stored (it reads back as an empty or // unreadable geometry), nor converted: an infinite one could convert to a finite pole. let mut finite = true; g.for_each_coord(|c| finite &= c.is_finite()); if !finite { return Err(DataError::Format(format!( - "row {}: its geometry has a coordinate that isn't a number, so it can't be saved", - id() + "{}: its geometry has a coordinate that isn't a number, so it can't be saved", + subject() ))); } let native = match how { @@ -977,6 +979,15 @@ fn maintain_rtree(conn: &Connection, rtree: Option<&str>, key: i64, extent: &Ext Ok(()) } +/// Why a stored geometry isn't there to compare or keep. +#[derive(Clone, Copy, Debug, PartialEq)] +enum Unread { + /// Its blob can't be read as a geometry. + Unreadable, + /// It reads, but can't be given in the system the layer holds. + Unconverted, +} + /// How the edits' coordinates meet the table's ([`EditTable::save`]). enum Held { /// The table's own. @@ -1429,6 +1440,30 @@ mod tests { assert_eq!(bounds, (0.0, 0.0, 2.0, 3.0)); } + /// Held in a third system, a stored geometry that can't be read is said to be unreadable, not + /// unconvertible, which would send the user to the coordinate system. + #[test] + fn gpkg_an_unreadable_geometry_held_in_a_third_system_is_said_unreadable() { + let (_dir, path) = fixture(); + let conn = Connection::open(&path).unwrap(); + conn.execute_batch( + "INSERT INTO roads (fid, geom, name, lanes) VALUES (2,x'00','unreadable',2); + CREATE TRIGGER modify_other AFTER UPDATE OF name ON roads WHEN NEW.fid=1 + BEGIN UPDATE roads SET lanes=7 WHERE fid=2; END;", + ) + .unwrap(); + let table = EditTable::open(&path, "roads").unwrap(); + let read = table.read_editable(MAX_EDITABLE).unwrap(); + let mercator = Crs::WebMercator; + let to = table.coord_crs().to(mercator).unwrap(); + let mut feature = read.features[0].clone(); + feature.geometry = feature.geometry.as_ref().and_then(|g| to.whole_geometry(g)); + feature.attrs[0] = Value::Text("edited".into()); + let edits = Edits { updates: vec![(feature, read.versions[0].1)], ..Default::default() }; + let error = table.save(&edits, &table.info().fields, [2].into_iter(), &read.revision, mercator).unwrap_err().to_string(); + assert!(error.contains("stored geometry can't be read") && !error.contains("converted"), "{error}"); + } + #[test] fn gpkg_conflict_replace_evictions_are_removed_but_earlier_external_deletes_are_not() { let (_dir, path) = fixture(); diff --git a/crates/data/src/source/mod.rs b/crates/data/src/source/mod.rs index 3e338ca9d3..370be97f76 100644 --- a/crates/data/src/source/mod.rs +++ b/crates/data/src/source/mod.rs @@ -603,7 +603,7 @@ pub trait FeatureSource: Send + Sync { /// ([`Request::own`]) tests its features against that box (a file read in place, PostGIS), so /// a map in that system keeps its window in map units for it. A complete visit does so only /// where the source says so through [`FeatureSource::visit_request_chunks`]. A source that reads by the longitude/latitude extent - /// whatever it is given (another database, a service, a converted copy) says no: its window is + /// whatever it is given (another database, a service) says no: its window is /// kept in longitude/latitude, as it reads. fn reads_own_box(&self) -> bool { false diff --git a/crates/data/src/source/parquet.rs b/crates/data/src/source/parquet.rs index 6631e6945f..9e76156427 100644 --- a/crates/data/src/source/parquet.rs +++ b/crates/data/src/source/parquet.rs @@ -757,6 +757,22 @@ impl FeatureSource for ParquetSource { if unbounded { crate::progress::begin(usize::try_from(matched).unwrap_or(0)); } + // What the features kept hold, across every group: the per-group budget bounds one + // group's decode, this the rows the sample keeps until the read returns. Charged as rows + // are kept, and counted again over what the sample still holds when it has thinned (a + // pass over its rows that thinning has just made anyway). Within twice the budget: a row + // kept holds its slots and string capacity besides the values the budget counts. + let mut held = 0u64; + let held_limit = decoded.saturating_mul(2); + let mut charge = |items: &Vec, added: u64, thinned: bool, g: usize| -> Result<()> { + held = if thinned { items.iter().map(|f| super::memory::feature_bytes(f) as u64).sum() } else { held.saturating_add(added) }; + if held > held_limit { + return Err(DataError::Format(format!( + "GeoParquet: the features kept up to row group {g} hold {held} bytes, more than the {held_limit} bytes a read keeps (twice the decoded-column budget): choose a smaller view or a lower limit" + ))); + } + Ok(()) + }; for (&g, take) in groups.iter().zip(&takes) { if unbounded { crate::progress::check()?; @@ -778,6 +794,7 @@ impl FeatureSource for ParquetSource { if geoms.len() != wanted { return Err(DataError::Format(format!("GeoParquet: row group {g} has columns shorter than its rows"))); } + let mut thinned = false; for (k, (r, _)) in take.iter().enumerate().filter(|(_, t)| **t).enumerate() { if unbounded { crate::progress::step(1)?; @@ -795,22 +812,31 @@ impl FeatureSource for ParquetSource { if !geometry.as_ref().map_or(req.extent.is_none(), |g| g.inside) || !sample.wants() { continue; } + let before = sample.items.len(); sample.keep(Feature { id: base.saturating_add(r as u64 + 1), geometry: geometry.map(|p| p.geometry), attrs: Vec::new(), }); + thinned |= sample.items.len() <= before; } // The rows of this group the sample still holds, in order (it may have dropped some). let (chosen, mine) = rows_held(&sample.items, |f| f.id, base, take.len()); if mine.is_empty() { + charge(&sample.items, 0, thinned, g)?; continue; } + // A cancel during the last geometry step is heard as a cancel, not as the budget + // the attribute pass would refuse. + if unbounded { + crate::progress::check()?; + } let attrs: Vec = self.field_cols.iter().map(|&c| read_values(rg.as_ref(), c, &chosen, &budget)).collect::>()?; if attrs.iter().any(|a| a.values.len() != mine.len()) { return Err(DataError::Format(format!("GeoParquet: row group {g} has columns shorter than its rows"))); } + let mut added = 0u64; for (n, &i) in mine.iter().enumerate() { if let Some(f) = sample.items.get_mut(i) { f.attrs = attrs @@ -818,8 +844,10 @@ impl FeatureSource for ParquetSource { .enumerate() .map(|(field, col)| col.value(n, field, &mut unread_dates, &mut rounded_dates)) .collect(); + added = added.saturating_add(super::memory::feature_bytes(f) as u64); } } + charge(&sample.items, added, thinned, g)?; continue; } let attrs: Vec = @@ -852,7 +880,10 @@ impl FeatureSource for ParquetSource { let geometry = geometry.map(|p| p.geometry); let values = attrs.iter().enumerate().map(|(field, col)| col.value(k, field, &mut unread_dates, &mut rounded_dates)).collect(); - sample.keep(Feature { id: base.saturating_add(r as u64 + 1), geometry, attrs: values }); + let feature = Feature { id: base.saturating_add(r as u64 + 1), geometry, attrs: values }; + let (added, before) = (super::memory::feature_bytes(&feature) as u64, sample.items.len()); + sample.keep(feature); + charge(&sample.items, added, sample.items.len() <= before, g)?; } } let matched = (if late { sample.seen() } else { matched }).saturating_mul(thinned as u64); @@ -1191,6 +1222,7 @@ fn column_reader_within(rg: &dyn RowGroupReader, col: usize, limit: u64) -> Resu max_rep: desc.max_rep_level(), chunk_values: u64::try_from(chunk.num_values()).ok().filter(|&n| n > 0).unwrap_or(u64::MAX), note: note.clone(), + column: desc.path().string(), }; Ok((parquet::column::reader::get_column_reader(desc, Box::new(pages)), note)) } @@ -1314,6 +1346,8 @@ struct CheckedPages { /// The values the column chunk's footer says it holds, when it says (levels included). chunk_values: u64, note: Arc, + /// The column's name (its path), which a refusal names. + column: String, } impl Iterator for CheckedPages { @@ -1327,6 +1361,14 @@ impl Iterator for CheckedPages { } impl CheckedPages { + /// `e` with the column it is about named first, for a refusal of this reader's own. + fn named(&self, e: parquet::errors::ParquetError) -> parquet::errors::ParquetError { + match e { + parquet::errors::ParquetError::General(m) => parquet::errors::ParquetError::General(format!("column {}: {m}", self.column)), + other => other, + } + } + /// Refuses a dictionary page whose count its bytes can't hold, and a page of more bytes than /// its column chunk says it holds or than the read allows; the page's bytes otherwise. fn check_size(&self, page: &parquet::column::page::Page) -> parquet::errors::Result { @@ -1410,13 +1452,26 @@ impl CheckedPages { per_value: if delta { 8 } else { 4 }, }; let (count, end) = delta_stream(values, &bounds)?; - if delta { + // The lengths stream of a DELTA_LENGTH_BYTE_ARRAY page, or of a DELTA_BYTE_ARRAY page's + // suffixes, and the bytes after it. A prefix length past the value before it is refused by + // the crate itself. + let lengths = if delta { // The prefix lengths are followed by the suffixes, a DELTA_LENGTH_BYTE_ARRAY stream of as many. let rest = values.get(end..).ok_or_else(|| delta_err("its prefix lengths run past the page"))?; let (suffixes, _) = delta_stream(rest, &bounds)?; if suffixes != count { return Err(delta_err(&format!("it has {count} prefix lengths and {suffixes} suffixes"))); } + rest + } else { + values + }; + // The crate slices each value from the bytes after the lengths as they say, and panics + // on a slice past their end or a negative length. + let (total, at) = delta_lengths(lengths)?; + let left = lengths.len().saturating_sub(at) as u64; + if total > left { + return Err(delta_err(&format!("its values are longer than the page: {total} bytes, of {left} left"))); } Ok(()) } @@ -1514,21 +1569,76 @@ fn delta_stream(data: &[u8], bounds: &DeltaBounds) -> parquet::errors::Result<(u Ok((count, at)) } +/// The sum of the lengths a DELTA_BINARY_PACKED stream at the start of `data` holds, and the offset +/// where it ends, decoding each as the crate's `DeltaBitPackDecoder` does for 32-bit values. Its +/// layout has been checked by [`delta_stream`]; a negative length is refused. One pass over the +/// page's lengths, a few byte reads each, bounded by the count [`delta_stream`] held to the budget, +/// so no Cancel check is needed within a page. +fn delta_lengths(data: &[u8]) -> parquet::errors::Result<(u64, usize)> { + let cut = || delta_err("a stream header is cut off or malformed"); + let zigzag = |v: u64| ((v >> 1) as i64) ^ -((v & 1) as i64); + let negative = || delta_err("a value has a negative length"); + let mut at = 0usize; + let block = uleb(data, &mut at).ok_or_else(cut)?; + let mini_blocks = uleb(data, &mut at).ok_or_else(cut)?; + let count = uleb(data, &mut at).ok_or_else(cut)?; + let mut last = zigzag(uleb(data, &mut at).ok_or_else(cut)?) as i32; + if count == 0 { + return Ok((0, at)); + } + let per_mini = usize::try_from(block.checked_div(mini_blocks).ok_or_else(cut)?).map_err(|_| cut())?; + let widths = usize::try_from(mini_blocks).map_err(|_| cut())?; + let mut total = u64::try_from(last).map_err(|_| negative())?; + let mut left = count.saturating_sub(1); + while left > 0 { + let min_delta = zigzag(uleb(data, &mut at).ok_or_else(cut)?) as i32; + let end = at.checked_add(widths).ok_or_else(cut)?; + let bits = data.get(at..end).ok_or_else(cut)?.to_vec(); + at = end; + for width in bits { + if left == 0 { + break; + } + let width = usize::from(width); + let bytes = width.saturating_mul(per_mini) / 8; + let packed = data.get(at..at.saturating_add(bytes)).ok_or_else(cut)?; + for i in 0..per_mini { + if left == 0 { + break; + } + // Value `i`'s `width` bits (at most 32), least significant first: read from the + // five bytes that hold them, a missing byte as 0. + let bit = i * width; + let mut window = [0u8; 8]; + for (k, w) in window.iter_mut().take(5).enumerate() { + *w = packed.get(bit / 8 + k).copied().unwrap_or(0); + } + let v = (u64::from_le_bytes(window) >> (bit % 8)) & ((1u64 << width) - 1); + last = last.wrapping_add(min_delta).wrapping_add(v as u32 as i32); + total = total.saturating_add(u64::try_from(last).map_err(|_| negative())?); + left -= 1; + } + at = at.saturating_add(bytes); + } + } + Ok((total, at)) +} + impl parquet::column::page::PageReader for CheckedPages { /// The next page, or an error for a dictionary page whose count its bytes can't hold. fn get_next_page(&mut self) -> parquet::errors::Result> { let page = self.pages.get_next_page()?; if let Some(page) = &page { - let len = self.check_size(page)?; + let len = self.check_size(page).map_err(|e| self.named(e))?; if let parquet::column::page::Page::DataPage { encoding, .. } | parquet::column::page::Page::DataPageV2 { encoding, .. } = page && let Some(at) = [Encoding::DELTA_BYTE_ARRAY, Encoding::DELTA_LENGTH_BYTE_ARRAY].iter().position(|e| e == encoding) && !self.delta_listed.get(at).copied().unwrap_or(false) { - return Err(parquet::errors::ParquetError::General(format!( + return Err(self.named(parquet::errors::ParquetError::General(format!( "a page uses the {encoding} encoding, which its column chunk doesn't list" - ))); + )))); } - self.check_delta(page)?; + self.check_delta(page).map_err(|e| self.named(e))?; if let parquet::column::page::Page::DataPage { num_values, .. } | parquet::column::page::Page::DataPageV2 { num_values, .. } = page { @@ -2843,6 +2953,7 @@ mod tests { max_rep: 0, chunk_values: u64::MAX, note: Arc::new(PageNote::default()), + column: "height".into(), } .get_next_page() } @@ -2915,6 +3026,7 @@ mod tests { max_rep: 0, chunk_values: u64::MAX, note: Arc::new(PageNote::default()), + column: "height".into(), } .get_next_page() } @@ -2987,6 +3099,7 @@ mod tests { max_rep: 0, chunk_values: u64::MAX, note: note.clone(), + column: "c".into(), }; assert!(pages.get_next_page().unwrap().is_some()); assert_eq!((note.page.load(Ordering::Relaxed), note.in_page.load(Ordering::Relaxed)), (40, 1)); @@ -3113,6 +3226,7 @@ mod tests { max_rep: 0, chunk_values, note, + column: "c".into(), } .get_next_page() } @@ -3145,7 +3259,7 @@ mod tests { let lengths = Encoding::DELTA_LENGTH_BYTE_ARRAY; let sound = delta_bytes(3, [0; 4], b"ababab"); // Widths that need bits, over several blocks. - let wide = delta_bytes(300, [3, 0, 5, 7], b""); + let wide = delta_bytes(300, [3, 0, 5, 7], &[b'a'; 600]); for v2 in [false, true] { // Level bytes in front, in version 2 (a version 1 page of a column without levels has none). for levels in [0, 2] { @@ -3208,11 +3322,23 @@ mod tests { says(refused(odd, 3, delta), "it has 3 prefix lengths and 2 suffixes"); // Sound pages go through, and so does a column of nothing but nulls. for (values, n) in - [(sound.clone(), 3), (wide.clone(), 300), (delta_bytes(0, [0; 4], b""), 3), (delta_bytes(1, [0; 4], b"a"), 1)] + [(sound.clone(), 3), (wide.clone(), 300), (delta_bytes(0, [0; 4], b""), 3), (delta_bytes(1, [0; 4], b"aa"), 1)] { assert!(checked(page(values, n, delta), None, 1 << 30, true).unwrap().is_some(), "{at}"); } - assert!(checked(page(delta_flat(3, 4), 3, lengths), None, 1 << 30, true).unwrap().is_some(), "{at}"); + assert!( + checked(page([delta_flat(3, 4), b"ababab".to_vec()].concat(), 3, lengths), None, 1 << 30, true).unwrap().is_some(), + "{at}" + ); + // The lengths run one byte past the page, in either encoding: refused, as the + // crate would slice past the end. + says( + refused([delta_flat(3, 4), b"ababa".to_vec()].concat(), 3, lengths), + "its values are longer than the page: 6 bytes, of 5 left", + ); + says(refused(delta_bytes(3, [0; 4], b"ababa"), 3, delta), "its values are longer than the page: 6 bytes, of 5 left"); + // A negative length (zigzag 3 is -2). + says(refused([delta_flat(3, 3), b"ab".to_vec()].concat(), 3, lengths), "a value has a negative length"); } } } @@ -3221,7 +3347,7 @@ mod tests { /// the crate reads them, and a page with them cut off or in no encoding a page has is refused. #[test] fn checked_pages_find_the_values_after_a_version_one_pages_levels() { - let sound = delta_bytes(300, [3, 0, 5, 7], b""); + let sound = delta_bytes(300, [3, 0, 5, 7], &[b'a'; 600]); let rle = |bytes: &[u8]| [u32::try_from(bytes.len()).unwrap().to_le_bytes().to_vec(), bytes.to_vec()].concat(); let page = |levels: Vec, values: Vec, encoding| delta_page_with_levels(levels, values, 300, encoding); // A definition level stream of 3 bytes, then the values. @@ -3240,7 +3366,7 @@ mod tests { /// count allows it; and one the budget left can't hold the arrays of, though the whole limit could. #[test] fn checked_pages_hold_a_delta_count_to_the_chunk_and_the_budget_left() { - let values = delta_bytes(300, [3, 0, 5, 7], b""); + let values = delta_bytes(300, [3, 0, 5, 7], &[b'a'; 600]); let page = || delta_page(0, values.clone(), 300, Encoding::DELTA_BYTE_ARRAY, true); assert!(checked_in(page(), 0, 300, 2400).unwrap().is_some()); let error = checked_in(page(), 0, 299, u64::MAX).unwrap_err().to_string(); @@ -3312,8 +3438,8 @@ mod tests { both.extend(delta_flat(count, 4)); let error = checked(delta_page(0, both, count, Encoding::DELTA_BYTE_ARRAY, true), None, limit, true).unwrap_err().to_string(); assert!(error.contains("decoded-column budget"), "{error}"); - // The one array of DELTA_LENGTH_BYTE_ARRAY fits. - let page = delta_page(0, delta_flat(count, 4), count, Encoding::DELTA_LENGTH_BYTE_ARRAY, true); + // The one array of DELTA_LENGTH_BYTE_ARRAY fits (empty values, so the page holds them). + let page = delta_page(0, delta_flat(count, 0), count, Encoding::DELTA_LENGTH_BYTE_ARRAY, true); assert!(checked(page, None, limit, true).unwrap().is_some()); } @@ -3346,6 +3472,7 @@ mod tests { max_rep: 0, chunk_values: u64::MAX, note: Arc::new(PageNote::default()), + column: "c".into(), }; assert!(pages.get_next_page().unwrap().is_some()); } @@ -3393,6 +3520,7 @@ mod tests { max_rep: 0, chunk_values: u64::MAX, note: note.clone(), + column: "c".into(), }; let budget = Budget::new(1 << 20, 0); let pace = Pace { watch: Some((¬e, &budget)) }; diff --git a/crates/data/src/source/shp.rs b/crates/data/src/source/shp.rs index 53337cf7d3..a4a26613dc 100644 --- a/crates/data/src/source/shp.rs +++ b/crates/data/src/source/shp.rs @@ -146,7 +146,7 @@ impl ShpSource { let stamps = [Stamp::of(path), Stamp::of(&dbf)]; let mut notes = crate::loss::Notes::new(); let table = read_table(&dbf)?; - let cpg = crate::dbf::read_cpg(path, &mut notes)?; + let cpg = crate::dbf::read_cpg(path, table.ldid, &mut notes)?; crate::dbf::unused_cst(cpg.as_deref(), table.ldid, || crate::dbf::has_cst(path), &mut notes); let encoding = crate::dbf::encoding(cpg.as_deref(), table.ldid, &mut notes); let shp_len = std::fs::metadata(path)?.len(); diff --git a/crates/data/src/source/tests.rs b/crates/data/src/source/tests.rs index d9b4cd2e0f..9a1938b185 100644 --- a/crates/data/src/source/tests.rs +++ b/crates/data/src/source/tests.rs @@ -1083,7 +1083,8 @@ fn geoparquet_refuses_dictionary_counts_its_page_cannot_hold() { let md = md.into_builder().set_row_groups(groups).build(); ::parquet::file::metadata::ParquetMetaDataWriter::new(&mut bytes, &md).finish().unwrap(); let error = crate::io::read_layers("x.parquet", &bytes).err().unwrap().to_string(); - assert!(error.contains("dictionary page says it holds 2000000000 values"), "{error}"); + // The refusal names the column, so a file of several is told apart. + assert!(error.contains("column geometry: a dictionary page says it holds 2000000000 values"), "{error}"); } #[test] @@ -3148,7 +3149,7 @@ fn geojson_crs_is_read_only_from_the_feature_collection() { } #[test] -fn geojson_features_that_cant_be_converted_are_skipped_and_counted() { +fn geojson_features_that_cant_be_converted_are_kept_and_said() { // A coordinate the declared system can't convert (UTM 1e9 m east), or converts to beyond // longitude/latitude (Web Mercator 1e9 m east is longitude 8983°): the feature is kept as the // file holds it, said, and doesn't draw; nothing was lost, so a projection can still be @@ -5496,6 +5497,31 @@ fn parquet_geometry_column_is_charged_with_the_fields() { assert_eq!(source.read(&whole).unwrap().features.len(), 20); } +/// The rows a read keeps count against the budget across row groups too: groups that each fit +/// it, together over it, are refused with a way out; a budget they fit in reads them all. +#[test] +fn parquet_read_holds_the_rows_it_keeps_to_the_budget() { + let p = dir().join("decoded-total.parquet"); + let mut ds = Dataset::new("pts", GeometryType::Point, vec![Field::new("label", FieldType::Text)]); + for i in 0..20 { + ds.push(Some(Geometry::Point(Coord::new(-81.0, 0.0))), vec![Value::Text(format!("{}{i:02}", "x".repeat(1024)))]); + } + // Ten row groups of two rows, about 2 KiB of text each. + write_encoded_parquet_fixture(&ds, &p, 2, false, FixturePages::default()); + let whole = Request { extent: None, limit: 100, own: None }; + let source = parquet::ParquetSource::open_path(&p, "pts").unwrap().with_decoded_bytes(8 << 10); + // A whole read, and one of an extent whose rows are tested before their attributes are read. + let bounded = Request { extent: Some(Extent::new(-84.0, -1.0, -78.0, 1.0)), limit: 100, own: None }; + for req in [&whole, &bounded] { + let error = source.read(req).unwrap_err().to_string(); + assert!(error.contains("features kept up to row group") && error.contains("choose a smaller view or a lower limit"), "{error}"); + } + let source = parquet::ParquetSource::open_path(&p, "pts").unwrap().with_decoded_bytes(64 << 10); + for req in [&whole, &bounded] { + assert_eq!(source.read(req).unwrap().features.len(), 20); + } +} + /// A read takes only some rows of a column chunk far bigger than the budget: it is the rows taken /// and the size of a page that count, not the chunk's, so a view or a sample still reads (#2913). #[test] @@ -6501,7 +6527,7 @@ fn geopackage_index_holds_each_placed_feature_and_repeats() { /// The spatial index of a GeoPackage lists exactly the features with a place, for a layer with /// none, one of only null and empty geometries, a table added to a file that has another, and one -/// replaced there (and a point layer that turns out to hold multipoints, which restarts the export). +/// replaced there (and a point layer that holds multipoints). #[cfg(not(target_arch = "wasm32"))] #[test] fn geopackage_index_lists_only_features_with_a_place() { diff --git a/crates/data/src/sqlite.rs b/crates/data/src/sqlite.rs index 80d0f89ff9..3622892595 100644 --- a/crates/data/src/sqlite.rs +++ b/crates/data/src/sqlite.rs @@ -266,7 +266,7 @@ impl> Db { ) -> Result, String> { let floor = ptrs.saturating_add(2usize.saturating_mul(cells)); if floor > self.usable { - return Err(bad("overlapping cells")); + return Err(bad("a cell pointer array past the end of its page")); } let mut spans = Vec::with_capacity(cells); for i in 0..cells { @@ -917,6 +917,11 @@ mod tests { assert_eq!(rows(&leaf(&[450, 453], &[(450, [1, 1, 8, 0]), (453, [1, 2, 9, 0])])), Err(bad("overlapping cells"))); // Distinct cells side by side are read, each once. assert_eq!(rows(&leaf(&[450, 454], &[(450, [2, 1, 2, 0]), (454, [2, 2, 2, 0])])), Ok(2)); + // More cells than the page has room for pointers to: the pointer array itself runs past it. + let mut crowded = [0u8; 512]; + crowded[0] = 0x0d; + crowded[3..5].copy_from_slice(&300u16.to_be_bytes()); + assert_eq!(rows(&make_db(crowded)), Err(bad("a cell pointer array past the end of its page"))); } #[test] diff --git a/crates/data/tests/integration/shapefile_encoding.rs b/crates/data/tests/integration/shapefile_encoding.rs index 3c08a6fde3..2a9a9d1ffc 100644 --- a/crates/data/tests/integration/shapefile_encoding.rs +++ b/crates/data/tests/integration/shapefile_encoding.rs @@ -98,7 +98,7 @@ fn invalid_note(values: usize, field: &str, encoding: &str) -> String { /// What opening a `.dbf` says of its one field name that isn't valid in `encoding`, the first column. fn invalid_name_note(encoding: &str) -> String { format!( - "Shapefile: 1 field name isn't valid {encoding} and was read with U+FFFD in place of the bytes that can't be read, in field 1; {}", + "1 field name isn't valid {encoding} and was read with U+FFFD in place of the bytes that can't be read, in field 1; {}", cause(encoding) ) } @@ -649,11 +649,14 @@ fn check_ldid_readers(ldid: u8, text: &[u8], expected: &str, cpg: Option<&[u8]>, assert_eq!(ds.value(row, 0), &Value::Text(expected.into()), "LDID {ldid:02X} row {row}"); } }; + // Every read of the whole file names the layer in each note; the notes of opening a source + // read in place are named once it is read whole. + let whole: Vec = notes.iter().map(|n| if n.starts_with("places: ") { n.to_string() } else { format!("places: {n}") }).collect(); let layers = io::read_zip("places.zip", &rustgis_data::zip::write(&files).unwrap()).unwrap(); assert_eq!(layers.len(), 1); check(&layers[0].0, 3); assert_eq!(layers[0].1.skipped, 0); - assert_eq!(texts(&layers[0].1.messages), notes, "LDID {ldid:02X} ZIP notes"); + assert_eq!(texts(&layers[0].1.messages), whole, "LDID {ldid:02X} ZIP notes"); encoding_assumed(&layers[0].1.messages, ldid); #[cfg(not(target_arch = "wasm32"))] { @@ -666,15 +669,13 @@ fn check_ldid_readers(ldid: u8, text: &[u8], expected: &str, cpg: Option<&[u8]>, let (ds, report) = io::read_path(&path).unwrap(); check(&ds, 3); assert_eq!(report.skipped, 0); - assert_eq!(texts(&report.messages), notes, "LDID {ldid:02X} loose-file notes"); + assert_eq!(texts(&report.messages), whole, "LDID {ldid:02X} loose-file notes"); encoding_assumed(&report.messages, ldid); let src = open_shp(&path, "places").unwrap(); assert_eq!(src.info().fields[0].name, expected, "LDID {ldid:02X} streamed field name"); let opening: Vec<&str> = notes.iter().copied().filter(|n| !n.starts_with("places: ")).collect(); assert_eq!(texts(&src.info().notes), opening, "LDID {ldid:02X} streamed notes"); encoding_assumed(&src.info().notes, ldid); - let whole: Vec = - notes.iter().map(|n| if n.starts_with("places: ") { n.to_string() } else { format!("places: {n}") }).collect(); assert_eq!(texts(&rustgis_data::source::materialize(&src).unwrap().1.messages), whole, "LDID {ldid:02X} whole read in place"); for (request, rows, complete) in [(Request { extent: None, limit: 1, own: None }, 1, false), (Request::all(), 3, true)] { let batch = src.read(&request).unwrap(); @@ -714,10 +715,10 @@ fn documented_unsupported_ldids_and_unknown_markers_keep_lossy_utf8_with_a_diagn // The last byte isn't UTF-8: the name and the three values it is replaced in are counted. let (name, values) = (name_not_utf8_note(), not_utf8_note(3, "é�")); for &(ldid, page) in UNSUPPORTED_LDIDS { - let note = format!("Shapefile: unsupported .dbf code page 0x{ldid:02X} (code page {page}); using UTF-8"); + let note = format!("unsupported .dbf code page 0x{ldid:02X} (code page {page}); using UTF-8"); check_ldid_readers(ldid, b"\xc3\xa9\xff", "é�", None, &[¬e, &name, &values]); } - check_ldid_readers(0xFF, b"\xc3\xa9\xff", "é�", None, &["Shapefile: unsupported .dbf code page 0xFF; using UTF-8", &name, &values]); + check_ldid_readers(0xFF, b"\xc3\xa9\xff", "é�", None, &["unsupported .dbf code page 0xFF; using UTF-8", &name, &values]); } #[test] @@ -731,7 +732,7 @@ fn cpg_overrides_every_supported_or_unsupported_ldid() { #[test] fn unusable_cpg_falls_back_to_each_supported_decoder() { - let note = "Shapefile: unsupported or empty .cpg; using the .dbf code page, or UTF-8 if unavailable"; + let note = "unsupported or empty .cpg; using the .dbf code page, or UTF-8 if unavailable"; for &(markers, text, expected) in SUPPORTED_LDIDS { check_ldid_readers(markers[0], text, expected, Some(b"not-an-encoding"), &[note]); } @@ -740,7 +741,7 @@ fn unusable_cpg_falls_back_to_each_supported_decoder() { b"\xc3\xa9\xff", "é�", Some(b""), - &[note, "Shapefile: unsupported .dbf code page 0xFF; using UTF-8", &name_not_utf8_note(), ¬_utf8_note(3, "é�")], + &[note, "unsupported .dbf code page 0xFF; using UTF-8", &name_not_utf8_note(), ¬_utf8_note(3, "é�")], ); } @@ -797,6 +798,42 @@ fn malformed_values_are_counted_per_value_and_clean_text_says_nothing() { } } +/// A `.dbf` opened by itself names its layer in its encoding note, as a Shapefile's does, never +/// "Shapefile:"; an unreadable `.cpg` (here a folder) is said once, with what is used instead, +/// assumed only where the `.dbf` names no code page; a clean table with a valid `.cpg` says nothing. +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn a_standalone_dbf_names_its_layer_and_an_unreadable_cpg_is_said_once() { + let dir = tempfile::tempdir().unwrap(); + let write = |ldid: u8, cpg: Option<&[u8]>| { + let path = dir.path().join("places.dbf"); + let files = named_parts(b"name", b"plain", ldid, None, 1); + let dbf = files.iter().find(|(n, _)| n.ends_with(".dbf")).map(|(_, b)| b.clone()).unwrap(); + std::fs::write(&path, dbf).unwrap(); + let cpg_path = dir.path().join("places.cpg"); + let _ = std::fs::remove_file(&cpg_path); + let _ = std::fs::remove_dir(&cpg_path); + match cpg { + Some(b"") => std::fs::create_dir(&cpg_path).unwrap(), + Some(bytes) => std::fs::write(&cpg_path, bytes).unwrap(), + None => {} + } + io::read_path(&path).unwrap().1.messages + }; + let said = write(0xFF, None); + assert_eq!(texts(&said), ["places: unsupported .dbf code page 0xFF; using UTF-8"]); + // Unreadable: one note, coded when the `.dbf` names no code page, plain when it names one. + for (ldid, coded) in [(0x00, true), (0x57, false)] { + let said = write(ldid, Some(b"")); + let encoding: Vec<_> = said.iter().filter(|n| n.contains(".cpg")).collect(); + assert_eq!(encoding.len(), 1, "{said:?}"); + assert!(encoding[0].starts_with("places: could not read the .cpg ("), "{said:?}"); + assert!(encoding[0].ends_with("using the .dbf code page if RustGIS reads it, otherwise UTF-8"), "{said:?}"); + assert_eq!(encoding[0].loss == Some(rustgis_data::loss::LossCode::AssumedEncoding), coded, "{said:?}"); + } + assert!(write(0x57, Some(b"UTF-8")).is_empty()); +} + /// CST is advisory only, including ZIP and browser packaging, with exactly the decoder's /// existing CPG/LDID precedence. Compare data, fields and geometry against the same read without it. #[test] diff --git a/crates/data/tests/large_value_memory.rs b/crates/data/tests/large_value_memory.rs index 0d1e830122..a4674f79e2 100644 --- a/crates/data/tests/large_value_memory.rs +++ b/crates/data/tests/large_value_memory.rs @@ -29,13 +29,21 @@ fn peak_bytes() -> u64 { line.trim().trim_end_matches("kB").trim().parse::().unwrap() * 1024 } -/// How far `run` takes the peak past what is held as it starts. -fn growth(run: impl FnOnce()) -> u64 { +/// How far `run` takes the peak past what is held as it starts; `None` (`run` still run) where +/// the peak can't be set back, a host whose `/proc` is read-only or has no page monitor (some +/// containers), so a host problem doesn't read as a failure of what is measured. +fn growth(run: impl FnOnce()) -> Option { // Linux sets the peak back to what is held now. - std::fs::write("/proc/self/clear_refs", "5").unwrap(); + if let Err(e) = std::fs::write("/proc/self/clear_refs", "5") { + // On CI the peak is measured, never skipped. + assert!(std::env::var_os("CI").is_none(), "the peak can't be set back on CI ({e})"); + eprintln!("the peak can't be set back on this host ({e}), so it isn't measured"); + run(); + return None; + } let before = peak_bytes(); run(); - peak_bytes().saturating_sub(before) + Some(peak_bytes().saturating_sub(before)) } /// [`ROWS`] short lines with a wide table, then one line of `ITEM` bytes of points. @@ -70,8 +78,8 @@ fn a_large_value_or_shape_is_not_copied_for_a_download() { let number = || format!("+0.{}1", "0".repeat(ITEM)); let vertices = || (0..ITEM / 16).map(|i| Coord::new((i % 360) as f64 - 180.0, 1.5)).collect::>(); let mut over = Vec::new(); - let mut check = |name: &str, grew: u64| { - if grew >= MOST { + let mut check = |name: &str, grew: Option| { + if let Some(grew) = grew.filter(|g| *g >= MOST) { over.push(format!("{name}: the peak grew {} MiB", grew >> 20)); } }; @@ -155,7 +163,7 @@ fn a_large_value_or_shape_is_not_copied_for_a_download() { assert!(rustgis_data::io::write_bytes_noted_within(&ds, "shp", Crs::LonLat, "t", &limit).is_err()); }); assert!(limit.passed()); - if grew >= TABLE as u64 + MOST { + if let Some(grew) = grew.filter(|g| *g >= TABLE as u64 + MOST) { over.push(format!("Shapefile line after a table: the peak grew {} MiB", grew >> 20)); } diff --git a/crates/data/tests/projected_download_memory.rs b/crates/data/tests/projected_download_memory.rs index 5c7eb00898..91e6db443a 100644 --- a/crates/data/tests/projected_download_memory.rs +++ b/crates/data/tests/projected_download_memory.rs @@ -20,13 +20,21 @@ fn peak_bytes() -> usize { line.trim().trim_end_matches("kB").trim().parse::().unwrap() * 1024 } -/// How far `run` takes the peak past what is held as it starts. -fn growth(run: impl FnOnce()) -> usize { +/// How far `run` takes the peak past what is held as it starts; `None` (`run` still run) where +/// the peak can't be set back, a host whose `/proc` is read-only or has no page monitor (some +/// containers), so a host problem doesn't read as a failure of what is measured. +fn growth(run: impl FnOnce()) -> Option { // Linux sets the peak back to what is held now. - std::fs::write("/proc/self/clear_refs", "5").unwrap(); + if let Err(e) = std::fs::write("/proc/self/clear_refs", "5") { + // On CI the peak is measured, never skipped. + assert!(std::env::var_os("CI").is_none(), "the peak can't be set back on CI ({e})"); + eprintln!("the peak can't be set back on this host ({e}), so it isn't measured"); + run(); + return None; + } let before = peak_bytes(); run(); - peak_bytes().saturating_sub(before) + Some(peak_bytes().saturating_sub(before)) } /// The CSV notices, counted before a file is written, then each format, of which `shp`, `parquet` @@ -83,8 +91,10 @@ fn measure(case: &str) { said = rustgis_data::io::write_bytes_noted_within(&ds, format, crs, "t", &limit).err().map(|e| e.to_string()); passed = limit.passed(); }); - eprintln!("{case}: the peak grew {:.3} of the layer ({} KiB of {} KiB)", grew as f64 / held as f64, grew >> 10, held >> 10); - assert!(grew < held / 4, "{case}: the peak grew {} MiB, the layer holding {} MiB", grew >> 20, held >> 20); + if let Some(grew) = grew { + eprintln!("{case}: the peak grew {:.3} of the layer ({} KiB of {} KiB)", grew as f64 / held as f64, grew >> 10, held >> 10); + assert!(grew < held / 4, "{case}: the peak grew {} MiB, the layer holding {} MiB", grew >> 20, held >> 20); + } assert_eq!(said.is_some(), !notices, "{case}: an over-limit write is refused"); assert_eq!(passed, !whole && !notices, "{case}: {said:?}"); if whole { diff --git a/crates/engine/src/cmd/layer.rs b/crates/engine/src/cmd/layer.rs index c5b908de2d..5cab4ca5cc 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|.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.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|.topojson|.dxf|.kml|.gpx|.rss|.atom|.georss|.landxml|.xml (LandXML or GeoRSS); a file of several layers (a city model, KML, GPX and the like) gives 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") @@ -2830,13 +2830,14 @@ pub(crate) fn add_layers(s: &mut Session, p: &Value, file_name: &str, bytes: &[u // A layer picked leaves the document's ground overlays (pictures, not layers) out: said. 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, - ), + Ok((found, undrawn, over_budget)) if found.len() + undrawn + over_budget > 0 => { + let count = found.len() + undrawn + over_budget; + let what = if count == 1 { "ground overlay (picture) isn't" } else { "ground overlays (pictures) aren't" }; + s.notify( + format!("{file_name}: {count} {what} added with a layer picked; add the file without \"layer\" to draw them"), + false, + ) + } Ok(_) => {} Err(e) => s.notify(format!("{file_name}: its ground overlays (pictures) couldn't be read, so none is added: {e}"), false), } diff --git a/crates/engine/src/tests/held_databases.rs b/crates/engine/src/tests/held_databases.rs index 2a9d068d04..ea3c8c9707 100644 --- a/crates/engine/src/tests/held_databases.rs +++ b/crates/engine/src/tests/held_databases.rs @@ -276,6 +276,50 @@ fn a_geopackage_layer_held_in_a_third_system_saves_twice_in_place() { let _ = std::fs::remove_dir_all(&dir); } +/// A new feature of a GeoPackage layer held in a third system with a coordinate that isn't a +/// number is named as one on save, not as "row new". +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn a_geopackage_save_names_a_new_feature_as_one() { + use rustgis_data::{Coord, Dataset, Field, FieldType, Geometry, GeometryType, Value, raster::Crs}; + let dir = std::env::temp_dir().join(format!("rustgis-held-gpkg-unread-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + let path = dir.join("towns.gpkg"); + let lv95 = Crs::from_epsg(2056).unwrap(); + let utm = Crs::from_epsg(32632).unwrap(); + let mut ds = Dataset::new("towns", GeometryType::Point, vec![Field::new("name", FieldType::Text)]); + ds.push(Some(Geometry::Point(Coord::new(2_600_000.123, 1_200_000.456))), vec![Value::Text("Bern".into())]); + ds.push(Some(Geometry::Point(Coord::new(2_601_000.0, 1_201_000.0))), vec![Value::Text("Thun".into())]); + ds.crs = Some(lv95); + ds.held_in = lv95; + rustgis_data::io::write_path_in(&ds, &path, lv95).unwrap(); + let load = |s: &mut Session| { + let loaded = s.run("gpkg.addLayer", &json!({"path": path, "table": "towns", "name": "T"})).unwrap(); + let id = loaded["layer"].as_u64().unwrap() as u32; + s.map_mut().editing.settings.enabled = true; + let l = s.map_mut().layer_mut(id).unwrap(); + l.dataset = rustgis_data::io::project(&l.dataset, utm).unwrap(); + l.touch_geometry(); + let features: Vec<_> = l.dataset.features.iter().cloned().collect(); + if let Some(g) = l.gpkg.as_mut() { + g.versions = rustgis_map::source::versions_of(&features, &g.versions, &Default::default()); + } + id + }; + // A new feature whose coordinate isn't a number. + let mut s = Session::new(Project::default()); + let id = load(&mut s); + { + let l = s.map_mut().layer_mut(id).unwrap(); + l.dataset.push(Some(Geometry::Point(Coord::new(f64::NAN, 5_000_000.0))), vec![Value::Text("Nowhere".into())]); + l.touch_geometry(); + } + let e = s.run("gpkg.saveEdits", &json!({"layer": "T"})).unwrap_err(); + assert!(e.contains("a new feature: its geometry has a coordinate that isn't a number") && !e.contains("row new"), "{e}"); + let _ = std::fs::remove_dir_all(&dir); +} + /// A column of no fixed coordinate system whose rows say none (SRID 0), loaded with `"crs"`, is /// held in that system: read as stored, and edits written back as stored, still with SRID 0. /// `RUSTGIS_TEST_POSTGIS` names a database (`postgresql://…`) where the test may make and drop a diff --git a/crates/engine/tests/integration/never_silent_reading.rs b/crates/engine/tests/integration/never_silent_reading.rs index 2d4cdbc6fb..922faed77c 100644 --- a/crates/engine/tests/integration/never_silent_reading.rs +++ b/crates/engine/tests/integration/never_silent_reading.rs @@ -335,7 +335,7 @@ pub(super) fn cases(fixture_dir: &std::path::Path) -> Vec { "a.kml", kml(&[&kml_polygon("1,1 2,1 2,2 1,1")]), kml(&[&kml_polygon("1,1 x,y")]), - Imported("1 unreadable KML polygon hole was left out"), + Imported("1 KML polygon hole with fewer than three usable coordinates was left out"), ) }, case( diff --git a/crates/engine/tests/integration/read_routes.rs b/crates/engine/tests/integration/read_routes.rs index f698e620cf..3961e9ffc3 100644 --- a/crates/engine/tests/integration/read_routes.rs +++ b/crates/engine/tests/integration/read_routes.rs @@ -268,7 +268,7 @@ fn a_zips_own_notices_reach_the_layer_picked() { 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(); + let overlays: Vec<&String> = said.iter().filter(|n| n.contains("1 ground overlay (picture) isn't drawn")).collect(); assert!(overlays.len() == 1 && overlays[0].contains(named), "{i} {layer:?}: {said:?}"); } } @@ -290,7 +290,7 @@ fn a_kml_layer_picked_says_the_overlays_left_out() { 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(); + let left_out = said.iter().filter(|n| n.contains("1 ground overlay (picture) isn't added with a layer picked")).count(); assert_eq!(left_out, usize::from(picked), "picked {picked}: {said:?}"); } let _ = std::fs::remove_dir_all(&dir); diff --git a/crates/engine/tests/integration/zip_columns.rs b/crates/engine/tests/integration/zip_columns.rs index 28df8df0d6..5934cadec3 100644 --- a/crates/engine/tests/integration/zip_columns.rs +++ b/crates/engine/tests/integration/zip_columns.rs @@ -140,7 +140,7 @@ fn a_zips_other_members_ignore_the_columns_and_keep_their_notices() { assert!(s.map().layers.iter().any(|l| l.dataset.name == "a" && l.dataset.features.len() == 1)); assert!(s.map().layers.len() >= 2, "the KML's own layer stays"); assert!(said.iter().any(|t| t.contains("skipped") && t.contains("junk.txt")), "{said:?}"); - assert!(said.iter().any(|t| t.contains("1 ground overlays (pictures) aren't drawn from inside a zip, in o.kml (1)")), "{said:?}"); + assert!(said.iter().any(|t| t.contains("1 ground overlay (picture) isn't drawn from inside a zip, in o.kml (1)")), "{said:?}"); // Every notice but the columns' (there is none here) is what the zip says without the columns given. let (_, before) = add("path", &bytes, json!({})); let strip = diff --git a/crates/geolibre/src/lib.rs b/crates/geolibre/src/lib.rs index 40f4424777..0d1f62dd81 100644 --- a/crates/geolibre/src/lib.rs +++ b/crates/geolibre/src/lib.rs @@ -1084,10 +1084,13 @@ fn load( // A feature with a place that can't be given in longitude/latitude // is kept as read, and counted: it doesn't draw (#2032 C2f-4b). Each // place is converted to be checked; the layer keeps its own. - let (mut lost, mut beyond) = (0usize, 0usize); + let (mut lost, mut beyond, mut placed) = (0usize, 0usize, 0usize); for g in ds.features.rows().filter_map(|r| r.geometry()) { match Dataset::converted_to_lonlat(&to, g) { - Some(l) => beyond += usize::from(l.extent().beyond_lonlat()), + Some(l) => { + placed += 1; + beyond += usize::from(l.extent().beyond_lonlat()); + } None => lost += 1, } } @@ -1098,12 +1101,10 @@ fn load( job.crs.label() )); } - if lost > 0 { - let have = if lost == 1 { "feature has" } else { "features have" }; - messages.push(format!( - "{layer_name}: {lost} {have} a place in {} that can't be given in longitude/latitude: kept as read, but not drawn", - job.crs.label() - )); + // In the words every reader uses, with Define Projection's + // advice when none of them has a place. + if let Some(note) = rustgis_data::io::kept_unplaced_note("features", lost, placed == 0, job.crs) { + messages.push(format!("{layer_name}: {note}")); } } // Not held in a system it can't be converted from: kept as read, and said. @@ -1166,6 +1167,13 @@ fn colours_split( rgba } Ok(None) => bytes.to_vec(), + // Undecided: the band may not be colour at all, so no loss is claimed. + Err(rustgis_data::DataError::Unsupported(why)) => { + messages.push(format!( + "{layer_name}: its one band couldn't be checked for packed colours ({why}): it is kept as written; if it holds packed colours, their red byte is lost" + )); + bytes.to_vec() + } Err(e) => { messages.push(format!( "{layer_name}: its one band of packed colours couldn't be split into red, green and blue bands ({e}): it is kept as one band of 32-bit floats, which lose the red byte" diff --git a/crates/geolibre/src/tests.rs b/crates/geolibre/src/tests.rs index d88b9e7e7d..25a6655560 100644 --- a/crates/geolibre/src/tests.rs +++ b/crates/geolibre/src/tests.rs @@ -699,6 +699,12 @@ fn packed_colour_outputs_come_back_as_rgb_bands() { let (bytes, _, messages) = returned(&turned); assert_eq!(bytes, turned); assert!(messages.iter().any(|m| m.contains("couldn't be split") && m.contains("rotated or skewed")), "{messages:?}"); + // A rotated band of IDs whose no-data value (2^32 as read) is past every colour isn't colour: + // kept as written, and no loss of a red byte is said. + let ids = u32_tiff([1, 2, 3, 0xFFFF_FFFF], Some("4294967295"), true); + let (bytes, _, messages) = returned(&ids); + assert_eq!(bytes, ids); + assert!(messages.iter().all(|m| !m.contains("couldn't be split")), "{messages:?}"); // A file with no GeoTIFF tags has only a stand-in place: never written out as coordinates. let tagless = { let mut out = std::io::Cursor::new(Vec::new()); diff --git a/docs/user-guide/data-formats.md b/docs/user-guide/data-formats.md index c9be0e8a53..0c36ef1ce4 100644 --- a/docs/user-guide/data-formats.md +++ b/docs/user-guide/data-formats.md @@ -63,10 +63,10 @@ and common East Asian encodings are supported. The Esri `0x57` DBF marker is read as Windows-1252. An unreadable, empty, invalid, oversized or unsupported `.cpg` gives a notice and falls back to the DBF code page; an unsupported DBF code page gives a notice and falls back to UTF-8. Files without encoding metadata keep the UTF-8 default. Unsupported characters become -replacement characters, and when text isn't valid in the encoding it is read in (Big5 text with no -`.cpg` read as UTF-8, or a byte that isn't valid in the Shift_JIS, GBK, EUC-KR or Big5 a file declares, -say) a notice counts those values, names their fields, and names that encoding. This applies to zipped files and large -files read in place too. +replacement characters. When text isn't valid in the encoding it is read in (say, Big5 text with +no `.cpg`, read as UTF-8, or a byte that isn't valid in the Shift_JIS, GBK, EUC-KR or Big5 +encoding a file declares), a notice counts those values, names their fields and names that +encoding. This applies to zipped files and large files read in place too. See the [DBF language-driver support inventory](shapefile-encoding.md) for every recognized marker and the legacy code pages that still use the UTF-8 fallback. diff --git a/docs/user-guide/loss-codes.md b/docs/user-guide/loss-codes.md index 76a65b6ed2..556f67416b 100644 --- a/docs/user-guide/loss-codes.md +++ b/docs/user-guide/loss-codes.md @@ -54,7 +54,7 @@ A value could not be kept and was read or written as empty (null). Examples are **Where you see it:** reading a spreadsheet, Parquet, PostGIS or table-based source; reading DTED or GRIB rasters; Calculate Field. -**What to do:** Correct the value or use a destination field that can hold it. +**What to do:** Correct the value in the source, or, on export, use a destination field that can hold it. ### `dropped.calculation-result` { #dropped.calculation-result } @@ -78,7 +78,7 @@ A coordinate system's name or definition could not be written with the data, so **Where you see it:** exporting to a Shapefile (no .prj file) or to CSV; exporting layers on another body than the Earth; reading Zarr stores. -**What to do:** Keep the source file's coordinate system definition with the export, or export in WGS 84, which every format can name. +**What to do:** On reading, give the coordinate system in a form RustGIS reads ("crs" when adding the data, or Define Projection); on export, keep the source's coordinate system definition with it, or export in WGS 84, which every format can name. ### `dropped.feature` { #dropped.feature } @@ -94,15 +94,15 @@ A feature's geometry could not be read or written. The feature was kept without **Where you see it:** reading CSV with WKT, GPX, TopoJSON or MapInfo data; exporting layers with a place the target coordinate system cannot hold; Repair Geometry. -**What to do:** Correct the geometry in the source, or give the coordinate system its coordinates are in. +**What to do:** Correct the geometry in the source; when the notice names a coordinate system, give the one its coordinates are in. ### `dropped.over-limit` { #dropped.over-limit } RustGIS read only part of the data because it is past a size limit. -**Where you see it:** reading point-cloud (LAS and LAZ), DXF, KML or photo data, or a raster with a very long list of class names. +**Where you see it:** reading point-cloud (LAS and LAZ), DXF, GML, KML or photo data, or a raster with a very long list of class names. -**What to do:** Read less at once, such as by filtering or clipping the source first. +**What to do:** Read less at once, such as by filtering or clipping the source first, or keep fewer fields (columns) in it. ## Changed @@ -130,7 +130,7 @@ Text was cut short to fit a format or a limit. **Where you see it:** exporting to Shapefile (254 bytes per value); labels and annotations; reading raster band or class names. -**What to do:** Shorten the text to what the format holds (254 bytes for a Shapefile; nothing past a NUL character), or write to a format without the limit, such as GeoPackage. +**What to do:** Shorten the text or name in the source; on export, to what the format holds (254 bytes for a Shapefile; nothing past a NUL character), or write to a format without the limit, such as GeoPackage. ### `changed.body` { #changed.body } @@ -146,7 +146,7 @@ Text that is not valid in the encoding it was read with was read with a replacem **Where you see it:** reading a Shapefile or dBASE file, a DXF drawing, or feature service answers in PBF. -**What to do:** Put a .cpg file naming the file's own encoding beside it. +**What to do:** Give the source's encoding in a form RustGIS reads: a .cpg beside a Shapefile or dBASE file, a DXF saved as UTF-8 or with its $DWGCODEPAGE, or a service that sends UTF-8. ### `changed.rounded` { #changed.rounded } @@ -174,7 +174,7 @@ A datum RustGIS does not shift was treated as WGS 84, so places may be a little **Where you see it:** reading DTED rasters; exporting a layer that is not in WGS 84 to a format that holds only longitude and latitude. -**What to do:** Export in the layer's own coordinate system, or give that system with a known transformation to WGS 84. +**What to do:** On reading, give the coordinate system with a known transformation to WGS 84; on export, export in the layer's own coordinate system. ### `approximated.curve` { #approximated.curve }