From d2d1306b369cfba91bb0c989071343b461a43378 Mon Sep 17 00:00:00 2001 From: mavrick Date: Sat, 28 Nov 2026 10:39:20 -0600 Subject: [PATCH 01/12] fix(data): a Shapefile without a .cpg takes its code page from a .cst --- apps/rustgis-mobile/src/lib.rs | 6 +- apps/rustgis-web/src/web.rs | 3 +- crates/data/src/dbf.rs | 92 ++++++++----- crates/data/src/io.rs | 71 ++++++---- crates/data/src/publish.rs | 127 ++++++++++++++++-- crates/data/src/source/shp.rs | 8 +- crates/data/src/sync.rs | 7 +- .../tests/integration/shapefile_encoding.rs | 2 +- crates/engine/src/cmd/gp.rs | 6 +- crates/engine/src/cmd/layer.rs | 21 ++- crates/engine/src/observe.rs | 9 +- crates/engine/src/tests.rs | 18 ++- docs/user-guide/data-formats.md | 21 ++- docs/user-guide/data.md | 4 +- docs/user-guide/index.md | 4 +- docs/user-guide/shapefile-encoding.md | 20 +-- 16 files changed, 297 insertions(+), 122 deletions(-) diff --git a/apps/rustgis-mobile/src/lib.rs b/apps/rustgis-mobile/src/lib.rs index f1e7c25d64..b431f660d9 100644 --- a/apps/rustgis-mobile/src/lib.rs +++ b/apps/rustgis-mobile/src/lib.rs @@ -26,7 +26,7 @@ mod ios; pub use ios::main as ios_main; /// The files of `picked` to open, each by its path: all but the parts another of them reads from -/// beside it (a Shapefile's `.dbf`, `.shx`, `.prj` and `.cpg`, a MapInfo file's `.mid`), matched +/// beside it (a Shapefile's `.dbf`, `.shx`, `.prj`, `.cpg` and `.cst`, a MapInfo file's `.mid`), matched /// by name whatever the case. A part picked without its main file stays, and is refused by name. #[cfg_attr(not(any(target_os = "android", target_os = "ios", test)), expect(dead_code, reason = "only a phone picks files"))] fn without_sidecars(picked: Vec) -> Vec { @@ -36,7 +36,7 @@ fn without_sidecars(picked: Vec) -> Vec let mut kept = Vec::new(); for (path, (stem, extension)) in picked.iter().zip(&named) { let read_by = match extension.as_str() { - "dbf" | "shx" | "prj" | "cpg" => "shp", + "dbf" | "shx" | "prj" | "cpg" | "cst" => "shp", "mid" => "mif", _ => "", }; @@ -239,7 +239,7 @@ mod tests { #[test] fn parts_picked_with_their_file_are_left_to_it() { - assert_eq!(kept(&["roads.shp", "roads.dbf", "roads.shx", "roads.prj", "roads.cpg"]), ["roads.shp"]); + assert_eq!(kept(&["roads.shp", "roads.dbf", "roads.shx", "roads.prj", "roads.cpg", "roads.CsT"]), ["roads.shp"]); assert_eq!(kept(&["ROADS.SHP", "Roads.DBF", "parcels.mif", "parcels.MID"]), ["ROADS.SHP", "parcels.mif"]); } diff --git a/apps/rustgis-web/src/web.rs b/apps/rustgis-web/src/web.rs index 5185b55eac..ca285371fe 100644 --- a/apps/rustgis-web/src/web.rs +++ b/apps/rustgis-web/src/web.rs @@ -39,6 +39,7 @@ const DATA_EXTS: &[&str] = &[ "shx", "prj", "cpg", + "cst", "kml", "kmz", "gpx", @@ -1378,7 +1379,7 @@ fn services(inbox: Inbox, font_inbox: Inbox, notes: Notes, ctx: egui::Context, e } else if purpose == "script" { rfd::AsyncFileDialog::new().add_filter(rustgis_ui_egui::tl!("Script"), &["txt"]) } else if purpose == "shapefile" { - rfd::AsyncFileDialog::new().add_filter("Shapefile", &["shp", "dbf", "shx", "prj", "cpg", "zip"]) + rfd::AsyncFileDialog::new().add_filter("Shapefile", &["shp", "dbf", "shx", "prj", "cpg", "cst", "zip"]) } else if purpose == "project" { rfd::AsyncFileDialog::new().add_filter( rustgis_ui_egui::tl!("Projects and JSON data (RustGIS, GeoLibre)"), diff --git a/crates/data/src/dbf.rs b/crates/data/src/dbf.rs index 2910ca7b55..2e09432877 100644 --- a/crates/data/src/dbf.rs +++ b/crates/data/src/dbf.rs @@ -3,7 +3,7 @@ use encoding_rs as rs; use shapefile::dbase::{CodePageMark, UnicodeLossy, encoding::DynEncoding}; -const MAX_CPG_BYTES: usize = 1024; +const MAX_CODE_PAGE_BYTES: usize = 1024; /// Keep the selection thread-safe; dbase's dynamic decoder is created per read because it /// is `Send` but not `Sync`, whereas feature sources can be shared between readers. @@ -141,21 +141,23 @@ fn ldid_code_page(ldid: u8) -> Option { }) } -pub(crate) fn encoding(cpg: Option<&[u8]>, ldid: u8, notes: &mut crate::loss::Notes) -> DbfEncoding { - if let Some(bytes) = cpg { - let label = if bytes.len() <= MAX_CPG_BYTES { std::str::from_utf8(bytes).unwrap_or("") } else { "" }; - let label = label.trim().trim_start_matches('\u{feff}').trim(); - if let Some(encoding) = DbfEncoding::from_name(label) { - return encoding; +/// Reads the first usable declaration in order. The flag says whether Publish to Source can +/// write with the same selection, subject to its separate round-trip checks. +pub(crate) fn encoding(cpg: Option<&[u8]>, cst: Option<&[u8]>, ldid: u8, notes: &mut crate::loss::Notes) -> (DbfEncoding, bool) { + if let Some(encoding) = sidecar_encoding(cpg) { + return (encoding, true); + } + if let Some(encoding) = sidecar_encoding(cst) { + if cpg.is_some() { + notes.push("Shapefile: unsupported or empty .cpg"); } + notes.push(format!("Shapefile: code page taken from the .cst ({})", encoding.name())); + return (encoding, true); } - // A `.cpg` that can't be used: the file's own language driver gives the encoding, and then - // nothing is assumed; without one it is UTF-8, assumed. One that names a code page RustGIS - // can't read is said below, as assumed, on its own. - let page = (ldid != 0).then(|| ldid_code_page(ldid)).flatten(); + let page = ldid_code_page(ldid); 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"; + for ext in [cpg.map(|_| "cpg"), cst.map(|_| "cst")].into_iter().flatten() { + let text = format!("Shapefile: unsupported or empty .{ext}; 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 { @@ -164,10 +166,11 @@ pub(crate) fn encoding(cpg: Option<&[u8]>, ldid: u8, notes: &mut crate::loss::No } // No language driver: UTF-8, as it always was, without a note. if ldid == 0 { - return DbfEncoding::Utf8; + return (DbfEncoding::Utf8, cpg.is_none() && cst.is_none()); } if let Some(encoding) = resolved { - return encoding; + // Preserve the publish refusal for an unusable .cpg when there is no usable .cst. + return (encoding, cpg.is_none()); } let named = page.map_or_else(String::new, |p| match page_name(p) { Some(name) => format!(" (code page {p}, {name})"), @@ -177,7 +180,14 @@ pub(crate) fn encoding(cpg: Option<&[u8]>, ldid: u8, notes: &mut crate::loss::No crate::loss::LossCode::AssumedEncoding, format!("Shapefile: unsupported .dbf code page 0x{ldid:02X}{named}; using UTF-8"), )); - DbfEncoding::Utf8 + (DbfEncoding::Utf8, false) +} + +/// A label small enough to be a declaration, in one of the code pages a DBF can use. +pub(crate) fn sidecar_encoding(bytes: Option<&[u8]>) -> Option { + let bytes = bytes.filter(|b| b.len() <= MAX_CODE_PAGE_BYTES)?; + let label = std::str::from_utf8(bytes).ok()?.trim().trim_start_matches('\u{feff}').trim(); + DbfEncoding::from_name(label) } /// The name of a code page a language driver may name and RustGIS can't decode, for the note. @@ -203,7 +213,11 @@ pub(crate) const NO_OTHER_ENCODING: &str = "no .cpg file names another encoding /// The end of each note of text that isn't valid in `encoding`: for UTF-8, why the text was read as /// it ([`NO_OTHER_ENCODING`]); for another, that the file declares it. pub(crate) fn cause(encoding: &str) -> String { - if encoding == "UTF-8" { NO_OTHER_ENCODING.to_string() } else { format!("the .cpg or the .dbf's language driver declares {encoding}") } + if encoding == "UTF-8" { + NO_OTHER_ENCODING.to_string() + } else { + format!("the .cpg, .cst or the .dbf's language driver declares {encoding}") + } } /// What opening a `.dbf` says of its field names that aren't valid in its `encoding` ([`not_utf8`]), @@ -432,31 +446,33 @@ pub(crate) fn date(field: &[u8]) -> std::result::Result Option> { - match try_read_cpg(path) { +fn read_code_page(path: &std::path::Path, spellings: [&str; 8], notes: &mut crate::loss::Notes) -> Option> { + match try_read_code_page(path, spellings) { Ok(bytes) => bytes, Err(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})"))); + // The selection reports the fallback as it does for an unusable declaration. + notes.push(crate::loss::Note::plain(format!("could not read the .{} ({e})", spellings[0]))); Some(Vec::new()) } } } -/// Every ASCII case of the `.cpg` extension, the conventional spellings first: tried in turn, +/// Every ASCII case of the extension, the conventional spellings first: tried in turn, /// without scanning a potentially large directory, and the first there wins. pub(crate) const CPG_SPELLINGS: [&str; 8] = ["cpg", "CPG", "Cpg", "cPg", "cpG", "CPg", "CpG", "cPG"]; +pub(crate) const CST_SPELLINGS: [&str; 8] = ["cst", "CST", "Cst", "cSt", "csT", "CSt", "CsT", "cST"]; -fn try_read_cpg(path: &std::path::Path) -> std::io::Result>> { +/// Reads at most one byte more than a label can hold, so oversized declarations stay unusable. +pub(crate) fn try_read_code_page(path: &std::path::Path, spellings: [&str; 8]) -> std::io::Result>> { use std::io::Read; - for ext in CPG_SPELLINGS { - match crate::provenance::open(path.with_extension(ext)) { + for ext in spellings { + let part = path.with_extension(ext); + match crate::provenance::open(&part) { Ok(file) => { let mut bytes = Vec::new(); - (&file).take(MAX_CPG_BYTES as u64 + 1).read_to_end(&mut bytes)?; - if bytes.len() <= MAX_CPG_BYTES { - crate::provenance::buffer(&path.with_extension(ext), &file, &bytes); + (&file).take(MAX_CODE_PAGE_BYTES as u64 + 1).read_to_end(&mut bytes)?; + if bytes.len() <= MAX_CODE_PAGE_BYTES { + crate::provenance::buffer(&part, &file, &bytes); } return Ok(Some(bytes)); } @@ -467,6 +483,14 @@ fn try_read_cpg(path: &std::path::Path) -> std::io::Result>> { Ok(None) } +/// Reads encoding sidecars beside a Shapefile or DBF. Only a missing or unusable .cpg needs +/// the fallback .cst. +pub(crate) fn read_sidecars(path: &std::path::Path, notes: &mut crate::loss::Notes) -> (Option>, Option>) { + let cpg = read_code_page(path, CPG_SPELLINGS, notes); + let cst = if sidecar_encoding(cpg.as_deref()).is_none() { read_code_page(path, CST_SPELLINGS, notes) } else { None }; + (cpg, cst) +} + #[cfg(test)] mod tests { use super::*; @@ -600,14 +624,14 @@ mod tests { #[test] fn a_page_rustgis_cant_decode_is_named_in_the_note() { let mut notes = crate::loss::Notes::new(); - assert!(matches!(encoding(None, 0x6C, &mut notes), DbfEncoding::Utf8)); + assert!(matches!(encoding(None, None, 0x6C, &mut notes), (DbfEncoding::Utf8, false))); assert_eq!( notes.texts().collect::>(), ["Shapefile: 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); + encoding(None, None, 0xFF, &mut notes); assert_eq!(notes.texts().collect::>(), ["Shapefile: unsupported .dbf code page 0xFF; using UTF-8"]); assert_eq!(notes[0].loss, Some(crate::loss::LossCode::AssumedEncoding)); } @@ -616,7 +640,7 @@ mod tests { /// and with a code page that can't be decoded; a code page that is decoded is named by it. #[test] fn utf8_is_what_text_is_read_as_unless_another_encoding_is_named() { - let read = |cpg: Option<&[u8]>, ldid| encoding(cpg, ldid, &mut crate::loss::Notes::new()).name(); + let read = |cpg: Option<&[u8]>, ldid| encoding(cpg, None, ldid, &mut crate::loss::Notes::new()).0.name(); for (cpg, ldid) in [(None, 0), (None, 0xF0), (Some(b"UTF-8".as_slice()), 0x03), (Some(b"65001".as_slice()), 0), (None, 0x6C)] { assert_eq!(read(cpg, ldid), "UTF-8"); } @@ -634,7 +658,7 @@ mod tests { /// aren't. A DOS page gives every byte a character. #[test] fn bytes_that_cant_be_read_are_those_the_declared_decoder_replaces() { - let page = |cpg: &[u8]| encoding(Some(cpg), 0, &mut crate::loss::Notes::new()); + let page = |cpg: &[u8]| encoding(Some(cpg), None, 0, &mut crate::loss::Notes::new()).0; let (sjis, big5, utf8) = (page(b"932"), page(b"950"), page(b"UTF-8")); assert!(sjis.malformed(b"X\x82") && sjis.malformed(b"\x82 ") && sjis.malformed(b"\xff")); assert!(!sjis.malformed(b"\x93\x8c\x8b\x9e") && !sjis.malformed(b"plain") && !sjis.malformed(b"")); @@ -708,7 +732,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" + "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, .cst or the .dbf's language driver declares Big5" ) ); } diff --git a/crates/data/src/io.rs b/crates/data/src/io.rs index 66e8e72122..2d772f1084 100644 --- a/crates/data/src/io.rs +++ b/crates/data/src/io.rs @@ -451,11 +451,11 @@ pub fn read_bytes(file_name: &str, bytes: &[u8]) -> Result<(Dataset, ReadReport) // Picked or dropped with its .dbf, a Shapefile comes zipped (`gather_shapefiles`). "shp" => { return Err(DataError::Unsupported( - "shp on its own: add it together with its .dbf, which it needs, and its .shx and .prj if it has them (pick or drop them at once), or add them zipped".into(), + "shp on its own: add it together with its .dbf, which it needs, and its .shx, .prj, .cpg and .cst if it has them (pick or drop them at once), or add them zipped".into(), )); } - "dbf" => read_dbf(bytes.to_vec(), None, &name, &mut csv_memory_budget())?, - "shx" | "prj" | "cpg" => { + "dbf" => read_dbf(bytes.to_vec(), None, None, &name, &mut csv_memory_budget())?, + "shx" | "prj" | "cpg" | "cst" => { return Err(DataError::Unsupported(format!("{ext} on its own: it is part of a Shapefile; add it together with its .shp"))); } // The first layer (`read_layers` reads them all), saying what else the file holds. @@ -521,8 +521,8 @@ 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 (ds, mut report) = read_dbf(std::fs::read(path)?, cpg.as_deref(), &name, &mut csv_memory_budget())?; + let (cpg, cst) = crate::dbf::read_sidecars(path, &mut notes); + let (ds, mut report) = read_dbf(std::fs::read(path)?, cpg.as_deref(), cst.as_deref(), &name, &mut csv_memory_budget())?; report.messages.extend(notes.prefixed(&name)); (ds, report) } @@ -3830,12 +3830,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 (cpg, cst) = crate::dbf::read_sidecars(path, &mut notes); 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), + cpg, + cst, }; let (ds, mut report) = read_shapefile_parts(parts, name, crs)?; report.messages.extend(notes.prefixed(name)); @@ -3843,13 +3845,13 @@ pub fn read_shapefile_in(path: &Path, name: &str, crs: Option) -> Result<(D } /// The files of a Shapefile besides its `.shp` that [`gather_shapefiles`] zips with it. -const SHAPEFILE_SIDECARS: [&str; 4] = ["dbf", "shx", "prj", "cpg"]; +const SHAPEFILE_SIDECARS: [&str; 5] = ["dbf", "shx", "prj", "cpg", "cst"]; /// Gathers each Shapefile among files given together (several picked at once in the browser, or /// dropped at once) into a zip that reads as a zipped Shapefile: a `.shp` with the `.dbf` of the -/// same base name, ignoring case, and its `.shx`, `.prj` and `.cpg` when they are there. The zip, +/// same base name, ignoring case, and its `.shx`, `.prj`, `.cpg` and `.cst` when they are there. The zip, /// named after the `.shp`, takes its place; its parts go. Other files, and a `.shp` without its -/// `.dbf`, pass through as they came. A standalone `.dbf` with a `.cpg` is zipped with it too. +/// `.dbf`, pass through as they came. A standalone `.dbf` is zipped with its code-page declarations too. /// Files whose parts are too large to read together (more than [`max_bytes`], or the zip /// reader's limit) are left out, with an explanation in the messages returned with the files. pub fn gather_shapefiles(files: Vec<(String, Vec)>) -> (Vec<(String, Vec)>, Vec) { @@ -3879,14 +3881,19 @@ pub fn gather_shapefiles(files: Vec<(String, Vec)>) -> (Vec<(String, Vec *slot = Some(parts); } } - // A standalone DBF's .cpg travels through the browser's Services inbox in the same zip. + // A standalone DBF's code-page declaration travels through the browser's Services inbox in the same zip. for i in 0..files.len() { let Some(base) = files.get(i).and_then(Option::as_ref).filter(|(n, _)| ext_of(n) == "dbf").map(|(n, _)| stem(n)) else { continue; }; - let Some(j) = sidecar(&files, &base, "cpg") else { continue }; + let declarations = ["cpg", "cst"].map(|ext| sidecar(&files, &base, ext)); + if declarations.iter().all(Option::is_none) { + continue; + } let mut parts: Vec<_> = files.get_mut(i).and_then(Option::take).into_iter().collect(); - parts.extend(files.get_mut(j).and_then(Option::take)); + for j in declarations.into_iter().flatten() { + parts.extend(files.get_mut(j).and_then(Option::take)); + } if let Some(slot) = zips.get_mut(i) { *slot = Some(parts); } @@ -3952,6 +3959,11 @@ pub fn shapefile_part_urls(url: &str) -> Option> { ) } +/// Whether a downloaded .cpg is enough to select a decoder without fetching a .cst. +pub fn shapefile_cpg_is_usable(bytes: &[u8]) -> bool { + crate::dbf::sidecar_encoding(Some(bytes)).is_some() +} + /// A Shapefile fetched by its files' addresses as one zipped Shapefile ([`gather_shapefiles`]): /// the `.shp` named `file_name`, and the parts that answered, by extension. An error when the /// `.dbf` isn't among them or they are too large to read together. @@ -3974,7 +3986,7 @@ fn is_resource_fork(name: &str) -> bool { name.split('/').any(|part| part == "__MACOSX" || part.starts_with("._")) } -/// Which of its optional parts (`.shx`, `.prj`, `.cpg`) each Shapefile in a zip lacks, beside it +/// Which of its optional parts (`.shx`, `.prj`, a code-page declaration) each Shapefile in a zip lacks, beside it /// by its name: what a Shapefile added by its `.shp` address (#1238) was read without, to say so. /// One entry per `.shp` that lacks any, its name as in the zip, in name order. Only the `.shp`s /// [`read_zip`] reads count: those with their `.dbf`, not a macOS resource fork, the first @@ -4007,7 +4019,10 @@ pub fn shapefile_zip_lacks(bytes: &[u8]) -> Vec<(String, Vec<&'static str>)> { shps.into_iter() .take(MAX_ZIP_LAYERS) .filter_map(|(n, s)| { - let lacks: Vec<&'static str> = ["shx", "prj", "cpg"].into_iter().filter(|e| !lower.contains(&format!("{s}.{e}"))).collect(); + let lacks: Vec<&'static str> = ["shx", "prj", "cpg"] + .into_iter() + .filter(|e| !lower.contains(&format!("{s}.{e}")) && (*e != "cpg" || !lower.contains(&format!("{s}.cst")))) + .collect(); (!lacks.is_empty()).then(|| (n.clone(), lacks)) }) .collect() @@ -4106,7 +4121,7 @@ fn read_zip_layers_budget(file_name: &str, bytes: &[u8], opts: &CsvOptions, budg } let e = ext_of(n); !is_resource_fork(n) - && (matches!(e.as_str(), "shp" | "shx" | "dbf" | "prj" | "cpg" | "mid") + && (matches!(e.as_str(), "shp" | "shx" | "dbf" | "prj" | "cpg" | "cst" | "mid") || (e == "pbf" && lower(n).ends_with(".osm.pbf")) || (!matches!(e.as_str(), "zip" | "pbf") && READ_EXTENSIONS.contains(&e.as_str()))) }; @@ -4140,11 +4155,12 @@ fn read_zip_layers_budget(file_name: &str, bytes: &[u8], opts: &CsvOptions, budg let shx = take(&mut entries, &base, "shx").map(|(_, b)| b); let prj = take(&mut entries, &base, "prj").map(|(_, b)| String::from_utf8_lossy(&b).into_owned()); let cpg = take(&mut entries, &base, "cpg").map(|(_, b)| b); + let cst = take(&mut entries, &base, "cst").map(|(_, b)| b); let Some((_, dbf)) = take(&mut entries, &base, "dbf") else { skipped.push(format!("{n} (no .dbf beside it)")); continue; }; - match read_shapefile_parts(ShapefileParts { shp, shx, dbf, prj, cpg }, &name, crs) { + match read_shapefile_parts(ShapefileParts { shp, shx, dbf, prj, cpg, cst }, &name, crs) { Ok((mut dataset, report)) => { dataset.source = Some(format!("{file_name}/{n}")); out.push(LayerRead { dataset, report, styles: Vec::new() }); @@ -4177,7 +4193,7 @@ fn read_zip_layers_budget(file_name: &str, bytes: &[u8], opts: &CsvOptions, budg } let mut others: Vec<(String, Vec)> = entries .iter_mut() - .filter(|e| e.as_ref().is_some_and(|(n, _)| !matches!(ext_of(n).as_str(), "shp" | "shx" | "prj" | "cpg"))) + .filter(|e| e.as_ref().is_some_and(|(n, _)| !matches!(ext_of(n).as_str(), "shp" | "shx" | "prj" | "cpg" | "cst"))) .filter_map(Option::take) .collect(); others.sort_by(|a, b| a.0.cmp(&b.0)); @@ -4211,8 +4227,9 @@ fn read_zip_layers_budget(file_name: &str, bytes: &[u8], opts: &CsvOptions, budg // A city model has many layers. let read = if ext_of(&n) == "dbf" { let cpg = take(&mut entries, &stem(&n), "cpg").map(|(_, b)| b); + let cst = take(&mut entries, &stem(&n), "cst").map(|(_, b)| b); let name = Path::new(leaf).file_stem().and_then(|s| s.to_str()).unwrap_or("table"); - read_dbf(b, cpg.as_deref(), name, budget).map(|r| plain(vec![r])) + read_dbf(b, cpg.as_deref(), cst.as_deref(), name, budget).map(|r| plain(vec![r])) } else if is_city_model(leaf, &b) { read_city_member(leaf, &b, crs).map(plain) } else if is_delimited_name(leaf) { @@ -4400,10 +4417,10 @@ struct DbfRead { /// Opens dBASE attributes with the Shapefile reader's code-page and date/number handling. /// `name` is the layer's, for the error of a `.dbf` it can't open. -fn dbf_reader(mut bytes: Vec, cpg: Option<&[u8]>, name: &str) -> Result { +fn dbf_reader(mut bytes: Vec, cpg: Option<&[u8]>, cst: Option<&[u8]>, name: &str) -> Result { use std::io::Cursor; let mut declared = crate::loss::Notes::new(); - let encoding = crate::dbf::encoding(cpg, bytes.get(29).copied().unwrap_or(0), &mut declared); + let (encoding, _) = crate::dbf::encoding(cpg, cst, bytes.get(29).copied().unwrap_or(0), &mut declared); let mut encoding_notes = declared; // Counted before a date column is marked a character one below: its values aren't text. let (names, not_utf8) = crate::dbf::not_utf8(&bytes, &encoding); @@ -4446,8 +4463,8 @@ fn dbf_reader(mut bytes: Vec, cpg: Option<&[u8]>, name: &str) -> Result, cpg: Option<&[u8]>, name: &str, budget: &mut usize) -> Result<(Dataset, ReadReport)> { - let DbfRead { mut reader, fields, decimals, mut report, not_utf8, deleted, encoding } = dbf_reader(bytes, cpg, name)?; +fn read_dbf(bytes: Vec, cpg: Option<&[u8]>, cst: Option<&[u8]>, name: &str, budget: &mut usize) -> Result<(Dataset, ReadReport)> { + let DbfRead { mut reader, fields, decimals, mut report, not_utf8, deleted, encoding } = dbf_reader(bytes, cpg, cst, name)?; let mut ds = Dataset::new(name, GeometryType::None, fields); let mut counts = DbfCounts::new(ds.fields.len(), not_utf8, encoding); let allowance = *budget; @@ -4622,6 +4639,7 @@ pub(crate) struct ShapefileParts { pub dbf: Vec, pub prj: Option, pub cpg: Option>, + pub cst: Option>, } /// Decodes attributes and shapes together, tracking geometry lost during CRS conversion so @@ -4631,7 +4649,7 @@ pub(crate) fn read_shapefile_parts(parts: ShapefileParts, name: &str, crs: Optio use std::io::Cursor; let fmt = |e: shapefile::Error| DataError::Format(format!("Shapefile: {e}")); let DbfRead { reader: mut dbf, fields, decimals, mut report, not_utf8, deleted, encoding } = - dbf_reader(parts.dbf, parts.cpg.as_deref(), name)?; + dbf_reader(parts.dbf, parts.cpg.as_deref(), parts.cst.as_deref(), name)?; let mut shapes = match parts.shx { Some(shx) => shapefile::ShapeReader::with_shx(Cursor::new(parts.shp), Cursor::new(shx)), None => shapefile::ShapeReader::new(Cursor::new(parts.shp)), @@ -10123,11 +10141,11 @@ mod tests { let (parts, _) = shapefile_parts(&ds).unwrap(); let bytes = &parts.iter().find(|(ext, _)| *ext == "dbf").unwrap().1; let mut left = 1 << 20; - let (table, report) = read_dbf(bytes.clone(), None, "small", &mut left).unwrap(); + let (table, report) = read_dbf(bytes.clone(), None, None, "small", &mut left).unwrap(); assert_eq!(table.features.len(), 32); assert!(report.messages.is_empty()); let cost = (1 << 20) - left; - let error = read_dbf(bytes.clone(), None, "small", &mut (cost - 1)).unwrap_err(); + let error = read_dbf(bytes.clone(), None, None, "small", &mut (cost - 1)).unwrap_err(); assert!(matches!(error, DataError::Format(_)) && error.to_string().contains("memory budget"), "{error}"); let zip = crate::zip::write(&[("a.dbf".into(), bytes.clone()), ("b.dbf".into(), bytes.clone())]).unwrap(); let limited = read_zip_budget("tables.zip", &zip, None, &mut { cost }).unwrap(); @@ -10423,7 +10441,8 @@ mod tests { let urls = |u: &str| shapefile_part_urls(u).map(|v| v.into_iter().map(|(_, u)| u).collect::>()); assert_eq!( urls("https://geo.example.org/PI/TERESINA/HIDROGRAFIA/PI_2211001_RIOS_SIMPLES.shp").unwrap(), - ["dbf", "shx", "prj", "cpg"].map(|e| format!("https://geo.example.org/PI/TERESINA/HIDROGRAFIA/PI_2211001_RIOS_SIMPLES.{e}")) + ["dbf", "shx", "prj", "cpg", "cst"] + .map(|e| format!("https://geo.example.org/PI/TERESINA/HIDROGRAFIA/PI_2211001_RIOS_SIMPLES.{e}")) ); assert_eq!(urls("https://x.org/a/RIOS.SHP?token=1#f").unwrap()[0], "https://x.org/a/RIOS.DBF?token=1#f"); assert_eq!(urls("s3://bucket/rios.shp").unwrap()[2], "s3://bucket/rios.prj"); diff --git a/crates/data/src/publish.rs b/crates/data/src/publish.rs index ed247e0fa3..da05c262eb 100644 --- a/crates/data/src/publish.rs +++ b/crates/data/src/publish.rs @@ -23,7 +23,7 @@ //! Only then are the new parts written beside the old ones, checked again against the bytes //! meant, and renamed into place, the `.shp` last; any failure puts the old parts back //! ([`crate::io::place_shapefile`]). The file keeps its code page, column widths, decimals, -//! `.prj` and `.cpg` where the edits allow; sidecars RustGIS doesn't write (`.shp.xml`) are left. +//! `.prj` and text declarations where the edits allow; sidecars RustGIS doesn't write (`.shp.xml`) are left. use crate::dbf::{Column, RawTable}; use crate::io::{DbfStyle, ShapefileParts}; @@ -149,6 +149,7 @@ struct Original { dbf_path: PathBuf, prj: Option>, cpg: Option<(PathBuf, Vec)>, + cst: Option>, } /// Reads an original file at `p`, `None` when absent. The caller supplies format-specific size advice. @@ -163,7 +164,7 @@ fn read_part(p: &Path, size_error: fn(&str, u64) -> String) -> Result Result { let read = |part: &Path| read_part(part, crate::io::shapefile_size_error); let missing = |ext: &str| refused(path, format!("its .{ext} isn't there")); @@ -180,7 +181,12 @@ impl Original { break; } } - Ok(Original { shp, shx, dbf, dbf_path, prj, cpg }) + let cst = if crate::dbf::sidecar_encoding(cpg.as_ref().map(|(_, b)| b.as_slice())).is_none() { + crate::dbf::try_read_code_page(path, crate::dbf::CST_SPELLINGS)? + } else { + None + }; + Ok(Original { shp, shx, dbf, dbf_path, prj, cpg, cst }) } /// Its parts as the reader takes them. @@ -191,6 +197,7 @@ impl Original { dbf: self.dbf.clone(), prj: self.prj.as_ref().and_then(|p| String::from_utf8(p.clone()).ok()), cpg: self.cpg.as_ref().map(|(_, b)| b.clone()), + cst: self.cst.clone(), } } @@ -216,7 +223,7 @@ pub fn shapefile(ds: &Dataset, path: &Path, synced: &Synced) -> Result Result<()> { refuse_link(path, path)?; - for ext in ["shx", "dbf", "prj"].into_iter().chain(crate::dbf::CPG_SPELLINGS) { + for ext in ["shx", "dbf", "prj"].into_iter().chain(crate::dbf::CPG_SPELLINGS).chain(crate::dbf::CST_SPELLINGS) { refuse_link(path, &path.with_extension(ext))?; } refuse_link(path, &crate::io::dbf_sidecar(path))?; @@ -245,16 +252,13 @@ pub fn shapefile(ds: &Dataset, path: &Path, synced: &Synced) -> Result Result Result { Self::open_path_in(path, name, None) } @@ -146,8 +146,8 @@ 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 encoding = crate::dbf::encoding(cpg.as_deref(), table.ldid, &mut notes); + let (cpg, cst) = crate::dbf::read_sidecars(path, &mut notes); + let (encoding, _) = crate::dbf::encoding(cpg.as_deref(), cst.as_deref(), table.ldid, &mut notes); let shp_len = std::fs::metadata(path)?.len(); if shp_len > u64::from(u32::MAX) { return Err(bad("the .shp is larger than the format's 4 GB")); diff --git a/crates/data/src/sync.rs b/crates/data/src/sync.rs index d3ce1d08a0..79d892fdff 100644 --- a/crates/data/src/sync.rs +++ b/crates/data/src/sync.rs @@ -5,7 +5,7 @@ use serde::{Deserialize, Serialize}; /// The files of a source as they were at a moment: each one's name, size and SHA-256 hash, and -/// the files that weren't there. A Shapefile is its `.shp`, `.shx`, `.dbf`, `.prj` and `.cpg` +/// the files that weren't there. A Shapefile is its `.shp`, `.shx`, `.dbf`, `.prj`, `.cpg` and `.cst` /// (the ones its reader opens); a GeoJSON file is itself. Only the contents count: a file /// copied, touched or moved to another disk with the same bytes is the same file. #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] @@ -179,7 +179,7 @@ mod native { /// The files of the source at `path`, each as a name beside it and its path: for a /// Shapefile the companions its reader opens (the `.cpg` in whichever case is there, else - /// `.cpg`), otherwise the file alone. + /// `.cpg`, plus its `.cst` when present), otherwise the file alone. fn parts(path: &Path) -> Vec<(String, PathBuf)> { let mut paths = vec![path.to_path_buf()]; if path.extension().and_then(|e| e.to_str()).is_some_and(|e| e.eq_ignore_ascii_case("shp")) { @@ -191,6 +191,7 @@ mod native { .find(|p| p.is_file()) .unwrap_or_else(|| path.with_extension("cpg")); paths.push(cpg); + paths.extend(crate::dbf::CST_SPELLINGS.into_iter().map(|e| path.with_extension(e)).find(|p| p.is_file())); } paths.into_iter().map(|p| (p.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default(), p)).collect() } @@ -297,7 +298,7 @@ mod native { pub fn changed(&self, path: &Path) -> Result> { let now = parts(path); let mut changed = Vec::new(); - // Files there now that the record lacks (a `.cpg` added in another case); not the + // Files there now that the record lacks (an added encoding declaration); not the // `.cpg` name `parts` falls back to when there is none. for (name, p) in &now { if !self.files.iter().any(|(n, _)| n == name) && p.exists() { diff --git a/crates/data/tests/integration/shapefile_encoding.rs b/crates/data/tests/integration/shapefile_encoding.rs index af15695003..b39d8351be 100644 --- a/crates/data/tests/integration/shapefile_encoding.rs +++ b/crates/data/tests/integration/shapefile_encoding.rs @@ -82,7 +82,7 @@ const NO_OTHER_ENCODING: &str = "no .cpg file names another encoding RustGIS rea fn cause(encoding: &str) -> String { match encoding { "UTF-8" => NO_OTHER_ENCODING.to_string(), - other => format!("the .cpg or the .dbf's language driver declares {other}"), + other => format!("the .cpg, .cst or the .dbf's language driver declares {other}"), } } diff --git a/crates/engine/src/cmd/gp.rs b/crates/engine/src/cmd/gp.rs index 41dd0250dd..016c49ebd6 100644 --- a/crates/engine/src/cmd/gp.rs +++ b/crates/engine/src/cmd/gp.rs @@ -2559,7 +2559,7 @@ fn is_folder_target_ext(ext: &str) -> bool { /// Whether a file with this lowercase extension may be a Shapefile or GeoPackage sidecar. #[cfg(not(target_arch = "wasm32"))] fn is_folder_sidecar_ext(ext: &str) -> bool { - matches!(ext, "dbf" | "shx" | "prj" | "cpg" | "qpj" | "sbn" | "sbx" | "qix" | "xml" | "gpkg-wal" | "gpkg-shm" | "wal" | "shm") + matches!(ext, "dbf" | "shx" | "prj" | "cpg" | "cst" | "qpj" | "sbn" | "sbx" | "qix" | "xml" | "gpkg-wal" | "gpkg-shm" | "wal" | "shm") } /// Runs a geoprocessing tool in batch across multiple layers or files: under the control of the @@ -2831,7 +2831,7 @@ pub fn run_batch_with(s: &mut Session, p: &Value, control: &std::sync::Arc bool { } let shapefile = source.extension().is_some_and(|e| e.eq_ignore_ascii_case("shp")); let companion = |ext: &str| source.with_extension(ext).canonicalize().is_ok_and(|p| p.as_path() == destination); - shapefile && ["dbf", "shx", "prj", "cpg"].iter().any(|&ext| companion(ext) || companion(ext.to_ascii_uppercase().as_str())) + shapefile && ["dbf", "shx", "prj", "cpg", "cst"].iter().any(|&ext| companion(ext) || companion(ext.to_ascii_uppercase().as_str())) } /// Adds a tool's table to the project under its name: in place of a table of that name, or, for diff --git a/crates/engine/src/cmd/layer.rs b/crates/engine/src/cmd/layer.rs index c5d55e0d74..7c50fc83ad 100644 --- a/crates/engine/src/cmd/layer.rs +++ b/crates/engine/src/cmd/layer.rs @@ -51,7 +51,7 @@ pub fn commands() -> Vec { .params(r#"{"layer"?: name|id, "crs": "EPSG:… or WKT; reinterpret native coordinates, without rewriting the source file"}"#), C::new("layer.loadAll", "Load All Features", "Layers", load_all).roles(&[]).effects(crate::policy::Effects::NONE).when(need_streamed).params(r#"{"layer"?: name|id}"#), C::new("layer.addUrl", "Add Data From URL", "Home › Add › Add Data", add_url).roles(&[]).effects(crate::policy::Effects::NONE.with(crate::policy::Effect::Network)).params( - r#"{"url": "https://…/data.geojson|.csv|.parquet|.fgb|.gpkg|.zip|.shp (its .dbf fetched beside it, and its .shx, .prj and .cpg when there)|.kml|.kmz|.gpx|.tif|.grb|.grib|.grb2|.grib2 (GRIB)|.jp2 (JPEG 2000: desktop, through GDAL) (the format from the address, else the contents) | a .pmtiles archive", "bytes"?: "[first, last]: only these octets of a GRIB file (counted from 0, both included, as HTTP's Range and curl -r write them; at most 64 MB), read as the file (desktop and command line): a record found in its wgrib inventory; with bbox (desktop and command line), only the rows of the box are downloaded from a record of simple packing without a bitmap, and any other record is downloaded whole and cut to the box, with a notice", "format"?: "grib: with bytes, the address is a GRIB file whatever its name says", "name"?: text, "layer"?: "one layer of a zip, KML or GPX", "zoom"?: "bool: true frames everything added; false keeps the view, even on an empty map; omitted, the first content on an empty map is framed (a GeoParquet, FlatGeobuf or cloud-optimised GeoTIFF read in place likewise; a PMTiles or MBTiles archive ignores zoom and is framed on its bounds unless it covers the whole world)", "x"?, "y"?, "wkt"?, "crs"?, "delimiter"?, "paperSpace"?, "blocks"?, "stream"?, "as"? (as layer.addData), "whole"?: "bool: download a cloud-optimised GeoTIFF whole (as a raster layer) instead of reading it in place (an address without a file name is read in place when its first bytes are a cloud-optimised GeoTIFF)", "cog"?: "bool: the address is a cloud-optimised GeoTIFF whatever its name says (the app's probe found it so)", "bbox"?: "[west, south, east, north] in degrees | "view": a cloud-optimised GeoTIFF's window as a raster layer (desktop and command line), read by range at full resolution, in the file's coordinate system, with its colour table and class names; at most 64 million values (all bands); with bytes, the cells of a GRIB record the box touches", "cellSize"?: "with bbox: the coarsest overview whose cells are at most this size is read (the file's units; metres for longitude/latitude, a degree taken as 111.32 km)", "cube"?: "bool: a data cube's file: a tile layer that follows the time slider (stac.addCube adds them), kept one when the project opens again", "start"?, "end"?, "unit"?, "interval"?, "dates"?: "a GeoTIFF address with date placeholders ({date:YYYY}, {YYYY}{MM}{DD}), one file per date: the dates it spans and steps through (as time.set), turning the time slider on", "connection"?: "the id of the saved web-service connection it comes from (as service.add)", "service"?: "bool: a web service's features (an ArcGIS query, OGC API Features items): read in pages as service.add reads them, known by the address as its layers are, and an ArcGIS layer drawn as its description says", "bounds"?: "with service: [west, south, east, north], the layer's longitude/latitude bounds its axes are checked against", "from"?: "the web document address that named url (internal: enforces public-address reach)", "fromDocument"?: bool, "anonymous"?: bool (internal: a plugin-origin download must never adopt a saved login), "coverage"?: bool (a WCS coverage's GetCoverage address, service.coverage's: a GeoTIFF, else the service's error; one that doesn't say its system is read in the one the address asks for), "coverageCrs"?: "EPSG: (with coverage: the system it was asked in, service.coverage's coverageCrs, when the address doesn't say it)", "request"?: "number (internal: the download a plugin command left to the app, #1202)"}"#, + r#"{"url": "https://…/data.geojson|.csv|.parquet|.fgb|.gpkg|.zip|.shp (its .dbf fetched beside it, and its .shx, .prj and code-page declaration when there)|.kml|.kmz|.gpx|.tif|.grb|.grib|.grb2|.grib2 (GRIB)|.jp2 (JPEG 2000: desktop, through GDAL) (the format from the address, else the contents) | a .pmtiles archive", "bytes"?: "[first, last]: only these octets of a GRIB file (counted from 0, both included, as HTTP's Range and curl -r write them; at most 64 MB), read as the file (desktop and command line): a record found in its wgrib inventory; with bbox (desktop and command line), only the rows of the box are downloaded from a record of simple packing without a bitmap, and any other record is downloaded whole and cut to the box, with a notice", "format"?: "grib: with bytes, the address is a GRIB file whatever its name says", "name"?: text, "layer"?: "one layer of a zip, KML or GPX", "zoom"?: "bool: true frames everything added; false keeps the view, even on an empty map; omitted, the first content on an empty map is framed (a GeoParquet, FlatGeobuf or cloud-optimised GeoTIFF read in place likewise; a PMTiles or MBTiles archive ignores zoom and is framed on its bounds unless it covers the whole world)", "x"?, "y"?, "wkt"?, "crs"?, "delimiter"?, "paperSpace"?, "blocks"?, "stream"?, "as"? (as layer.addData), "whole"?: "bool: download a cloud-optimised GeoTIFF whole (as a raster layer) instead of reading it in place (an address without a file name is read in place when its first bytes are a cloud-optimised GeoTIFF)", "cog"?: "bool: the address is a cloud-optimised GeoTIFF whatever its name says (the app's probe found it so)", "bbox"?: "[west, south, east, north] in degrees | "view": a cloud-optimised GeoTIFF's window as a raster layer (desktop and command line), read by range at full resolution, in the file's coordinate system, with its colour table and class names; at most 64 million values (all bands); with bytes, the cells of a GRIB record the box touches", "cellSize"?: "with bbox: the coarsest overview whose cells are at most this size is read (the file's units; metres for longitude/latitude, a degree taken as 111.32 km)", "cube"?: "bool: a data cube's file: a tile layer that follows the time slider (stac.addCube adds them), kept one when the project opens again", "start"?, "end"?, "unit"?, "interval"?, "dates"?: "a GeoTIFF address with date placeholders ({date:YYYY}, {YYYY}{MM}{DD}), one file per date: the dates it spans and steps through (as time.set), turning the time slider on", "connection"?: "the id of the saved web-service connection it comes from (as service.add)", "service"?: "bool: a web service's features (an ArcGIS query, OGC API Features items): read in pages as service.add reads them, known by the address as its layers are, and an ArcGIS layer drawn as its description says", "bounds"?: "with service: [west, south, east, north], the layer's longitude/latitude bounds its axes are checked against", "from"?: "the web document address that named url (internal: enforces public-address reach)", "fromDocument"?: bool, "anonymous"?: bool (internal: a plugin-origin download must never adopt a saved login), "coverage"?: bool (a WCS coverage's GetCoverage address, service.coverage's: a GeoTIFF, else the service's error; one that doesn't say its system is read in the one the address asks for), "coverageCrs"?: "EPSG: (with coverage: the system it was asked in, service.coverage's coverageCrs, when the address doesn't say it)", "request"?: "number (internal: the download a plugin command left to the app, #1202)"}"#, ), C::new("layer.addDownload", "Add Downloaded Data", "Home › Add", add_download).roles(&[]).effects(crate::policy::Effects::NONE.with(crate::policy::Effect::Reserved).with(crate::policy::Effect::Files)) .params(r#"{"id": a download the app finished (Home › Add › Add Data › From URL), "url": its address, "name"?: text, "layer"?: text, "zoom"?: bool, "x"?, "y"?, "wkt"?, "crs"?, "delimiter"?, "paperSpace"?, "blocks"?, "stream"?, "as"? (as layer.addData), "service"?: bool (a service's features: their axes (when they came as GeoJSON) and paging are checked, and the address is kept as the layer's source), "bounds"?: [west, south, east, north] (with service: the layer's longitude/latitude bounds from its capabilities, which its axes are checked against; without bounds they are left as they come; ignored without service), "coverage"?: bool (a WCS coverage: a GeoTIFF, else the service's error, and its request kept as the layer's source), "coverageCrs"?: "EPSG:" (internal, with coverage: the system service.coverage's request asks it in (its coverageCrs), for an answer that doesn't say its own, when the address doesn't say it), "drawingInfo"?: object (internal, with service: an ArcGIS layer's drawingInfo from its description, which the layer is drawn with), "geolibreProject"?: bool (internal: downloaded project JSON), "geolibreLayer"?: {"token", "record"} (internal: reserved imported layer and its saved style), "geolibreZarr"?: bool (internal: an imported Zarr slice as GeoTIFF), "connection"?: "as layer.addUrl", "anonymous"?: bool (internal: preserves a plugin-origin download's anonymous reads), "request"?: number (internal: the download a plugin command left to the app, #1202), "window"?: {"bbox", "cellSize"?, "cog"?} (internal: what a cloud-optimised GeoTIFF's window the app read off the frame asked for, for a task to read it again, #1330)}"#), @@ -2581,7 +2581,7 @@ fn link_choice(path: &str, tables: &[String]) -> Option { #[cfg(not(target_arch = "wasm32"))] pub(crate) struct Opened { /// The size and modification time of the file and those beside it of its name (a - /// Shapefile's `.dbf`, `.prj` and `.cpg`) as it was opened: an opening of files changed since + /// Shapefile's `.dbf`, `.prj` and code-page declaration) as it was opened: an opening of files changed since /// isn't taken, as its features' places, boxes and fields are those of what they held then. stamp: Option)>>, source: Result, rustgis_data::DataError>, @@ -5861,7 +5861,7 @@ fn over_shared_limit(e: String) -> String { } /// What a Shapefile added by its `.shp` address (#1238) was read without, said: its `.shx`, `.prj` -/// or `.cpg` when they weren't found beside it. The address is said without its keys or signature; +/// or encoding declaration when they weren't found beside it. The address is said without its keys or signature; /// a `crs` given (`p`) stands for the `.prj`. fn parts_left_out(url: &str, bytes: &[u8], p: &Value) -> Option { rustgis_data::io::shapefile_part_urls(url)?; @@ -5903,7 +5903,7 @@ fn parts_left_out(url: &str, bytes: &[u8], p: &Value) -> Option { } /// A Shapefile by its `.shp` address, waited for (#1238): the `.shp`, then its `.dbf`, `.shx`, -/// `.prj` and `.cpg` beside it (each but the `.dbf` only when it is there), zipped, within one +/// `.prj` and its encoding declaration beside it (each but the `.dbf` only when it is there), zipped, within one /// download's budget together. #[cfg(not(target_arch = "wasm32"))] fn download_shapefile_blocking_with(url: &str, public: bool) -> Result, String> { @@ -5935,6 +5935,9 @@ fn download_shapefile_blocking_with(url: &str, public: bool) -> Result, let mut left = cache::MAX_DOWNLOAD.saturating_sub(shp.len()); let mut got = Vec::new(); for (ext, u) in parts { + if skip_cst(ext, &got) { + continue; + } match within(&u, left, part_absences(ext, &u)).and_then(|b| page_part(ext, b)) { Ok(None) => {} Ok(Some(b)) => { @@ -5951,7 +5954,7 @@ fn download_shapefile_blocking_with(url: &str, public: bool) -> Result, /// Downloads a file the user named by its address off the frame, as `cache::download_limited` /// does, for the app to add when it lands: a Shapefile's `.shp` address brings its `.dbf`, `.shx`, -/// `.prj` and `.cpg` too, one after another, and `done` gets them zipped (#1238), within `max` +/// `.prj` and its encoding declaration too, one after another, and `done` gets them zipped (#1238), within `max` /// bytes together. pub fn download_data(url: &str, max: usize, done: crate::render::rustgis_tiles::cache::Done) { download_data_from(url, false, max, done); @@ -6006,6 +6009,11 @@ fn zipped_within(name: &str, shp: Vec, got: Vec<(&'static str, Vec)>, le Ok(zip) } +/// A .cst is only needed when the earlier .cpg could not select an encoding. +fn skip_cst(ext: &str, got: &[(&str, Vec)]) -> bool { + ext == "cst" && got.iter().any(|(e, b)| *e == "cpg" && rustgis_data::io::shapefile_cpg_is_usable(b)) +} + /// The next of a Shapefile's parts for [`download_data`], then the zip once they are all in: the /// steps of `download_shapefile_blocking_with` as callbacks, sharing its rules (`part_not_there`, /// `part_failed`, `zipped_within`), so a change to one goes in both. @@ -6022,6 +6030,9 @@ fn download_parts( done(zipped_within(&name, shp, got, left)); return; }; + if skip_cst(ext, &got) { + return download_parts(name, shp, parts, got, left, public, done); + } let next = url.clone(); let omit = part_absences(ext, &url); let step: crate::render::rustgis_tiles::cache::Done = Box::new(move |r| match r.and_then(|b| page_part(ext, b)) { diff --git a/crates/engine/src/observe.rs b/crates/engine/src/observe.rs index d8c28e3144..c997c672d3 100644 --- a/crates/engine/src/observe.rs +++ b/crates/engine/src/observe.rs @@ -111,7 +111,7 @@ impl Observation { } /// A monitored source at its linked path, with the companions its reader reads or sizes: a - /// Shapefile's lowercase `.dbf`, `.shx` and `.prj` and every ASCII-case `.cpg` + /// Shapefile's lowercase `.dbf`, `.shx` and `.prj` and every ASCII-case `.cpg` and `.cst` /// (`rustgis_data::dbf`), a MapInfo file's `.mid` (`rustgis_data::io`), a SQLite file's /// `-wal` and `-journal`, or a DuckDB database's `.wal` (commits not yet checkpointed, as the /// DuckDB conversion's cache key counts them). A missing source is @@ -121,7 +121,10 @@ impl Observation { let primary = FileRevision::read(path, Presence::Optional, "source")?; let mut companions = Vec::new(); if has_extension(path, &["shp"]) { - for ext in ["dbf", "shx", "prj", "cpg", "CPG", "Cpg", "cPg", "cpG", "CPg", "CpG", "cPG"] { + for ext in [ + "dbf", "shx", "prj", "cpg", "CPG", "Cpg", "cPg", "cpG", "CPg", "CpG", "cPG", "cst", "CST", "Cst", "cSt", "csT", "CSt", + "CsT", "cST", + ] { companions.push(FileRevision::read(&path.with_extension(ext), Presence::Optional, "source")?); } } else if has_extension(path, &["mif"]) { @@ -217,7 +220,7 @@ mod tests { #[test] fn shapefile_and_mapinfo_components_the_reader_opens_are_observed() { let dir = dir("components"); - for (main, exts) in [("roads.shp", &["dbf", "shx", "prj", "cpg", "CPG"][..]), ("roads.mif", &["mid"][..])] { + for (main, exts) in [("roads.shp", &["dbf", "shx", "prj", "cpg", "CPG", "cst", "CsT"][..]), ("roads.mif", &["mid"][..])] { let main = dir.join(main); std::fs::write(&main, b"shapes").unwrap(); let path = main.display().to_string(); diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index 35be46260e..b41a74fd5f 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -26141,7 +26141,7 @@ fn unreadable_plugin_blocklist_warns() { } /// A Shapefile published as loose files is added by its `.shp` address (#1238): its `.dbf`, -/// `.shx`, `.prj` and `.cpg` are fetched beside it with the address's query, and its `.prj` places +/// `.shx`, `.prj` and the encoding declaration are fetched beside it with the address's query, and its `.prj` places /// it; the parts that aren't there are done without, said, but not its `.dbf`, nor a part a /// signed address is refused. An address answering with a zip is read as one. Left to the app (a /// plugin's command), the address waits for the app, which fetches the parts the same way. @@ -26157,6 +26157,8 @@ fn shapefile_by_its_shp_address() { let (parts, _) = rustgis_data::io::shapefile_parts_in(&utm, Crs::from_epsg(31983).unwrap()).unwrap(); let mut files: Vec<(String, Vec)> = parts.iter().map(|(e, b)| (format!("/PI/TERESINA/HIDROGRAFIA/PI_2211001_RIOS.{e}?token=1"), b.clone())).collect(); + files.extend(parts.iter().filter(|(e, _)| *e != "cpg").map(|(e, b)| (format!("/cst/rios.{e}"), b.clone()))); + files.push(("/cst/rios.cst".into(), b"ISO-8859-1".to_vec())); // The same without its .prj and .cpg, and one without its .dbf. files.extend(parts.iter().filter(|(e, _)| !matches!(*e, "prj" | "cpg")).map(|(e, b)| (format!("/plain/rios.{e}"), b.clone()))); files.extend(parts.iter().filter(|(e, _)| !matches!(*e, "prj" | "cpg")).map(|(e, b)| (format!("/keyed/rios.{e}?token=zz"), b.clone()))); @@ -26199,6 +26201,12 @@ fn shapefile_by_its_shp_address() { for ext in ["shp", "dbf", "shx", "prj", "cpg"] { assert!(asked_for.contains(&format!("/PI/TERESINA/HIDROGRAFIA/PI_2211001_RIOS.{ext}?token=1")), "{ext}: {asked_for:?}"); } + assert!(!asked_for.iter().any(|path| path.contains(".cst")), "{asked_for:?}"); + let mark = s.notice_mark(); + s.run("layer.addUrl", &json!({"url": format!("{base}/cst/rios.shp"), "name": "Com cst"})).unwrap(); + let said = s.notices_since(mark); + assert!(said.iter().any(|n| n.text.contains("code page taken from the .cst")), "{said:?}"); + assert!(!said.iter().any(|n| n.text.contains("optional files")), "{said:?}"); // Without a .prj or .cpg (404), it is read as a local Shapefile without them. let r = s.run("layer.addUrl", &json!({"url": format!("{base}/plain/rios.shp"), "name": "Sem prj"})).unwrap(); assert_eq!(r["features"], 1, "{r}"); @@ -26323,6 +26331,14 @@ fn shapefile_by_its_shp_address() { assert!(s.map().layer_by_name("Pela janela").is_some()); let said = s.notices_since(mark); assert!(!said.iter().any(|n| n.text.contains("optional files")), "{said:?}"); + let cst = format!("{base}/cst/rios.shp"); + let id = s.download_started(); + assert!(s.download_landed(id, fetch(&cst, 1 << 20).unwrap())); + let mark = s.notice_mark(); + s.run("layer.addDownload", &json!({"id": id, "url": cst, "name": "Com cst pela janela"})).unwrap(); + let said = s.notices_since(mark); + assert!(said.iter().any(|n| n.text.contains("code page taken from the .cst")), "{said:?}"); + assert!(!said.iter().any(|n| n.text.contains("optional files")), "{said:?}"); // Through the app too, what was left out is said. let plain = format!("{base}/plain/rios.shp"); let id = s.download_started(); diff --git a/docs/user-guide/data-formats.md b/docs/user-guide/data-formats.md index 04344f7b15..5f2e14ca58 100644 --- a/docs/user-guide/data-formats.md +++ b/docs/user-guide/data-formats.md @@ -21,7 +21,7 @@ export names its feature. | GeoJSON | `.geojson`, `.json` | Home › Add › Add Data, or drop the file | Features with typed attributes; a single-member `GeometryCollection` is unwrapped (including nested single-member collections). Empty or multi-member collections are unsupported: the whole feature, including its attributes, is skipped and counted in an unreadable-geometry notice. A FeatureCollection's legacy `crs` member (`{"type": "name", "properties": {"name": "urn:ogc:def:crs:EPSG::28992"}}`) is honoured for EPSG codes (`EPSG:28992`, `urn:ogc:def:crs:EPSG::28992`, `urn:ogc:def:crs:EPSG:6.6:28992`) and for `CRS84`: a projected or other non-WGS 84 system is the layer's own: its coordinates are kept as the file holds them and drawn in the map's projection (Layer properties, export in it, Define Projection); `CRS84` and `EPSG:4326` are longitude/latitude already, so the coordinates stay as they are and the layer has no other coordinate system. Coordinates are x/y (easting/northing, or longitude/latitude) whatever the EPSG axis order. A `crs` that isn't understood (a `link`, WKT or PROJ text, any other name, an unknown code) is named in a notice and the coordinates are read as longitude/latitude. A feature whose coordinates can't be converted is kept as the file holds it and counted in a notice; it doesn't draw. One whose coordinates convert to beyond ±180.5° longitude or ±90.5° latitude (the declared system doesn't fit the numbers) is kept too, and a notice says it may draw out of place (see [Places with no longitude/latitude](#places-with-no-longitudelatitude)). A feature read as longitude/latitude (no `crs`, `CRS84` or `EPSG:4326`, or a `crs` that isn't understood) with a position whose longitude is within ±180.5° but whose latitude is past ±90.5° is kept, and one notice counts them: longitude and latitude may be swapped. A `crs` on a feature, a geometry or a lone Feature is ignored. GeoJSON is always written in WGS 84 without a `crs`. Desktop FeatureCollections larger than 32 MiB use an in-place reader (which honours `crs` too, reading the file once more to check the features convert); layers with more than 100,000 features stream a view at a time. Other GeoJSON files load whole: a FeatureCollection up to 32 MiB, or any with `"stream": false`, up to the size read into memory (256 MiB in the web app; on the desktop about 512 MiB for every 16 GiB of memory, up to 4 GiB: `fileBytes` in [Environments](analysis.md)); another GeoJSON document larger than 32 MiB up to 256 MiB, as it is read as it is added. A GeoJSON read whole whose attribute table (a cell for every field in every feature) would take more than 8 times that size is refused, saying the table's size: many features with properties spread over many fields. | | Delimited text | `.csv`, `.tsv`, `.txt`, recognised `.dat`; UTF-8 `.csv.gz`, `.tsv.gz`, `.txt.gz`, `.dat.gz` | Add Data, or Home › Add › Add Data › Delimited Text… to choose the columns from the file's header | Comma, semicolon, tab or pipe separated (found from the header, or `"delimiter"`); `info.fileColumns` lists the columns and the ones found. Points from x/y columns (named like longitude/latitude, in English or another language such as `經度`/`緯度`, GTFS `stop_lon`/`stop_lat` or easting/northing, or chosen with `"x"` and `"y"`), or any geometry from a WKT/EWKT column (named like `wkt` or `geometry`, or `"wkt"`). When an inferred pair exceeds degree ranges, a recognised longitude/latitude pair is preferred only if its in-range, non-0,0 points cover at least as many rows as the first pair can place, unless a projected `"crs"` is given (see [Delimited Text](data.md) for aliases and sampling). Coordinates in another system are converted from `"crs"` (`EPSG:2263`, or WKT) or an EWKT `SRID=`; rows still read outside longitude/latitude are counted in a notice. Points placed at exactly 0,0 are kept and counted in a notice, as they may represent missing coordinates. Uncompressed text is UTF-8, or UTF-16 with its byte-order mark; other uncompressed files are read as Windows-1252 (Latin-1, as many public sources still publish CSV), with a notice saying so. Gzip input is UTF-8 only, streamed within the size read into memory of expanded text (256 MiB in the web app); decompress other encodings and add as `.txt`. Retained CSV rows and cells have a separate estimated memory budget (256 MiB in the browser; a quarter of physical memory between 256 MiB and 4 GiB on desktop). A file without coordinates opens as a standalone table. | | Shapefile | `.shp` with `.dbf` (and `.shx`), or zipped (`.zip`) | Add Data or drop the file; in the web app, pick or drop the `.shp` and `.dbf` together, with the `.shx` and `.prj` if there are (they open as one layer), or the zip | A zip may hold several Shapefiles, in folders, and other vector files (GeoJSON, CSV, GeoParquet, FlatGeobuf); each becomes a layer or standalone table, at most 32 layers and tables together for the whole archive (Shapefiles first, so other files are left out when Shapefiles fill it). A `.dbf` without a `.shp` of the same name in its folder (such as a flood map's `L_` tables) opens as a standalone table, with its `.cpg` when present. An orphan MapInfo `.mid` without its `.mif` is skipped and named in the archive's notice. Delimited `.txt` members (including GTFS tables) are read; unrecognised text members and single-column `README.txt` documentation are skipped with a notice and macOS `__MACOSX` entries are passed over, and a member that can't be read is skipped and named in a notice. `"x"`, `"y"` and `"wkt"` given to Add Data apply to a zip's delimited members and to the first sheet of its workbooks, as to the file by itself, and `"delimiter"` to its delimited members only, so a zip of several tables with the same columns gives points together. A member that lacks a column given is read without them; one notice says how many members took the columns and names those that didn't, with the column each lacks. Other members ignore all of them. Converted to longitude/latitude from the coordinate system in its `.prj` (EPSG, Esri or OGC WKT, or WKT2 as PROJ and QGIS write it; Web Mercator, UTM, State Plane and other common projections); without a `.prj` it must be in longitude/latitude. On the desktop, one with more than 100,000 shapes (counted from its `.shx`) is read in place, a view at a time. A shape with a coordinate that isn't a number (NaN, infinity) keeps its attributes without geometry when the whole layer is read, in place too, and is counted in a notice; a view of an area, which holds no feature without geometry, leaves it out. Numeric (`N`) and floating point (`F`) fields are read at full double precision; on whole-file reads, `nan` or `inf` becomes empty and is counted in a notice. Date (`D`) fields are read as dates; a blank or zero date is empty, and one that isn't a date (`20260230`) is empty and counted in a notice. | -| dBASE table | `.dbf`, with `.cpg` when present | Add Data or drop the file; in the browser, pick or drop the `.dbf` and `.cpg` together, or zip them | Without a `.shp` beside it, opens as an editable standalone table. Uses the same code page, field types and loss notices as Shapefile attributes (including integer, double, Boolean and date fields). On the desktop, picking a `.dbf` with a `.shp` beside it opens that Shapefile instead; in the browser pick its parts together. ZIP tables share the archive's 32-layer/table budget. | +| dBASE table | `.dbf`, with `.cpg` or `.cst` when present | Add Data or drop the file; in the browser, pick or drop the `.dbf` and its encoding sidecars together, or zip them | Without a `.shp` beside it, opens as an editable standalone table. Uses the same code page, field types and loss notices as Shapefile attributes (including integer, double, Boolean and date fields). On the desktop, picking a `.dbf` with a `.shp` beside it opens that Shapefile instead; in the browser pick its parts together. ZIP tables share the archive's 32-layer/table budget. | | KML / KMZ | `.kml`, `.kmz` | Add Data, drop the file, or upload it in the web app | A layer for each kind of geometry (points, lines, polygons), with each placemark's name, description, folder path and extended data (a key named like the `name`, `description`, `folder`, `style` or source `id` column, ignoring case, gets a column of its own, such as `NAME_1`, unless it only repeats that column). A placemark's XML `id`, when present, is kept in a text `id` column; a distinct extended-data `id` is renamed with a notice. Declared Schema fields are kept even when every value is null. Extended-data values explicitly typed as XML Schema strings keep their exact text, including surrounding spaces. For descriptions, only the exact `description` key is treated as a repeated copy; case variants keep a separate column and report the rename. Description text, including surrounding whitespace, is kept as written; an empty description is empty text and an absent one is null. Styles are kept: the layer is drawn by unique values of its `style` field, with each KML style's line and fill colours, widths and icon colours (up to 64 styles). Multi-geometries and `gx:Track`s are read. Ground overlays (pictures on a `LatLonBox`, turned by its `rotation`) are raster layers kept in the project: the picture inside a KMZ, or a file beside a KML (not a web address, nor outside its folder); a `gx:LatLonQuad` isn't drawn. | | GPX | `.gpx` | Add Data, drop the file, or upload it in the web app | Waypoints, routes, tracks (one line per track, its segments as parts) and track points (with elevation and time) as separate layers. | | Spreadsheets | `.xlsx`, `.xlsm`, `.xlsb`, `.xls`, `.ods` | Add Data (or Delimited Text… to choose the columns), drop the file, or upload it in the web app | One sheet at a time, read like delimited text: the first non-empty row names the columns, and x/y or WKT columns (found, or given with `"x"`, `"y"`, `"wkt"` and `"crs"`) make the geometry; a sheet without them is a table. The first sheet is added and the others named in a notice; `"layer"` picks one, and `info.fileLayers` lists them. Dates read as ISO 8601. ZIP-based workbooks share a 1 GiB expanded-member budget (256 MiB in the browser), including relationships and metadata, with or without a preamble. Workbooks with ambiguous ZIP directories are refused. A sheet's dense grid is limited to 20 million cells (4 million in the browser); ODS sheets load together and share that cell allowance, with repetition checked before loading. Repeated ODS text shares the expanded-byte allowance; row/column counts beyond the reader's 1,048,576 × 16,384 dimensions are refused, not truncated. Repeated blank margins that need no dense grid remain supported within those dimensions. | @@ -55,18 +55,16 @@ GeoParquet or FlatGeobuf text column holding `` keeps it as text. Number, fields read past the spaces (`' 2535'` in a number column is 2535). To clean the spaces, use `trim()` in Calculate Field; text typed into the attribute table is trimmed. -Shapefile text uses the encoding in its `.cpg` sidecar first, then the language-driver code in -the `.dbf` header. Include the `.cpg` when picking or dropping loose files in the web app. +Shapefile text uses the first supported encoding in its `.cpg` sidecar, its `.cst` sidecar, +or the language-driver code in its `.dbf` header, in that order. Include the sidecars when +picking or dropping loose files in the web app. A notice identifies a code page taken from a `.cst`. UTF-8 (including `65001`), DOS code pages such as CP437 and CP850 (numeric, `CP` or `IBM` labels), Windows code pages such as `1252`, `CP1252` and `Windows-1252`, ISO-8859 encodings 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. +is read as Windows-1252. An unreadable, empty, invalid, oversized or unsupported declaration gives +a notice before RustGIS tries the next source. UTF-8 is the final fallback. Bytes that are invalid +in the selected encoding become replacement characters, and a notice counts those values and +names their fields and encoding. The same rules apply to ZIPs and large files read in place. 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. @@ -98,7 +96,8 @@ uploaded file. Native formats include GeoJSON, delimited text, GeoParquet, FlatG zipped Shapefiles, KML/KMZ, GPX, spreadsheets, GeoRSS, GML, DXF, TopoJSON, CityJSON, CityGML, LiDAR and rasters. A Shapefile published as loose files, one address per part, is added by its `.shp` address: the `.dbf` beside it (same name and folder) is fetched too, and the `.shx`, `.prj` and `.cpg` when they -are there, within the same download limit together. Their extensions follow the `.shp`'s case: a +are there. RustGIS also tries the `.cst` if the `.cpg` provides no usable encoding. All parts +share one download limit. Their extensions follow the `.shp`'s case: a `.SHP` asks for `.DBF`, `.SHX`, and so on. An optional part that answers 404 or 410, or 403 to an address without keys or a user and password (S3's answer for a missing file), or a web page in its place, is left out, and a notice names it. The parts are looked up beside the address as given diff --git a/docs/user-guide/data.md b/docs/user-guide/data.md index 9a25c89312..3bf0895922 100644 --- a/docs/user-guide/data.md +++ b/docs/user-guide/data.md @@ -304,8 +304,8 @@ code-only identifiers and GeoTIFF's coordinate transformation 17 don't name the nothing. The datum's ellipsoid is retained for datum transformations and exported coordinate system definitions. -Shapefile text uses a supported `.cpg` encoding, otherwise the `.dbf` code page, with UTF-8 as -the fallback. Keep the sidecar files together. A shape with a coordinate that isn't a number (NaN, +Shapefile text uses a supported encoding from the `.cpg`, `.cst` or `.dbf` header, in that +order, with UTF-8 as the fallback. Keep the sidecar files together. A shape with a coordinate that isn't a number (NaN, which some programs write for an empty point, or an infinity) has no place: its feature keeps its attributes without geometry, and a notice says how many (a large Shapefile read in place on the desktop leaves the whole record out, counted with its unreadable shapes). A project, project package or map package is never saved with such a diff --git a/docs/user-guide/index.md b/docs/user-guide/index.md index 94a8599a34..5830663527 100644 --- a/docs/user-guide/index.md +++ b/docs/user-guide/index.md @@ -303,7 +303,7 @@ Reload Data even when the folder's timestamp has not changed. **Changed on disk (desktop).** While the app is open, RustGIS looks at the files its linked layers and local tile archives read every 5 seconds and when its window regains focus, in every map of the project. It reads only metadata (size, modification time and the file's identity: on -Linux and macOS its status-change time too, on Windows its creation time), never the data: a Shapefile's `.dbf`, `.shx`, `.prj` and `.cpg` count with its +Linux and macOS its status-change time too, on Windows its creation time), never the data: a Shapefile's `.dbf`, `.shx`, `.prj`, `.cpg` and `.cst` count with its `.shp`, a MapInfo file's `.mid` with its `.mif`, a GeoPackage, MBTiles or `.sqlite` file's `-wal` and `-journal` with it, and a DuckDB database's `.wal` with it (a `.db` file gets both). Other sidecars (a raster's `.aux.xml` or `.prj`) aren't watched. A change is reported once two looks in a row agree: @@ -448,7 +448,7 @@ refuses, with nothing written, when: - the file can't hold the layer as it is: a feature without a shape, a field name longer than 10 bytes, text in characters the file's code page lacks. -The file keeps its code page (its `.cpg` and the language driver in its `.dbf`), each column's +The file keeps its code page (its `.cpg`, `.cst` and the language driver in its `.dbf`), each column's width, decimals and type where the values still fit, and its `.prj`. A column that can't hold an edited value gets one that can, and a notice names it with its old and new form; a field deleted or renamed in the layer leaves its column out of the file, and a notice names it too. A layer read in another diff --git a/docs/user-guide/shapefile-encoding.md b/docs/user-guide/shapefile-encoding.md index 03a761bd3d..cd8724298c 100644 --- a/docs/user-guide/shapefile-encoding.md +++ b/docs/user-guide/shapefile-encoding.md @@ -1,9 +1,10 @@ # Shapefile DBF language drivers -A valid `.cpg` takes precedence over the language driver ID (LDID, byte 29 of the `.dbf` -header). Without a usable `.cpg`, the following inventory describes RustGIS's LDID decoding. +RustGIS chooses a supported `.cpg` first, then a supported `.cst`, then the language driver ID +(LDID, byte 29 of the `.dbf` header). The following inventory describes RustGIS's LDID decoding +when neither sidecar provides a usable declaration. All numbers in the marker column are hexadecimal. These are language-driver identifiers, -not the numeric code-page labels accepted in a `.cpg`. +not the numeric code-page labels accepted in a `.cpg` or `.cst`. ## Decoded markers @@ -55,19 +56,18 @@ Cyrillic character. The test uses `8A E8 E5 E2` → `Киев`, which both mappi These markers emit a diagnostic naming the marker and code page, then use lossy UTF-8. Unknown markers also emit a diagnostic and use lossy UTF-8. Valid UTF-8 survives, malformed -bytes become replacement characters, and the records remain available. An unusable `.cpg` -adds its own diagnostic before falling back to the LDID. Supplying a valid `.cpg` bypasses -the LDID and its unsupported-code-page diagnostic. +bytes become replacement characters, and the records remain available. An unusable sidecar +adds its own diagnostic before falling back to the next source. A usable sidecar takes precedence +over the LDID, and a notice identifies an encoding taken from a `.cst`. Whenever text is read as UTF-8 (the markers in this section, unknown markers, `00`, `F0` or a -UTF-8 `.cpg`), a notice counts the text values whose bytes aren't valid UTF-8 and names their +UTF-8 declaration), a notice counts the text values whose bytes aren't valid UTF-8 and names their fields, and another counts such field names. A file whose text is all valid UTF-8 gives neither. Text read in a code page that is decoded here (932 Shift_JIS, 936 GBK, 949 EUC-KR, 950 Big5, the Windows pages and the rest) is counted the same way when its bytes aren't valid in that page: the -notices say how many values and field names, in which fields, and that the `.cpg` or the `.dbf`'s -language driver declares it. The DOS pages (437, 850, 852, 861, 865) give every byte a -character, so nothing in them is replaced. +notices say how many values and field names were affected, which fields they were in, and which +encoding the file declares. The DOS pages (437, 850, 852, 861, 865) give every byte a character. The existing transitive `yore` 1.4.0 package has CP737, CP857, CP860 and CP863 decoders, but RustGIS's current `dbase` adapter does not expose them. Making these available would From ce2de26d0bf214765363494b1cfd0af5aedc210a Mon Sep 17 00:00:00 2001 From: mavrick Date: Sat, 28 Nov 2026 14:32:10 -0600 Subject: [PATCH 02/12] fix(data): refuse publishing with an unusable Shapefile .cst --- crates/data/src/dbf.rs | 33 +++++++++++------- crates/data/src/io.rs | 2 ++ crates/data/src/publish.rs | 25 +++++++++++++- crates/data/src/sync.rs | 34 +++++++++++++++++-- .../tests/integration/shapefile_encoding.rs | 6 ++-- crates/engine/src/cmd/gp.rs | 9 +++-- crates/engine/src/observe.rs | 19 ++++++++--- crates/engine/src/tests.rs | 11 +++--- docs/user-guide/data-formats.md | 11 +++--- docs/user-guide/loss-codes.md | 4 +-- docs/user-guide/shapefile-encoding.md | 14 ++++---- 11 files changed, 126 insertions(+), 42 deletions(-) diff --git a/crates/data/src/dbf.rs b/crates/data/src/dbf.rs index 2e09432877..2ff3745faf 100644 --- a/crates/data/src/dbf.rs +++ b/crates/data/src/dbf.rs @@ -3,7 +3,7 @@ use encoding_rs as rs; use shapefile::dbase::{CodePageMark, UnicodeLossy, encoding::DynEncoding}; -const MAX_CODE_PAGE_BYTES: usize = 1024; +pub(crate) const MAX_CODE_PAGE_BYTES: usize = 1024; /// Keep the selection thread-safe; dbase's dynamic decoder is created per read because it /// is `Send` but not `Sync`, whereas feature sources can be shared between readers. @@ -151,13 +151,21 @@ pub(crate) fn encoding(cpg: Option<&[u8]>, cst: Option<&[u8]>, ldid: u8, notes: if cpg.is_some() { notes.push("Shapefile: unsupported or empty .cpg"); } + // A .cst is a convention and can name the wrong encoding. A single-byte code page + // can decode any byte, so the note is the only sign of which declaration was used. notes.push(format!("Shapefile: code page taken from the .cst ({})", encoding.name())); return (encoding, true); } let page = ldid_code_page(ldid); let resolved = page.and_then(DbfEncoding::from_number); - for ext in [cpg.map(|_| "cpg"), cst.map(|_| "cst")].into_iter().flatten() { - let text = format!("Shapefile: unsupported or empty .{ext}; using the .dbf code page, or UTF-8 if unavailable"); + let unusable = match (cpg, cst) { + (Some(_), Some(_)) => Some(".cpg and .cst"), + (Some(_), None) => Some(".cpg"), + (None, Some(_)) => Some(".cst"), + (None, None) => None, + }; + if let Some(sidecars) = unusable { + let text = format!("Shapefile: unsupported or empty {sidecars}; 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 { @@ -166,11 +174,11 @@ pub(crate) fn encoding(cpg: Option<&[u8]>, cst: Option<&[u8]>, ldid: u8, notes: } // No language driver: UTF-8, as it always was, without a note. if ldid == 0 { - return (DbfEncoding::Utf8, cpg.is_none() && cst.is_none()); + return (DbfEncoding::Utf8, unusable.is_none()); } if let Some(encoding) = resolved { - // Preserve the publish refusal for an unusable .cpg when there is no usable .cst. - return (encoding, cpg.is_none()); + // Publish keeps the sidecars, so edited text must agree with their declaration. + return (encoding, unusable.is_none()); } let named = page.map_or_else(String::new, |p| match page_name(p) { Some(name) => format!(" (code page {p}, {name})"), @@ -205,10 +213,10 @@ fn page_name(page: u16) -> Option<&'static str> { } /// The end of each note of text that isn't UTF-8: why a `.dbf`'s text was read as UTF-8, and what -/// names another encoding. A `.cpg` comes before the code page, so text is read as UTF-8 only when -/// no `.cpg` names another encoding RustGIS reads: the file names none, names UTF-8, or names a -/// code page RustGIS can't decode. -pub(crate) const NO_OTHER_ENCODING: &str = "no .cpg file names another encoding RustGIS reads (a .cpg file containing 950 names Big5)"; +/// names another encoding. A usable `.cpg` or `.cst` comes before the DBF language driver, so +/// at this point no `.cpg` or `.cst` file names another encoding RustGIS reads. +pub(crate) const NO_OTHER_ENCODING: &str = + "no .cpg or .cst file names another encoding RustGIS reads (a .cpg or .cst file containing 950 names Big5)"; /// The end of each note of text that isn't valid in `encoding`: for UTF-8, why the text was read as /// it ([`NO_OTHER_ENCODING`]); for another, that the file declares it. @@ -459,8 +467,9 @@ fn read_code_page(path: &std::path::Path, spellings: [&str; 8], notes: &mut crat /// Every ASCII case of the extension, the conventional spellings first: tried in turn, /// without scanning a potentially large directory, and the first there wins. -pub(crate) const CPG_SPELLINGS: [&str; 8] = ["cpg", "CPG", "Cpg", "cPg", "cpG", "CPg", "CpG", "cPG"]; -pub(crate) const CST_SPELLINGS: [&str; 8] = ["cst", "CST", "Cst", "cSt", "csT", "CSt", "CsT", "cST"]; +pub const CPG_SPELLINGS: [&str; 8] = ["cpg", "CPG", "Cpg", "cPg", "cpG", "CPg", "CpG", "cPG"]; +/// Every ASCII case of the `.cst` extension, in the order tried by the DBF reader. +pub const CST_SPELLINGS: [&str; 8] = ["cst", "CST", "Cst", "cSt", "csT", "CSt", "CsT", "cST"]; /// Reads at most one byte more than a label can hold, so oversized declarations stay unusable. pub(crate) fn try_read_code_page(path: &std::path::Path, spellings: [&str; 8]) -> std::io::Result>> { diff --git a/crates/data/src/io.rs b/crates/data/src/io.rs index 2d772f1084..3553109548 100644 --- a/crates/data/src/io.rs +++ b/crates/data/src/io.rs @@ -6,6 +6,8 @@ use std::path::Path; use serde::ser::{Serialize, SerializeMap, Serializer}; use serde_json::{Map, Value as Json, json}; +pub use crate::dbf::{CPG_SPELLINGS, CST_SPELLINGS}; + use crate::capped::Limit; use crate::raster::{Crs, planetary}; use crate::{Coord, DataError, Dataset, Field, FieldType, Geometry, GeometryType, ReadReport, Result, Value}; diff --git a/crates/data/src/publish.rs b/crates/data/src/publish.rs index da05c262eb..5e995940e2 100644 --- a/crates/data/src/publish.rs +++ b/crates/data/src/publish.rs @@ -1472,7 +1472,11 @@ mod tests { let (loose, report) = crate::io::read_path(&path).unwrap(); let clean_read = |ds: &Dataset, messages: &[crate::loss::Note]| { assert_eq!(ds.features[0].attrs[0], Value::Text("Muñoz".into())); - assert!(messages.iter().any(|m| m.loss.is_none() && m.contains("code page taken from the .cst")), "{messages:?}"); + assert_eq!( + messages.iter().filter(|m| m.loss.is_none() && m.contains("code page taken from the .cst")).count(), + 1, + "{messages:?}" + ); assert!(!messages.iter().any(|m| m.loss == Some(crate::loss::LossCode::ChangedEncoding)), "{messages:?}"); }; clean_read(&loose, &report.messages); @@ -1515,6 +1519,25 @@ mod tests { ); assert!(invalid_text(&report.messages), "{:?}", report.messages); + std::fs::write(&cpg, "not-a-code-page").unwrap(); + let (_, report) = crate::io::read_path(&path).unwrap(); + let mut assumptions = report.messages.iter().filter(|m| m.loss == Some(crate::loss::LossCode::AssumedEncoding)); + let assumed = assumptions.next().expect("the fallback is reported"); + assert!(assumed.contains(".cpg and .cst"), "{assumed:?}"); + assert!(assumptions.next().is_none(), "{:?}", report.messages); + std::fs::remove_file(&cpg).unwrap(); + + // Read can fall back to Windows-1252, but publish would keep the unusable .cst. + dbf[29] = 0x57; + std::fs::write(&dbf_path, &dbf).unwrap(); + let (mut fallback, sync) = read(&path); + assert_eq!(fallback.features[0].attrs[0], Value::Text("Café".into())); + fallback.features.set_value(0, 0, Value::Text("Cafés".into())).unwrap(); + let e = shapefile(&fallback, &path, &sync).err().expect("publish must refuse the unusable .cst").to_string(); + assert!(e.contains("unsupported or empty .cst") && e.contains("nothing was written"), "{e}"); + assert_eq!(std::fs::read(&dbf_path).unwrap(), dbf); + assert_eq!(std::fs::read(&cst).unwrap(), b"not-a-code-page"); + dbf[29] = 0xF0; // UTF-8 in the header must lose to a usable .cst. std::fs::write(&dbf_path, &dbf).unwrap(); std::fs::write(&cst, "ISO-8859-1").unwrap(); diff --git a/crates/data/src/sync.rs b/crates/data/src/sync.rs index 79d892fdff..8067326ba5 100644 --- a/crates/data/src/sync.rs +++ b/crates/data/src/sync.rs @@ -207,12 +207,21 @@ mod native { } /// The SHA-256 of the file's bytes, read a block at a time, each counted as progress - /// ([`crate::progress`]) and stopping once the run is cancelled. + /// ([`crate::progress`]) and stopping once the run is cancelled. An oversized .cst + /// leaves the source without a sync record, so it can't be published. fn sha256(path: &Path) -> Result { use sha2::Digest; use std::io::Read; - let mut file = crate::provenance::open(path)?; + let file = crate::provenance::open(path)?; let metadata = file.metadata().ok(); + let cst = path.extension().is_some_and(|ext| ext.eq_ignore_ascii_case("cst")); + let limit = crate::dbf::MAX_CODE_PAGE_BYTES as u64; + let too_large = || DataError::Format(format!("{} is too large to record for Publish to Source", path.display())); + if cst && metadata.as_ref().is_some_and(|m| m.len() > limit) { + return Err(too_large()); + } + // Bound the hash even if the declaration grows after the metadata check. + let mut file = file.take(if cst { limit + 1 } else { u64::MAX }); let mut hasher = sha2::Sha256::new(); let mut buf = vec![0u8; 1 << 16]; loop { @@ -223,6 +232,9 @@ mod native { hasher.update(buf.get(..n).unwrap_or_default()); crate::progress::step(n)?; } + if cst && file.limit() == 0 { + return Err(too_large()); + } let hash: String = hasher.finalize().iter().map(|b| format!("{b:02x}")).collect(); crate::provenance::hashed(path, metadata.as_ref(), hash.clone()); Ok(hash) @@ -388,6 +400,24 @@ mod tests { assert!(sync.changed(&path).unwrap().is_empty()); } + /// Reading still runs with an oversized declaration, but there is no publish baseline. + #[test] + fn an_oversized_cst_prevents_recording_a_publish_baseline() { + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("a.shp"); + let cst = path.with_extension("CsT"); + std::fs::write(&path, "shp").unwrap(); + std::fs::write(&cst, vec![b' '; crate::dbf::MAX_CODE_PAGE_BYTES]).unwrap(); + let record = FileSync::read(&path).unwrap(); + std::fs::File::options().write(true).open(&cst).unwrap().set_len(crate::dbf::MAX_CODE_PAGE_BYTES as u64 + 1).unwrap(); + let (read, sync) = FileSync::around(&path, || std::fs::read_to_string(&path)).unwrap(); + assert_eq!(read.unwrap(), "shp"); + assert!(sync.is_none()); + let changed = record.changed(&path).unwrap(); + assert_eq!(changed.len(), 1); + assert!(changed[0].eq_ignore_ascii_case("a.cst"), "{changed:?}"); + } + #[test] fn changes_are_named_and_a_touch_is_not_one() { let dir = tempfile::tempdir().unwrap(); diff --git a/crates/data/tests/integration/shapefile_encoding.rs b/crates/data/tests/integration/shapefile_encoding.rs index b39d8351be..13dc13cd55 100644 --- a/crates/data/tests/integration/shapefile_encoding.rs +++ b/crates/data/tests/integration/shapefile_encoding.rs @@ -75,10 +75,10 @@ fn named_parts(field: &[u8], text: &[u8], ldid: u8, cpg: Option<&[u8]>, rows: us } /// Why text was read as UTF-8, as the notes of text that isn't UTF-8 end. -const NO_OTHER_ENCODING: &str = "no .cpg file names another encoding RustGIS reads (a .cpg file containing 950 names Big5)"; +const NO_OTHER_ENCODING: &str = "no .cpg or .cst file names another encoding RustGIS reads (a .cpg or .cst file containing 950 names Big5)"; -/// The end of a notice of text that isn't valid in `encoding`: UTF-8 is read when no `.cpg` names -/// another, so it says that; another encoding was declared, so it names it. +/// The end of a notice of text that isn't valid in `encoding`: for UTF-8 it explains why no +/// `.cpg` or `.cst` selected another encoding. For another encoding it names what was declared. fn cause(encoding: &str) -> String { match encoding { "UTF-8" => NO_OTHER_ENCODING.to_string(), diff --git a/crates/engine/src/cmd/gp.rs b/crates/engine/src/cmd/gp.rs index 016c49ebd6..43bfad18cb 100644 --- a/crates/engine/src/cmd/gp.rs +++ b/crates/engine/src/cmd/gp.rs @@ -4052,7 +4052,7 @@ fn names_file(source: &str, destination: &std::path::Path) -> bool { } let shapefile = source.extension().is_some_and(|e| e.eq_ignore_ascii_case("shp")); let companion = |ext: &str| source.with_extension(ext).canonicalize().is_ok_and(|p| p.as_path() == destination); - shapefile && ["dbf", "shx", "prj", "cpg", "cst"].iter().any(|&ext| companion(ext) || companion(ext.to_ascii_uppercase().as_str())) + shapefile && ["dbf", "DBF", "shx", "SHX", "prj", "PRJ", "cpg", "CPG"].into_iter().chain(rustgis_data::io::CST_SPELLINGS).any(companion) } /// Adds a tool's table to the project under its name: in place of a table of that name, or, for @@ -5134,9 +5134,12 @@ mod file_tests { std::fs::write(&archive, b"zip").unwrap(); std::fs::write(&companion, b"dbf").unwrap(); let archive_file = archive.canonicalize().unwrap(); - let companion_file = companion.canonicalize().unwrap(); + let cst = root.join("roads.CsT"); + std::fs::write(&cst, b"ISO-8859-1").unwrap(); + let source = root.join("roads.shp").display().to_string(); assert!(names_file(&archive.join("roads.shp").display().to_string(), &archive_file)); - assert!(names_file(&root.join("roads.shp").display().to_string(), &companion_file)); + assert!(names_file(&source, &companion.canonicalize().unwrap())); + assert!(names_file(&source, &cst.canonicalize().unwrap())); assert!(!names_file(&root.join("roads.dbf").display().to_string(), &archive_file)); std::fs::remove_dir_all(root).unwrap(); } diff --git a/crates/engine/src/observe.rs b/crates/engine/src/observe.rs index c997c672d3..4932aaadf2 100644 --- a/crates/engine/src/observe.rs +++ b/crates/engine/src/observe.rs @@ -23,6 +23,8 @@ enum Presence { Required, /// Missing is `None`; an empty file is a revision (a monitored source, a Shapefile component). Optional, + /// Only regular files count as encoding declarations. + OptionalFile, /// A SQLite `-wal`/`-journal`: missing or empty is `None`, since SQLite creates an empty /// `-wal` even for a read-only open of a clean WAL-mode file and cannot remove it again. Sidecar, @@ -42,6 +44,9 @@ impl FileRevision { return Ok(None); } if !metadata.is_file() { + if presence == Presence::OptionalFile { + return Ok(None); + } let article = if noun == "archive" { "an" } else { "a" }; return Err(format!("{shown}: expected {article} {noun} file; restore the file and retry")); } @@ -121,12 +126,12 @@ impl Observation { let primary = FileRevision::read(path, Presence::Optional, "source")?; let mut companions = Vec::new(); if has_extension(path, &["shp"]) { - for ext in [ - "dbf", "shx", "prj", "cpg", "CPG", "Cpg", "cPg", "cpG", "CPg", "CpG", "cPG", "cst", "CST", "Cst", "cSt", "csT", "CSt", - "CsT", "cST", - ] { + for ext in ["dbf", "shx", "prj"].into_iter().chain(rustgis_data::io::CPG_SPELLINGS) { companions.push(FileRevision::read(&path.with_extension(ext), Presence::Optional, "source")?); } + for ext in rustgis_data::io::CST_SPELLINGS { + companions.push(FileRevision::read(&path.with_extension(ext), Presence::OptionalFile, "source")?); + } } else if has_extension(path, &["mif"]) { // Its attributes: the spellings `rustgis_data::io` reads. for ext in ["mid", "MID", "Mid"] { @@ -226,6 +231,12 @@ mod tests { let path = main.display().to_string(); let mut observed = Observation::source(&path).unwrap(); assert!(!observed.missing()); + if main.extension().is_some_and(|ext| ext == "shp") { + let cst = main.with_extension("cst"); + std::fs::create_dir(&cst).unwrap(); + assert_eq!(Observation::source(&path).unwrap(), observed); + std::fs::remove_dir(&cst).unwrap(); + } // Created and rewritten: every component the reader opens counts. for ext in exts { let component = main.with_extension(ext); diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index b41a74fd5f..7f9f45ce3b 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -2164,10 +2164,11 @@ fn a_streamed_shapefile_says_text_that_isnt_utf8_once_and_in_its_exports() { let dir = Dir(std::env::temp_dir().join(format!("rustgis-streamed-not-utf8-{}-{nanos}", std::process::id()))); std::fs::create_dir_all(&dir.0).unwrap(); // What the notice must carry: the count, the field and the replacement, not its wording. - // `encoding` is what the text was read in, and the end of the note says why: no `.cpg` named - // another encoding for UTF-8, or that the file declares the code page. + // `encoding` is what the text was read in, and the end of the note says why: no `.cpg` or `.cst` + // named another encoding for UTF-8, or that the file declares the code page. let says = |t: &str, encoding: &str| { - let why = if encoding == "UTF-8" { "no .cpg file names another encoding".to_string() } else { format!("declares {encoding}") }; + let why = + if encoding == "UTF-8" { "no .cpg or .cst file names another encoding".to_string() } else { format!("declares {encoding}") }; ["1 text value", "'NAME'", "U+FFFD", ".cpg", &format!("isn't valid {encoding}"), &why].iter().all(|k| t.contains(k)) }; // 臺北101 in Big5, and as many bytes of ASCII. The last value is named Big5 by its language @@ -26205,7 +26206,7 @@ fn shapefile_by_its_shp_address() { let mark = s.notice_mark(); s.run("layer.addUrl", &json!({"url": format!("{base}/cst/rios.shp"), "name": "Com cst"})).unwrap(); let said = s.notices_since(mark); - assert!(said.iter().any(|n| n.text.contains("code page taken from the .cst")), "{said:?}"); + assert_eq!(said.iter().filter(|n| n.text.contains("code page taken from the .cst")).count(), 1, "{said:?}"); assert!(!said.iter().any(|n| n.text.contains("optional files")), "{said:?}"); // Without a .prj or .cpg (404), it is read as a local Shapefile without them. let r = s.run("layer.addUrl", &json!({"url": format!("{base}/plain/rios.shp"), "name": "Sem prj"})).unwrap(); @@ -26337,7 +26338,7 @@ fn shapefile_by_its_shp_address() { let mark = s.notice_mark(); s.run("layer.addDownload", &json!({"id": id, "url": cst, "name": "Com cst pela janela"})).unwrap(); let said = s.notices_since(mark); - assert!(said.iter().any(|n| n.text.contains("code page taken from the .cst")), "{said:?}"); + assert_eq!(said.iter().filter(|n| n.text.contains("code page taken from the .cst")).count(), 1, "{said:?}"); assert!(!said.iter().any(|n| n.text.contains("optional files")), "{said:?}"); // Through the app too, what was left out is said. let plain = format!("{base}/plain/rios.shp"); diff --git a/docs/user-guide/data-formats.md b/docs/user-guide/data-formats.md index 5f2e14ca58..6a7663c4ca 100644 --- a/docs/user-guide/data-formats.md +++ b/docs/user-guide/data-formats.md @@ -61,10 +61,13 @@ picking or dropping loose files in the web app. A notice identifies a code page UTF-8 (including `65001`), DOS code pages such as CP437 and CP850 (numeric, `CP` or `IBM` labels), Windows code pages such as `1252`, `CP1252` and `Windows-1252`, ISO-8859 encodings and common East Asian encodings are supported. The Esri `0x57` DBF marker -is read as Windows-1252. An unreadable, empty, invalid, oversized or unsupported declaration gives -a notice before RustGIS tries the next source. UTF-8 is the final fallback. Bytes that are invalid -in the selected encoding become replacement characters, and a notice counts those values and -names their fields and encoding. The same rules apply to ZIPs and large files read in place. +is read as Windows-1252. An unreadable, empty, invalid, oversized or unsupported `.cpg` or `.cst` +gives a notice before RustGIS tries the next source. 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 without a usable `.cpg` or `.cst` 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. 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..ea3f651efe 100644 --- a/docs/user-guide/loss-codes.md +++ b/docs/user-guide/loss-codes.md @@ -210,6 +210,6 @@ The file does not say which coordinate system its coordinates are in, or says on The file does not name its text encoding, or names one RustGIS does not read, so RustGIS assumed one (UTF-8, or Latin-1 for a DXF). -**Where you see it:** reading a Shapefile or dBASE file without a usable .cpg file, or a DXF drawing without a known code page. +**Where you see it:** reading a Shapefile or dBASE file without a usable `.cpg` or `.cst`, or a DXF drawing without a known code page. -**What to do:** Give the file's encoding in a form RustGIS reads: a .cpg beside a Shapefile or dBASE file naming UTF-8 or its Windows code page, or a DXF saved as UTF-8. +**What to do:** Give the file's encoding in a form RustGIS reads: a `.cpg` or `.cst` beside a Shapefile or dBASE file naming UTF-8 or its Windows code page, or a DXF saved as UTF-8. diff --git a/docs/user-guide/shapefile-encoding.md b/docs/user-guide/shapefile-encoding.md index cd8724298c..53e7c06f02 100644 --- a/docs/user-guide/shapefile-encoding.md +++ b/docs/user-guide/shapefile-encoding.md @@ -56,18 +56,20 @@ Cyrillic character. The test uses `8A E8 E5 E2` → `Киев`, which both mappi These markers emit a diagnostic naming the marker and code page, then use lossy UTF-8. Unknown markers also emit a diagnostic and use lossy UTF-8. Valid UTF-8 survives, malformed -bytes become replacement characters, and the records remain available. An unusable sidecar -adds its own diagnostic before falling back to the next source. A usable sidecar takes precedence -over the LDID, and a notice identifies an encoding taken from a `.cst`. +bytes become replacement characters, and the records remain available. An unusable `.cpg` or +`.cst` gives a diagnostic before falling back to the next source. Supplying a usable `.cpg` or +`.cst` bypasses the LDID and its unsupported-code-page diagnostic. A note identifies an encoding +taken from a `.cst`. Whenever text is read as UTF-8 (the markers in this section, unknown markers, `00`, `F0` or a -UTF-8 declaration), a notice counts the text values whose bytes aren't valid UTF-8 and names their +UTF-8 `.cpg` or `.cst`), a notice counts the text values whose bytes aren't valid UTF-8 and names their fields, and another counts such field names. A file whose text is all valid UTF-8 gives neither. Text read in a code page that is decoded here (932 Shift_JIS, 936 GBK, 949 EUC-KR, 950 Big5, the Windows pages and the rest) is counted the same way when its bytes aren't valid in that page: the -notices say how many values and field names were affected, which fields they were in, and which -encoding the file declares. The DOS pages (437, 850, 852, 861, 865) give every byte a character. +notices say how many values and field names, in which fields, and that the `.cpg`, `.cst` or the +`.dbf`'s language driver declares it. The DOS pages (437, 850, 852, 861, 865) give every byte a +character, so nothing in them is replaced. The existing transitive `yore` 1.4.0 package has CP737, CP857, CP860 and CP863 decoders, but RustGIS's current `dbase` adapter does not expose them. Making these available would From c53868cc2ca435847274ffaa5855036e4c1afd04 Mon Sep 17 00:00:00 2001 From: mavrick Date: Sat, 28 Nov 2026 15:02:30 -0600 Subject: [PATCH 03/12] docs(data): align encoding loss guidance with CST support --- crates/data/src/loss.rs | 2 +- docs/user-guide/loss-codes.md | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/crates/data/src/loss.rs b/crates/data/src/loss.rs index 62a4a050f4..e41fa8eb57 100644 --- a/crates/data/src/loss.rs +++ b/crates/data/src/loss.rs @@ -195,7 +195,7 @@ loss_codes! { "assumed.encoding", Assumed, "The file does not name its text encoding, or names one RustGIS does not read, so RustGIS assumed one (UTF-8, or Latin-1 for a DXF).", - "Give the file's encoding in a form RustGIS reads: a .cpg beside a Shapefile or dBASE file naming UTF-8 or its Windows code page, or a DXF saved as UTF-8." + "Give the file's encoding in a form RustGIS reads: a .cpg or .cst beside a Shapefile or dBASE file naming UTF-8 or its Windows code page, or a DXF saved as UTF-8." ), } diff --git a/docs/user-guide/loss-codes.md b/docs/user-guide/loss-codes.md index ea3f651efe..6453abbdbc 100644 --- a/docs/user-guide/loss-codes.md +++ b/docs/user-guide/loss-codes.md @@ -212,4 +212,4 @@ The file does not name its text encoding, or names one RustGIS does not read, so **Where you see it:** reading a Shapefile or dBASE file without a usable `.cpg` or `.cst`, or a DXF drawing without a known code page. -**What to do:** Give the file's encoding in a form RustGIS reads: a `.cpg` or `.cst` beside a Shapefile or dBASE file naming UTF-8 or its Windows code page, or a DXF saved as UTF-8. +**What to do:** Give the file's encoding in a form RustGIS reads: a .cpg or .cst beside a Shapefile or dBASE file naming UTF-8 or its Windows code page, or a DXF saved as UTF-8. From 04026a433e180b1c57c393b93529d3e7dcc3cd2c Mon Sep 17 00:00:00 2001 From: mavrick Date: Sat, 28 Nov 2026 18:40:10 -0600 Subject: [PATCH 04/12] fix(data): bound and isolate Shapefile encoding declarations --- apps/rustgis-web/src/web.rs | 47 +++- crates/data/src/dbf.rs | 379 ++++++++++++++++++++------ crates/data/src/io.rs | 141 +++++++--- crates/data/src/provenance.rs | 7 +- crates/data/src/publish.rs | 301 +++++++++++++++++--- crates/data/src/source/shp.rs | 38 ++- crates/data/src/sync.rs | 191 ++++++++++--- crates/data/src/zip.rs | 94 ++++++- crates/engine/src/cmd/gp.rs | 27 +- crates/engine/src/cmd/layer.rs | 57 +++- crates/engine/src/observe.rs | 27 +- crates/engine/src/tests.rs | 26 +- crates/tiles/src/cache.rs | 7 + docs/user-guide/data-formats.md | 16 +- docs/user-guide/index.md | 21 +- docs/user-guide/loss-codes.md | 2 + docs/user-guide/shapefile-encoding.md | 20 +- 17 files changed, 1135 insertions(+), 266 deletions(-) diff --git a/apps/rustgis-web/src/web.rs b/apps/rustgis-web/src/web.rs index ca285371fe..10b10013ba 100644 --- a/apps/rustgis-web/src/web.rs +++ b/apps/rustgis-web/src/web.rs @@ -512,7 +512,9 @@ impl eframe::App for WebShell { /// Reads files picked or dropped together into the inbox, all at once, each Shapefile's loose /// parts zipped into one (`gather_shapefiles`) so it opens as a layer; `mark` starts each name. async fn read_together(mut files: Vec, mark: &str, inbox: &Inbox, notes: Notes) { - let mut read = Vec::new(); + use rustgis_ui_egui::rustgis_engine::data::io::{SHAPEFILE_CODE_PAGE_LIMIT, shapefile_cpg_is_usable}; + + let mut read: Vec<(String, Vec)> = Vec::new(); // The assistant's pictures: no more are read than a message takes, and those left out, or // too large, are said once each kind. let pictures = mark == rustgis_ui_egui::ASSISTANT_PICK; @@ -526,8 +528,25 @@ async fn read_together(mut files: Vec, mark: &str, inbox: &Inbox, notes.lock().unwrap_or_else(|e| e.into_inner()).push((text, true)); } let mut too_large = Vec::new(); + // The fallback declarations go last so a picked .cpg can make reading the .cst unnecessary. + files.sort_by_key(|f| f.name().to_ascii_lowercase().ends_with(".cst")); for file in files { let name = file.name(); + if let Some((stem, ext)) = name.rsplit_once('.') + && ext.eq_ignore_ascii_case("cst") + { + if read.iter().any(|(name, b)| { + name.rsplit_once('.').is_some_and(|(base, ext)| { + stem.eq_ignore_ascii_case(base) && ext.eq_ignore_ascii_case("cpg") && shapefile_cpg_is_usable(b) + }) + }) { + continue; + } + if file.size() >= SHAPEFILE_CODE_PAGE_LIMIT as f64 { + read.push((name, Vec::new())); + continue; + } + } let shortcut = mark == rustgis_ui_egui::SHORTCUT_PICK || (mark.is_empty() && name.to_ascii_lowercase().ends_with(".rgisshortcuts")); if shortcut && file.size() > rustgis_ui_egui::SHORTCUT_FILE_MAX_BYTES as f64 { notes @@ -690,6 +709,7 @@ const STALL_MS: i32 = 30_000; async fn unless_stalled( step: js_sys::Promise, abort: Option<&web_sys::AbortController>, + wait_ms: i32, ) -> Option> { let Some(abort) = abort else { return Some(wasm_bindgen_futures::JsFuture::from(step).await) }; let stalled = wasm_bindgen::JsValue::from_str("rustgis-stalled"); @@ -697,7 +717,7 @@ async fn unless_stalled( let handle = std::cell::Cell::new(None); let timer = js_sys::Promise::new(&mut |resolve, _| { if let Some(w) = web_sys::window() { - handle.set(w.set_timeout_with_callback_and_timeout_and_arguments_1(&resolve, STALL_MS, &marker).ok()); + handle.set(w.set_timeout_with_callback_and_timeout_and_arguments_1(&resolve, wait_ms, &marker).ok()); } }); let raced = wasm_bindgen_futures::JsFuture::from(js_sys::Promise::race(&js_sys::Array::of2(&step, &timer))).await; @@ -748,6 +768,19 @@ async fn fetch_reached( omit: &'static [u16], ) -> Result { use rustgis_ui_egui::rustgis_engine::render::rustgis_tiles::{cache::RequestDiagnostics, failure::Failure}; + use rustgis_ui_egui::rustgis_engine::{ + data::io::SHAPEFILE_CODE_PAGE_LIMIT, + render::rustgis_tiles::{cache, logins}, + }; + let (unmarked, limit) = cache::split_download_limit(url); + let optional_cst = limit == Some(SHAPEFILE_CODE_PAGE_LIMIT) + && logins::inner(unmarked).split(['?', '#']).next().is_some_and(|p| p.to_ascii_lowercase().ends_with(".cst")); + let deadline = optional_cst.then(|| web_time::Instant::now() + std::time::Duration::from_secs(2)); + let wait_ms = || { + deadline.map_or(STALL_MS, |until| { + i32::try_from(until.saturating_duration_since(web_time::Instant::now()).as_millis()).unwrap_or(STALL_MS) + }) + }; let mut diagnostics = RequestDiagnostics::with_capture(url, "GET", capture); diagnostics.omit_statuses(omit); let answer = async { @@ -756,7 +789,7 @@ async fn fetch_reached( &still, || async { let window = web_sys::window().ok_or("no window")?; - let gives_up = cache::gives_up_when_stalled(url, ceiling); + let gives_up = optional_cst || cache::gives_up_when_stalled(url, ceiling); // A data download carries its caller's budget (at most MAX_DOWNLOAD); other fetches use 64 MB. let (url, limit) = cache::split_download_limit(url); let max = limit.map(|n| n as u64).unwrap_or(64 << 20); @@ -776,7 +809,7 @@ async fn fetch_reached( // An ArcGIS sign-in's token, for the portal and the servers it covers, renewed first when it // is about to expire. It goes as the request's `token` parameter, not a header: ArcGIS's // query endpoints answer the header's CORS preflight with an error. - if !bare && !explicit { + if !bare && !explicit && !optional_cst { crate::arcgis::renew_if_due(url, still.clone()).await; crate::copernicus::renew_if_due(url, still.clone()).await; cache::check_still(&still)?; @@ -851,11 +884,11 @@ async fn fetch_reached( let err = |e: wasm_bindgen::JsValue| { if authenticated { "the browser couldn't process the authenticated request".to_string() } else { format!("{e:?}") } }; - let stalled = || format!("nothing came in {} seconds", STALL_MS / 1000); + let stalled = || if optional_cst { "the optional .cst download timed out".into() } else { format!("nothing came in {} seconds", STALL_MS / 1000) }; let result = async { // A refused fetch is an opaque TypeError ("Failed to fetch") by design. Keep its message // only on requests without a login: even a browser's error may repeat credentials. - let resp: web_sys::Response = unless_stalled(promise, abort.as_ref()) + let resp: web_sys::Response = unless_stalled(promise, abort.as_ref(), wait_ms()) .await .ok_or_else(|| { diagnostics.timed_out(); @@ -916,7 +949,7 @@ async fn fetch_reached( loop { // Headers came and then the body stalled: given up as a fetch that doesn't answer. // (Aborting the fetch has cancelled its body too.) - let Some(chunk) = unless_stalled(reader.read(), abort.as_ref()).await else { + let Some(chunk) = unless_stalled(reader.read(), abort.as_ref(), wait_ms()).await else { diagnostics.timed_out(); return Err(stalled()); }; diff --git a/crates/data/src/dbf.rs b/crates/data/src/dbf.rs index 2ff3745faf..a97cb2ed30 100644 --- a/crates/data/src/dbf.rs +++ b/crates/data/src/dbf.rs @@ -1,5 +1,7 @@ //! Shared Shapefile character encoding selection for whole-file and streamed reads. +use std::path::{Path, PathBuf}; + use encoding_rs as rs; use shapefile::dbase::{CodePageMark, UnicodeLossy, encoding::DynEncoding}; @@ -28,7 +30,7 @@ impl DbfEncoding { } /// Whether `text` holds bytes this encoding can't read. Its decoder puts U+FFFD in place of - /// them without a word, so the read counts them itself ([`not_utf8`]). It asks the decoder + /// them without a word, so the read counts them itself ([`text_notices`]). It asks the decoder /// `dbase` calls, so a count is of the values that were replaced. A DOS page gives every /// byte a character, so nothing is. pub(crate) fn malformed(&self, text: &[u8]) -> bool { @@ -43,11 +45,26 @@ impl DbfEncoding { pub(crate) fn name(&self) -> &'static str { match self { Self::Standard(encoding) => encoding.name(), - Self::Oem(_) => "a DOS code page", + Self::Oem(mark) => match mark { + CodePageMark::CP437 => "DOS 437", + CodePageMark::CP850 => "DOS 850", + CodePageMark::CP852 => "DOS 852", + CodePageMark::CP861 => "DOS 861", + CodePageMark::CP865 => "DOS 865", + _ => "a DOS code page", + }, Self::Utf8 => "UTF-8", } } + fn is_single_byte(&self) -> bool { + match self { + Self::Standard(encoding) => encoding.is_single_byte(), + Self::Oem(_) => true, + Self::Utf8 => false, + } + } + fn from_number(number: u16) -> Option { // DOS 437, 850, 852, 861 and 865 go to dbase's OEM adapter; DOS 866 and the other pages // decoded here keep encoding_rs, because dbase's yore adapter is strict for those and can @@ -141,61 +158,92 @@ fn ldid_code_page(ldid: u8) -> Option { }) } -/// Reads the first usable declaration in order. The flag says whether Publish to Source can -/// write with the same selection, subject to its separate round-trip checks. -pub(crate) fn encoding(cpg: Option<&[u8]>, cst: Option<&[u8]>, ldid: u8, notes: &mut crate::loss::Notes) -> (DbfEncoding, bool) { - if let Some(encoding) = sidecar_encoding(cpg) { - return (encoding, true); - } - if let Some(encoding) = sidecar_encoding(cst) { - if cpg.is_some() { - notes.push("Shapefile: unsupported or empty .cpg"); +/// The decoder selected for a table and the checks that its declaration requires. +pub(crate) struct EncodingChoice { + pub encoding: DbfEncoding, + /// Why a write that keeps the original declarations would be unsafe. + #[cfg(not(target_arch = "wasm32"))] + pub refusal: Option, + /// A single-byte .cst may conceal UTF-8 text left by a writer that ignored it. + pub check_utf8: bool, +} + +impl EncodingChoice { + fn new(encoding: DbfEncoding, check_utf8: bool, _refusal: Option) -> Self { + Self { + encoding, + check_utf8, + #[cfg(not(target_arch = "wasm32"))] + refusal: _refusal, } - // A .cst is a convention and can name the wrong encoding. A single-byte code page - // can decode any byte, so the note is the only sign of which declaration was used. - notes.push(format!("Shapefile: code page taken from the .cst ({})", encoding.name())); - return (encoding, true); + } +} + +/// Selects the first usable declaration, with the tradeoffs of the .cst fallback +/// reported here so whole-file and in-place reads use the same precedence. +pub(crate) fn encoding(cpg: Option<&[u8]>, cst: Option<&[u8]>, ldid: u8, notes: &mut crate::loss::Notes) -> EncodingChoice { + use crate::loss::{LossCode, Note}; + + if let Some(encoding) = sidecar_encoding(cpg) { + return EncodingChoice::new(encoding, false, None); } let page = ldid_code_page(ldid); let resolved = page.and_then(DbfEncoding::from_number); + if let Some((label, encoding)) = + cst.and_then(sidecar_label).and_then(|label| DbfEncoding::from_name(label).map(|encoding| (label, encoding))) + { + let chosen = format!("Shapefile: code page taken from the .cst ({label:?}, read as {})", encoding.name()); + let conflict = resolved.filter(|other| other.name() != encoding.name()); + let refusal = if let Some(other) = conflict { + let message = format!("{chosen}; 1 encoding conflict with .dbf language driver 0x{ldid:02X} ({})", other.name()); + notes.push(Note::loss(LossCode::ChangedEncoding, &message)); + Some(format!("{message}; reconcile the .dbf and .cst encoding declarations, then add the file again")) + } else { + notes.push(chosen); + None + }; + let refusal = if cpg.is_some() { + notes.push("Shapefile: unsupported or empty .cpg; using the .cst"); + Some("its .cpg is unsupported or empty; repair or remove it, then add the file again".into()) + } else { + refusal + }; + let check_utf8 = encoding.is_single_byte(); + return EncodingChoice::new(encoding, check_utf8, refusal); + } let unusable = match (cpg, cst) { (Some(_), Some(_)) => Some(".cpg and .cst"), (Some(_), None) => Some(".cpg"), (None, Some(_)) => Some(".cst"), (None, None) => None, }; - if let Some(sidecars) = unusable { - let text = format!("Shapefile: unsupported or empty {sidecars}; 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 { - crate::loss::Note::plain(text) - }); - } - // No language driver: UTF-8, as it always was, without a note. - if ldid == 0 { - return (DbfEncoding::Utf8, unusable.is_none()); - } - if let Some(encoding) = resolved { - // Publish keeps the sidecars, so edited text must agree with their declaration. - return (encoding, unusable.is_none()); + let refusal = unusable.map(|sidecars| { + let unreadable = if cst.is_some() { " (including unreadable declarations)" } else { "" }; + let text = format!("Shapefile: unsupported or empty {sidecars}{unreadable}; using the .dbf code page, or UTF-8 if unavailable"); + notes.push(if ldid == 0 { Note::loss(LossCode::AssumedEncoding, text) } else { Note::plain(text) }); + format!("unsupported or empty {sidecars}; repair or remove the declaration, then add the file again") + }); + if ldid == 0 || resolved.is_some() { + return EncodingChoice::new(resolved.unwrap_or(DbfEncoding::Utf8), false, refusal); } let named = page.map_or_else(String::new, |p| match page_name(p) { Some(name) => format!(" (code page {p}, {name})"), None => format!(" (code page {p})"), }); - notes.push(crate::loss::Note::loss( - crate::loss::LossCode::AssumedEncoding, - format!("Shapefile: unsupported .dbf code page 0x{ldid:02X}{named}; using UTF-8"), - )); - (DbfEncoding::Utf8, false) + let message = format!("Shapefile: unsupported .dbf code page 0x{ldid:02X}{named}; using UTF-8"); + notes.push(Note::loss(LossCode::AssumedEncoding, &message)); + EncodingChoice::new(DbfEncoding::Utf8, false, refusal.or(Some(message))) } /// A label small enough to be a declaration, in one of the code pages a DBF can use. pub(crate) fn sidecar_encoding(bytes: Option<&[u8]>) -> Option { - let bytes = bytes.filter(|b| b.len() <= MAX_CODE_PAGE_BYTES)?; - let label = std::str::from_utf8(bytes).ok()?.trim().trim_start_matches('\u{feff}').trim(); - DbfEncoding::from_name(label) + DbfEncoding::from_name(sidecar_label(bytes?)?) +} + +/// Decodes the bounded label itself without changing its spelling for diagnostics. +fn sidecar_label(bytes: &[u8]) -> Option<&str> { + let bytes = (bytes.len() <= MAX_CODE_PAGE_BYTES).then_some(bytes)?; + Some(std::str::from_utf8(bytes).ok()?.trim().trim_start_matches('\u{feff}').trim()) } /// The name of a code page a language driver may name and RustGIS can't decode, for the note. @@ -228,7 +276,7 @@ pub(crate) fn cause(encoding: &str) -> String { } } -/// What opening a `.dbf` says of its field names that aren't valid in its `encoding` ([`not_utf8`]), +/// What opening a `.dbf` says of its field names that aren't valid in its `encoding` ([`text_notices`]), /// naming the first five by their column (from 1). `None` when there are none. pub(crate) fn not_utf8_names_note(columns: &[usize], encoding: &str) -> Option { let (what, label) = match columns.len() { @@ -253,8 +301,57 @@ pub(crate) fn not_utf8_names_note(columns: &[usize], encoding: &str) -> Option (Vec, Vec) { - let lossy = |text: &[u8]| encoding.malformed(text.split(|b| *b == 0).next().unwrap_or(&[])); +pub(crate) fn text_notices(dbf: &[u8], encoding: &DbfEncoding, check_utf8: bool) -> (Vec, Vec, Option) { + let mut evidence = check_utf8.then(Utf8Evidence::default); + let (names, values) = inspect_text(dbf, |text| { + if let Some(evidence) = &mut evidence { + evidence.observe(text); + } + encoding.malformed(text) + }); + (names, values, evidence.and_then(|evidence| evidence.notice(encoding))) +} + +/// Counts suspicious UTF-8 text in a whole DBF, using the same byte ranges as its decoder. +#[cfg(not(target_arch = "wasm32"))] +pub(crate) fn utf8_under_cst(dbf: &[u8]) -> Utf8Evidence { + let mut evidence = Utf8Evidence::default(); + inspect_text(dbf, |text| { + evidence.observe(text); + false + }); + evidence +} + +/// Evidence that non-ASCII text already uses UTF-8, gathered without retaining the values. +#[derive(Clone, Copy, Default)] +pub(crate) struct Utf8Evidence { + non_ascii: usize, + invalid: bool, +} + +impl Utf8Evidence { + pub(crate) fn observe(&mut self, text: &[u8]) { + if !self.invalid && !text.is_ascii() { + self.non_ascii += 1; + self.invalid = std::str::from_utf8(text).is_err(); + } + } + + /// The count refers only to text visited by this read, which can be a streamed sample. + pub(crate) fn notice(self, encoding: &DbfEncoding) -> Option { + (!self.invalid && self.non_ascii > 0).then(|| { + crate::loss::Note::loss( + crate::loss::LossCode::ChangedEncoding, + format!("Shapefile: all text inspected is valid UTF-8, including {} non-ASCII field names or values; decoded with {} as declared by the .cst", self.non_ascii, encoding.name()), + ) + }) + } +} + +/// Inspects the text bytes of every live DBF row and field name, before NUL padding. +fn inspect_text(dbf: &[u8], mut inspect: impl FnMut(&[u8]) -> bool) -> (Vec, Vec) { + let mut lossy = |text: &[u8]| inspect(text.split(|b| *b == 0).next().unwrap_or(&[])); let header_len = usize::from(u16::from_le_bytes([dbf.get(8).copied().unwrap_or(0), dbf.get(9).copied().unwrap_or(0)])); let rows = dbf.get(4..8).and_then(|b| <[u8; 4]>::try_from(b).ok()).map_or(0, |b| u32::from_le_bytes(b) as usize); let mut names = Vec::new(); @@ -262,7 +359,7 @@ pub(crate) fn not_utf8(dbf: &[u8], encoding: &DbfEncoding) -> (Vec, Vec (Vec, Vec std::result::Result Option> { - match try_read_code_page(path, spellings) { - Ok(bytes) => bytes, - Err(e) => { - // The selection reports the fallback as it does for an unusable declaration. - notes.push(crate::loss::Note::plain(format!("could not read the .{} ({e})", spellings[0]))); - Some(Vec::new()) +/// All case spellings, in lookup order, without scanning the directory. +const CPG_SPELLINGS: [&str; 8] = ["cpg", "CPG", "Cpg", "cPg", "cpG", "CPg", "CpG", "cPG"]; +const CST_SPELLINGS: [&str; 8] = ["cst", "CST", "Cst", "cSt", "csT", "CSt", "CsT", "cST"]; + +/// Possible code-page sidecars, first .cpg then .cst, beside a Shapefile or a standalone DBF. +pub fn declaration_paths(path: &Path) -> impl Iterator + '_ { + CPG_SPELLINGS.into_iter().chain(CST_SPELLINGS).map(|ext| path.with_extension(ext)) +} + +/// A declaration and the exact path selected. Empty bytes represent an unreadable declaration, +/// so callers can fall back with the same notice as for an empty file. +pub(crate) struct Declaration { + pub path: PathBuf, + pub bytes: Option>, + pub error: Option, +} + +impl Declaration { + pub(crate) fn bytes(&self) -> &[u8] { + self.bytes.as_deref().unwrap_or_default() + } + + #[cfg(not(target_arch = "wasm32"))] + pub(crate) fn leased(&self) -> bool { + self.error.as_ref().is_some_and(|e| e.kind() == std::io::ErrorKind::WouldBlock) + } +} + +/// Finds the first regular spelling. A non-file spelling cannot hide a later regular one. +/// If no spelling works, remember the unusable declaration so the read can explain its fallback. +/// A regular .cpg that failed to open or read keeps the same precedence and diagnostic as before. +fn read_declaration(paths: impl Iterator, cpg: bool, wait: bool) -> crate::Result> { + use crate::DataError; + use std::io::{self, Read}; + let mut unusable = None; + for path in paths { + let opened = if wait { open_with_lease_retry(&path, cpg) } else { open_declaration(&path).map_err(DataError::from) }; + let file = match opened { + Ok(Some(file)) => file, + Ok(None) => { + unusable.get_or_insert(Declaration { path, bytes: None, error: None }); + continue; + } + Err(DataError::Io(e)) if e.kind() == io::ErrorKind::NotFound => continue, + Err(DataError::Io(error)) if cpg || error.kind() == io::ErrorKind::WouldBlock => { + return Ok(Some(Declaration { path, bytes: None, error: Some(error) })); + } + Err(DataError::Io(error)) => { + unusable.get_or_insert(Declaration { path, bytes: None, error: Some(error) }); + continue; + } + Err(error) => return Err(error), + }; + if cpg { + crate::provenance::opened(&path, &file); + } + let mut bytes = Vec::new(); + let declaration = match (&file).take(MAX_CODE_PAGE_BYTES as u64 + 1).read_to_end(&mut bytes) { + Ok(_) => Declaration { path, bytes: Some(bytes), error: None }, + Err(error) => Declaration { path, bytes: None, error: Some(error) }, + }; + if let Some(bytes) = declaration.bytes.as_deref().filter(|b| b.len() <= MAX_CODE_PAGE_BYTES) { + crate::provenance::buffer(&declaration.path, &file, bytes); } + return Ok(Some(declaration)); } + Ok(unusable) } -/// Every ASCII case of the extension, the conventional spellings first: tried in turn, -/// without scanning a potentially large directory, and the first there wins. -pub const CPG_SPELLINGS: [&str; 8] = ["cpg", "CPG", "Cpg", "cPg", "cpG", "CPg", "CpG", "cPG"]; -/// Every ASCII case of the `.cst` extension, in the order tried by the DBF reader. -pub const CST_SPELLINGS: [&str; 8] = ["cst", "CST", "Cst", "cSt", "csT", "CSt", "CsT", "cST"]; - -/// Reads at most one byte more than a label can hold, so oversized declarations stay unusable. -pub(crate) fn try_read_code_page(path: &std::path::Path, spellings: [&str; 8]) -> std::io::Result>> { - use std::io::Read; - for ext in spellings { - let part = path.with_extension(ext); - match crate::provenance::open(&part) { - Ok(file) => { - let mut bytes = Vec::new(); - (&file).take(MAX_CODE_PAGE_BYTES as u64 + 1).read_to_end(&mut bytes)?; - if bytes.len() <= MAX_CODE_PAGE_BYTES { - crate::provenance::buffer(&part, &file, &bytes); +/// A nonblocking regular-file open asks a lease holder to release its lease. Keep waiting +/// for a .cpg, as an ordinary open does. An optional .cst gets only a short grace period. +/// Each attempt uses the same safe open and checks Cancel before waiting again. +pub(crate) fn open_with_lease_retry(path: &Path, _cpg: bool) -> crate::Result> { + let first = open_declaration(path); + #[cfg(unix)] + { + use std::io::ErrorKind::WouldBlock; + use std::time::{Duration, Instant}; + if first.as_ref().is_err_and(|error| error.kind() == WouldBlock) { + let until = Instant::now() + Duration::from_millis(200); + loop { + crate::progress::check()?; + let wait = if _cpg { + Duration::from_millis(20) + } else { + until.saturating_duration_since(Instant::now()).min(Duration::from_millis(20)) + }; + if wait.is_zero() { + break; + } + std::thread::sleep(wait); + crate::progress::check()?; + let attempt = open_declaration(path); + if !attempt.as_ref().is_err_and(|error| error.kind() == WouldBlock) { + return Ok(attempt?); } - return Ok(Some(bytes)); } - Err(e) if e.kind() == std::io::ErrorKind::NotFound => {} - Err(e) => return Err(e), } } - Ok(None) + Ok(first?) +} + +/// Opens a regular declaration only. On Unix, nonblocking open and a descriptor check cover +/// a path swapped for a FIFO between the metadata check and the open. +fn open_declaration(path: &Path) -> std::io::Result> { + if !std::fs::metadata(path)?.is_file() { + return Ok(None); + } + #[cfg(unix)] + let file = { + use rustix::fs::{Mode, OFlags, open}; + std::fs::File::from(open(path, OFlags::RDONLY | OFlags::NONBLOCK | OFlags::CLOEXEC | OFlags::NOCTTY, Mode::empty())?) + }; + #[cfg(not(unix))] + let file = std::fs::File::open(path)?; + Ok(file.metadata()?.is_file().then_some(file)) } -/// Reads encoding sidecars beside a Shapefile or DBF. Only a missing or unusable .cpg needs -/// the fallback .cst. -pub(crate) fn read_sidecars(path: &std::path::Path, notes: &mut crate::loss::Notes) -> (Option>, Option>) { - let cpg = read_code_page(path, CPG_SPELLINGS, notes); - let cst = if sidecar_encoding(cpg.as_deref()).is_none() { read_code_page(path, CST_SPELLINGS, notes) } else { None }; - (cpg, cst) +/// Reads the same bounded declarations for decoding, sync and Publish. A usable .cpg +/// suppresses every lookup of a .cst. +pub(crate) fn read_sidecar_files(path: &Path) -> crate::Result<(Option, Option)> { + let cpg = read_declaration(declaration_paths(path).take(CPG_SPELLINGS.len()), true, true)?; + let cst = if sidecar_encoding(cpg.as_ref().map(Declaration::bytes)).is_none() { + read_declaration(declaration_paths(path).skip(CPG_SPELLINGS.len()), false, true)? + } else { + None + }; + Ok((cpg, cst)) +} + +/// A disk watch checks the small .cpg label without waiting for a lease to end. When the +/// .cpg does not apply, the .cst is only observed by metadata. +#[cfg(not(target_arch = "wasm32"))] +pub(crate) fn read_sidecar_files_now(path: &Path) -> crate::Result<(Option, Option)> { + let cpg = read_declaration(declaration_paths(path).take(CPG_SPELLINGS.len()), true, false)?; + let cst = if sidecar_encoding(cpg.as_ref().map(Declaration::bytes)).is_none() && !cpg.as_ref().is_some_and(Declaration::leased) { + declaration_paths(path) + .skip(CPG_SPELLINGS.len()) + .find(|p| std::fs::metadata(p).is_ok_and(|m| m.is_file())) + .map(|path| Declaration { path, bytes: None, error: None }) + } else { + None + }; + Ok((cpg, cst)) +} + +/// Like [`read_sidecar_files`] when only the contents are needed. +pub(crate) fn read_sidecars(path: &Path, notes: &mut crate::loss::Notes) -> crate::Result<(Option>, Option>)> { + let (cpg, cst) = read_sidecar_files(path)?; + if let Some(unreadable) = cpg.as_ref().filter(|declaration| declaration.bytes.is_none()) { + let reason = unreadable.error.as_ref().map_or_else(|| "not a regular file".to_string(), std::io::Error::to_string); + notes.push(format!("could not read the .cpg ({reason})")); + } + let bytes = |found: Declaration| found.bytes.unwrap_or_default(); + Ok((cpg.map(bytes), cst.map(bytes))) } #[cfg(test)] mod tests { use super::*; + fn not_utf8(dbf: &[u8], encoding: &DbfEncoding) -> (Vec, Vec) { + let (names, values, _) = text_notices(dbf, encoding, false); + (names, values) + } + /// A `.dbf` date is a day, blank or zeros are empty, and anything else isn't a date. #[test] fn dbf_dates() { @@ -633,7 +845,10 @@ mod tests { #[test] fn a_page_rustgis_cant_decode_is_named_in_the_note() { let mut notes = crate::loss::Notes::new(); - assert!(matches!(encoding(None, None, 0x6C, &mut notes), (DbfEncoding::Utf8, false))); + let choice = encoding(None, None, 0x6C, &mut notes); + assert!(matches!(choice.encoding, DbfEncoding::Utf8)); + #[cfg(not(target_arch = "wasm32"))] + assert!(choice.refusal.is_some()); assert_eq!( notes.texts().collect::>(), ["Shapefile: unsupported .dbf code page 0x6C (code page 863, DOS French Canadian); using UTF-8"] @@ -649,7 +864,7 @@ mod tests { /// and with a code page that can't be decoded; a code page that is decoded is named by it. #[test] fn utf8_is_what_text_is_read_as_unless_another_encoding_is_named() { - let read = |cpg: Option<&[u8]>, ldid| encoding(cpg, None, ldid, &mut crate::loss::Notes::new()).0.name(); + let read = |cpg: Option<&[u8]>, ldid| encoding(cpg, None, ldid, &mut crate::loss::Notes::new()).encoding.name(); for (cpg, ldid) in [(None, 0), (None, 0xF0), (Some(b"UTF-8".as_slice()), 0x03), (Some(b"65001".as_slice()), 0), (None, 0x6C)] { assert_eq!(read(cpg, ldid), "UTF-8"); } @@ -659,7 +874,7 @@ mod tests { assert_eq!(read(None, 0x4D), "GBK"); assert_eq!(read(None, 0x4E), "EUC-KR"); assert_eq!(read(Some(b"1252"), 0xF0), "windows-1252"); - assert_eq!(read(None, 0x01), "a DOS code page"); + assert_eq!(read(None, 0x01), "DOS 437"); } /// Bytes an encoding can't read are told by its own decoder: a lead byte with nothing after it, @@ -667,7 +882,7 @@ mod tests { /// aren't. A DOS page gives every byte a character. #[test] fn bytes_that_cant_be_read_are_those_the_declared_decoder_replaces() { - let page = |cpg: &[u8]| encoding(Some(cpg), None, 0, &mut crate::loss::Notes::new()).0; + let page = |cpg: &[u8]| encoding(Some(cpg), None, 0, &mut crate::loss::Notes::new()).encoding; let (sjis, big5, utf8) = (page(b"932"), page(b"950"), page(b"UTF-8")); assert!(sjis.malformed(b"X\x82") && sjis.malformed(b"\x82 ") && sjis.malformed(b"\xff")); assert!(!sjis.malformed(b"\x93\x8c\x8b\x9e") && !sjis.malformed(b"plain") && !sjis.malformed(b"")); diff --git a/crates/data/src/io.rs b/crates/data/src/io.rs index 3553109548..629df76e73 100644 --- a/crates/data/src/io.rs +++ b/crates/data/src/io.rs @@ -6,7 +6,7 @@ use std::path::Path; use serde::ser::{Serialize, SerializeMap, Serializer}; use serde_json::{Map, Value as Json, json}; -pub use crate::dbf::{CPG_SPELLINGS, CST_SPELLINGS}; +pub use crate::dbf::declaration_paths; use crate::capped::Limit; use crate::raster::{Crs, planetary}; @@ -523,7 +523,7 @@ pub fn read_path(path: &Path) -> Result<(Dataset, ReadReport)> { "dbf" => { check_size(path)?; let mut notes = crate::loss::Notes::new(); - let (cpg, cst) = crate::dbf::read_sidecars(path, &mut notes); + let (cpg, cst) = crate::dbf::read_sidecars(path, &mut notes)?; let (ds, mut report) = read_dbf(std::fs::read(path)?, cpg.as_deref(), cst.as_deref(), &name, &mut csv_memory_budget())?; report.messages.extend(notes.prefixed(&name)); (ds, report) @@ -3832,7 +3832,7 @@ 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 (cpg, cst) = crate::dbf::read_sidecars(path, &mut notes); + let (cpg, cst) = crate::dbf::read_sidecars(path, &mut notes)?; let parts = ShapefileParts { shp: crate::provenance::read(path)?, shx: if shx.is_file() { Some(crate::provenance::read(shx)?) } else { None }, @@ -3857,6 +3857,11 @@ const SHAPEFILE_SIDECARS: [&str; 5] = ["dbf", "shx", "prj", "cpg", "cst"]; /// Files whose parts are too large to read together (more than [`max_bytes`], or the zip /// reader's limit) are left out, with an explanation in the messages returned with the files. pub fn gather_shapefiles(files: Vec<(String, Vec)>) -> (Vec<(String, Vec)>, Vec) { + gather_shapefiles_within(files, u64::MAX) +} + +/// Leaves out a .cst if the resulting ZIP would exceed the caller's byte budget. +fn gather_shapefiles_within(files: Vec<(String, Vec)>, optional_budget: u64) -> (Vec<(String, Vec)>, Vec) { let ext_of = |n: &str| Path::new(n).extension().and_then(|e| e.to_str()).map(|e| e.to_ascii_lowercase()).unwrap_or_default(); let stem = |n: &str| Path::new(n).file_stem().and_then(|s| s.to_str()).unwrap_or("").to_ascii_lowercase(); let sidecar = |files: &[Option<(String, Vec)>], base: &str, ext: &str| { @@ -3901,18 +3906,27 @@ pub fn gather_shapefiles(files: Vec<(String, Vec)>) -> (Vec<(String, Vec } } // The zip must open again: within the read size and the zip reader's inflated total. - // Read once for the whole run: it reads what the computer has free (#2431). let max = max_bytes(); let limit = crate::zip::MAX_TOTAL.min(usize::try_from(max).unwrap_or(usize::MAX)); let (mut out, mut problems) = (Vec::new(), Vec::new()); for (file, parts) in files.into_iter().zip(zips) { out.extend(file); - let Some(parts) = parts else { + let Some(mut parts) = parts else { continue; }; + let usable_cpg = parts.iter().any(|(n, b)| ext_of(n) == "cpg" && shapefile_cpg_is_usable(b)); + parts.retain_mut(|(n, b)| { + if ext_of(n) != "cst" { + return true; + } + if b.len() > crate::dbf::MAX_CODE_PAGE_BYTES { + *b = Vec::new(); + } + !usable_cpg + }); let shp = parts.first().map(|(n, _)| n.clone()).unwrap_or_else(|| "layer.shp".into()); let zip_name = format!("{}.zip", Path::new(&shp).file_stem().and_then(|s| s.to_str()).unwrap_or("layer")); - let total = parts.iter().fold(0usize, |sum, (_, b)| sum.saturating_add(b.len())); + let total = parts.iter().filter(|(n, _)| ext_of(n) != "cst").fold(0usize, |sum, (_, b)| sum.saturating_add(b.len())); // Said by the limit it passed: the size read into memory (which follows the computer's // memory), or the most a zip expands to. if total as u64 > max { @@ -3927,7 +3941,12 @@ pub fn gather_shapefiles(files: Vec<(String, Vec)>) -> (Vec<(String, Vec )); continue; } - match crate::zip::write(&parts) { + let zip = if parts.last().is_some_and(|(n, _)| ext_of(n) == "cst") { + crate::zip::write_with_optional_tail(&parts, usize::try_from(max.min(optional_budget)).unwrap_or(usize::MAX)) + } else { + crate::zip::write(&parts) + }; + match zip { Ok(zip) if zip.len() as u64 <= max => out.push((zip_name, zip)), Ok(zip) => problems.push(format!("{shp}: zipped together: {}", too_large_said(zip.len() as u64, max))), Err(e) => problems.push(format!("{shp}: its data files couldn't be zipped together: {e}")), @@ -3961,6 +3980,9 @@ pub fn shapefile_part_urls(url: &str) -> Option> { ) } +/// Largest optional code-page download, including a byte to detect an oversized label. +pub const SHAPEFILE_CODE_PAGE_LIMIT: usize = crate::dbf::MAX_CODE_PAGE_BYTES + 1; + /// Whether a downloaded .cpg is enough to select a decoder without fetching a .cst. pub fn shapefile_cpg_is_usable(bytes: &[u8]) -> bool { crate::dbf::sidecar_encoding(Some(bytes)).is_some() @@ -3970,13 +3992,23 @@ pub fn shapefile_cpg_is_usable(bytes: &[u8]) -> bool { /// the `.shp` named `file_name`, and the parts that answered, by extension. An error when the /// `.dbf` isn't among them or they are too large to read together. pub fn zip_shapefile_parts(file_name: &str, shp: Vec, parts: Vec<(&str, Vec)>) -> std::result::Result, String> { + zip_shapefile_parts_for_download(file_name, shp, parts, usize::MAX) +} + +/// Packages the downloaded files, leaving out .cst if it would put the ZIP over the download budget. +pub fn zip_shapefile_parts_for_download( + file_name: &str, + shp: Vec, + parts: Vec<(&str, Vec)>, + max: usize, +) -> std::result::Result, String> { let stem = Path::new(file_name).file_stem().and_then(|s| s.to_str()).filter(|s| !s.is_empty()).unwrap_or("layer"); if !parts.iter().any(|(e, _)| e.eq_ignore_ascii_case("dbf")) { return Err(format!("{stem}.shp: its .dbf isn't beside it")); } let mut files = vec![(format!("{stem}.shp"), shp)]; files.extend(parts.into_iter().map(|(e, b)| (format!("{stem}.{}", e.to_ascii_lowercase()), b))); - let (out, problems) = gather_shapefiles(files); + let (out, problems) = gather_shapefiles_within(files, max as u64); out.into_iter() .find(|(n, _)| n.ends_with(".zip")) .map(|(_, b)| b) @@ -3995,19 +4027,27 @@ fn is_resource_fork(name: &str) -> bool { /// [`MAX_ZIP_LAYERS`] in name order (the reader counts those it reads, so past a damaged one it /// reads one more than these). Empty for bytes that aren't a zip. pub fn shapefile_zip_lacks(bytes: &[u8]) -> Vec<(String, Vec<&'static str>)> { - // The entries' names only: `want` sees each, and none is inflated. - let names = std::cell::RefCell::new(Vec::new()); - if crate::zip::read_matching(bytes, |n| { - if !is_resource_fork(n) { - names.borrow_mut().push(n.to_string()); - } - false - }) + // Read the names, saving only the .cpg headers for a bounded usability check. + let mut names = Vec::new(); + let mut pages = std::collections::BTreeMap::new(); + if crate::zip::read_deferring( + bytes, + |_| false, + |n, member| { + if !is_resource_fork(n) { + names.push(n.to_string()); + let lower = n.to_ascii_lowercase(); + if lower.ends_with(".cpg") { + pages.entry(lower).or_insert(member); + } + } + true + }, + ) .is_err() { return Vec::new(); } - let names = names.into_inner(); // A set: a served zip may hold up to 65,535 entries. let lower: std::collections::HashSet = names.iter().map(|n| n.to_ascii_lowercase()).collect(); // The Shapefiles the reader takes: in name order, with their `.dbf`, as many as it reads. @@ -4021,10 +4061,17 @@ pub fn shapefile_zip_lacks(bytes: &[u8]) -> Vec<(String, Vec<&'static str>)> { shps.into_iter() .take(MAX_ZIP_LAYERS) .filter_map(|(n, s)| { - let lacks: Vec<&'static str> = ["shx", "prj", "cpg"] - .into_iter() - .filter(|e| !lower.contains(&format!("{s}.{e}")) && (*e != "cpg" || !lower.contains(&format!("{s}.cst")))) - .collect(); + let mut lacks: Vec<&'static str> = ["shx", "prj"].into_iter().filter(|e| !lower.contains(&format!("{s}.{e}"))).collect(); + if !lower.contains(&format!("{s}.cst")) { + let cpg = format!("{s}.cpg"); + match pages.get(&cpg) { + None => lacks.push("cpg"), + Some(page) if !page.read_small(bytes, &cpg, SHAPEFILE_CODE_PAGE_LIMIT).is_ok_and(|b| shapefile_cpg_is_usable(&b)) => { + lacks.push("cst"); + } + Some(_) => {} + } + } (!lacks.is_empty()).then(|| (n.clone(), lacks)) }) .collect() @@ -4123,14 +4170,30 @@ fn read_zip_layers_budget(file_name: &str, bytes: &[u8], opts: &CsvOptions, budg } let e = ext_of(n); !is_resource_fork(n) - && (matches!(e.as_str(), "shp" | "shx" | "dbf" | "prj" | "cpg" | "cst" | "mid") + && (matches!(e.as_str(), "shp" | "shx" | "dbf" | "prj" | "cpg" | "mid") || (e == "pbf" && lower(n).ends_with(".osm.pbf")) || (!matches!(e.as_str(), "zip" | "pbf") && READ_EXTENSIONS.contains(&e.as_str()))) }; - let entries = crate::zip::read_matching(bytes, wanted).map_err(|e| DataError::Format(format!("{file_name}: {e}")))?; - crate::progress::check()?; // Sidecar files by their path without the extension, compared without regard to case. let stem = |n: &str| lower(n.get(..n.len().saturating_sub(ext_of(n).len() + 1)).unwrap_or(n)); + let mut declarations = std::collections::BTreeMap::new(); + let entries = crate::zip::read_deferring(bytes, wanted, |name, member| { + if ext_of(name) != "cst" || is_resource_fork(name) { + return false; + } + declarations.entry(stem(name)).or_insert_with(|| (name.to_owned(), member)); + true + }) + .map_err(|e| DataError::Format(format!("{file_name}: {e}")))?; + crate::progress::check()?; + let mut fallback = |base: &str, cpg: Option<&[u8]>| { + if shapefile_cpg_is_usable(cpg.unwrap_or_default()) { + return None; + } + let (name, member) = declarations.remove(base)?; + // A broken declaration is equivalent to an empty one for selection and its notice. + Some(member.read_small(bytes, &name, SHAPEFILE_CODE_PAGE_LIMIT).unwrap_or_default()) + }; // Entries are taken out as they're used, so no file's bytes are copied. let mut entries: Vec)>> = entries.into_iter().map(Some).collect(); let mut shps: Vec = entries.iter().flatten().filter(|(n, _)| ext_of(n) == "shp").map(|(n, _)| n.clone()).collect(); @@ -4157,11 +4220,11 @@ fn read_zip_layers_budget(file_name: &str, bytes: &[u8], opts: &CsvOptions, budg let shx = take(&mut entries, &base, "shx").map(|(_, b)| b); let prj = take(&mut entries, &base, "prj").map(|(_, b)| String::from_utf8_lossy(&b).into_owned()); let cpg = take(&mut entries, &base, "cpg").map(|(_, b)| b); - let cst = take(&mut entries, &base, "cst").map(|(_, b)| b); let Some((_, dbf)) = take(&mut entries, &base, "dbf") else { skipped.push(format!("{n} (no .dbf beside it)")); continue; }; + let cst = fallback(&base, cpg.as_deref()); match read_shapefile_parts(ShapefileParts { shp, shx, dbf, prj, cpg, cst }, &name, crs) { Ok((mut dataset, report)) => { dataset.source = Some(format!("{file_name}/{n}")); @@ -4229,7 +4292,7 @@ fn read_zip_layers_budget(file_name: &str, bytes: &[u8], opts: &CsvOptions, budg // A city model has many layers. let read = if ext_of(&n) == "dbf" { let cpg = take(&mut entries, &stem(&n), "cpg").map(|(_, b)| b); - let cst = take(&mut entries, &stem(&n), "cst").map(|(_, b)| b); + let cst = fallback(&stem(&n), cpg.as_deref()); let name = Path::new(leaf).file_stem().and_then(|s| s.to_str()).unwrap_or("table"); read_dbf(b, cpg.as_deref(), cst.as_deref(), name, budget).map(|r| plain(vec![r])) } else if is_city_model(leaf, &b) { @@ -4421,11 +4484,12 @@ struct DbfRead { /// `name` is the layer's, for the error of a `.dbf` it can't open. fn dbf_reader(mut bytes: Vec, cpg: Option<&[u8]>, cst: Option<&[u8]>, name: &str) -> Result { use std::io::Cursor; - let mut declared = crate::loss::Notes::new(); - let (encoding, _) = crate::dbf::encoding(cpg, cst, bytes.get(29).copied().unwrap_or(0), &mut declared); - let mut encoding_notes = declared; + let mut encoding_notes = crate::loss::Notes::new(); + let choice = crate::dbf::encoding(cpg, cst, bytes.get(29).copied().unwrap_or(0), &mut encoding_notes); + let encoding = choice.encoding; // Counted before a date column is marked a character one below: its values aren't text. - let (names, not_utf8) = crate::dbf::not_utf8(&bytes, &encoding); + let (names, not_utf8, suspicious) = crate::dbf::text_notices(&bytes, &encoding, choice.check_utf8); + encoding_notes.extend(suspicious); encoding_notes.extend(crate::dbf::not_utf8_names_note(&names, encoding.name())); let deleted = crate::dbf::take_deleted(&mut bytes); crate::dbf::readable_header_date(&mut bytes); @@ -10479,27 +10543,24 @@ mod tests { let lacks = |z: &[u8]| shapefile_zip_lacks(z).into_iter().map(|(n, e)| format!("{n}: {}", e.join(" "))).collect::>(); assert_eq!(lacks(&zip_shapefile_parts("RIOS_SIMPLES.shp", shp.clone(), no_prj).unwrap()), ["RIOS_SIMPLES.shp: prj cpg"]); assert!(shapefile_zip_lacks(&shp).is_empty(), "not a zip"); + let entry = |n: &str| (n.to_string(), if n.ends_with(".cpg") { b"UTF-8".to_vec() } else { shp.clone() }); // Another file's .prj isn't this one's. - let mixed: Vec<(String, Vec)> = - [("roads.shp", &shp), ("roads.dbf", &shp), ("roads.shx", &shp), ("roads.cpg", &shp), ("other.prj", &shp)] - .map(|(n, b)| (n.to_string(), b.clone())) - .into(); + let mixed = ["roads.shp", "roads.dbf", "roads.shx", "roads.cpg", "other.prj"].map(entry); assert_eq!(lacks(&crate::zip::write(&mixed).unwrap()), ["roads.shp: prj"]); // A stray .shp without its .dbf, and a macOS resource fork, aren't read, so they lack nothing. let mut whole: Vec<(String, Vec)> = - ["roads.shp", "roads.dbf", "roads.shx", "roads.prj", "roads.cpg", "stray.shp", "__MACOSX/._roads.shp"] - .map(|n| (n.to_string(), shp.clone())) - .into(); + ["roads.shp", "roads.dbf", "roads.shx", "roads.prj", "roads.cpg", "stray.shp", "__MACOSX/._roads.shp"].map(entry).into(); assert!(shapefile_zip_lacks(&crate::zip::write(&whole).unwrap()).is_empty()); whole.retain(|(n, _)| n != "roads.prj"); assert_eq!(lacks(&crate::zip::write(&whole).unwrap()), ["roads.shp: prj"]); + whole.iter_mut().find(|(n, _)| n == "roads.cpg").unwrap().1 = b"invalid code page".to_vec(); + assert_eq!(lacks(&crate::zip::write(&whole).unwrap()), ["roads.shp: prj cst"]); // Each Shapefile for itself: one with its .prj, one without. - let two: Vec<(String, Vec)> = - ["a.shp", "a.dbf", "a.shx", "a.prj", "a.cpg", "b.shp", "b.dbf", "b.shx", "b.cpg"].map(|n| (n.to_string(), shp.clone())).into(); + let two = ["a.shp", "a.dbf", "a.shx", "a.prj", "a.cpg", "b.shp", "b.dbf", "b.shx", "b.cpg"].map(entry); assert_eq!(lacks(&crate::zip::write(&two).unwrap()), ["b.shp: prj"]); // As many as the reader reads: of 40 without a .prj, the first 32 by name. let many: Vec<(String, Vec)> = - (0..40).flat_map(|i| ["shp", "dbf", "shx", "cpg"].map(|e| (format!("s{i:02}.{e}"), shp.clone()))).collect(); + (0..40).flat_map(|i| ["shp", "dbf", "shx", "cpg"].map(|e| entry(&format!("s{i:02}.{e}")))).collect(); let said = shapefile_zip_lacks(&crate::zip::write(&many).unwrap()); assert_eq!((said.len(), said[0].0.as_str(), said[31].0.as_str()), (MAX_ZIP_LAYERS, "s00.shp", "s31.shp")); let no_dbf: Vec<_> = others.into_iter().filter(|(e, _)| *e != "dbf").collect(); diff --git a/crates/data/src/provenance.rs b/crates/data/src/provenance.rs index 535372aafd..ccc1390dec 100644 --- a/crates/data/src/provenance.rs +++ b/crates/data/src/provenance.rs @@ -357,13 +357,18 @@ pub(crate) fn hashed(path: &Path, metadata: Option<&Metadata>, sha256: String) { pub fn open(path: impl AsRef) -> std::io::Result { let path = path.as_ref(); let file = File::open(path)?; + opened(path, &file); + Ok(file) +} + +/// Records an open whose caller needed different flags from the default. +pub(crate) fn opened(path: &Path, file: &File) { if active() { let metadata = file.metadata().ok(); if metadata.as_ref().is_none_or(Metadata::is_file) { observe(path, metadata.as_ref(), None); } } - Ok(file) } /// Reads once; a cheap digest uses those bytes, never a second file read. diff --git a/crates/data/src/publish.rs b/crates/data/src/publish.rs index 5e995940e2..72eca6f153 100644 --- a/crates/data/src/publish.rs +++ b/crates/data/src/publish.rs @@ -173,19 +173,21 @@ impl Original { let dbf = read(&dbf_path)?.ok_or_else(|| missing("dbf"))?; let shx = read(&path.with_extension("shx"))?; let prj = read(&path.with_extension("prj"))?; - let mut cpg = None; - for ext in crate::dbf::CPG_SPELLINGS { - let p = path.with_extension(ext); - if let Some(bytes) = read(&p)? { - cpg = Some((p, bytes)); - break; - } - } - let cst = if crate::dbf::sidecar_encoding(cpg.as_ref().map(|(_, b)| b.as_slice())).is_none() { - crate::dbf::try_read_code_page(path, crate::dbf::CST_SPELLINGS)? - } else { - None - }; + let (cpg, cst) = crate::dbf::read_sidecar_files(path)?; + let cpg = cpg + .map(|d| match d.error { + Some(e) => Err(DataError::Io(e)), + None => { + let bytes = d.bytes.unwrap_or_default(); + let max = crate::io::max_bytes(); + if bytes.len() > crate::dbf::MAX_CODE_PAGE_BYTES && std::fs::metadata(&d.path)?.len() > max { + return Err(DataError::Format(crate::io::shapefile_size_error(&d.path.to_string_lossy(), max))); + } + Ok((d.path, bytes)) + } + }) + .transpose()?; + let cst = cst.map(|d| d.bytes.unwrap_or_default()); Ok(Original { shp, shx, dbf, dbf_path, prj, cpg, cst }) } @@ -223,10 +225,14 @@ pub fn shapefile(ds: &Dataset, path: &Path, synced: &Synced) -> Result Result<()> { refuse_link(path, path)?; - for ext in ["shx", "dbf", "prj"].into_iter().chain(crate::dbf::CPG_SPELLINGS).chain(crate::dbf::CST_SPELLINGS) { + for ext in ["shx", "dbf", "prj"] { refuse_link(path, &path.with_extension(ext))?; } refuse_link(path, &crate::io::dbf_sidecar(path))?; + for declaration in crate::dbf::declaration_paths(path).filter(|p| p.extension().is_some_and(|ext| ext.eq_ignore_ascii_case("cpg"))) + { + refuse_link(path, &declaration)?; + } let changed = synced.files.changed(path)?; if changed.is_empty() { return Ok(()); @@ -250,14 +256,22 @@ pub fn shapefile(ds: &Dataset, path: &Path, synced: &Synced) -> Result mkfifoat(CWD, &cpg, Mode::RUSR | Mode::WUSR).unwrap(), + "socket" => drop(std::os::unix::net::UnixListener::bind(&cpg).unwrap()), + _ => std::os::unix::fs::symlink("/dev/zero", &cpg).unwrap(), + } + let (_, report) = crate::io::read_path(&path).unwrap(); + assert!(report.messages.iter().any(|m| m.contains("code page taken from the .cst")), "{:?}", report.messages); + crate::source::open_path(&path, None).unwrap(); + crate::io::read_path(&path.with_extension("dbf")).unwrap(); + let (mut ds, sync) = read(&path); + ds.features.set_value(0, 0, Value::Text("Café".into())).unwrap(); + let before = std::fs::read(path.with_extension("dbf")).unwrap(); + let e = shapefile(&ds, &path, &sync).err().expect("an unusable .cpg must prevent Publish").to_string(); + assert!( + e.contains("nothing was written") && (e.contains(".cpg is unsupported or empty") || e.contains("symbolic link")), + "{e}" + ); + assert_eq!(std::fs::read(path.with_extension("dbf")).unwrap(), before); + std::fs::remove_file(cpg).unwrap(); + } + send.send(()).unwrap(); + }) + .unwrap(); + // test-wait: the previous .cpg open could block on a pipe. + recv.recv_timeout(std::time::Duration::from_secs(5)).unwrap(); + worker.join().unwrap(); + } + /// An unusable .cpg continues to prevent publishing, even with a usable .cst and any LDID. + #[test] + fn cst_does_not_make_an_unusable_cpg_writable() { + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("parcels.shp"); + crate::io::write_path(&parcels(), &path).unwrap(); + let dbf_path = path.with_extension("dbf"); + let mut dbf = std::fs::read(&dbf_path).unwrap(); + std::fs::write(path.with_extension("cst"), "ISO-8859-1").unwrap(); + + for cpg in ["BIG5-UAO", "", "cp863"] { + std::fs::write(path.with_extension("cpg"), cpg).unwrap(); + for ldid in [0, 0x57, 0x6c] { + dbf[29] = ldid; + std::fs::write(&dbf_path, &dbf).unwrap(); + let (mut ds, sync) = read(&path); + ds.features.set_value(0, 0, Value::Text("Café".into())).unwrap(); + let error = shapefile(&ds, &path, &sync).err().expect("Publish must refuse an unusable .cpg"); + assert!(error.to_string().contains(".cpg is unsupported or empty"), "{error}"); + assert_eq!(std::fs::read(&dbf_path).unwrap(), dbf); + } + } + } + + /// Two resolving, disagreeing LDIDs are loss notices and refuse Publish. A usable .cpg + /// has priority, and an equivalent LDID preserves the informational .cst notice. + #[test] + fn cst_disagreements_are_reported_and_refuse_publish() { + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("parcels.shp"); + crate::io::write_path(&parcels(), &path).unwrap(); + let cpg = path.with_extension("cpg"); + std::fs::remove_file(&cpg).unwrap(); + let cst = path.with_extension("cst"); + std::fs::write(&cst, "ISO-8859-1").unwrap(); + let dbf_path = path.with_extension("dbf"); + let mut dbf = std::fs::read(&dbf_path).unwrap(); + for (ldid, other) in [(0xF0, "UTF-8"), (0xC9, "windows-1251"), (0x57, "windows-1252")] { + dbf[29] = ldid; + std::fs::write(&dbf_path, &dbf).unwrap(); + let (_, whole) = crate::io::read_path(&path).unwrap(); + let source = crate::source::open_path(&path, None).unwrap(); + let (_, streamed) = crate::source::materialize(source.as_ref()).unwrap(); + for notes in [whole.messages, streamed.messages] { + let declaration = notes.iter().find(|m| m.contains("code page taken from the .cst")).unwrap(); + assert!(declaration.contains("ISO-8859-1") && declaration.contains("windows-1252"), "{}", declaration.as_str()); + if ldid == 0x57 { + assert_eq!(declaration.loss, None); + } else { + assert_eq!(declaration.loss, Some(crate::loss::LossCode::ChangedEncoding)); + assert!(declaration.contains("1 encoding conflict") && declaration.contains(other), "{}", declaration.as_str()); + } + } + if ldid != 0x57 { + let (mut ds, sync) = read(&path); + ds.features.set_value(0, 0, Value::Text("Café".into())).unwrap(); + let error = shapefile(&ds, &path, &sync).err().expect("Publish must refuse a conflicting LDID"); + assert!(error.to_string().contains(other), "{error}"); + } + } std::fs::write(&cpg, "UTF-8").unwrap(); let (_, report) = crate::io::read_path(&path).unwrap(); - assert!(invalid_text(&report.messages), "{:?}", report.messages); assert!(!report.messages.iter().any(|m| m.contains("code page taken from the .cst")), "{:?}", report.messages); + } - std::fs::remove_file(&cpg).unwrap(); - std::fs::write(&cst, "UTF-8").unwrap(); - let (_, report) = crate::io::read_path(&path).unwrap(); - assert!(report.messages.iter().any(|m| m.loss.is_none() && m.contains("code page taken from the .cst")), "{:?}", report.messages); - assert!(invalid_text(&report.messages), "{:?}", report.messages); + /// Older writers could leave valid non-ASCII UTF-8 bytes beside a single-byte .cst. + #[test] + fn cst_warns_when_all_inspected_text_is_utf8() { + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("parcels.shp"); + crate::io::write_path(&parcels(), &path).unwrap(); + std::fs::remove_file(path.with_extension("cpg")).unwrap(); + std::fs::write(path.with_extension("cst"), "ISO-8859-1").unwrap(); + let dbf_path = path.with_extension("dbf"); + let mut dbf = std::fs::read(&dbf_path).unwrap(); + dbf[29] = 0; + let owner = dbf.windows(5).position(|b| b == b"Smith").unwrap(); + for (text, suspicious) in [(b"Caf\xc3\xa9", true), (b"Mu\xf1oz", false)] { + dbf[owner..owner + 5].copy_from_slice(text); + std::fs::write(&dbf_path, &dbf).unwrap(); + let (_, whole) = crate::io::read_path(&path).unwrap(); + let source = crate::source::open_path(&path, None).unwrap(); + let (_, streamed) = crate::source::materialize(source.as_ref()).unwrap(); + for messages in [whole.messages, streamed.messages] { + let notes: Vec<_> = messages.iter().filter(|m| m.contains("all text inspected is valid UTF-8")).collect(); + assert_eq!(notes.len(), usize::from(suspicious), "{messages:?}"); + if suspicious { + assert!(notes[0].contains("1 non-ASCII") && notes[0].loss == Some(crate::loss::LossCode::ChangedEncoding)); + } + } + let (mut ds, sync) = read(&path); + ds.features.set_value(0, 0, Value::Text("Café".into())).unwrap(); + if suspicious { + let error = shapefile(&ds, &path, &sync).err().expect("Publish must refuse suspicious UTF-8"); + assert!(error.to_string().contains("all text inspected is valid UTF-8"), "{error}"); + } else { + shapefile(&ds, &path, &sync).unwrap(); + } + } + } + + /// Corrupt or oversized ZIP declarations trigger fallback in their own layer only. + #[test] + fn bad_zip_cst_is_optional_and_its_members_are_read_per_stem() { + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("parcels.shp"); + crate::io::write_path(&parcels(), &path).unwrap(); + let mut files = Vec::new(); + for stem in ["a", "b"] { + for ext in ["shp", "shx", "dbf", "prj"] { + files.push((format!("{stem}.{ext}"), std::fs::read(path.with_extension(ext)).unwrap())); + } + } + files.push(("b.cpg".into(), b"UTF-8".to_vec())); + files.push(("b.cst".into(), b"ISO-8859-1".to_vec())); + for corruption in ["encrypted", "checksum", "compression", "oversized"] { + let label = if corruption == "oversized" { vec![b'X'; crate::dbf::MAX_CODE_PAGE_BYTES + 2] } else { b"ISO-8859-1".to_vec() }; + files.push(("a.cst".into(), label)); + let mut zip = crate::zip::write(&files).unwrap(); + files.pop(); + let mut at = u32::from_le_bytes(zip[zip.len() - 6..zip.len() - 2].try_into().unwrap()) as usize; + for _ in &files { + if &zip[at + 46..at + 51] == b"b.cst" { + // The .cpg makes even an encrypted .cst irrelevant to this member. + zip[at + 8] |= 1; + } + at += 46 + u16::from_le_bytes(zip[at + 28..at + 30].try_into().unwrap()) as usize; + } + assert_eq!(&zip[at + 46..at + 51], b"a.cst"); + match corruption { + "encrypted" => zip[at + 8] |= 1, + "checksum" => zip[at + 16] ^= 1, + "compression" => zip[at + 10] = 12, + _ => {} + } + let layers = crate::io::read_zip("parts.zip", &zip).unwrap(); + assert_eq!(layers.len(), 2); + assert_eq!(layers[0].1.messages.iter().filter(|m| m.contains("unsupported or empty .cst")).count(), 1, "{corruption}"); + assert!(!layers[1].1.messages.iter().any(|m| m.contains(".cst")), "{corruption}"); + } } /// What a read loses is refused before the edits are: text a read trims, a feature without a diff --git a/crates/data/src/source/shp.rs b/crates/data/src/source/shp.rs index e6e9e85668..7a67dbdac6 100644 --- a/crates/data/src/source/shp.rs +++ b/crates/data/src/source/shp.rs @@ -69,6 +69,7 @@ pub struct ShpSource { index: index::Index, table: Table, encoding: crate::dbf::DbfEncoding, + utf8_evidence: Option, reproject: Reproject, /// Whether every record's stored box holds its shape, as reads by area take the boxes on /// trust: [`BOXES_UNKNOWN`] until a whole read has looked, then [`BOXES_HOLD`] or @@ -146,8 +147,10 @@ impl ShpSource { let stamps = [Stamp::of(path), Stamp::of(&dbf)]; let mut notes = crate::loss::Notes::new(); let table = read_table(&dbf)?; - let (cpg, cst) = crate::dbf::read_sidecars(path, &mut notes); - let (encoding, _) = crate::dbf::encoding(cpg.as_deref(), cst.as_deref(), table.ldid, &mut notes); + let (cpg, cst) = crate::dbf::read_sidecars(path, &mut notes)?; + let choice = crate::dbf::encoding(cpg.as_deref(), cst.as_deref(), table.ldid, &mut notes); + let encoding = choice.encoding; + let mut utf8_evidence = choice.check_utf8.then(crate::dbf::Utf8Evidence::default); let shp_len = std::fs::metadata(path)?.len(); if shp_len > u64::from(u32::MAX) { return Err(bad("the .shp is larger than the format's 4 GB")); @@ -243,7 +246,7 @@ impl ShpSource { crate::loss::Note::loss(crate::loss::LossCode::AssumedCrs, text) }); } - let (names, not_utf8) = read_names(&dbf, table.columns.len(), &encoding)?; + let (names, not_utf8) = read_names(&dbf, table.columns.len(), &encoding, utf8_evidence.as_mut())?; notes.extend(crate::dbf::not_utf8_names_note(¬_utf8, encoding.name())); let fields = table.columns.iter().zip(names).map(|(c, n)| Field::new(n, c.out)).collect(); let mut info = SourceInfo { @@ -266,7 +269,7 @@ impl ShpSource { } // Points too: each record's own type is read, whatever the header says. let boxes = AtomicU8::new(BOXES_UNKNOWN); - Ok(ShpSource { info, shp: path.to_path_buf(), dbf, index, table, encoding, reproject, boxes, stamps }) + Ok(ShpSource { info, shp: path.to_path_buf(), dbf, index, table, encoding, utf8_evidence, reproject, boxes, stamps }) } } @@ -327,6 +330,7 @@ impl ShpSource { let mut row = vec![0u8; self.table.row_len]; let (mut skipped, mut unread_dates, mut null_text, mut boxed_off, mut not_utf8) = (0, Vec::new(), Vec::new(), 0u64, Vec::new()); let mut nonfinite = Vec::new(); + let mut utf8_evidence = self.utf8_evidence; let mut deleted = 0usize; // Shapes whose coordinates aren't numbers given without geometry, and of them those under // a box the index takes. @@ -400,6 +404,9 @@ impl ShpSource { deleted += 1; return Ok(()); } + if let Some(evidence) = &mut utf8_evidence { + self.table.observe_text(&row, evidence); + } self.table.values(&row, &encoding, &self.encoding, &mut unread_dates, &mut null_text, &mut not_utf8, &mut nonfinite) } else { vec![Value::Null; self.table.columns.len()] @@ -429,6 +436,7 @@ impl ShpSource { .chain(kept_no_number_note(kept_no_number, kept_boxed, false)) .chain(deleted_note(deleted, false).map(crate::loss::Note::from)) .chain(nonfinite_note(&self.info.fields, &nonfinite, false)) + .chain(utf8_evidence.and_then(|evidence| evidence.notice(&self.encoding))) .collect(), not_utf8, }) @@ -475,6 +483,7 @@ impl FeatureSource for ShpSource { let mut features = Vec::new(); let (mut skipped, mut unread_dates, mut null_text, mut boxed_off, mut not_utf8) = (0, Vec::new(), Vec::new(), 0u64, Vec::new()); let mut nonfinite = Vec::new(); + let mut utf8_evidence = self.utf8_evidence; let mut deleted = 0usize; // Shapes whose coordinates aren't numbers given without geometry, and of them those under // a box the index takes. @@ -546,6 +555,9 @@ impl FeatureSource for ShpSource { if late && !sample.wants() { return Ok(()); } + if let Some(evidence) = &mut utf8_evidence { + self.table.observe_text(&row, evidence); + } self.table.values(&row, &encoding, &self.encoding, &mut unread_dates, &mut null_text, &mut not_utf8, &mut nonfinite) } else { if late && !sample.wants() { @@ -590,6 +602,7 @@ impl FeatureSource for ShpSource { // The values a late read decodes are of the records its sample keeps (geometry checks // aside), so its count is of a sample whenever the sample isn't the whole layer. .chain(nonfinite_note(&self.info.fields, &nonfinite, !complete)) + .chain(utf8_evidence.and_then(|evidence| evidence.notice(&self.encoding))) .collect(), not_utf8, }) @@ -929,6 +942,13 @@ fn read_table(path: &Path) -> Result { } impl Table { + /// Checks only text cells of the current row; an in-place read never scans extra records. + fn observe_text(&self, row: &[u8], evidence: &mut crate::dbf::Utf8Evidence) { + for c in self.columns.iter().filter(|c| c.ty == b'C') { + evidence.observe(padded(row.get(1 + c.offset..1 + c.offset + c.len).unwrap_or_default())); + } + } + /// A row's values (after its deletion flag), counting in `unread_dates` the dates that /// aren't ones ([`Batch::unread_dates`]), in `null_text` the text `` read as null /// ([`Batch::null_text`]) and in `not_utf8` the text that isn't valid in `declared`, the @@ -980,7 +1000,12 @@ impl Table { /// The `.dbf`'s column names, in order (read again: the layout above keeps only offsets), and the /// columns (from 1) whose names aren't valid in its `encoding` ([`crate::dbf::not_utf8_names_note`]). -fn read_names(path: &Path, n: usize, encoding: &crate::dbf::DbfEncoding) -> Result<(Vec, Vec)> { +fn read_names( + path: &Path, + n: usize, + encoding: &crate::dbf::DbfEncoding, + mut evidence: Option<&mut crate::dbf::Utf8Evidence>, +) -> Result<(Vec, Vec)> { let decoder = encoding.decoder(); let mut f = BufReader::new(crate::provenance::open(path)?); f.seek(SeekFrom::Start(32))?; @@ -992,6 +1017,9 @@ fn read_names(path: &Path, n: usize, encoding: &crate::dbf::DbfEncoding) -> Resu let name = d.get(..11).unwrap_or(&[]); let end = name.iter().position(|b| *b == 0).unwrap_or(name.len()); let name = name.get(..end).unwrap_or(&[]); + if let Some(evidence) = &mut evidence { + evidence.observe(name); + } if encoding.malformed(name) { not_utf8.push(out.len() + 1); } diff --git a/crates/data/src/sync.rs b/crates/data/src/sync.rs index 8067326ba5..a2a63c3702 100644 --- a/crates/data/src/sync.rs +++ b/crates/data/src/sync.rs @@ -5,8 +5,8 @@ use serde::{Deserialize, Serialize}; /// The files of a source as they were at a moment: each one's name, size and SHA-256 hash, and -/// the files that weren't there. A Shapefile is its `.shp`, `.shx`, `.dbf`, `.prj`, `.cpg` and `.cst` -/// (the ones its reader opens); a GeoJSON file is itself. Only the contents count: a file +/// the files that weren't there. A Shapefile includes its `.shp`, `.shx`, `.dbf`, `.prj`, and its +/// active code-page declarations (a usable `.cpg` makes `.cst` irrelevant); a GeoJSON file is itself. Only the contents count: a file /// copied, touched or moved to another disk with the same bytes is the same file. #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] pub struct FileSync { @@ -177,23 +177,113 @@ mod native { use crate::{DataError, Result}; use std::path::{Path, PathBuf}; - /// The files of the source at `path`, each as a name beside it and its path: for a - /// Shapefile the companions its reader opens (the `.cpg` in whichever case is there, else - /// `.cpg`, plus its `.cst` when present), otherwise the file alone. + /// The regular source parts, excluding declarations whose contents and sizes are bounded. fn parts(path: &Path) -> Vec<(String, PathBuf)> { let mut paths = vec![path.to_path_buf()]; - if path.extension().and_then(|e| e.to_str()).is_some_and(|e| e.eq_ignore_ascii_case("shp")) { - // The table in whichever case the reader finds it. + if has_extension(path, "shp") { paths.extend([path.with_extension("shx"), crate::io::dbf_sidecar(path), path.with_extension("prj")]); - let cpg = crate::dbf::CPG_SPELLINGS - .iter() - .map(|e| path.with_extension(e)) - .find(|p| p.is_file()) - .unwrap_or_else(|| path.with_extension("cpg")); - paths.push(cpg); - paths.extend(crate::dbf::CST_SPELLINGS.into_iter().map(|e| path.with_extension(e)).find(|p| p.is_file())); } - paths.into_iter().map(|p| (p.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default(), p)).collect() + paths.into_iter().map(|p| (name(&p), p)).collect() + } + + fn name(path: &Path) -> String { + path.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default() + } + + fn has_extension(path: &Path, ext: &str) -> bool { + path.extension().is_some_and(|e| e.eq_ignore_ascii_case(ext)) + } + + struct Declarations { + files: Vec<(String, Option)>, + exclude_cst: bool, + cpg_error: Option, + } + + /// Uses the decoder's selected paths. A .cst that cannot be fully inspected has no + /// content stamp. Retains the existing whole-file stamp for an oversized regular .cpg. + fn declarations(path: &Path, hash: bool) -> Result { + let mut files = Vec::new(); + if !has_extension(path, "shp") { + return Ok(Declarations { files, exclude_cst: false, cpg_error: None }); + } + let (cpg, cst) = if hash { crate::dbf::read_sidecar_files(path)? } else { crate::dbf::read_sidecar_files_now(path)? }; + let exclude_cst = crate::dbf::sidecar_encoding(cpg.as_ref().map(crate::dbf::Declaration::bytes)).is_some() + || (!hash && cpg.as_ref().is_some_and(crate::dbf::Declaration::leased)); + let mut cpg_error = None; + let (cpg_name, cpg_stamp) = match cpg { + None => (name(&path.with_extension("cpg")), None), + Some(declaration) => { + cpg_error = declaration.error.map(DataError::from); + let stamp = match declaration.bytes { + _ if !hash => size_stamp(&declaration.path), + Some(bytes) if bytes.len() <= crate::dbf::MAX_CODE_PAGE_BYTES => Some(stamp_bytes(&bytes)), + Some(_) => match stamp_large_cpg(&declaration.path) { + Ok(stamp) => stamp, + Err(DataError::Cancelled) => return Err(DataError::Cancelled), + Err(e) => { + cpg_error = Some(e); + None + } + }, + None => None, + }; + (name(&declaration.path), stamp) + } + }; + files.push((cpg_name, cpg_stamp)); + if let Some(cst) = cst { + let stamp = if hash { + cst.bytes.filter(|b| b.len() <= crate::dbf::MAX_CODE_PAGE_BYTES).map(|b| stamp_bytes(&b)) + } else { + size_stamp(&cst.path).filter(|s| s.len <= crate::dbf::MAX_CODE_PAGE_BYTES as u64) + }; + files.push((name(&cst.path), stamp)); + } + Ok(Declarations { files, exclude_cst, cpg_error }) + } + + /// Sync keeps checking changes to a regular .cpg even if the decoder refuses its size. + fn stamp_large_cpg(path: &Path) -> Result> { + let Some(file) = crate::dbf::open_with_lease_retry(path, true)? else { + return Ok(None); + }; + let len = file.metadata()?.len(); + Ok(Some(FileStamp { len, sha256: hash_file(path, file)? })) + } + + /// A watch uses only the length for comparison, with metadata errors treated as absence. + fn size_stamp(path: &Path) -> Option { + len(path).ok().flatten().map(|len| FileStamp { len, sha256: String::new() }) + } + + fn stamp_bytes(bytes: &[u8]) -> FileStamp { + use sha2::Digest; + FileStamp { len: bytes.len() as u64, sha256: sha2::Sha256::digest(bytes).iter().map(|b| format!("{b:02x}")).collect() } + } + + /// Keeps an absent declaration out of the change list unless this record held its bytes. + /// Older records may include an unused .cst. It drops out of comparisons with a usable .cpg. + fn declaration_changes(before: &FileSync, now: &Declarations, same: impl Fn(&FileStamp, &FileStamp) -> bool) -> Vec { + let find = |name, files: &[(String, Option)]| files.iter().find(|(n, _)| n == name).and_then(|(_, stamp)| stamp.clone()); + let mut changed = Vec::new(); + for (name, stamp) in &now.files { + if let Some(stamp) = stamp + && find(name, &before.files).is_none_or(|old| !same(&old, stamp)) + { + changed.push(name.clone()); + } + } + for (name, stamp) in &before.files { + let part = Path::new(name); + if (has_extension(part, "cpg") || (has_extension(part, "cst") && !now.exclude_cst)) + && stamp.is_some() + && find(name, &now.files).is_none() + { + changed.push(name.clone()); + } + } + changed } /// The file's size, or `None` when it isn't there. @@ -206,22 +296,16 @@ mod native { } } - /// The SHA-256 of the file's bytes, read a block at a time, each counted as progress - /// ([`crate::progress`]) and stopping once the run is cancelled. An oversized .cst - /// leaves the source without a sync record, so it can't be published. + /// The SHA-256 of an ordinary source part, counted as progress and cancellable by block. fn sha256(path: &Path) -> Result { + hash_file(path, crate::provenance::open(path)?) + } + + /// Hashes the already opened file, including code pages opened with safe flags. + fn hash_file(path: &Path, mut file: std::fs::File) -> Result { use sha2::Digest; use std::io::Read; - let file = crate::provenance::open(path)?; let metadata = file.metadata().ok(); - let cst = path.extension().is_some_and(|ext| ext.eq_ignore_ascii_case("cst")); - let limit = crate::dbf::MAX_CODE_PAGE_BYTES as u64; - let too_large = || DataError::Format(format!("{} is too large to record for Publish to Source", path.display())); - if cst && metadata.as_ref().is_some_and(|m| m.len() > limit) { - return Err(too_large()); - } - // Bound the hash even if the declaration grows after the metadata check. - let mut file = file.take(if cst { limit + 1 } else { u64::MAX }); let mut hasher = sha2::Sha256::new(); let mut buf = vec![0u8; 1 << 16]; loop { @@ -232,9 +316,6 @@ mod native { hasher.update(buf.get(..n).unwrap_or_default()); crate::progress::step(n)?; } - if cst && file.limit() == 0 { - return Err(too_large()); - } let hash: String = hasher.finalize().iter().map(|b| format!("{b:02x}")).collect(); crate::provenance::hashed(path, metadata.as_ref(), hash.clone()); Ok(hash) @@ -248,6 +329,10 @@ mod native { impl FileSync { /// The files of the source at `path` as they are now, each read whole to hash it. pub fn read(path: &Path) -> Result { + let declarations = declarations(path, true)?; + if let Some(error) = declarations.cpg_error { + return Err(error); + } let parts = parts(path); let total = parts.iter().filter_map(|(_, p)| std::fs::metadata(p).ok()).map(|m| m.len()).sum(); crate::progress::begin(count(total)); @@ -259,6 +344,7 @@ mod native { }; files.push((name, stamp)); } + files.extend(declarations.files); Ok(FileSync { files }) } @@ -266,14 +352,10 @@ mod native { /// the bytes written to it) by those bytes, so a write made since by someone else isn't /// taken for this one; any other part as it is on the disk. pub fn of_written(path: &Path, written: &[(PathBuf, Vec)]) -> Result { - use sha2::Digest; let mut files = Vec::new(); for (name, p) in parts(path) { let stamp = match written.iter().find(|(w, _)| *w == p) { - Some((_, bytes)) => Some(FileStamp { - len: bytes.len() as u64, - sha256: sha2::Sha256::digest(bytes).iter().map(|b| format!("{b:02x}")).collect(), - }), + Some((_, bytes)) => Some(stamp_bytes(bytes)), None => match len(&p)? { None => None, Some(len) => Some(FileStamp { len, sha256: sha256(&p)? }), @@ -281,6 +363,11 @@ mod native { }; files.push((name, stamp)); } + if let Some((p, bytes)) = written.iter().find(|(p, _)| has_extension(p, "cpg")) { + files.push((name(p), Some(stamp_bytes(bytes)))); + } else { + files.extend(declarations(path, true)?.files); + } Ok(FileSync { files }) } @@ -309,9 +396,8 @@ mod native { /// thread does it on a thread of its own. Errs only when the run is cancelled. pub fn changed(&self, path: &Path) -> Result> { let now = parts(path); - let mut changed = Vec::new(); - // Files there now that the record lacks (an added encoding declaration); not the - // `.cpg` name `parts` falls back to when there is none. + let mut changed = + if has_extension(path, "shp") { declaration_changes(self, &declarations(path, true)?, |a, b| a == b) } else { Vec::new() }; for (name, p) in &now { if !self.files.iter().any(|(n, _)| n == name) && p.exists() { changed.push(name.clone()); @@ -320,6 +406,9 @@ mod native { let total = self.files.iter().filter_map(|(_, s)| s.as_ref()).map(|s| s.len).sum(); crate::progress::begin(count(total)); for (name, was) in &self.files { + if has_extension(path, "shp") && (has_extension(Path::new(name), "cpg") || has_extension(Path::new(name), "cst")) { + continue; + } let Some((_, p)) = now.iter().find(|(n, _)| n == name) else { // Out of the set now: changed if it held anything. if was.is_some() { @@ -344,13 +433,21 @@ mod native { } /// The names of the files that differ from this record by what metadata alone shows: - /// added, removed, or another length. Reads no file, so a change that keeps every length - /// isn't seen; [`FileSync::changed`] hashes them. An unreadable file counts as differing. + /// added, removed, or another length. A bounded, nonwaiting label read decides which + /// declaration applies. [`FileSync::changed`] also hashes the source data. pub fn resized(&self, path: &Path) -> Vec { let now = parts(path); let mut differ: Vec = now.iter().filter(|(name, p)| !self.files.iter().any(|(n, _)| n == name) && p.exists()).map(|(n, _)| n.clone()).collect(); + if has_extension(path, "shp") + && let Ok(declarations) = declarations(path, false) + { + differ.extend(declaration_changes(self, &declarations, |a, b| a.len == b.len)); + } for (name, was) in &self.files { + if has_extension(path, "shp") && (has_extension(Path::new(name), "cpg") || has_extension(Path::new(name), "cst")) { + continue; + } let is = now.iter().find(|(n, _)| n == name).map(|(_, p)| len(p)); let same = match (was, is) { (None, None | Some(Ok(None))) => true, @@ -400,9 +497,9 @@ mod tests { assert!(sync.changed(&path).unwrap().is_empty()); } - /// Reading still runs with an oversized declaration, but there is no publish baseline. + /// The optional declaration cannot take the whole layer's sync record with it. #[test] - fn an_oversized_cst_prevents_recording_a_publish_baseline() { + fn an_oversized_cst_has_no_stamp_and_is_ignored_with_a_usable_cpg() { let dir = tempfile::tempdir().unwrap(); let path = dir.path().join("a.shp"); let cst = path.with_extension("CsT"); @@ -412,10 +509,18 @@ mod tests { std::fs::File::options().write(true).open(&cst).unwrap().set_len(crate::dbf::MAX_CODE_PAGE_BYTES as u64 + 1).unwrap(); let (read, sync) = FileSync::around(&path, || std::fs::read_to_string(&path)).unwrap(); assert_eq!(read.unwrap(), "shp"); - assert!(sync.is_none()); + let sync = sync.unwrap(); + assert!(sync.files.iter().any(|(n, s)| n.eq_ignore_ascii_case("a.CsT") && s.is_none())); let changed = record.changed(&path).unwrap(); assert_eq!(changed.len(), 1); assert!(changed[0].eq_ignore_ascii_case("a.cst"), "{changed:?}"); + + std::fs::write(path.with_extension("cpg"), "1252").unwrap(); + let with_cpg = FileSync::read(&path).unwrap(); + assert!(with_cpg.files.iter().all(|(n, _)| !n.eq_ignore_ascii_case("a.CsT"))); + std::fs::write(cst, "UTF-8").unwrap(); + assert!(with_cpg.changed(&path).unwrap().is_empty()); + assert!(with_cpg.resized(&path).is_empty()); } #[test] diff --git a/crates/data/src/zip.rs b/crates/data/src/zip.rs index d2ccff7880..ed0ab364e7 100644 --- a/crates/data/src/zip.rs +++ b/crates/data/src/zip.rs @@ -41,16 +41,33 @@ pub fn write(entries: &[(String, Vec)]) -> Result, String> { Ok(out) } +/// Writes a ZIP, omitting its final optional member if it would exceed `budget`. +pub(crate) fn write_with_optional_tail(entries: &[(String, Vec)], budget: usize) -> Result, String> { + let mut out = Vec::new(); + write_entries_to(entries, &mut out, Some(budget))?; + Ok(out) +} + /// [`write`]'s archive, written to `out` as it is made (a buffer held to a limit stops it there). /// Besides `out`, it holds the central directory and one entry's compressed bytes at a time. pub(crate) fn write_to(entries: &[(String, Vec)], out: &mut impl std::io::Write) -> Result<(), String> { + write_entries_to(entries, out, None) +} + +/// Writes each compressed entry once. The tail's admission includes its local and central +/// records and the end record, which lets an optional sidecar fit without rewriting the data. +fn write_entries_to( + entries: &[(String, Vec)], + out: &mut impl std::io::Write, + optional_tail_budget: Option, +) -> Result<(), String> { let too_big = || "the archive is too large for a zip file".to_string(); let failed = |e: std::io::Error| e.to_string(); - let count = u16::try_from(entries.len()).map_err(|_| too_big())?; + let mut count = u16::try_from(entries.len()).map_err(|_| too_big())?; // How much of the archive is written: where the next entry starts. let mut written: usize = 0; let mut central = Vec::new(); - for (name, data) in entries { + for (i, (name, data)) in entries.iter().enumerate() { let n = name.as_bytes(); let name_len = u16::try_from(n.len()).map_err(|_| too_big())?; let data_len = u32::try_from(data.len()).map_err(|_| too_big())?; @@ -86,10 +103,19 @@ pub(crate) fn write_to(entries: &[(String, Vec)], out: &mut impl std::io::Wr h }; let local = header(0x0403_4B50, false); + let directory_entry = header(0x0201_4B50, true); + if i + 1 == entries.len() + && optional_tail_budget.is_some_and(|budget| { + add(&[written, local.len(), body.len(), central.len(), directory_entry.len(), 22]).is_none_or(|size| size > budget) + }) + { + count -= 1; + break; + } out.write_all(&local).map_err(failed)?; out.write_all(body).map_err(failed)?; written = written.saturating_add(local.len()).saturating_add(body.len()); - central.extend_from_slice(&header(0x0201_4B50, true)); + central.extend_from_slice(&directory_entry); } let cd_offset = u32::try_from(written).map_err(|_| too_big())?; let cd_len = u32::try_from(central.len()).map_err(|_| too_big())?; @@ -151,7 +177,7 @@ pub fn read_matching(bytes: &[u8], want: impl Fn(&str) -> bool) -> Result bool, budget: usize) -> Result)>, String> { - read_within(bytes, |name| !name.ends_with('/') && want(name), budget, false).map_err(Failure::message) + read_within(bytes, |name| !name.ends_with('/') && want(name), budget, false, |_, _| false).map_err(Failure::message) } /// Why a read failed. @@ -233,10 +259,27 @@ fn effective_name<'a>(raw: &'a [u8], mut extra: &'a [u8]) -> Option<&'a [u8]> { /// within `budget` inflated bytes in all. Cancel is looked at between members; inflating one /// member, up to [`MAX_ENTRY`], isn't interrupted. pub(crate) fn read_all_within(bytes: &[u8], budget: usize) -> Result)>, Failure> { - read_within(bytes, |_| true, budget, true) + read_within(bytes, |_| true, budget, true, |_, _| false) +} + +/// Reads the requested entries and hands deferred member headers to the caller without +/// decompressing or charging them. The caller may read a member later under its own limit. +pub(crate) fn read_deferring( + bytes: &[u8], + want: impl Fn(&str) -> bool, + mut defer: impl FnMut(&str, Member) -> bool, +) -> Result)>, String> { + read_within(bytes, |n| !n.ends_with('/') && want(n), MAX_TOTAL, false, |n, m| !n.ends_with('/') && defer(n, m)) + .map_err(Failure::message) } -fn read_within(bytes: &[u8], want: impl Fn(&str) -> bool, budget: usize, spreadsheet: bool) -> Result)>, Failure> { +fn read_within( + bytes: &[u8], + want: impl Fn(&str) -> bool, + budget: usize, + spreadsheet: bool, + mut defer: impl FnMut(&str, Member) -> bool, +) -> Result)>, Failure> { let mut budget = budget.min(MAX_TOTAL); let bad = || Failure::Layout("not a zip archive (or a damaged one)".to_string()); let eocd = if spreadsheet { @@ -303,9 +346,42 @@ fn read_within(bytes: &[u8], want: impl Fn(&str) -> bool, budget: usize, spreads }; let name = String::from_utf8_lossy(name).into_owned(); p = add(&[p, 46, nl, xl, cl]).ok_or_else(bad)?; - if !want(&name) { + let member = Member { method, flags, crc, csize, usize_, local, offset }; + if defer(&name, member) || !want(&name) { continue; } + let data = member.read(bytes, &name, budget)?; + budget -= data.len(); + out.push((name, data)); + } + Ok(out) +} + +/// Central-directory information for a member, with its contents still compressed. +#[derive(Clone, Copy)] +pub(crate) struct Member { + method: usize, + flags: usize, + crc: usize, + csize: usize, + usize_: usize, + local: usize, + offset: usize, +} + +impl Member { + /// Bounds the compressed bytes too, allowing for Deflate's framing overhead. + pub(crate) fn read_small(self, bytes: &[u8], name: &str, limit: usize) -> Result, Failure> { + if self.csize > limit.saturating_mul(2) { + return Err(Failure::Member(format!("{name} is too large to read as a declaration"))); + } + self.read(bytes, name, limit) + } + + /// Checks and expands just this member, bounded even when its local data lies about its size. + pub(crate) fn read(self, bytes: &[u8], name: &str, budget: usize) -> Result, Failure> { + let Self { method, flags, crc, csize, usize_, local, offset } = self; + let bad = || Failure::Layout("not a zip archive (or a damaged one)".to_string()); // Say what's wrong first: an encrypted entry or a ZIP64 one isn't damaged data. if flags & 1 != 0 { return Err(Failure::Member(format!("{name} is encrypted; its contents can't be read"))); @@ -340,13 +416,11 @@ fn read_within(bytes: &[u8], want: impl Fn(&str) -> bool, budget: usize, spreads if data.len() != usize_ { return Err(Failure::Member(format!("{name} is damaged (wrong size)"))); } - budget -= data.len(); if crc32(&data) as usize != crc { return Err(Failure::Member(format!("{name} is damaged (checksum mismatch)"))); } - out.push((name, data)); + Ok(data) } - Ok(out) } #[cfg(test)] diff --git a/crates/engine/src/cmd/gp.rs b/crates/engine/src/cmd/gp.rs index 43bfad18cb..8cbe21c163 100644 --- a/crates/engine/src/cmd/gp.rs +++ b/crates/engine/src/cmd/gp.rs @@ -4000,14 +4000,20 @@ struct Ran { started: u64, } +/// Resolves an output's identity even when its final path component does not exist yet. #[cfg(not(target_arch = "wasm32"))] -fn write_file_output(s: &Session, path: &std::path::Path, bytes: &[u8]) -> Result<(), String> { +fn output_path(path: &std::path::Path) -> std::io::Result { // A new file has no canonical path yet: resolve its folder, so a file created inside a loaded // source directory is refused as well as one replaced there. - let resolved = path.canonicalize().or_else(|error| { + path.canonicalize().or_else(|error| { let parent = path.parent().filter(|p| !p.as_os_str().is_empty()).unwrap_or(std::path::Path::new(".")); path.file_name().map(|name| parent.canonicalize().map(|p| p.join(name))).unwrap_or(Err(error)) - }); + }) +} + +#[cfg(not(target_arch = "wasm32"))] +fn write_file_output(s: &Session, path: &std::path::Path, bytes: &[u8]) -> Result<(), String> { + let resolved = output_path(path); if let Ok(destination) = resolved { if s.path.iter().chain(s.opened_package.iter()).any(|project| project.canonicalize().is_ok_and(|project| project == destination)) { return Err("destination is the open project's file; choose a different output file".into()); @@ -4052,7 +4058,9 @@ fn names_file(source: &str, destination: &std::path::Path) -> bool { } let shapefile = source.extension().is_some_and(|e| e.eq_ignore_ascii_case("shp")); let companion = |ext: &str| source.with_extension(ext).canonicalize().is_ok_and(|p| p.as_path() == destination); - shapefile && ["dbf", "DBF", "shx", "SHX", "prj", "PRJ", "cpg", "CPG"].into_iter().chain(rustgis_data::io::CST_SPELLINGS).any(companion) + (shapefile && ["dbf", "DBF", "shx", "SHX", "prj", "PRJ"].into_iter().any(companion)) + || ((shapefile || source.extension().is_some_and(|e| e.eq_ignore_ascii_case("dbf"))) + && rustgis_data::io::declaration_paths(source).any(|p| output_path(&p).is_ok_and(|p| p == destination))) } /// Adds a tool's table to the project under its name: in place of a table of that name, or, for @@ -5134,12 +5142,17 @@ mod file_tests { std::fs::write(&archive, b"zip").unwrap(); std::fs::write(&companion, b"dbf").unwrap(); let archive_file = archive.canonicalize().unwrap(); - let cst = root.join("roads.CsT"); - std::fs::write(&cst, b"ISO-8859-1").unwrap(); + let dbf = root.join("roads.dbf"); + std::fs::write(&dbf, b"dbf").unwrap(); let source = root.join("roads.shp").display().to_string(); assert!(names_file(&archive.join("roads.shp").display().to_string(), &archive_file)); assert!(names_file(&source, &companion.canonicalize().unwrap())); - assert!(names_file(&source, &cst.canonicalize().unwrap())); + for sidecar in rustgis_data::io::declaration_paths(&dbf) { + std::fs::write(&sidecar, b"ISO-8859-1").unwrap(); + let sidecar = sidecar.canonicalize().unwrap(); + assert!(names_file(&source, &sidecar), "{sidecar:?}"); + assert!(names_file(&dbf.display().to_string(), &sidecar), "{sidecar:?}"); + } assert!(!names_file(&root.join("roads.dbf").display().to_string(), &archive_file)); std::fs::remove_dir_all(root).unwrap(); } diff --git a/crates/engine/src/cmd/layer.rs b/crates/engine/src/cmd/layer.rs index 7c50fc83ad..db093c3029 100644 --- a/crates/engine/src/cmd/layer.rs +++ b/crates/engine/src/cmd/layer.rs @@ -5887,7 +5887,8 @@ fn parts_left_out(url: &str, bytes: &[u8], p: &Value) -> Option { (if shp.chars().count() > 80 { format!("{}…", shp.chars().take(79).collect::()) } else { shp }, lacks) }) .map(|(shp, lacks)| { - let names = lacks.iter().map(|e| format!(".{e}")).collect::>().join(", "); + let names = + lacks.iter().map(|e| if *e == "cpg" { ".cpg or .cst".into() } else { format!(".{e}") }).collect::>().join(", "); let crs = if lacks.contains(&"prj") && !given_crs { "; its coordinates are read as longitude/latitude" } else { "" }; let them = if lacks.len() == 1 { "it" } else { "them" }; format!( @@ -5910,7 +5911,7 @@ fn download_shapefile_blocking_with(url: &str, public: bool) -> Result, use crate::render::rustgis_tiles::cache; let parts = rustgis_data::io::shapefile_part_urls(url).unwrap_or_default(); if public { - for (_, part) in &parts { + for (_, part) in parts.iter().filter(|(ext, _)| *ext != "cst") { crate::render::rustgis_tiles::address::check(part, Some(url)).map_err(|e| part_failed(part, e))?; } } @@ -5918,12 +5919,13 @@ fn download_shapefile_blocking_with(url: &str, public: bool) -> Result, let until = std::time::Instant::now() + cache::BLOCKING_TIMEOUT; // Past it, a part isn't asked for at all (a zero timeout may mean none), and a timeout says // where a large file goes instead. - let within = |u: &str, max: usize, omit: &'static [u16]| match until.saturating_duration_since(std::time::Instant::now()) { + let within = |u: &str, max: usize, omit: &'static [u16], cap| match until.saturating_duration_since(std::time::Instant::now()).min(cap) + { w if w.is_zero() => Err(cache::large_file_hint("timed out".into())), w if public => cache::download_public_omitting_within(u, max, w, omit).map_err(cache::large_file_hint), w => cache::download_blocking_omitting_within(u, max, w, omit).map_err(cache::large_file_hint), }; - let shp = within(url, cache::MAX_DOWNLOAD, &[]).map_err(|e| part_failed(url, e))?; + let shp = within(url, cache::MAX_DOWNLOAD, &[], cache::BLOCKING_TIMEOUT).map_err(|e| part_failed(url, e))?; // Already zipped (a server answering the address with its parts): read as it is. if is_zip(&shp) { return Ok(shp); @@ -5938,7 +5940,14 @@ fn download_shapefile_blocking_with(url: &str, public: bool) -> Result, if skip_cst(ext, &got) { continue; } - match within(&u, left, part_absences(ext, &u)).and_then(|b| page_part(ext, b)) { + if ext == "cst" { + let result = within(&u, rustgis_data::io::SHAPEFILE_CODE_PAGE_LIMIT, part_absences(ext, &u), CST_WAIT); + if let Some(b) = optional_cst(result)? { + got.push((ext, b)); + } + break; + } + match within(&u, left, part_absences(ext, &u), cache::BLOCKING_TIMEOUT).and_then(|b| page_part(ext, b)) { Ok(None) => {} Ok(Some(b)) => { left = left.saturating_sub(b.len()); @@ -5968,7 +5977,7 @@ pub fn download_data_from(url: &str, public: bool, max: usize, done: crate::rend return if public { cache::download_public_limited(url, max, done) } else { cache::download_limited(url, max, done) }; }; if public { - for (_, part) in &parts { + for (_, part) in parts.iter().filter(|(ext, _)| *ext != "cst") { if let Err(e) = crate::render::rustgis_tiles::address::check(part, Some(url)) { return done(Err(part_failed(part, e))); } @@ -6001,14 +6010,28 @@ pub fn download_data_from(url: &str, public: bool, max: usize, done: crate::rend /// download thread natively, on the page's event loop in the web app (as the web app's loose /// Shapefiles picked or dropped are zipped, #426). fn zipped_within(name: &str, shp: Vec, got: Vec<(&'static str, Vec)>, left: usize) -> Result, String> { - let max = got.iter().fold(shp.len().saturating_add(left), |n, (_, b)| n.saturating_add(b.len())); - let zip = rustgis_data::io::zip_shapefile_parts(name, shp, got)?; + let max = got.iter().filter(|(ext, _)| *ext != "cst").fold(shp.len().saturating_add(left), |n, (_, b)| n.saturating_add(b.len())); + let zip = rustgis_data::io::zip_shapefile_parts_for_download(name, shp, got, max)?; if zip.len() > max { return Err(format!("larger than {max} bytes, zipped")); } Ok(zip) } +const CST_WAIT: std::time::Duration = std::time::Duration::from_secs(2); + +/// A failed optional request leaves the .cst absent. Cancellation still stops the add. +fn optional_cst(result: Result, String>) -> Result>, String> { + use crate::render::rustgis_tiles::cache; + cache::check_still(&cache::current_still())?; + rustgis_data::progress::check().map_err(|e| e.to_string())?; + match result { + Ok(bytes) => page_part("cst", bytes), + Err(e) if e == cache::DROPPED => Err(e), + Err(_) => Ok(None), + } +} + /// A .cst is only needed when the earlier .cpg could not select an encoding. fn skip_cst(ext: &str, got: &[(&str, Vec)]) -> bool { ext == "cst" && got.iter().any(|(e, b)| *e == "cpg" && rustgis_data::io::shapefile_cpg_is_usable(b)) @@ -6033,8 +6056,24 @@ fn download_parts( if skip_cst(ext, &got) { return download_parts(name, shp, parts, got, left, public, done); } - let next = url.clone(); let omit = part_absences(ext, &url); + if ext == "cst" { + crate::render::rustgis_tiles::cache::download_part_within( + &url, + rustgis_data::io::SHAPEFILE_CODE_PAGE_LIMIT, + CST_WAIT, + omit, + public, + Box::new(move |r| { + done(optional_cst(r).and_then(|b| { + got.extend(b.map(|b| (ext, b))); + zipped_within(&name, shp, got, left) + })); + }), + ); + return; + } + let next = url.clone(); let step: crate::render::rustgis_tiles::cache::Done = Box::new(move |r| match r.and_then(|b| page_part(ext, b)) { Ok(None) => download_parts(name, shp, parts, got, left, public, done), Ok(Some(b)) => { diff --git a/crates/engine/src/observe.rs b/crates/engine/src/observe.rs index 4932aaadf2..c32edd70ce 100644 --- a/crates/engine/src/observe.rs +++ b/crates/engine/src/observe.rs @@ -35,6 +35,7 @@ impl FileRevision { let shown = path.display(); let metadata = match std::fs::metadata(path) { Ok(metadata) => metadata, + Err(_) if presence == Presence::OptionalFile => return Ok(None), Err(e) if presence != Presence::Required && e.kind() == std::io::ErrorKind::NotFound => return Ok(None), Err(e) => { return Err(format!("{shown}: could not observe {noun} metadata ({e}); finish writing or restore the file and retry")); @@ -50,9 +51,11 @@ impl FileRevision { let article = if noun == "archive" { "an" } else { "a" }; return Err(format!("{shown}: expected {article} {noun} file; restore the file and retry")); } - let modified = metadata - .modified() - .map_err(|e| format!("{shown}: could not observe the {noun} modification time ({e}); check file access and retry"))?; + let modified = match metadata.modified() { + Ok(modified) => modified, + Err(_) if presence == Presence::OptionalFile => return Ok(None), + Err(e) => return Err(format!("{shown}: could not observe the {noun} modification time ({e}); check file access and retry")), + }; #[cfg(unix)] use std::os::unix::fs::MetadataExt; #[cfg(windows)] @@ -116,8 +119,8 @@ impl Observation { } /// A monitored source at its linked path, with the companions its reader reads or sizes: a - /// Shapefile's lowercase `.dbf`, `.shx` and `.prj` and every ASCII-case `.cpg` and `.cst` - /// (`rustgis_data::dbf`), a MapInfo file's `.mid` (`rustgis_data::io`), a SQLite file's + /// Shapefile's lowercase `.dbf`, `.shx` and `.prj`, every ASCII-case `.cpg` and `.cst` + /// of a Shapefile or standalone DBF, a MapInfo file's `.mid` (`rustgis_data::io`), a SQLite file's /// `-wal` and `-journal`, or a DuckDB database's `.wal` (commits not yet checkpointed, as the /// DuckDB conversion's cache key counts them). A missing source is /// [`Observation::missing`], not an error. @@ -126,11 +129,13 @@ impl Observation { let primary = FileRevision::read(path, Presence::Optional, "source")?; let mut companions = Vec::new(); if has_extension(path, &["shp"]) { - for ext in ["dbf", "shx", "prj"].into_iter().chain(rustgis_data::io::CPG_SPELLINGS) { + for ext in ["dbf", "shx", "prj"] { companions.push(FileRevision::read(&path.with_extension(ext), Presence::Optional, "source")?); } - for ext in rustgis_data::io::CST_SPELLINGS { - companions.push(FileRevision::read(&path.with_extension(ext), Presence::OptionalFile, "source")?); + } + if has_extension(path, &["shp", "dbf"]) { + for declaration in rustgis_data::io::declaration_paths(path) { + companions.push(FileRevision::read(&declaration, Presence::OptionalFile, "source")?); } } else if has_extension(path, &["mif"]) { // Its attributes: the spellings `rustgis_data::io` reads. @@ -225,7 +230,11 @@ mod tests { #[test] fn shapefile_and_mapinfo_components_the_reader_opens_are_observed() { let dir = dir("components"); - for (main, exts) in [("roads.shp", &["dbf", "shx", "prj", "cpg", "CPG", "cst", "CsT"][..]), ("roads.mif", &["mid"][..])] { + for (main, exts) in [ + ("roads.shp", &["dbf", "shx", "prj", "cpg", "CPG", "cst", "CsT"][..]), + ("standalone.dbf", &["CpG", "CSt"][..]), + ("roads.mif", &["mid"][..]), + ] { let main = dir.join(main); std::fs::write(&main, b"shapes").unwrap(); let path = main.display().to_string(); diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index 7f9f45ce3b..20e9e48217 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -26160,6 +26160,11 @@ fn shapefile_by_its_shp_address() { parts.iter().map(|(e, b)| (format!("/PI/TERESINA/HIDROGRAFIA/PI_2211001_RIOS.{e}?token=1"), b.clone())).collect(); files.extend(parts.iter().filter(|(e, _)| *e != "cpg").map(|(e, b)| (format!("/cst/rios.{e}"), b.clone()))); files.push(("/cst/rios.cst".into(), b"ISO-8859-1".to_vec())); + // A keyed server refuses the optional .cst. The ordinary .cpg request succeeds with + // an unusable label so the fallback really is fetched. + files.extend(parts.iter().filter(|(e, _)| *e != "cpg").map(|(e, b)| (format!("/signed/cst.{e}?sig=1"), b.clone()))); + files.push(("/signed/cst.cpg?sig=1".into(), b"bad-label".to_vec())); + // The same without its .prj and .cpg, and one without its .dbf. files.extend(parts.iter().filter(|(e, _)| !matches!(*e, "prj" | "cpg")).map(|(e, b)| (format!("/plain/rios.{e}"), b.clone()))); files.extend(parts.iter().filter(|(e, _)| !matches!(*e, "prj" | "cpg")).map(|(e, b)| (format!("/keyed/rios.{e}?token=zz"), b.clone()))); @@ -26208,11 +26213,18 @@ fn shapefile_by_its_shp_address() { let said = s.notices_since(mark); assert_eq!(said.iter().filter(|n| n.text.contains("code page taken from the .cst")).count(), 1, "{said:?}"); assert!(!said.iter().any(|n| n.text.contains("optional files")), "{said:?}"); + let refused_cst = format!("{base}/signed/cst.shp?sig=1"); + let mark = s.notice_mark(); + let r = s.run("layer.addUrl", &json!({"url": refused_cst, "name": "Optional CST refused"})).unwrap(); + assert_eq!(r["features"], 1, "{r}"); + let said = s.notices_since(mark); + assert!(said.iter().any(|n| n.text.contains("no .cst found or readable beside it")), "{said:?}"); + assert!(asked.lock().unwrap().iter().any(|path| path == "/signed/cst.cst?sig=1")); // Without a .prj or .cpg (404), it is read as a local Shapefile without them. let r = s.run("layer.addUrl", &json!({"url": format!("{base}/plain/rios.shp"), "name": "Sem prj"})).unwrap(); assert_eq!(r["features"], 1, "{r}"); let said = &s.notices.last().unwrap().text; - assert!(said.contains("no .prj, .cpg found or readable beside it (2 of 3") && said.contains("longitude/latitude"), "{said}"); + assert!(said.contains("no .prj, .cpg or .cst found or readable beside it (2 of 3") && said.contains("longitude/latitude"), "{said}"); assert!(said.contains("/plain/rios.shp: rios.shp: no .prj") && !said.contains("omitted]"), "{said}"); // Their 404s are expected: noted once for the server, not recorded as failed requests. let records = s.diagnostics.records(); @@ -26224,7 +26236,7 @@ fn shapefile_by_its_shp_address() { // With its coordinate system given, nothing is assumed of the missing .prj. s.run("layer.addUrl", &json!({"url": format!("{base}/plain/rios.shp"), "name": "Com crs", "crs": "EPSG:31983"})).unwrap(); let said = &s.notices.last().unwrap().text; - assert!(said.contains("no .prj, .cpg found or readable beside it") && !said.contains("longitude/latitude"), "{said}"); + assert!(said.contains("no .prj, .cpg or .cst found or readable beside it") && !said.contains("longitude/latitude"), "{said}"); // A secret query taken out of the address in the notice is said; no query, no marker. s.run("layer.addUrl", &json!({"url": format!("{base}/keyed/rios.shp?token=zz"), "name": "Keyed", "crs": "EPSG:31983"})).unwrap(); let said = &s.notices.last().unwrap().text; @@ -26260,7 +26272,7 @@ fn shapefile_by_its_shp_address() { // Parts answered with a web page are done without, and said; a .dbf answered so is refused. let r = s.run("layer.addUrl", &json!({"url": format!("{base}/spa/rios.shp"), "name": "SPA"})).unwrap(); assert_eq!(r["features"], 1, "{r}"); - assert!(s.notices.last().unwrap().text.contains("no .prj, .cpg found or readable beside it"), "{:?}", s.notices.last()); + assert!(s.notices.last().unwrap().text.contains("no .prj, .cpg or .cst found or readable beside it"), "{:?}", s.notices.last()); let e = s.run("layer.addUrl", &json!({"url": format!("{base}/spa/sem_dbf.shp")})).unwrap_err(); assert!(e.contains("/spa/sem_dbf.dbf: a web page answered, not a .dbf"), "{e}"); // A page answering for the .shp itself fails at once, its parts not asked for. @@ -26340,6 +26352,12 @@ fn shapefile_by_its_shp_address() { let said = s.notices_since(mark); assert_eq!(said.iter().filter(|n| n.text.contains("code page taken from the .cst")).count(), 1, "{said:?}"); assert!(!said.iter().any(|n| n.text.contains("optional files")), "{said:?}"); + let id = s.download_started(); + assert!(s.download_landed(id, fetch(&refused_cst, 1 << 20).unwrap())); + let mark = s.notice_mark(); + s.run("layer.addDownload", &json!({"id": id, "url": refused_cst, "name": "Optional CST refused in app"})).unwrap(); + let said = s.notices_since(mark); + assert!(said.iter().any(|n| n.text.contains("no .cst found or readable beside it")), "{said:?}"); // Through the app too, what was left out is said. let plain = format!("{base}/plain/rios.shp"); let id = s.download_started(); @@ -26347,7 +26365,7 @@ fn shapefile_by_its_shp_address() { let mark = s.notice_mark(); s.run("layer.addDownload", &json!({"id": id, "url": plain, "name": "Sem prj pela janela"})).unwrap(); let said = s.notices_since(mark); - assert!(said.iter().any(|n| n.text.contains("no .prj, .cpg found or readable beside it (2 of 3")), "{said:?}"); + assert!(said.iter().any(|n| n.text.contains("no .prj, .cpg or .cst found or readable beside it (2 of 3")), "{said:?}"); // A download too large for the budget together is refused: the .shp and .dbf land, and the // .shx goes over the 2 bytes left, named without the address's token. let e = fetch(&url, 200).unwrap_err(); diff --git a/crates/tiles/src/cache.rs b/crates/tiles/src/cache.rs index e59970d5b0..02b72328f8 100644 --- a/crates/tiles/src/cache.rs +++ b/crates/tiles/src/cache.rs @@ -1879,6 +1879,13 @@ pub fn download_public_limited_omitting(url: &str, max: usize, omit: &'static [u download_reaching(url, max, DOWNLOAD_TIMEOUT, omit, Reaching::Public, Box::new(move |r| done(r.map_err(|f| f.message)))); } +/// Downloads an optional part, with its own native deadline and the caller's reach and +/// expected statuses. The browser fetcher supplies its own deadline. +pub fn download_part_within(url: &str, max: usize, timeout: std::time::Duration, omit: &'static [u16], public: bool, done: Done) { + let reach = if public { Reaching::Public } else { Reaching::Any }; + download_reaching(url, max, timeout, omit, reach, Box::new(move |r| done(r.map_err(|f| f.message)))); +} + /// Which addresses a native download may connect to. #[derive(Clone, Copy)] enum Reaching { diff --git a/docs/user-guide/data-formats.md b/docs/user-guide/data-formats.md index 6a7663c4ca..9f88763e65 100644 --- a/docs/user-guide/data-formats.md +++ b/docs/user-guide/data-formats.md @@ -55,14 +55,15 @@ GeoParquet or FlatGeobuf text column holding `` keeps it as text. Number, fields read past the spaces (`' 2535'` in a number column is 2535). To clean the spaces, use `trim()` in Calculate Field; text typed into the attribute table is trimmed. -Shapefile text uses the first supported encoding in its `.cpg` sidecar, its `.cst` sidecar, -or the language-driver code in its `.dbf` header, in that order. Include the sidecars when -picking or dropping loose files in the web app. A notice identifies a code page taken from a `.cst`. +Shapefile text uses a supported `.cpg` first. RustGIS checks the `.cst` only if the +`.cpg` is missing or unusable, then falls back to the language-driver code in the `.dbf` header. +Include the sidecars when picking or dropping loose files in the web app. When a `.cst` supplies +the encoding, a notice gives the declaration's label and the decoder RustGIS used. UTF-8 (including `65001`), DOS code pages such as CP437 and CP850 (numeric, `CP` or `IBM` labels), Windows code pages such as `1252`, `CP1252` and `Windows-1252`, ISO-8859 encodings 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` or `.cst` -gives a notice before RustGIS tries the next source. An unsupported DBF code page gives a notice +is read as Windows-1252. When a declaration that RustGIS checks is unreadable, empty, invalid, +oversized or unsupported, RustGIS says so and tries the next source. 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 without a usable `.cpg` or `.cst` read as UTF-8, or a byte that isn't valid in the @@ -99,8 +100,9 @@ uploaded file. Native formats include GeoJSON, delimited text, GeoParquet, FlatG zipped Shapefiles, KML/KMZ, GPX, spreadsheets, GeoRSS, GML, DXF, TopoJSON, CityJSON, CityGML, LiDAR and rasters. A Shapefile published as loose files, one address per part, is added by its `.shp` address: the `.dbf` beside it (same name and folder) is fetched too, and the `.shx`, `.prj` and `.cpg` when they -are there. RustGIS also tries the `.cst` if the `.cpg` provides no usable encoding. All parts -share one download limit. Their extensions follow the `.shp`'s case: a +are there. RustGIS tries a short, bounded `.cst` request if the `.cpg` provides no usable +encoding. If the optional request fails or stalls, RustGIS says the declaration was unavailable +and continues opening the layer. The files share a download limit. Their extensions follow the `.shp`'s case: a `.SHP` asks for `.DBF`, `.SHX`, and so on. An optional part that answers 404 or 410, or 403 to an address without keys or a user and password (S3's answer for a missing file), or a web page in its place, is left out, and a notice names it. The parts are looked up beside the address as given diff --git a/docs/user-guide/index.md b/docs/user-guide/index.md index 5830663527..2799618f66 100644 --- a/docs/user-guide/index.md +++ b/docs/user-guide/index.md @@ -303,8 +303,9 @@ Reload Data even when the folder's timestamp has not changed. **Changed on disk (desktop).** While the app is open, RustGIS looks at the files its linked layers and local tile archives read every 5 seconds and when its window regains focus, in every map of the project. It reads only metadata (size, modification time and the file's identity: on -Linux and macOS its status-change time too, on Windows its creation time), never the data: a Shapefile's `.dbf`, `.shx`, `.prj`, `.cpg` and `.cst` count with its -`.shp`, a MapInfo file's `.mid` with its `.mif`, a GeoPackage, MBTiles or `.sqlite` file's `-wal` +Linux and macOS its status-change time too, on Windows its creation time). A Shapefile's +`.dbf`, `.shx` and `.prj` count with its `.shp`. The `.cpg` and `.cst` declarations are +also watched for Shapefiles and standalone DBFs. A MapInfo file's `.mid` with its `.mif`, a GeoPackage, MBTiles or `.sqlite` file's `-wal` and `-journal` with it, and a DuckDB database's `.wal` with it (a `.db` file gets both). Other sidecars (a raster's `.aux.xml` or `.prj`) aren't watched. A change is reported once two looks in a row agree: a stability check, not proof the writer has finished (one that pauses for longer may be reported @@ -420,7 +421,8 @@ found shows in the status bar. CLI and Python: `source.syncState` with `{"layer" The desktop's Layers pane also marks such a layer as it goes: **(edits not published)** once it holds rows its file lacks (its rows are hashed in the background while the pane shows the layer, once after the project opens and again after each edit), and **(changed on disk)** when the file changes, by the same look at its -metadata as for linked files, never its data. A file whose length differs from the record, or +metadata as for linked files, with bounded reads of code-page labels to decide which applies. +A file whose length differs from the record, or that gained or lost a part, is marked even when it changed while the project was closed; one changed then without a change of length is found by Source File State or Publish. The row's tooltip says what to do; no notification offers Reload Data, which can't read such a layer. @@ -448,6 +450,19 @@ refuses, with nothing written, when: - the file can't hold the layer as it is: a feature without a shape, a field name longer than 10 bytes, text in characters the file's code page lacks. +A usable `.cpg` makes the `.cst` irrelevant to the source record and to Publish. Otherwise, +an unreadable or unsupported declaration, an LDID that disagrees with a usable `.cst`, or +apparently UTF-8 text under a single-byte `.cst` prevents Publish. Verify the actual encoding, +then repair the declarations and add the source again before applying the edits. + +An older project may have a source record that predates `.cst` support. A `.cst` that RustGIS can record can +appear as a newly added part in **Source File State**, even if it was already on disk. Publish +then refuses to write. **Reload Data** is unavailable for these whole-file layers. Keep the +edited layer, add the source again, and reapply the edits to the newly added layer. RustGIS +0.8.0 opens projects saved with the new source record. It ignores `.cst` when it reads a +Shapefile and treats a recorded `.cst` with a content stamp as a changed part, so use a version +that supports `.cst` to publish such a layer. + The file keeps its code page (its `.cpg`, `.cst` and the language driver in its `.dbf`), each column's width, decimals and type where the values still fit, and its `.prj`. A column that can't hold an edited value gets one that can, and a notice names it with its old and new form; a field diff --git a/docs/user-guide/loss-codes.md b/docs/user-guide/loss-codes.md index 6453abbdbc..097ce276bb 100644 --- a/docs/user-guide/loss-codes.md +++ b/docs/user-guide/loss-codes.md @@ -145,6 +145,8 @@ Longitude and latitude on a body other than the Earth were written as Earth coor Text that is not valid in the encoding it was read with was read with a replacement character in its place. **Where you see it:** reading a Shapefile or dBASE file, a DXF drawing, or feature service answers in PBF. +A Shapefile read can also report conflicting encoding declarations or text that appears to be +UTF-8 under a single-byte `.cst` declaration. **What to do:** Put a .cpg file naming the file's own encoding beside it. diff --git a/docs/user-guide/shapefile-encoding.md b/docs/user-guide/shapefile-encoding.md index 53e7c06f02..b6cc705314 100644 --- a/docs/user-guide/shapefile-encoding.md +++ b/docs/user-guide/shapefile-encoding.md @@ -1,7 +1,7 @@ # Shapefile DBF language drivers -RustGIS chooses a supported `.cpg` first, then a supported `.cst`, then the language driver ID -(LDID, byte 29 of the `.dbf` header). The following inventory describes RustGIS's LDID decoding +A usable `.cpg` selects the decoder by itself. Otherwise RustGIS checks the `.cst` and +then the language driver ID (LDID, byte 29 of the `.dbf` header). The following inventory describes RustGIS's LDID decoding when neither sidecar provides a usable declaration. All numbers in the marker column are hexadecimal. These are language-driver identifiers, not the numeric code-page labels accepted in a `.cpg` or `.cst`. @@ -56,10 +56,18 @@ Cyrillic character. The test uses `8A E8 E5 E2` → `Киев`, which both mappi These markers emit a diagnostic naming the marker and code page, then use lossy UTF-8. Unknown markers also emit a diagnostic and use lossy UTF-8. Valid UTF-8 survives, malformed -bytes become replacement characters, and the records remain available. An unusable `.cpg` or -`.cst` gives a diagnostic before falling back to the next source. Supplying a usable `.cpg` or -`.cst` bypasses the LDID and its unsupported-code-page diagnostic. A note identifies an encoding -taken from a `.cst`. +bytes become replacement characters, and the records remain available. When RustGIS checks an +unusable declaration, it gives a diagnostic before falling back to the next source. When a `.cst` supplies the +encoding, RustGIS reports its label and decoder. A resolvable LDID that names a different +decoder gives an encoding-loss notice. A single-byte decoder can read UTF-8 bytes as different +characters, so RustGIS also warns if every field name and value it examined is valid UTF-8 and +any of them contains non-ASCII bytes. An in-place read checks the rows it visits. Both notices +fail a strict read and signal that the declaration should be checked before publishing. + +On disk, a declaration must be a regular file or a link to one. If a regular `.cst` is +temporarily locked by a file lease, RustGIS gives the holder a brief chance to release it. +A `.cst` that stays unreadable gives a fallback notice. A leased regular `.cpg` can wait for +the lease to end, as before. Whenever text is read as UTF-8 (the markers in this section, unknown markers, `00`, `F0` or a UTF-8 `.cpg` or `.cst`), a notice counts the text values whose bytes aren't valid UTF-8 and names their From 6e11cf502c52f023773d8a85c664e3d839e1d102 Mon Sep 17 00:00:00 2001 From: mavrick Date: Sun, 29 Nov 2026 12:40:59 -0600 Subject: [PATCH 05/12] fix(data): advise about unused CST encoding declarations --- apps/rustgis-web/src/web.rs | 8 +- crates/data/src/dbf.rs | 112 +++++++++++++++++- crates/data/src/io.rs | 56 +++++++-- crates/data/src/provenance.rs | 7 +- crates/data/src/source/shp.rs | 1 + .../tests/integration/shapefile_encoding.rs | 91 ++++++++++++++ docs/user-guide/data.md | 9 +- 7 files changed, 269 insertions(+), 15 deletions(-) diff --git a/apps/rustgis-web/src/web.rs b/apps/rustgis-web/src/web.rs index bb6088b34a..72f4e6ee09 100644 --- a/apps/rustgis-web/src/web.rs +++ b/apps/rustgis-web/src/web.rs @@ -45,6 +45,7 @@ const DATA_EXTS: &[&str] = &[ "shx", "prj", "cpg", + "cst", "kml", "kmz", "gpx", @@ -543,6 +544,11 @@ async fn read_together(mut files: Vec, mark: &str, inbox: &Inbox, let mut too_large = Vec::new(); for file in files { let name = file.name(); + // Data sidecars travel as presence markers; script and tool pickers keep their own reads. + if (mark.is_empty() || mark == rustgis_ui_egui::SHAPEFILE_PICK) && name.to_ascii_lowercase().ends_with(".cst") { + read.push((name, Vec::new())); + continue; + } let shortcut = mark == rustgis_ui_egui::SHORTCUT_PICK || (mark.is_empty() && name.to_ascii_lowercase().ends_with(".rgisshortcuts")); if shortcut && file.size() > rustgis_ui_egui::SHORTCUT_FILE_MAX_BYTES as f64 { notes @@ -1401,7 +1407,7 @@ fn services(inbox: Inbox, font_inbox: Inbox, notes: Notes, ctx: egui::Context, e } else if purpose == "script" { rfd::AsyncFileDialog::new().add_filter(rustgis_ui_egui::tl!("Script"), &["txt"]) } else if purpose == "shapefile" { - rfd::AsyncFileDialog::new().add_filter("Shapefile", &["shp", "dbf", "shx", "prj", "cpg", "zip"]) + rfd::AsyncFileDialog::new().add_filter("Shapefile", &["shp", "dbf", "shx", "prj", "cpg", "cst", "zip"]) } else if let Some(exts) = crate::picker::filter_extensions(purpose) { let label = if purpose == "project" { rustgis_ui_egui::tl!("Projects and JSON data (RustGIS, QGIS, GeoLibre)") diff --git a/crates/data/src/dbf.rs b/crates/data/src/dbf.rs index 2910ca7b55..dc3877f683 100644 --- a/crates/data/src/dbf.rs +++ b/crates/data/src/dbf.rs @@ -431,6 +431,24 @@ pub(crate) fn date(field: &[u8]) -> std::result::Result, ldid: u8, present: impl FnOnce() -> bool, notes: &mut crate::loss::Notes) { + let usable_cpg = cpg + .filter(|b| b.len() <= MAX_CPG_BYTES) + .and_then(|b| std::str::from_utf8(b).ok()) + .and_then(|s| DbfEncoding::from_name(s.trim().trim_start_matches('\u{feff}').trim())) + .is_some(); + if !usable_cpg && 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, copy that label into a same-basename .cpg and reopen the data; otherwise confirm the encoding with the provider")); + } +} + +/// Checks only names, including unreadable files and symlinks, without opening optional CST. +pub(crate) fn has_cst(path: &std::path::Path) -> bool { + ["cst", "CST", "Cst", "cSt", "csT", "CSt", "CsT", "cST"].iter().any(|ext| std::fs::symlink_metadata(path.with_extension(ext)).is_ok()) +} + /// 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) -> Option> { match try_read_cpg(path) { @@ -445,14 +463,23 @@ pub(crate) fn read_cpg(path: &std::path::Path, notes: &mut crate::loss::Notes) - } /// Every ASCII case of the `.cpg` extension, the conventional spellings first: tried in turn, -/// without scanning a potentially large directory, and the first there wins. +/// without scanning a potentially large directory. Non-file spellings are skipped; the first +/// regular file wins. pub(crate) const CPG_SPELLINGS: [&str; 8] = ["cpg", "CPG", "Cpg", "cPg", "cpG", "CPg", "CpG", "cPG"]; +/// Skips special-file spellings, retaining an unusable-declaration notice if none is regular. fn try_read_cpg(path: &std::path::Path) -> std::io::Result>> { use std::io::Read; + let mut non_file = false; for ext in CPG_SPELLINGS { - match crate::provenance::open(path.with_extension(ext)) { - Ok(file) => { + let candidate = path.with_extension(ext); + match open_cpg(&candidate) { + Ok(None) => { + non_file = true; + continue; + } + Ok(Some(file)) => { + crate::provenance::opened(&candidate, &file); let mut bytes = Vec::new(); (&file).take(MAX_CPG_BYTES as u64 + 1).read_to_end(&mut bytes)?; if bytes.len() <= MAX_CPG_BYTES { @@ -464,13 +491,92 @@ fn try_read_cpg(path: &std::path::Path) -> std::io::Result>> { Err(e) => return Err(e), } } + if non_file { + return Err(std::io::Error::other("not a regular file")); + } Ok(None) } +/// Checks before and after opening. Unix nonblocking open covers a FIFO swapped in between; +/// ordinary regular-file leases still wait, as before, with cancellation between attempts. +fn open_cpg(path: &std::path::Path) -> std::io::Result> { + if !std::fs::metadata(path)?.is_file() { + return Ok(None); + } + #[cfg(unix)] + let file = loop { + use rustix::fs::{Mode, OFlags, open}; + match open(path, OFlags::RDONLY | OFlags::NONBLOCK | OFlags::CLOEXEC | OFlags::NOCTTY, Mode::empty()) { + Ok(fd) => break std::fs::File::from(fd), + Err(rustix::io::Errno::AGAIN) => { + crate::progress::check().map_err(std::io::Error::other)?; + std::thread::sleep(std::time::Duration::from_millis(20)); + } + Err(e) => return Err(e.into()), + } + }; + #[cfg(not(unix))] + let file = std::fs::File::open(path)?; + Ok(file.metadata()?.is_file().then_some(file)) +} + #[cfg(test)] mod tests { use super::*; + /// Run a potentially blocking read in a child so a regression fails within a bounded wait. + #[cfg(unix)] + #[test] + fn cpg_special_files_do_not_block() { + use std::process::{Command, Stdio}; + if std::env::var_os("RUSTGIS_CPG_CHILD").is_some() { + let dir = tempfile::tempdir().unwrap(); + 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()), Some(Vec::new())); + // A rejected spelling must not hide a later regular one. + std::fs::write(path.with_extension("CpG"), b"1252").unwrap(); + assert_eq!(read_cpg(&path, &mut crate::loss::Notes::new()), Some(b"1252".to_vec())); + std::fs::remove_file(&cpg).unwrap(); + std::fs::remove_file(path.with_extension("CpG")).unwrap(); + let socket = std::os::unix::net::UnixListener::bind(&cpg).unwrap(); + assert_eq!(read_cpg(&path, &mut crate::loss::Notes::new()), Some(Vec::new())); + drop(socket); + std::fs::remove_file(&cpg).unwrap(); + std::fs::create_dir(&cpg).unwrap(); + assert_eq!(read_cpg(&path, &mut crate::loss::Notes::new()), Some(Vec::new())); + 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()), Some(Vec::new())); + 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()), Some(b"1252".to_vec())); + return; + } + let mut child = Command::new(std::env::current_exe().unwrap()) + .args(["--exact", "dbf::tests::cpg_special_files_do_not_block", "--nocapture"]) + .env("RUSTGIS_CPG_CHILD", "1") + .stdout(Stdio::inherit()) + .stderr(Stdio::inherit()) + .spawn() + .unwrap(); + let until = std::time::Instant::now() + std::time::Duration::from_secs(3); + loop { + if let Some(status) = child.try_wait().unwrap() { + assert!(status.success()); + break; + } + if std::time::Instant::now() >= until { + child.kill().unwrap(); + child.wait().unwrap(); + panic!("CPG read blocked on a special file"); + } + std::thread::sleep(std::time::Duration::from_millis(10)); // test-wait: bound a child that may hang on the FIFO; no completion signal on failure. + } + } + /// A `.dbf` date is a day, blank or zeros are empty, and anything else isn't a date. #[test] fn dbf_dates() { diff --git a/crates/data/src/io.rs b/crates/data/src/io.rs index 9ef8f4c54e..4efe951eff 100644 --- a/crates/data/src/io.rs +++ b/crates/data/src/io.rs @@ -530,7 +530,9 @@ pub fn read_path(path: &Path) -> Result<(Dataset, ReadReport)> { check_size(path)?; let mut notes = crate::loss::Notes::new(); let cpg = crate::dbf::read_cpg(path, &mut notes); - let (ds, mut report) = read_dbf(std::fs::read(path)?, cpg.as_deref(), &name, &mut csv_memory_budget())?; + 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 (ds, mut report) = read_dbf(bytes, cpg.as_deref(), &name, &mut csv_memory_budget())?; report.messages.extend(notes.prefixed(&name)); (ds, report) } @@ -4162,6 +4164,7 @@ pub fn read_shapefile_in(path: &Path, name: &str, crs: Option) -> Result<(D 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 (ds, mut report) = read_shapefile_parts(parts, name, crs)?; report.messages.extend(notes.prefixed(name)); Ok((ds, report)) @@ -4172,9 +4175,9 @@ const SHAPEFILE_SIDECARS: [&str; 4] = ["dbf", "shx", "prj", "cpg"]; /// Gathers each Shapefile among files given together (several picked at once in the browser, or /// dropped at once) into a zip that reads as a zipped Shapefile: a `.shp` with the `.dbf` of the -/// same base name, ignoring case, and its `.shx`, `.prj` and `.cpg` when they are there. The zip, +/// same base name, ignoring case, and its `.shx`, `.prj`, `.cpg` and `.cst` when they are there. The zip, /// named after the `.shp`, takes its place; its parts go. Other files, and a `.shp` without its -/// `.dbf`, pass through as they came. A standalone `.dbf` with a `.cpg` is zipped with it too. +/// `.dbf`, pass through as they came. A standalone `.dbf` with a `.cpg` or `.cst` is zipped with it too. /// Files whose parts are too large to read together (more than [`max_bytes`], or the zip /// reader's limit) are left out, with an explanation in the messages returned with the files. pub fn gather_shapefiles(files: Vec<(String, Vec)>) -> (Vec<(String, Vec)>, Vec) { @@ -4185,7 +4188,13 @@ pub fn gather_shapefiles(files: Vec<(String, Vec)>) -> (Vec<(String, Vec }; // Files are taken out as they're zipped, so none is copied twice; each zip goes where its // `.shp` was. - let mut files: Vec)>> = files.into_iter().map(Some).collect(); + let mut files: Vec)>> = files + .into_iter() + .map(|(n, b)| { + let bytes = if ext_of(&n) == "cst" { Vec::new() } else { b }; + Some((n, bytes)) + }) + .collect(); let mut zips: Vec)>>> = files.iter().map(|_| None).collect(); for i in 0..files.len() { let Some(base) = files.get(i).and_then(Option::as_ref).filter(|(n, _)| ext_of(n) == "shp").map(|(n, _)| stem(n)) else { @@ -4195,7 +4204,7 @@ pub fn gather_shapefiles(files: Vec<(String, Vec)>) -> (Vec<(String, Vec continue; } let mut parts: Vec<(String, Vec)> = files.get_mut(i).and_then(Option::take).into_iter().collect(); - for ext in SHAPEFILE_SIDECARS { + for ext in SHAPEFILE_SIDECARS.into_iter().chain(["cst"]) { if let Some(part) = sidecar(&files, &base, ext).and_then(|j| files.get_mut(j)).and_then(Option::take) { parts.push(part); } @@ -4209,9 +4218,14 @@ pub fn gather_shapefiles(files: Vec<(String, Vec)>) -> (Vec<(String, Vec let Some(base) = files.get(i).and_then(Option::as_ref).filter(|(n, _)| ext_of(n) == "dbf").map(|(n, _)| stem(n)) else { continue; }; - let Some(j) = sidecar(&files, &base, "cpg") else { continue }; + let companions: Vec<_> = ["cpg", "cst"].iter().filter_map(|ext| sidecar(&files, &base, ext)).collect(); + if companions.is_empty() { + continue; + } let mut parts: Vec<_> = files.get_mut(i).and_then(Option::take).into_iter().collect(); - parts.extend(files.get_mut(j).and_then(Option::take)); + for j in companions { + parts.extend(files.get_mut(j).and_then(Option::take)); + } if let Some(slot) = zips.get_mut(i) { *slot = Some(parts); } @@ -4421,6 +4435,7 @@ 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); + let cst_names = std::cell::RefCell::new(std::collections::BTreeSet::new()); let wanted = |n: &str| { if crate::progress::check().is_err() { return false; @@ -4430,6 +4445,10 @@ fn read_zip_layers_budget(file_name: &str, bytes: &[u8], opts: &CsvOptions, budg return false; } let e = ext_of(n); + if e == "cst" && !is_resource_fork(n) { + cst_names.borrow_mut().insert(lower(n)); + return false; // Presence only: never inflate or validate this optional member. + } !is_resource_fork(n) && (matches!(e.as_str(), "shp" | "shx" | "dbf" | "prj" | "cpg" | "mid") || (e == "pbf" && lower(n).ends_with(".osm.pbf")) @@ -4447,6 +4466,7 @@ fn read_zip_layers_budget(file_name: &str, bytes: &[u8], opts: &CsvOptions, budg let take = |entries: &mut Vec)>>, base: &str, ext: &str| -> Option<(String, Vec)> { entries.iter_mut().find(|e| e.as_ref().is_some_and(|(n, _)| ext_of(n) == ext && stem(n) == base))?.take() }; + 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(); @@ -4469,8 +4489,16 @@ fn read_zip_layers_budget(file_name: &str, bytes: &[u8], opts: &CsvOptions, budg skipped.push(format!("{n} (no .dbf beside it)")); continue; }; + let mut advisory = crate::loss::Notes::new(); + crate::dbf::unused_cst( + cpg.as_deref(), + dbf.get(29).copied().unwrap_or(0), + || cst_names.contains(&format!("{base}.cst")), + &mut advisory, + ); match read_shapefile_parts(ShapefileParts { shp, shx, dbf, prj, cpg }, &name, crs) { - Ok((mut dataset, report)) => { + Ok((mut dataset, mut report)) => { + report.messages.extend(advisory.prefixed(&name)); dataset.source = Some(format!("{file_name}/{n}")); out.push(LayerRead { dataset, report, styles: Vec::new() }); } @@ -4537,7 +4565,17 @@ fn read_zip_layers_budget(file_name: &str, bytes: &[u8], opts: &CsvOptions, budg let read = if ext_of(&n) == "dbf" { let cpg = take(&mut entries, &stem(&n), "cpg").map(|(_, b)| b); let name = Path::new(leaf).file_stem().and_then(|s| s.to_str()).unwrap_or("table"); - read_dbf(b, cpg.as_deref(), name, budget).map(|r| plain(vec![r])) + let mut advisory = crate::loss::Notes::new(); + crate::dbf::unused_cst( + cpg.as_deref(), + b.get(29).copied().unwrap_or(0), + || cst_names.contains(&format!("{}.cst", stem(&n))), + &mut advisory, + ); + read_dbf(b, cpg.as_deref(), name, budget).map(|(ds, mut report)| { + report.messages.extend(advisory.prefixed(name)); + plain(vec![(ds, report)]) + }) } else if is_city_model(leaf, &b) { read_city_member(leaf, &b, crs).map(plain) } else if is_delimited_name(leaf) { diff --git a/crates/data/src/provenance.rs b/crates/data/src/provenance.rs index 535372aafd..08f76ec87c 100644 --- a/crates/data/src/provenance.rs +++ b/crates/data/src/provenance.rs @@ -357,13 +357,18 @@ pub(crate) fn hashed(path: &Path, metadata: Option<&Metadata>, sha256: String) { pub fn open(path: impl AsRef) -> std::io::Result { let path = path.as_ref(); let file = File::open(path)?; + opened(path, &file); + Ok(file) +} + +/// Records an already opened input from its handle, including a caller's specialized safe open. +pub(crate) fn opened(path: &Path, file: &File) { if active() { let metadata = file.metadata().ok(); if metadata.as_ref().is_none_or(Metadata::is_file) { observe(path, metadata.as_ref(), None); } } - Ok(file) } /// Reads once; a cheap digest uses those bytes, never a second file read. diff --git a/crates/data/src/source/shp.rs b/crates/data/src/source/shp.rs index d063459f0b..9a49e65645 100644 --- a/crates/data/src/source/shp.rs +++ b/crates/data/src/source/shp.rs @@ -147,6 +147,7 @@ impl ShpSource { let mut notes = crate::loss::Notes::new(); let table = read_table(&dbf)?; let cpg = crate::dbf::read_cpg(path, &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(); if shp_len > u64::from(u32::MAX) { diff --git a/crates/data/tests/integration/shapefile_encoding.rs b/crates/data/tests/integration/shapefile_encoding.rs index af15695003..656c422f37 100644 --- a/crates/data/tests/integration/shapefile_encoding.rs +++ b/crates/data/tests/integration/shapefile_encoding.rs @@ -796,3 +796,94 @@ fn malformed_values_are_counted_per_value_and_clean_text_says_nothing() { assert_eq!(texts(&rustgis_data::source::materialize(&src).unwrap().1.messages), [invalid_note(1, "name", "Shift_JIS")]); } } + +/// 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] +fn unused_cst_advises_without_changing_decoding() { + #[cfg(not(target_arch = "wasm32"))] + use rustgis_data::source::FeatureSource; + let advisory = |notes: &rustgis_data::loss::Notes, expected: bool| { + let found: Vec<_> = notes.iter().filter(|n| n.contains("unused .cst")).collect(); + assert_eq!(found.len(), usize::from(expected), "{notes:?}"); + if expected { + assert!(found[0].contains("trusted") && found[0].contains(".cpg and reopen")); + assert_eq!(found[0].loss, None); + } + }; + for (ldid, cpg, warn) in [ + (0, None, true), + (0x6c, None, true), + (0, Some(b"bogus".as_slice()), true), + (0, Some(b"1252".as_slice()), false), + (0x57, None, false), + (0xf0, None, false), + (0xc9, None, false), + ] { + let baseline = parts(b"Mu\xf1oz", ldid, cpg); + let mut with = baseline.clone(); + with.push(("places.CsT".into(), b"1252".to_vec())); + let same = |a: &Dataset, b: &Dataset| { + assert_eq!(names(a), names(b)); + assert_eq!(a.fields, b.fields); + assert_eq!(a.features.row(0).unwrap().geometry(), b.features.row(0).unwrap().geometry()); + }; + let base = io::read_zip("places.zip", &rustgis_data::zip::write(&baseline).unwrap()).unwrap(); + advisory(&base[0].1.messages, false); + let read = io::read_zip("places.zip", &rustgis_data::zip::write(&with).unwrap()).unwrap(); + same(&base[0].0, &read[0].0); + advisory(&read[0].1.messages, warn); + let (gathered, problems) = io::gather_shapefiles(with.clone()); + assert!(problems.is_empty()); + assert_eq!(gathered.len(), 1); + let gathered = io::read_zip(&gathered[0].0, &gathered[0].1).unwrap(); + same(&base[0].0, &gathered[0].0); + advisory(&gathered[0].1.messages, warn); + let table: Vec<_> = with.iter().filter(|(n, _)| n.ends_with("dbf") || n.ends_with("cpg") || n.ends_with("CsT")).cloned().collect(); + let (gathered, problems) = io::gather_shapefiles(table); + assert!(problems.is_empty()); + let table = io::read_zip(&gathered[0].0, &gathered[0].1).unwrap(); + assert_eq!(names(&base[0].0), names(&table[0].0)); + advisory(&table[0].1.messages, warn); + #[cfg(not(target_arch = "wasm32"))] + { + let dir = tempfile::tempdir().unwrap(); + for (n, b) in with { + std::fs::write(dir.path().join(n), b).unwrap(); + } + let path = dir.path().join("places.shp"); + let (whole, report) = io::read_path(&path).unwrap(); + same(&base[0].0, &whole); + advisory(&report.messages, warn); + let src = open_shp(&path, "places").unwrap(); + advisory(&src.info().notes, warn); + let (streamed, _) = rustgis_data::source::materialize(&src).unwrap(); + same(&base[0].0, &streamed); + let (table, report) = io::read_path(&path.with_extension("dbf")).unwrap(); + assert_eq!(names(&whole), names(&table)); + advisory(&report.messages, warn); + // Presence needs no read permission and never observes CST as an input. + let capture = rustgis_data::provenance::Capture::start(); + io::read_path(&path).unwrap(); + assert!(!capture.inputs().iter().any(|i| i.path.ends_with("CsT"))); + } + } +} + +/// An optional CST with an unreadable ZIP body must not turn a valid layer into a failure. +#[test] +fn damaged_cst_zip_body_is_not_read() { + let mut files = parts(b"plain", 0, None); + files.push(("places.cst".into(), vec![b'x'; 100])); + let mut zip = rustgis_data::zip::write(&files).unwrap(); + // Unsupported compression in its central record would fail if this member were requested. + let at = zip + .windows(4) + .enumerate() + .find_map(|(at, b)| (b == b"PK\x01\x02" && zip.get(at + 46..at + 56) == Some(b"places.cst")).then_some(at)) + .unwrap(); + zip[at + 10..at + 12].copy_from_slice(&99u16.to_le_bytes()); + let read = io::read_zip("places.zip", &zip).unwrap(); + assert_eq!(names(&read[0].0), [Value::Text("plain".into())]); + assert_eq!(read[0].1.messages.iter().filter(|n| n.contains("unused .cst")).count(), 1); +} diff --git a/docs/user-guide/data.md b/docs/user-guide/data.md index cf024a9d75..28ade4d6b9 100644 --- a/docs/user-guide/data.md +++ b/docs/user-guide/data.md @@ -305,7 +305,14 @@ nothing. The datum's ellipsoid is retained for datum transformations and exported coordinate system definitions. Shapefile text uses a supported `.cpg` encoding, otherwise the `.dbf` code page, with UTF-8 as -the fallback. Keep the sidecar files together. A shape with a coordinate that isn't a number (NaN, +the fallback. Keep the sidecar files together. RustGIS does not decode using `.cst`. When neither +a usable `.cpg` nor a supported DBF language driver declares the encoding, an accompanying +`.cst` produces an advisory: if you trust its encoding label, copy that label into a +same-basename `.cpg` and reopen the data, or confirm the encoding with the provider. This applies +to local whole and streamed Shapefiles, standalone DBF files, ZIP members, and loose browser +files picked together. CST contents are never read. Loose URL imports do not probe for CST; +a downloaded ZIP can report it from the member names. The advisory changes no decoded values, +saved project data, sync tracking or Publish behavior. A shape with a coordinate that isn't a number (NaN, which some programs write for an empty point, or an infinity) has no place: its feature keeps its attributes without geometry, and a notice says how many (a large Shapefile read in place on the desktop leaves the whole record out, counted with its unreadable shapes). A project, project package or map package is never saved with such a From c3a47db77f4dcdf2c1af21cdd072a000425bb005 Mon Sep 17 00:00:00 2001 From: mavrick Date: Sun, 29 Nov 2026 17:17:14 -0600 Subject: [PATCH 06/12] fix(data): retain picker payloads and refuse special Publish parts --- crates/data/src/dbf.rs | 4 +-- crates/data/src/io.rs | 26 ++++++++++----- crates/data/src/publish.rs | 67 +++++++++++++++++++++++++++++++++++--- 3 files changed, 81 insertions(+), 16 deletions(-) diff --git a/crates/data/src/dbf.rs b/crates/data/src/dbf.rs index dc3877f683..8699238b81 100644 --- a/crates/data/src/dbf.rs +++ b/crates/data/src/dbf.rs @@ -473,7 +473,7 @@ fn try_read_cpg(path: &std::path::Path) -> std::io::Result>> { let mut non_file = false; for ext in CPG_SPELLINGS { let candidate = path.with_extension(ext); - match open_cpg(&candidate) { + match open_regular_file(&candidate) { Ok(None) => { non_file = true; continue; @@ -499,7 +499,7 @@ fn try_read_cpg(path: &std::path::Path) -> std::io::Result>> { /// Checks before and after opening. Unix nonblocking open covers a FIFO swapped in between; /// ordinary regular-file leases still wait, as before, with cancellation between attempts. -fn open_cpg(path: &std::path::Path) -> std::io::Result> { +pub(crate) fn open_regular_file(path: &std::path::Path) -> std::io::Result> { if !std::fs::metadata(path)?.is_file() { return Ok(None); } diff --git a/crates/data/src/io.rs b/crates/data/src/io.rs index 4efe951eff..e28885374f 100644 --- a/crates/data/src/io.rs +++ b/crates/data/src/io.rs @@ -4188,13 +4188,12 @@ pub fn gather_shapefiles(files: Vec<(String, Vec)>) -> (Vec<(String, Vec }; // Files are taken out as they're zipped, so none is copied twice; each zip goes where its // `.shp` was. - let mut files: Vec)>> = files - .into_iter() - .map(|(n, b)| { - let bytes = if ext_of(&n) == "cst" { Vec::new() } else { b }; - Some((n, bytes)) - }) - .collect(); + let mut files: Vec)>> = files.into_iter().map(Some).collect(); + // Only actual companions become presence markers; unrelated picker payloads pass through. + let marker = |(name, bytes): (String, Vec)| { + let bytes = if ext_of(&name) == "cst" { Vec::new() } else { bytes }; + (name, bytes) + }; let mut zips: Vec)>>> = files.iter().map(|_| None).collect(); for i in 0..files.len() { let Some(base) = files.get(i).and_then(Option::as_ref).filter(|(n, _)| ext_of(n) == "shp").map(|(n, _)| stem(n)) else { @@ -4206,7 +4205,7 @@ pub fn gather_shapefiles(files: Vec<(String, Vec)>) -> (Vec<(String, Vec let mut parts: Vec<(String, Vec)> = files.get_mut(i).and_then(Option::take).into_iter().collect(); for ext in SHAPEFILE_SIDECARS.into_iter().chain(["cst"]) { if let Some(part) = sidecar(&files, &base, ext).and_then(|j| files.get_mut(j)).and_then(Option::take) { - parts.push(part); + parts.push(marker(part)); } } if let Some(slot) = zips.get_mut(i) { @@ -4224,7 +4223,7 @@ pub fn gather_shapefiles(files: Vec<(String, Vec)>) -> (Vec<(String, Vec } let mut parts: Vec<_> = files.get_mut(i).and_then(Option::take).into_iter().collect(); for j in companions { - parts.extend(files.get_mut(j).and_then(Option::take)); + parts.extend(files.get_mut(j).and_then(Option::take).map(marker)); } if let Some(slot) = zips.get_mut(i) { *slot = Some(parts); @@ -11001,6 +11000,15 @@ mod tests { assert!(note.contains("m51.mif") && !note.contains("m52.mif") && note.ends_with("; and 5 more"), "{note:?}"); } + /// Files unrelated to a gathered Shapefile retain their payload, regardless of extension. + #[test] + fn gathering_keeps_unmatched_cst_payload() { + let files = vec![("model.cst".to_string(), b"map.zoomFull".to_vec())]; + let (gathered, notes) = gather_shapefiles(files.clone()); + assert_eq!(gathered, files); + assert!(notes.is_empty()); + } + /// A Shapefile's loose files picked or dropped together are zipped into one, which reads as a /// layer; parts of different Shapefiles stay apart, and other files pass through. #[test] diff --git a/crates/data/src/publish.rs b/crates/data/src/publish.rs index ed247e0fa3..45beb53df1 100644 --- a/crates/data/src/publish.rs +++ b/crates/data/src/publish.rs @@ -153,12 +153,24 @@ struct Original { /// Reads an original file at `p`, `None` when absent. The caller supplies format-specific size advice. fn read_part(p: &Path, size_error: fn(&str, u64) -> String) -> Result>> { - match std::fs::metadata(p) { - Ok(m) if m.len() > crate::io::max_bytes() => Err(DataError::Format(size_error(&p.to_string_lossy(), crate::io::max_bytes()))), - Ok(_) => Ok(Some(std::fs::read(p)?)), - Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(None), - Err(e) => Err(e.into()), + use std::io::Read; + let file = match crate::dbf::open_regular_file(p) { + Ok(Some(file)) => file, + Ok(None) => return Err(refused(p, "not a regular file")), + Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(None), + Err(e) => return Err(e.into()), + }; + let max = crate::io::max_bytes(); + let too_large = || DataError::Format(size_error(&p.to_string_lossy(), max)); + if file.metadata()?.len() > max { + return Err(too_large()); + } + let mut bytes = Vec::new(); + file.take(max.saturating_add(1)).read_to_end(&mut bytes)?; + if bytes.len() as u64 > max { + return Err(too_large()); } + Ok(Some(bytes)) } impl Original { @@ -961,6 +973,51 @@ mod tests { (read.0, Synced { files: files.unwrap(), rows, native: None }) } + /// Publishing must refuse a skipped FIFO spelling without waiting for a pipe writer. + #[cfg(unix)] + #[test] + fn publish_cpg_fifo_does_not_block() { + use std::process::Command; + if std::env::var_os("RUSTGIS_PUBLISH_CPG_CHILD").is_some() { + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("parcels.shp"); + written(&parcels(), &path); + std::fs::remove_file(path.with_extension("cpg")).unwrap(); + assert!(Command::new("mkfifo").arg(path.with_extension("cpg")).status().unwrap().success()); + // The two spellings are distinct only on a case-sensitive filesystem. + if path.with_extension("CPG").exists() { + return; + } + std::fs::write(path.with_extension("CPG"), b"UTF-8").unwrap(); + let (mut ds, sync) = read(&path); + assert!(sync.files.changed(&path).unwrap().is_empty()); + ds.features.set_value(0, 0, Value::Text("Smyth".into())); + let before = std::fs::read(path.with_extension("dbf")).unwrap(); + let error = shapefile(&ds, &path, &sync).err().unwrap().to_string(); + assert!(error.contains("regular file"), "{error}"); + assert_eq!(std::fs::read(path.with_extension("dbf")).unwrap(), before); + return; + } + let mut child = Command::new(std::env::current_exe().unwrap()) + .args(["--exact", "publish::tests::publish_cpg_fifo_does_not_block", "--nocapture"]) + .env("RUSTGIS_PUBLISH_CPG_CHILD", "1") + .spawn() + .unwrap(); + let until = std::time::Instant::now() + std::time::Duration::from_secs(3); + loop { + if let Some(status) = child.try_wait().unwrap() { + assert!(status.success()); + break; + } + if std::time::Instant::now() >= until { + child.kill().unwrap(); + child.wait().unwrap(); + panic!("Publish blocked on a CPG FIFO"); + } + std::thread::sleep(std::time::Duration::from_millis(10)); // test-wait: bound the child when a FIFO blocks Publish; no completion signal on failure. + } + } + /// An edit is written back: the file reads as the layer, keeps its columns and `.prj`, and /// its new record matches the files as they are. #[test] From c2c80f42d322cd4229dbcce99ed766d97c23197e Mon Sep 17 00:00:00 2001 From: mavrick Date: Sun, 29 Nov 2026 18:03:39 -0600 Subject: [PATCH 07/12] test(data): skip the FIFO alias on case-insensitive filesystems --- crates/data/src/dbf.rs | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/crates/data/src/dbf.rs b/crates/data/src/dbf.rs index 8699238b81..de765b9fa1 100644 --- a/crates/data/src/dbf.rs +++ b/crates/data/src/dbf.rs @@ -536,10 +536,13 @@ mod tests { assert!(Command::new("mkfifo").arg(&cpg).status().unwrap().success()); assert_eq!(read_cpg(&path, &mut crate::loss::Notes::new()), Some(Vec::new())); // A rejected spelling must not hide a later regular one. - std::fs::write(path.with_extension("CpG"), b"1252").unwrap(); - assert_eq!(read_cpg(&path, &mut crate::loss::Notes::new()), Some(b"1252".to_vec())); + // 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()), Some(b"1252".to_vec())); + std::fs::remove_file(path.with_extension("CpG")).unwrap(); + } std::fs::remove_file(&cpg).unwrap(); - std::fs::remove_file(path.with_extension("CpG")).unwrap(); let socket = std::os::unix::net::UnixListener::bind(&cpg).unwrap(); assert_eq!(read_cpg(&path, &mut crate::loss::Notes::new()), Some(Vec::new())); drop(socket); From f1885cf72bf0f3c911e2e008896760175cd3726e Mon Sep 17 00:00:00 2001 From: mavrick Date: Sun, 29 Nov 2026 18:14:31 -0600 Subject: [PATCH 08/12] fix(data): retain unrelated browser picks and protect CPG companions --- apps/rustgis-web/src/picker.rs | 15 +++++++++++++++ apps/rustgis-web/src/web.rs | 7 ++++++- crates/data/src/dbf.rs | 7 +++++-- crates/data/src/io.rs | 2 ++ .../data/tests/integration/shapefile_encoding.rs | 15 +++++++++++++++ crates/engine/src/cmd/gp.rs | 14 +++++++++++++- docs/user-guide/data.md | 4 +++- 7 files changed, 59 insertions(+), 5 deletions(-) diff --git a/apps/rustgis-web/src/picker.rs b/apps/rustgis-web/src/picker.rs index 1811bcf637..3db3aaa1f5 100644 --- a/apps/rustgis-web/src/picker.rs +++ b/apps/rustgis-web/src/picker.rs @@ -3,6 +3,12 @@ use rustgis_ui_egui::{GEOLIBRE_EXTS, ITEM_EXTS, PROJECT_EXTS}; +/// Names whose CST contents can be replaced by a presence marker during a data pick. +pub(crate) fn cst_markers(names: impl Iterator) -> std::collections::HashSet { + let names: std::collections::HashSet<_> = names.map(|name| name.to_ascii_lowercase()).collect(); + names.iter().filter(|name| name.strip_suffix(".cst").is_some_and(|stem| names.contains(&format!("{stem}.dbf")))).cloned().collect() +} + /// Returns the static extension filter list for a named picker `purpose`, when it uses one. pub(crate) fn filter_extensions(purpose: &str) -> Option<&'static [&'static str]> { match purpose { @@ -18,6 +24,15 @@ pub(crate) fn filter_extensions(purpose: &str) -> Option<&'static [&'static str] mod tests { use super::*; + /// Unrelated CST files keep their payload; matched DBF companions need only their names. + #[test] + fn cst_markers_require_a_matching_table() { + let names = ["roads.SHP", "ROADS.dbf", "Roads.CsT", "notes.cst", "lone.shp", "lone.cst", "table.DBF", "table.cst"]; + let markers = cst_markers(names.into_iter().map(str::to_string)); + assert_eq!(markers, ["roads.cst".to_string(), "table.cst".to_string()].into_iter().collect()); + assert!(cst_markers(["notes.cst".to_string()].into_iter()).is_empty()); + } + /// The browser picker re-exports `ui-egui`'s canonical project and item extension slices. #[test] fn browser_picker_extensions_match_ui_egui_lists() { diff --git a/apps/rustgis-web/src/web.rs b/apps/rustgis-web/src/web.rs index 72f4e6ee09..6010019198 100644 --- a/apps/rustgis-web/src/web.rs +++ b/apps/rustgis-web/src/web.rs @@ -541,11 +541,16 @@ async fn read_together(mut files: Vec, mark: &str, inbox: &Inbox, ); notes.lock().unwrap_or_else(|e| e.into_inner()).push((text, true)); } + let markers = if mark.is_empty() || mark == rustgis_ui_egui::SHAPEFILE_PICK { + crate::picker::cst_markers(files.iter().map(|file| file.name())) + } else { + Default::default() + }; let mut too_large = Vec::new(); for file in files { let name = file.name(); // Data sidecars travel as presence markers; script and tool pickers keep their own reads. - if (mark.is_empty() || mark == rustgis_ui_egui::SHAPEFILE_PICK) && name.to_ascii_lowercase().ends_with(".cst") { + if markers.contains(&name.to_ascii_lowercase()) { read.push((name, Vec::new())); continue; } diff --git a/crates/data/src/dbf.rs b/crates/data/src/dbf.rs index de765b9fa1..431600dc0d 100644 --- a/crates/data/src/dbf.rs +++ b/crates/data/src/dbf.rs @@ -446,9 +446,12 @@ pub(crate) fn unused_cst(cpg: Option<&[u8]>, ldid: u8, present: impl FnOnce() -> /// Checks only names, including unreadable files and symlinks, without opening optional CST. pub(crate) fn has_cst(path: &std::path::Path) -> bool { - ["cst", "CST", "Cst", "cSt", "csT", "CSt", "CsT", "cST"].iter().any(|ext| std::fs::symlink_metadata(path.with_extension(ext)).is_ok()) + CST_SPELLINGS.iter().any(|ext| std::fs::symlink_metadata(path.with_extension(ext)).is_ok()) } +/// 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) -> Option> { match try_read_cpg(path) { @@ -465,7 +468,7 @@ pub(crate) fn read_cpg(path: &std::path::Path, notes: &mut crate::loss::Notes) - /// Every ASCII case of the `.cpg` extension, the conventional spellings first: tried in turn, /// without scanning a potentially large directory. Non-file spellings are skipped; the first /// regular file wins. -pub(crate) const CPG_SPELLINGS: [&str; 8] = ["cpg", "CPG", "Cpg", "cPg", "cpG", "CPg", "CpG", "cPG"]; +pub const CPG_SPELLINGS: [&str; 8] = ["cpg", "CPG", "Cpg", "cPg", "cpG", "CPg", "CpG", "cPG"]; /// Skips special-file spellings, retaining an unusable-declaration notice if none is regular. fn try_read_cpg(path: &std::path::Path) -> std::io::Result>> { diff --git a/crates/data/src/io.rs b/crates/data/src/io.rs index e28885374f..2040bf4866 100644 --- a/crates/data/src/io.rs +++ b/crates/data/src/io.rs @@ -13,6 +13,8 @@ use crate::capped::Limit; use crate::raster::{Crs, planetary}; use crate::{Coord, DataError, Dataset, Field, FieldType, Geometry, GeometryType, ReadReport, Result, Value}; +pub use crate::dbf::CPG_SPELLINGS; + /// Largest file read into memory in the browser, on a 32-bit build, or on a computer whose memory /// isn't known (256 MiB): the floor of [`max_bytes`]. Also where a file stops being read whole and /// is read in place instead (a GeoJSON file, a Shapefile), or handed to GDAL (an OpenStreetMap diff --git a/crates/data/tests/integration/shapefile_encoding.rs b/crates/data/tests/integration/shapefile_encoding.rs index 656c422f37..f4129f54fd 100644 --- a/crates/data/tests/integration/shapefile_encoding.rs +++ b/crates/data/tests/integration/shapefile_encoding.rs @@ -870,6 +870,21 @@ fn unused_cst_advises_without_changing_decoding() { } } +/// An unused declaration is informational even when all current text is ASCII. +#[test] +fn unused_cst_ascii_advisory_is_not_a_loss() { + let baseline = parts(b"plain", 0, None); + let mut with = baseline.clone(); + with.push(("places.cst".into(), b"1252".to_vec())); + let base = io::read_zip("places.zip", &rustgis_data::zip::write(&baseline).unwrap()).unwrap(); + let read = io::read_zip("places.zip", &rustgis_data::zip::write(&with).unwrap()).unwrap(); + assert_eq!(names(&base[0].0), names(&read[0].0)); + assert!(!base[0].1.messages.iter().any(|n| n.contains("unused .cst"))); + let notices: Vec<_> = read[0].1.messages.iter().filter(|n| n.contains("unused .cst")).collect(); + assert_eq!(notices.len(), 1); + assert_eq!(notices[0].loss, None); +} + /// An optional CST with an unreadable ZIP body must not turn a valid layer into a failure. #[test] fn damaged_cst_zip_body_is_not_read() { diff --git a/crates/engine/src/cmd/gp.rs b/crates/engine/src/cmd/gp.rs index 474c845b60..25e2562466 100644 --- a/crates/engine/src/cmd/gp.rs +++ b/crates/engine/src/cmd/gp.rs @@ -4076,8 +4076,10 @@ fn names_file(source: &str, destination: &std::path::Path) -> bool { return true; } let shapefile = source.extension().is_some_and(|e| e.eq_ignore_ascii_case("shp")); + let dbf = source.extension().is_some_and(|e| e.eq_ignore_ascii_case("dbf")); let companion = |ext: &str| source.with_extension(ext).canonicalize().is_ok_and(|p| p.as_path() == destination); - shapefile && ["dbf", "shx", "prj", "cpg"].iter().any(|&ext| companion(ext) || companion(ext.to_ascii_uppercase().as_str())) + (shapefile && ["dbf", "shx", "prj"].iter().any(|&ext| companion(ext) || companion(ext.to_ascii_uppercase().as_str()))) + || ((shapefile || dbf) && rustgis_data::io::CPG_SPELLINGS.iter().any(|ext| companion(ext))) } /// Adds a tool's table to the project under its name: in place of a table of that name, or, for @@ -5163,6 +5165,16 @@ mod file_tests { assert!(names_file(&archive.join("roads.shp").display().to_string(), &archive_file)); assert!(names_file(&root.join("roads.shp").display().to_string(), &companion_file)); assert!(!names_file(&root.join("roads.dbf").display().to_string(), &archive_file)); + // All reader spellings are protected, including standalone table declarations. + for extension in ["shp", "dbf"] { + let source = root.join(format!("roads.{extension}")); + std::fs::write(&source, b"source").unwrap(); + for ext in rustgis_data::io::CPG_SPELLINGS { + let declaration = source.with_extension(ext); + std::fs::write(&declaration, b"1252").unwrap(); + assert!(names_file(&source.to_string_lossy(), &declaration.canonicalize().unwrap()), "{extension}: {ext}"); + } + } std::fs::remove_dir_all(root).unwrap(); } diff --git a/docs/user-guide/data.md b/docs/user-guide/data.md index 2a799b0cd7..b9128b54bc 100644 --- a/docs/user-guide/data.md +++ b/docs/user-guide/data.md @@ -311,7 +311,9 @@ a usable `.cpg` nor a supported DBF language driver declares the encoding, an ac same-basename `.cpg` and reopen the data, or confirm the encoding with the provider. This applies to local whole and streamed Shapefiles, standalone DBF files, ZIP members, and loose browser files picked together. CST contents are never read. Loose URL imports do not probe for CST; -a downloaded ZIP can report it from the member names. The advisory changes no decoded values, +a downloaded ZIP can report it from the member names. This is an informational reminder about +unused metadata, including for ASCII-only text, rather than a report of changed or lost values. +The advisory changes no decoded values, saved project data, sync tracking or Publish behavior. A shape with a coordinate that isn't a number (NaN, which some programs write for an empty point, or an infinity) has no place: its feature keeps its attributes without geometry, and a notice says how many (a large Shapefile read in place on the From 526f7ec9654af8fba7d6c93e9d88af4ebc26f13c Mon Sep 17 00:00:00 2001 From: mavrick Date: Sun, 29 Nov 2026 18:53:52 -0600 Subject: [PATCH 09/12] fix(data): protect DBF spellings and ignore nonfile CST hints --- crates/data/src/dbf.rs | 26 ++++++++++++++++++++++++-- crates/data/src/io.rs | 9 ++++----- crates/engine/src/cmd/gp.rs | 10 +++++++++- 3 files changed, 37 insertions(+), 8 deletions(-) diff --git a/crates/data/src/dbf.rs b/crates/data/src/dbf.rs index 431600dc0d..9ec6d740b6 100644 --- a/crates/data/src/dbf.rs +++ b/crates/data/src/dbf.rs @@ -444,9 +444,9 @@ pub(crate) fn unused_cst(cpg: Option<&[u8]>, ldid: u8, present: impl FnOnce() -> } } -/// Checks only names, including unreadable files and symlinks, without opening optional CST. +/// Stats regular files and links to them, without opening optional CST contents. pub(crate) fn has_cst(path: &std::path::Path) -> bool { - CST_SPELLINGS.iter().any(|ext| std::fs::symlink_metadata(path.with_extension(ext)).is_ok()) + CST_SPELLINGS.iter().any(|ext| std::fs::metadata(path.with_extension(ext)).is_ok_and(|m| m.is_file())) } /// Every ASCII case of the optional CST hint's extension. @@ -527,6 +527,28 @@ pub(crate) fn open_regular_file(path: &std::path::Path) -> std::io::Result Option { ["shp", "SHP", "Shp", "sHp", "shP", "SHp", "ShP", "sHP"].iter().map(|e| path.with_extension(e)).find(|p| p.is_file()) } +/// Every ASCII case of a Shapefile attribute table's extension, in reader preference order. +pub const DBF_SPELLINGS: [&str; 8] = ["dbf", "DBF", "Dbf", "dBf", "dbF", "DBf", "DbF", "dBF"]; + /// Finds the attributes beside a Shapefile, accepting every ASCII case of `.dbf` in whole /// and streamed reads. A missing sidecar keeps the usual lowercase path for the error. pub fn dbf_sidecar(path: &Path) -> std::path::PathBuf { - ["dbf", "DBF", "Dbf", "dBf", "dbF", "DBf", "DbF", "dBF"] - .iter() - .map(|e| path.with_extension(e)) - .find(|p| p.is_file()) - .unwrap_or_else(|| path.with_extension("dbf")) + DBF_SPELLINGS.iter().map(|e| path.with_extension(e)).find(|p| p.is_file()).unwrap_or_else(|| path.with_extension("dbf")) } /// Reads a Shapefile with an optional source CRS replacing its `.prj`, before any geometry is diff --git a/crates/engine/src/cmd/gp.rs b/crates/engine/src/cmd/gp.rs index 25e2562466..7672e18184 100644 --- a/crates/engine/src/cmd/gp.rs +++ b/crates/engine/src/cmd/gp.rs @@ -4078,7 +4078,9 @@ fn names_file(source: &str, destination: &std::path::Path) -> bool { let shapefile = source.extension().is_some_and(|e| e.eq_ignore_ascii_case("shp")); let dbf = source.extension().is_some_and(|e| e.eq_ignore_ascii_case("dbf")); let companion = |ext: &str| source.with_extension(ext).canonicalize().is_ok_and(|p| p.as_path() == destination); - (shapefile && ["dbf", "shx", "prj"].iter().any(|&ext| companion(ext) || companion(ext.to_ascii_uppercase().as_str()))) + (shapefile + && (rustgis_data::io::DBF_SPELLINGS.iter().any(|ext| companion(ext)) + || ["shx", "prj"].iter().any(|&ext| companion(ext) || companion(ext.to_ascii_uppercase().as_str())))) || ((shapefile || dbf) && rustgis_data::io::CPG_SPELLINGS.iter().any(|ext| companion(ext))) } @@ -5175,6 +5177,12 @@ mod file_tests { assert!(names_file(&source.to_string_lossy(), &declaration.canonicalize().unwrap()), "{extension}: {ext}"); } } + // Attribute-table spelling follows the same list as the Shapefile reader too. + for ext in rustgis_data::io::DBF_SPELLINGS { + let table = root.join(format!("roads.{ext}")); + std::fs::write(&table, b"dbf").unwrap(); + assert!(names_file(&root.join("roads.shp").to_string_lossy(), &table.canonicalize().unwrap()), "{ext}"); + } std::fs::remove_dir_all(root).unwrap(); } From 8e6aba711cda71e87c02daeb2c72a2caf62fd4db Mon Sep 17 00:00:00 2001 From: mavrick Date: Sun, 29 Nov 2026 19:43:37 -0600 Subject: [PATCH 10/12] fix(data): preserve CPG cancellation and bound publish buffer growth --- crates/data/src/dbf.rs | 46 ++++++++++++++----- crates/data/src/io.rs | 4 +- crates/data/src/publish.rs | 17 ++++++- crates/data/src/source/shp.rs | 2 +- .../tests/integration/shapefile_encoding.rs | 2 +- docs/user-guide/data.md | 5 +- 6 files changed, 57 insertions(+), 19 deletions(-) diff --git a/crates/data/src/dbf.rs b/crates/data/src/dbf.rs index 9ec6d740b6..9a8c100c87 100644 --- a/crates/data/src/dbf.rs +++ b/crates/data/src/dbf.rs @@ -440,7 +440,7 @@ pub(crate) fn unused_cst(cpg: Option<&[u8]>, ldid: u8, present: impl FnOnce() -> .and_then(|s| DbfEncoding::from_name(s.trim().trim_start_matches('\u{feff}').trim())) .is_some(); if !usable_cpg && 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, copy that label into a same-basename .cpg and reopen the data; otherwise confirm the encoding with the provider")); + 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")); } } @@ -453,15 +453,21 @@ pub(crate) fn has_cst(path: &std::path::Path) -> bool { 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) -> Option> { - match try_read_cpg(path) { - Ok(bytes) => bytes, - Err(e) => { +pub(crate) fn read_cpg(path: &std::path::Path, notes: &mut crate::loss::Notes) -> crate::Result>> { + cpg_result(try_read_cpg(path), 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>> { + 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})"))); - Some(Vec::new()) + Ok(Some(Vec::new())) } + Err(e) => Err(e), } } @@ -527,6 +533,22 @@ pub(crate) fn open_regular_file(path: &std::path::Path) -> std::io::Result Result<(Dataset, ReadReport)> { "dbf" => { check_size(path)?; let mut notes = crate::loss::Notes::new(); - let cpg = crate::dbf::read_cpg(path, &mut notes); + 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 (ds, mut report) = read_dbf(bytes, cpg.as_deref(), &name, &mut csv_memory_budget())?; @@ -4163,7 +4163,7 @@ pub fn read_shapefile_in(path: &Path, name: &str, crs: Option) -> Result<(D 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), + 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 (ds, mut report) = read_shapefile_parts(parts, name, crs)?; diff --git a/crates/data/src/publish.rs b/crates/data/src/publish.rs index 45beb53df1..79b5410ea5 100644 --- a/crates/data/src/publish.rs +++ b/crates/data/src/publish.rs @@ -162,10 +162,13 @@ fn read_part(p: &Path, size_error: fn(&str, u64) -> String) -> Result max { + let len = file.metadata()?.len(); + if len > max { return Err(too_large()); } let mut bytes = Vec::new(); + let capacity = usize::try_from(len).map_err(|_| too_large())?; + bytes.try_reserve_exact(capacity).map_err(|e| std::io::Error::new(std::io::ErrorKind::OutOfMemory, e))?; file.take(max.saturating_add(1)).read_to_end(&mut bytes)?; if bytes.len() as u64 > max { return Err(too_large()); @@ -923,6 +926,18 @@ mod tests { use super::*; use crate::{Coord, Field, GeometryType}; + /// A part just above a growth boundary needs one part's storage, rather than double capacity. + #[test] + fn original_part_buffer_follows_the_file_length() { + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("part.dbf"); + let len = 1024 * 1024 + 1; + std::fs::File::create(&path).unwrap().set_len(len as u64).unwrap(); + let bytes = read_part(&path, crate::io::shapefile_size_error).unwrap().unwrap(); + assert_eq!(bytes.len(), len); + assert!(bytes.capacity() <= len + 4096, "{} bytes reserved for a {len}-byte part", bytes.capacity()); + } + /// A layer held in the file's own system (#2032 C2) is written as it is held; one held in /// another is converted from it, without matching the file as read in longitude/latitude. #[test] diff --git a/crates/data/src/source/shp.rs b/crates/data/src/source/shp.rs index 9a49e65645..53337cf7d3 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, &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/tests/integration/shapefile_encoding.rs b/crates/data/tests/integration/shapefile_encoding.rs index f4129f54fd..3c08a6fde3 100644 --- a/crates/data/tests/integration/shapefile_encoding.rs +++ b/crates/data/tests/integration/shapefile_encoding.rs @@ -807,7 +807,7 @@ fn unused_cst_advises_without_changing_decoding() { let found: Vec<_> = notes.iter().filter(|n| n.contains("unused .cst")).collect(); assert_eq!(found.len(), usize::from(expected), "{notes:?}"); if expected { - assert!(found[0].contains("trusted") && found[0].contains(".cpg and reopen")); + assert!(found[0].contains("trusted") && found[0].contains(".cpg (replacing an unusable declaration if present) and reopen")); assert_eq!(found[0].loss, None); } }; diff --git a/docs/user-guide/data.md b/docs/user-guide/data.md index b9128b54bc..3dec7524dd 100644 --- a/docs/user-guide/data.md +++ b/docs/user-guide/data.md @@ -307,8 +307,9 @@ exported coordinate system definitions. Shapefile text uses a supported `.cpg` encoding, otherwise the `.dbf` code page, with UTF-8 as the fallback. Keep the sidecar files together. RustGIS does not decode using `.cst`. When neither a usable `.cpg` nor a supported DBF language driver declares the encoding, an accompanying -`.cst` produces an advisory: if you trust its encoding label, copy that label into a -same-basename `.cpg` and reopen the data, or confirm the encoding with the provider. This applies +`.cst` produces an advisory: if you trust its encoding label, write that label to a +same-basename `.cpg` (replacing an unusable declaration if present) and reopen the data, or +confirm the encoding with the provider. This applies to local whole and streamed Shapefiles, standalone DBF files, ZIP members, and loose browser files picked together. CST contents are never read. Loose URL imports do not probe for CST; a downloaded ZIP can report it from the member names. This is an informational reminder about From ee1a30f764c228941686f40e43d03f71649b5ab2 Mon Sep 17 00:00:00 2001 From: mavrick Date: Sun, 29 Nov 2026 20:36:30 -0600 Subject: [PATCH 11/12] fix(mobile): keep matched CST hints with their picked data --- apps/rustgis-mobile/src/lib.rs | 18 ++++++++++--- apps/rustgis-mobile/src/shell.rs | 45 +++++++++++++++++++++++++++++++- crates/data/src/dbf.rs | 29 +++++++++++--------- crates/data/src/io.rs | 5 +--- docs/user-guide/data.md | 5 ++-- 5 files changed, 78 insertions(+), 24 deletions(-) diff --git a/apps/rustgis-mobile/src/lib.rs b/apps/rustgis-mobile/src/lib.rs index 1c9d8b3f5d..dce86c467b 100644 --- a/apps/rustgis-mobile/src/lib.rs +++ b/apps/rustgis-mobile/src/lib.rs @@ -28,8 +28,9 @@ mod typed; pub use ios::main as ios_main; /// The files of `picked` to open, each by its path: all but the parts another of them reads from -/// beside it (a Shapefile's `.dbf`, `.shx`, `.prj` and `.cpg`, a MapInfo file's `.mid`), matched -/// by name whatever the case. A part picked without its main file stays, and is refused by name. +/// beside it (a Shapefile's `.dbf`, `.shx`, `.prj`, `.cpg` and unused `.cst`, a DBF's unused +/// `.cst`, a MapInfo file's `.mid`), matched by name whatever the case. A part picked without +/// its main file stays, and is refused by name. #[cfg_attr(not(any(target_os = "android", target_os = "ios", test)), expect(dead_code, reason = "only a phone picks files"))] fn without_sidecars(picked: Vec) -> Vec { let lower = |part: Option<&std::ffi::OsStr>| part.map(|p| p.to_string_lossy().to_lowercase()).unwrap_or_default(); @@ -39,6 +40,13 @@ fn without_sidecars(picked: Vec) -> Vec for (path, (stem, extension)) in picked.iter().zip(&named) { let read_by = match extension.as_str() { "dbf" | "shx" | "prj" | "cpg" => "shp", + "cst" => { + if has(stem, "shp") { + "shp" + } else { + "dbf" + } + } "mid" => "mif", _ => "", }; @@ -241,8 +249,10 @@ mod tests { #[test] fn parts_picked_with_their_file_are_left_to_it() { - assert_eq!(kept(&["roads.shp", "roads.dbf", "roads.shx", "roads.prj", "roads.cpg"]), ["roads.shp"]); - assert_eq!(kept(&["ROADS.SHP", "Roads.DBF", "parcels.mif", "parcels.MID"]), ["ROADS.SHP", "parcels.mif"]); + assert_eq!(kept(&["roads.shp", "roads.dbf", "roads.shx", "roads.prj", "roads.cpg", "roads.cst"]), ["roads.shp"]); + assert_eq!(kept(&["ROADS.SHP", "Roads.DBF", "roads.CsT", "parcels.mif", "parcels.MID"]), ["ROADS.SHP", "parcels.mif"]); + assert_eq!(kept(&["table.DBF", "table.CST", "notes.cst"]), ["table.DBF", "notes.cst"]); + assert_eq!(kept(&["roads.cst"]), ["roads.cst"]); } #[test] diff --git a/apps/rustgis-mobile/src/shell.rs b/apps/rustgis-mobile/src/shell.rs index b165cc8af6..2fc4d7c6be 100644 --- a/apps/rustgis-mobile/src/shell.rs +++ b/apps/rustgis-mobile/src/shell.rs @@ -465,8 +465,20 @@ fn read_batch(purpose: &str, mut files: Vec<(String, PathBuf)>, inbox: &Inbox, p let max = PICK_MAX_BYTES; let mut read = Vec::new(); let mut too_large = Vec::new(); + // Only a Shapefile dialog's matched CST is a presence marker. Other picks keep their bytes. + let dbf_names: std::collections::HashSet<_> = if mark == rustgis_ui_egui::SHAPEFILE_PICK { + files.iter().map(|(name, _)| name.to_ascii_lowercase()).filter(|name| name.ends_with(".dbf")).collect() + } else { + std::collections::HashSet::new() + }; for (name, path) in files { - let shortcut = mark == rustgis_ui_egui::SHORTCUT_PICK || (mark.is_empty() && name.to_ascii_lowercase().ends_with(".rgisshortcuts")); + let lower = name.to_ascii_lowercase(); + if lower.strip_suffix(".cst").is_some_and(|stem| dbf_names.contains(&format!("{stem}.dbf"))) { + read.push((name, Vec::new())); + remove_copy(&path); + continue; + } + let shortcut = mark == rustgis_ui_egui::SHORTCUT_PICK || (mark.is_empty() && lower.ends_with(".rgisshortcuts")); let size = std::fs::metadata(&path).map(|m| m.len()).unwrap_or(0); if shortcut && size > rustgis_ui_egui::SHORTCUT_FILE_MAX_BYTES as u64 { say(Problem::ShortcutTooLarge { name }); @@ -1229,6 +1241,37 @@ mod tests { assert_eq!(*inbox.lock().unwrap(), vec![(crate::mark("dxf:7"), Vec::::new())]); } + /// The dialog needs only a matched CST's name; unrelated payloads still count and arrive whole. + #[test] + fn a_shapefile_pick_keeps_cst_presence_without_reading_its_body() { + let dir = std::env::temp_dir().join(format!("rustgis-mobile-cst-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + // The picker packages these bytes; the dialog reads the DBF from that package later. + let table = b"DBF payload"; + let unrelated = b"keep me"; + let files = [("table.DBF", &table[..]), ("TABLE.CsT", &b"label"[..]), ("notes.cst", &unrelated[..])] + .into_iter() + .map(|(name, bytes)| { + let path = dir.join(name); + std::fs::write(&path, bytes).unwrap(); + (name.to_string(), path) + }) + .collect(); + let (inbox, problems) = (Inbox::default(), Problems::default()); + let mut held = 0; + read_batch("shapefile", files, &inbox, &problems, &mut held); + assert!(problems.lock().unwrap().is_empty()); + assert_eq!(held, (table.len() + unrelated.len()) as u64); + let read = inbox.lock().unwrap(); + assert_eq!(read.len(), 2); + assert!( + read.iter() + .any(|(name, bytes)| name == &format!("{}notes.cst", rustgis_ui_egui::SHAPEFILE_PICK) && bytes.as_slice() == unrelated) + ); + assert!(read.iter().any(|(name, bytes)| name == &format!("{}table.zip", rustgis_ui_egui::SHAPEFILE_PICK) && !bytes.is_empty())); + assert!(!dir.exists()); + } + /// A script picked for Load… over the pane's limit is refused before it is read, naming it; one /// within it reaches the inbox marked for the pane. #[test] diff --git a/crates/data/src/dbf.rs b/crates/data/src/dbf.rs index 9a8c100c87..6d88b75efd 100644 --- a/crates/data/src/dbf.rs +++ b/crates/data/src/dbf.rs @@ -141,13 +141,11 @@ fn ldid_code_page(ldid: u8) -> Option { }) } +/// Selects a supported CPG, otherwise the language driver and then UTF-8. +/// Unusable declarations and unsupported nonzero drivers add their existing fallback notes. pub(crate) fn encoding(cpg: Option<&[u8]>, ldid: u8, notes: &mut crate::loss::Notes) -> DbfEncoding { - if let Some(bytes) = cpg { - let label = if bytes.len() <= MAX_CPG_BYTES { std::str::from_utf8(bytes).unwrap_or("") } else { "" }; - let label = label.trim().trim_start_matches('\u{feff}').trim(); - if let Some(encoding) = DbfEncoding::from_name(label) { - return encoding; - } + if let Some(encoding) = cpg_encoding(cpg) { + return encoding; } // A `.cpg` that can't be used: the file's own language driver gives the encoding, and then // nothing is assumed; without one it is UTF-8, assumed. One that names a code page RustGIS @@ -434,16 +432,18 @@ pub(crate) fn date(field: &[u8]) -> std::result::Result, ldid: u8, present: impl FnOnce() -> bool, notes: &mut crate::loss::Notes) { - let usable_cpg = cpg - .filter(|b| b.len() <= MAX_CPG_BYTES) - .and_then(|b| std::str::from_utf8(b).ok()) - .and_then(|s| DbfEncoding::from_name(s.trim().trim_start_matches('\u{feff}').trim())) - .is_some(); - if !usable_cpg && ldid_code_page(ldid).and_then(DbfEncoding::from_number).is_none() && present() { + 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")); } } +/// The decoder named by a bounded UTF-8 CPG label, with its optional BOM and padding removed. +fn cpg_encoding(cpg: Option<&[u8]>) -> Option { + cpg.filter(|b| b.len() <= MAX_CPG_BYTES) + .and_then(|b| std::str::from_utf8(b).ok()) + .and_then(|s| DbfEncoding::from_name(s.trim().trim_start_matches('\u{feff}').trim())) +} + /// Stats regular files and links to them, without opening optional CST contents. pub(crate) fn has_cst(path: &std::path::Path) -> bool { CST_SPELLINGS.iter().any(|ext| std::fs::metadata(path.with_extension(ext)).is_ok_and(|m| m.is_file())) @@ -476,6 +476,9 @@ fn cpg_result(result: std::io::Result>>, notes: &mut crate::loss: /// regular file wins. pub const CPG_SPELLINGS: [&str; 8] = ["cpg", "CPG", "Cpg", "cPg", "cpG", "CPg", "CpG", "cPG"]; +/// Every ASCII case of a Shapefile attribute table's extension, in reader preference order. +pub const DBF_SPELLINGS: [&str; 8] = ["dbf", "DBF", "Dbf", "dBf", "dbF", "DBf", "DbF", "dBF"]; + /// Skips special-file spellings, retaining an unusable-declaration notice if none is regular. fn try_read_cpg(path: &std::path::Path) -> std::io::Result>> { use std::io::Read; @@ -507,7 +510,7 @@ fn try_read_cpg(path: &std::path::Path) -> std::io::Result>> { } /// Checks before and after opening. Unix nonblocking open covers a FIFO swapped in between; -/// ordinary regular-file leases still wait, as before, with cancellation between attempts. +/// regular-file leases retry with cancellation between attempts instead of blocking in the kernel. pub(crate) fn open_regular_file(path: &std::path::Path) -> std::io::Result> { if !std::fs::metadata(path)?.is_file() { return Ok(None); diff --git a/crates/data/src/io.rs b/crates/data/src/io.rs index 4ffab45b73..d92e38ddd5 100644 --- a/crates/data/src/io.rs +++ b/crates/data/src/io.rs @@ -13,7 +13,7 @@ use crate::capped::Limit; use crate::raster::{Crs, planetary}; use crate::{Coord, DataError, Dataset, Field, FieldType, Geometry, GeometryType, ReadReport, Result, Value}; -pub use crate::dbf::CPG_SPELLINGS; +pub use crate::dbf::{CPG_SPELLINGS, DBF_SPELLINGS}; /// Largest file read into memory in the browser, on a 32-bit build, or on a computer whose memory /// isn't known (256 MiB): the floor of [`max_bytes`]. Also where a file stops being read whole and @@ -4135,9 +4135,6 @@ pub fn shapefile_for_dbf(path: &Path) -> Option { ["shp", "SHP", "Shp", "sHp", "shP", "SHp", "ShP", "sHP"].iter().map(|e| path.with_extension(e)).find(|p| p.is_file()) } -/// Every ASCII case of a Shapefile attribute table's extension, in reader preference order. -pub const DBF_SPELLINGS: [&str; 8] = ["dbf", "DBF", "Dbf", "dBf", "dbF", "DBf", "DbF", "dBF"]; - /// Finds the attributes beside a Shapefile, accepting every ASCII case of `.dbf` in whole /// and streamed reads. A missing sidecar keeps the usual lowercase path for the error. pub fn dbf_sidecar(path: &Path) -> std::path::PathBuf { diff --git a/docs/user-guide/data.md b/docs/user-guide/data.md index 3dec7524dd..9f3f1918a5 100644 --- a/docs/user-guide/data.md +++ b/docs/user-guide/data.md @@ -310,8 +310,9 @@ a usable `.cpg` nor a supported DBF language driver declares the encoding, an ac `.cst` produces an advisory: if you trust its encoding label, write that label to a same-basename `.cpg` (replacing an unusable declaration if present) and reopen the data, or confirm the encoding with the provider. This applies -to local whole and streamed Shapefiles, standalone DBF files, ZIP members, and loose browser -files picked together. CST contents are never read. Loose URL imports do not probe for CST; +to local whole and streamed Shapefiles, standalone DBF files, ZIP members, and loose files +picked together in the browser or phone app. Encoding selection does not read CST contents. +Loose URL imports do not probe for CST; a downloaded ZIP can report it from the member names. This is an informational reminder about unused metadata, including for ASCII-only text, rather than a report of changed or lost values. The advisory changes no decoded values, From 151b766092ff614377ffc72338f49ff924b9c1a8 Mon Sep 17 00:00:00 2001 From: mavrick Date: Sun, 29 Nov 2026 21:18:47 -0600 Subject: [PATCH 12/12] fix(data): retire CST picker markers when their table read fails --- apps/rustgis-mobile/src/shell.rs | 23 +++++++++++++++++++++++ apps/rustgis-web/src/picker.rs | 20 ++++++++++++++++++++ apps/rustgis-web/src/web.rs | 1 + docs/user-guide/data.md | 13 +++++++------ 4 files changed, 51 insertions(+), 6 deletions(-) diff --git a/apps/rustgis-mobile/src/shell.rs b/apps/rustgis-mobile/src/shell.rs index 2fc4d7c6be..9f1304a497 100644 --- a/apps/rustgis-mobile/src/shell.rs +++ b/apps/rustgis-mobile/src/shell.rs @@ -504,6 +504,14 @@ fn read_batch(purpose: &str, mut files: Vec<(String, PathBuf)>, inbox: &Inbox, p } remove_copy(&path); } + let read_dbfs: std::collections::HashSet<_> = + read.iter().map(|(name, _)| name.to_ascii_lowercase()).filter(|name| name.ends_with(".dbf")).collect(); + read.retain(|(name, _)| { + name.to_ascii_lowercase().strip_suffix(".cst").is_none_or(|stem| { + let dbf = format!("{stem}.dbf"); + !dbf_names.contains(&dbf) || read_dbfs.contains(&dbf) + }) + }); if !too_large.is_empty() { say(Problem::PicturesTooLarge { names: too_large }); } @@ -1272,6 +1280,21 @@ mod tests { assert!(!dir.exists()); } + /// The failed DBF's own error is enough: its CST marker is never delivered as another file. + #[test] + fn a_failed_dbf_read_retires_its_phone_cst_marker() { + let dir = std::env::temp_dir().join(format!("rustgis-mobile-cst-failed-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let cst = dir.join("roads.cst"); + std::fs::write(&cst, b"label").unwrap(); + let (inbox, problems) = (Inbox::default(), Problems::default()); + let files = vec![("roads.dbf".into(), dir.join("roads.dbf")), ("roads.cst".into(), cst)]; + read_batch("shapefile", files, &inbox, &problems, &mut 0); + assert!(inbox.lock().unwrap().is_empty()); + assert!(matches!(problems.lock().unwrap().as_slice(), [Problem::Unread { name, .. }] if name == "roads.dbf")); + assert!(!dir.exists()); + } + /// A script picked for Load… over the pane's limit is refused before it is read, naming it; one /// within it reaches the inbox marked for the pane. #[test] diff --git a/apps/rustgis-web/src/picker.rs b/apps/rustgis-web/src/picker.rs index 3db3aaa1f5..df75ef8d82 100644 --- a/apps/rustgis-web/src/picker.rs +++ b/apps/rustgis-web/src/picker.rs @@ -9,6 +9,15 @@ pub(crate) fn cst_markers(names: impl Iterator) -> std::collectio names.iter().filter(|name| name.strip_suffix(".cst").is_some_and(|stem| names.contains(&format!("{stem}.dbf")))).cloned().collect() } +/// Discards synthetic markers whose DBF failed to read; original picker payloads stay intact. +pub(crate) fn discard_failed_cst_markers(read: &mut Vec<(String, Vec)>, markers: &std::collections::HashSet) { + let usable = cst_markers(read.iter().map(|(name, _)| name.clone())); + read.retain(|(name, _)| { + let lower = name.to_ascii_lowercase(); + !markers.contains(&lower) || usable.contains(&lower) + }); +} + /// Returns the static extension filter list for a named picker `purpose`, when it uses one. pub(crate) fn filter_extensions(purpose: &str) -> Option<&'static [&'static str]> { match purpose { @@ -24,6 +33,17 @@ pub(crate) fn filter_extensions(purpose: &str) -> Option<&'static [&'static str] mod tests { use super::*; + #[test] + fn failed_dbf_reads_retire_only_their_synthetic_cst_markers() { + let markers = ["roads.cst".to_string()].into_iter().collect(); + let mut read = vec![("roads.CST".into(), vec![]), ("empty.cst".into(), vec![]), ("notes.cst".into(), b"keep".to_vec())]; + discard_failed_cst_markers(&mut read, &markers); + assert_eq!(read, vec![("empty.cst".into(), vec![]), ("notes.cst".into(), b"keep".to_vec())]); + let mut read = vec![("roads.DBF".into(), b"table".to_vec()), ("roads.CST".into(), vec![])]; + discard_failed_cst_markers(&mut read, &markers); + assert_eq!(read.len(), 2); + } + /// Unrelated CST files keep their payload; matched DBF companions need only their names. #[test] fn cst_markers_require_a_matching_table() { diff --git a/apps/rustgis-web/src/web.rs b/apps/rustgis-web/src/web.rs index 6010019198..9d2276ef28 100644 --- a/apps/rustgis-web/src/web.rs +++ b/apps/rustgis-web/src/web.rs @@ -579,6 +579,7 @@ async fn read_together(mut files: Vec, mark: &str, inbox: &Inbox, read.push((name, bytes)); } } + crate::picker::discard_failed_cst_markers(&mut read, &markers); if let Some(first) = too_large.first() { let why = rustgis_ui_egui::rustgis_assistant::attach::too_large(first.clone()); let text = if too_large.len() == 1 { diff --git a/docs/user-guide/data.md b/docs/user-guide/data.md index 9f3f1918a5..627106eb86 100644 --- a/docs/user-guide/data.md +++ b/docs/user-guide/data.md @@ -309,14 +309,15 @@ the fallback. Keep the sidecar files together. RustGIS does not decode using `.c a usable `.cpg` nor a supported DBF language driver declares the encoding, an accompanying `.cst` produces an advisory: if you trust its encoding label, write that label to a same-basename `.cpg` (replacing an unusable declaration if present) and reopen the data, or -confirm the encoding with the provider. This applies -to local whole and streamed Shapefiles, standalone DBF files, ZIP members, and loose files +confirm the encoding with the provider. This applies to local whole and streamed Shapefiles, +standalone DBF files, ZIP members, and loose files picked together in the browser or phone app. Encoding selection does not read CST contents. -Loose URL imports do not probe for CST; -a downloaded ZIP can report it from the member names. This is an informational reminder about +Loose URL imports do not probe for CST; a downloaded ZIP can report it from the member names. +This is an informational reminder about unused metadata, including for ASCII-only text, rather than a report of changed or lost values. -The advisory changes no decoded values, -saved project data, sync tracking or Publish behavior. A shape with a coordinate that isn't a number (NaN, +The advisory changes no decoded values, saved project data, sync tracking or Publish behavior. + +A shape with a coordinate that isn't a number (NaN, which some programs write for an empty point, or an infinity) has no place: its feature keeps its attributes without geometry, and a notice says how many (a large Shapefile read in place on the desktop leaves the whole record out, counted with its unreadable shapes). A project, project package or map package is never saved with such a