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..9f1304a497 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 }); @@ -492,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 }); } @@ -1229,6 +1249,52 @@ 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()); + } + + /// 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 1811bcf637..df75ef8d82 100644 --- a/apps/rustgis-web/src/picker.rs +++ b/apps/rustgis-web/src/picker.rs @@ -3,6 +3,21 @@ 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() +} + +/// 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 { @@ -18,6 +33,26 @@ 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() { + 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 bb6088b34a..9d2276ef28 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", @@ -540,9 +541,19 @@ 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 markers.contains(&name.to_ascii_lowercase()) { + 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 @@ -568,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 { @@ -1401,7 +1413,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..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 @@ -431,28 +429,69 @@ pub(crate) fn date(field: &[u8]) -> std::result::Result, ldid: u8, present: impl FnOnce() -> bool, notes: &mut crate::loss::Notes) { + if cpg_encoding(cpg).is_none() && ldid_code_page(ldid).and_then(DbfEncoding::from_number).is_none() && present() { + notes.push(crate::loss::Note::plain("Shapefile: an unused .cst sidecar exists; RustGIS does not read .cst encoding declarations. If its encoding label is trusted, write that label to a same-basename .cpg (replacing an unusable declaration if present) and reopen the data; otherwise confirm the encoding with the provider")); + } +} + +/// 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())) +} + +/// 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) { - 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), } } /// 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. -pub(crate) const CPG_SPELLINGS: [&str; 8] = ["cpg", "CPG", "Cpg", "cPg", "cpG", "CPg", "CpG", "cPG"]; +/// without scanning a potentially large directory. Non-file spellings are skipped; the first +/// 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; + 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_regular_file(&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 +503,133 @@ 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; +/// 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); + } + #[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::*; + /// A cancelled lease wait ends the import; ordinary optional-file failures keep their notice. + #[test] + fn cpg_cancellation_is_not_an_encoding_fallback() { + let mut notes = crate::loss::Notes::new(); + let cancelled = std::io::Error::other(crate::DataError::Cancelled); + assert!(matches!(cpg_result(Err(cancelled), &mut notes), Err(crate::DataError::Cancelled))); + assert!(notes.is_empty()); + let unreadable = std::io::Error::new(std::io::ErrorKind::PermissionDenied, "permission denied"); + assert_eq!(cpg_result(Err(unreadable), &mut notes).unwrap(), Some(Vec::new())); + assert_eq!(notes.len(), 1); + assert_eq!(notes[0].text, "could not read the .cpg (permission denied)"); + notes.clear(); + assert_eq!(cpg_result(Ok(None), &mut notes).unwrap(), None); + assert!(notes.is_empty()); + } + + /// Directories and dangling links are not encoding hints; a regular unread label is. + #[test] + fn cst_presence_requires_a_regular_file() { + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("places.shp"); + let cst = path.with_extension("cst"); + assert!(!has_cst(&path)); + std::fs::create_dir(&cst).unwrap(); + assert!(!has_cst(&path)); + std::fs::remove_dir(&cst).unwrap(); + std::fs::write(&cst, b"1252").unwrap(); + assert!(has_cst(&path)); + std::fs::remove_file(&cst).unwrap(); + #[cfg(unix)] + { + std::os::unix::fs::symlink("label", &cst).unwrap(); + assert!(!has_cst(&path)); + std::fs::write(dir.path().join("label"), b"1252").unwrap(); + assert!(has_cst(&path)); + } + } + + /// 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()).unwrap(), Some(Vec::new())); + // A rejected spelling must not hide a later regular one. + // A case-insensitive filesystem gives this spelling to the FIFO itself. + if !path.with_extension("CpG").exists() { + std::fs::write(path.with_extension("CpG"), b"1252").unwrap(); + assert_eq!(read_cpg(&path, &mut crate::loss::Notes::new()).unwrap(), Some(b"1252".to_vec())); + std::fs::remove_file(path.with_extension("CpG")).unwrap(); + } + std::fs::remove_file(&cpg).unwrap(); + let socket = std::os::unix::net::UnixListener::bind(&cpg).unwrap(); + assert_eq!(read_cpg(&path, &mut crate::loss::Notes::new()).unwrap(), Some(Vec::new())); + drop(socket); + std::fs::remove_file(&cpg).unwrap(); + std::fs::create_dir(&cpg).unwrap(); + assert_eq!(read_cpg(&path, &mut crate::loss::Notes::new()).unwrap(), Some(Vec::new())); + std::fs::remove_dir(&cpg).unwrap(); + std::os::unix::fs::symlink("/dev/zero", &cpg).unwrap(); + assert_eq!(read_cpg(&path, &mut crate::loss::Notes::new()).unwrap(), Some(Vec::new())); + std::fs::remove_file(&cpg).unwrap(); + std::fs::write(dir.path().join("label"), b"1252").unwrap(); + std::os::unix::fs::symlink("label", &cpg).unwrap(); + assert_eq!(read_cpg(&path, &mut crate::loss::Notes::new()).unwrap(), Some(b"1252".to_vec())); + 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..d92e38ddd5 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, 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 /// is read in place instead (a GeoJSON file, a Shapefile), or handed to GDAL (an OpenStreetMap @@ -529,8 +531,10 @@ pub fn read_path(path: &Path) -> Result<(Dataset, ReadReport)> { "dbf" => { check_size(path)?; let mut notes = crate::loss::Notes::new(); - let cpg = crate::dbf::read_cpg(path, &mut notes); - let (ds, mut report) = read_dbf(std::fs::read(path)?, cpg.as_deref(), &name, &mut csv_memory_budget())?; + 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())?; report.messages.extend(notes.prefixed(&name)); (ds, report) } @@ -4134,11 +4138,7 @@ pub fn shapefile_for_dbf(path: &Path) -> Option { /// 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 @@ -4160,8 +4160,9 @@ 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)?; report.messages.extend(notes.prefixed(name)); Ok((ds, report)) @@ -4172,9 +4173,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) { @@ -4186,6 +4187,11 @@ 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(); + // 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 { @@ -4195,9 +4201,9 @@ 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); + parts.push(marker(part)); } } if let Some(slot) = zips.get_mut(i) { @@ -4209,9 +4215,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).map(marker)); + } if let Some(slot) = zips.get_mut(i) { *slot = Some(parts); } @@ -4421,6 +4432,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 +4442,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 +4463,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 +4486,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 +4562,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) { @@ -10963,6 +10998,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/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/publish.rs b/crates/data/src/publish.rs index ed247e0fa3..79b5410ea5 100644 --- a/crates/data/src/publish.rs +++ b/crates/data/src/publish.rs @@ -153,12 +153,27 @@ 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)); + 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()); + } + Ok(Some(bytes)) } impl Original { @@ -911,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] @@ -961,6 +988,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] diff --git a/crates/data/src/source/shp.rs b/crates/data/src/source/shp.rs index d063459f0b..53337cf7d3 100644 --- a/crates/data/src/source/shp.rs +++ b/crates/data/src/source/shp.rs @@ -146,7 +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 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..3c08a6fde3 100644 --- a/crates/data/tests/integration/shapefile_encoding.rs +++ b/crates/data/tests/integration/shapefile_encoding.rs @@ -796,3 +796,109 @@ 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 (replacing an unusable declaration if present) 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 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() { + 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/crates/engine/src/cmd/gp.rs b/crates/engine/src/cmd/gp.rs index 474c845b60..7672e18184 100644 --- a/crates/engine/src/cmd/gp.rs +++ b/crates/engine/src/cmd/gp.rs @@ -4076,8 +4076,12 @@ 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 + && (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))) } /// Adds a tool's table to the project under its name: in place of a table of that name, or, for @@ -5163,6 +5167,22 @@ 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}"); + } + } + // 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(); } diff --git a/docs/user-guide/data.md b/docs/user-guide/data.md index e206f25c0c..627106eb86 100644 --- a/docs/user-guide/data.md +++ b/docs/user-guide/data.md @@ -305,7 +305,19 @@ 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, 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 +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, 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