From cdebb5cb06afe29a439cc5c9bf83dea78cafc3d1 Mon Sep 17 00:00:00 2001 From: mavrick Date: Thu, 3 Dec 2026 01:27:39 -0600 Subject: [PATCH] feat(data): override dBASE encoding on import --- .../rustgis-python/python/rustgis/__init__.py | 13 +- crates/data/src/dbf.rs | 50 ++++-- crates/data/src/io.rs | 129 ++++++++++---- crates/data/src/lib.rs | 12 +- crates/data/src/loss.rs | 4 +- crates/data/src/publish.rs | 15 +- crates/data/src/source/mod.rs | 7 +- crates/data/src/source/shp.rs | 20 ++- .../tests/integration/shapefile_encoding.rs | 17 +- crates/engine/command-surface.txt | 6 +- crates/engine/src/cmd/layer.rs | 160 ++++++++++++------ crates/engine/src/cmd/plugins.rs | 1 + crates/engine/src/cmd/raster.rs | 38 +++-- crates/engine/src/cmd/repair.rs | 1 + crates/engine/src/peer.rs | 1 + crates/engine/src/project.rs | 9 +- crates/engine/src/project_capabilities.rs | 21 +++ crates/engine/src/tests.rs | 98 ++++++++++- crates/map/src/lib.rs | 1 + crates/map/src/look.rs | 15 +- crates/map/src/source.rs | 27 ++- crates/plugins/src/tools.rs | 1 + crates/ui-egui/src/layerchooser.rs | 19 ++- docs/maintaining.md | 4 + docs/user-guide/data-formats.md | 8 +- docs/user-guide/data.md | 10 +- docs/user-guide/loss-codes.md | 4 +- docs/user-guide/shapefile-encoding.md | 6 +- schema/fixtures/dbf_encoding.rgis | 18 ++ schema/project.schema.json | 9 + 30 files changed, 550 insertions(+), 174 deletions(-) create mode 100644 schema/fixtures/dbf_encoding.rgis diff --git a/apps/rustgis-python/python/rustgis/__init__.py b/apps/rustgis-python/python/rustgis/__init__.py index 17524ec978..9905442d40 100644 --- a/apps/rustgis-python/python/rustgis/__init__.py +++ b/apps/rustgis-python/python/rustgis/__init__.py @@ -697,7 +697,14 @@ def __iter__(self) -> Iterator[Layer]: """The active map's layers, top first.""" return iter([Layer._of(self, int(entry["id"])) for entry in self.layers()]) - def add_data(self, path: PathLike, name: Optional[str] = None, **params: Any) -> Any: + def add_data( + self, + path: PathLike, + name: Optional[str] = None, + *, + encoding: Optional[Union[str, int]] = None, + **params: Any, + ) -> Any: """Adds a file as a layer, or as a standalone table when it has no geometry. Args: @@ -707,6 +714,8 @@ def add_data(self, path: PathLike, name: Optional[str] = None, **params: Any) -> name: The layer's name (the file's name when left out). Native multi-layer imports apply it only to the first layer. GDAL or DuckDB files split into several layers keep their generated names and report the ignored name in a notice. + encoding: A dBASE code page name or number (e.g. ``"Shift_JIS"`` or ``932``) for + Shapefiles and dBASE tables, including ZIP members. Overrides file metadata. **params: More ``layer.addData`` parameters, e.g. ``layer=`` for one table of a GeoPackage, ``x=`` and ``y=`` for a CSV's coordinate columns. @@ -717,6 +726,8 @@ def add_data(self, path: PathLike, name: Optional[str] = None, **params: Any) -> command, args = self._data_command(path) if name is not None: params["name"] = name + if encoding is not None: + params["encoding"] = encoding return self._outputs(self.run(command, {**args, **params})) def add_geojson(self, data: Union[Dict[str, Any], str, PathLike], name: str = "GeoJSON") -> Any: diff --git a/crates/data/src/dbf.rs b/crates/data/src/dbf.rs index b1fcfd932a..6e15149d2c 100644 --- a/crates/data/src/dbf.rs +++ b/crates/data/src/dbf.rs @@ -48,6 +48,17 @@ impl DbfEncoding { } } + pub(crate) fn parse(name: &str) -> crate::Result { + if name.len() <= MAX_CPG_BYTES + && let Some(encoding) = Self::from_name(name.trim()) + { + return Ok(encoding); + } + Err(crate::DataError::Format( + "unsupported dBASE encoding; use an ASCII-compatible WHATWG encoding name (such as UTF-8, Shift_JIS, GBK, EUC-KR, Big5 or windows-1252) or code page 437, 850, 852, 861, 865, 866, 874, 932, 936, 949, 950, 10000, 10007, 1250–1258 or 65001".into(), + )) + } + 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 @@ -192,17 +203,8 @@ 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)"; - -/// 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}") } -} +/// Advice in a loss notice for DBF text that could not be decoded. +pub(crate) const ENCODING_HINT: &str = "if the file uses another code page, supply it with encoding or a .cpg file"; /// What opening a `.dbf` says of its field names that aren't valid in its `encoding` ([`not_utf8`]), /// naming the first five by their column (from 1). `None` when there are none. @@ -214,11 +216,8 @@ pub(crate) fn not_utf8_names_note(columns: &[usize], encoding: &str) -> Option = columns.iter().take(5).map(usize::to_string).collect(); let more = if columns.len() > 5 { format!(" and {} more", columns.len() - 5) } else { String::new() }; - let text = format!( - "{what} read with U+FFFD in place of the bytes that can't be read, in {label} {}{more}; {}", - named.join(", "), - cause(encoding) - ); + let text = + format!("{what} read with U+FFFD in place of the bytes that can't be read, in {label} {}{more}; {ENCODING_HINT}", named.join(", ")); Some(crate::loss::Note::loss(crate::loss::LossCode::ChangedEncoding, text)) } @@ -522,6 +521,21 @@ pub(crate) fn unused_cst(cpg: Option<&[u8]>, ldid: u8, present: impl FnOnce() -> } } +/// Reads sidecars only when the caller relies on their declarations. +pub(crate) fn cpg_for_read( + path: &std::path::Path, + ldid: u8, + override_name: Option<&str>, + notes: &mut crate::loss::Notes, +) -> crate::Result>> { + if override_name.is_some() { + return Ok(None); + } + let cpg = read_cpg(path, ldid, notes)?; + unused_cst(cpg.as_deref(), ldid, || has_cst(path), notes); + Ok(cpg) +} + /// 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) @@ -1002,7 +1016,7 @@ mod tests { let two = two.as_str(); assert!(two.starts_with("2 field names aren't valid UTF-8 and were read with U+FFFD"), "{two}"); assert!(two.contains("in fields 3, 7;"), "{two}"); - assert!(two.ends_with(NO_OTHER_ENCODING), "{two}"); + assert!(two.ends_with(ENCODING_HINT), "{two}"); let many = not_utf8_names_note(&[1, 2, 3, 4, 5, 6, 7], "UTF-8").unwrap(); let many = many.as_str(); assert!(many.contains("in fields 1, 2, 3, 4, 5 and 2 more;"), "{many}"); @@ -1010,7 +1024,7 @@ mod tests { assert_eq!( not_utf8_names_note(&[1], "Big5").as_ref().map(crate::loss::Note::as_str), Some( - "1 field name isn't valid Big5 and was read with U+FFFD in place of the bytes that can't be read, in field 1; the .cpg or the .dbf's language driver declares Big5" + "1 field name isn't valid Big5 and was read with U+FFFD in place of the bytes that can't be read, in field 1; if the file uses another code page, supply it with encoding or a .cpg file" ) ); } diff --git a/crates/data/src/io.rs b/crates/data/src/io.rs index 53b7d07651..e4cd1660c4 100644 --- a/crates/data/src/io.rs +++ b/crates/data/src/io.rs @@ -440,6 +440,11 @@ fn first_layer(file_name: &str, bytes: &[u8]) -> Result<(Dataset, ReadReport)> { /// file name's extension. A Shapefile needs its sidecar files, so it comes zipped (`.zip`, whose /// first layer is read). pub fn read_bytes(file_name: &str, bytes: &[u8]) -> Result<(Dataset, ReadReport)> { + read_bytes_with_encoding(file_name, bytes, None) +} + +/// Reads an upload, optionally choosing the encoding for a standalone dBASE table. +pub fn read_bytes_with_encoding(file_name: &str, bytes: &[u8], encoding: Option<&str>) -> Result<(Dataset, ReadReport)> { let path = Path::new(file_name); let ext = path.extension().and_then(|e| e.to_str()).unwrap_or("").to_ascii_lowercase(); let name = path.file_stem().and_then(|s| s.to_str()).unwrap_or("layer").to_string(); @@ -464,7 +469,7 @@ pub fn read_bytes(file_name: &str, bytes: &[u8]) -> Result<(Dataset, ReadReport) "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(), )); } - "dbf" => read_dbf(bytes.to_vec(), None, &name, &mut csv_memory_budget())?, + "dbf" => read_dbf(bytes.to_vec(), None, &name, &mut csv_memory_budget(), encoding)?, "shx" | "prj" | "cpg" => { return Err(DataError::Unsupported(format!("{ext} on its own: it is part of a Shapefile; add it together with its .shp"))); } @@ -502,8 +507,13 @@ pub fn read_owned(file_name: &str, bytes: Vec) -> Result<(Dataset, ReadRepor /// Reads a vector file by extension. pub fn read_path(path: &Path) -> Result<(Dataset, ReadReport)> { + read_path_with_encoding(path, None) +} + +/// Reads a vector file, optionally overriding the dBASE encoding of a loose Shapefile or table. +pub fn read_path_with_encoding(path: &Path, encoding: Option<&str>) -> Result<(Dataset, ReadReport)> { if let Some(shp) = shapefile_for_dbf(path) { - return read_path(&shp); + return read_path_with_encoding(&shp, encoding); } let ext = path.extension().and_then(|e| e.to_str()).unwrap_or("").to_ascii_lowercase(); let name = path.file_stem().and_then(|s| s.to_str()).unwrap_or("layer").to_string(); @@ -533,13 +543,12 @@ pub fn read_path(path: &Path) -> Result<(Dataset, ReadReport)> { let mut notes = crate::loss::Notes::new(); let bytes = std::fs::read(path)?; let ldid = bytes.get(29).copied().unwrap_or(0); - let cpg = crate::dbf::read_cpg(path, ldid, &mut notes)?; - crate::dbf::unused_cst(cpg.as_deref(), ldid, || crate::dbf::has_cst(path), &mut notes); - let (ds, mut report) = read_dbf(bytes, cpg.as_deref(), &name, &mut csv_memory_budget())?; + let cpg = crate::dbf::cpg_for_read(path, ldid, encoding, &mut notes)?; + let (ds, mut report) = read_dbf(bytes, cpg.as_deref(), &name, &mut csv_memory_budget(), encoding)?; report.messages.extend(notes.prefixed(&name)); (ds, report) } - "shp" => read_shapefile_in(path, &name, None)?, + "shp" => read_shapefile_with_encoding(path, &name, None, encoding)?, "zip" | "kml" | "kmz" | "gpx" | "gml" | "dxf" | "pbf" | "topojson" => { check_size(path)?; read_bytes(&path.display().to_string(), &crate::provenance::read(path)?)? @@ -4310,6 +4319,11 @@ pub fn dbf_sidecar(path: &Path) -> std::path::PathBuf { /// Reads a Shapefile with an optional source CRS replacing its `.prj`, before any geometry is /// converted. This changes only interpretation; the files on disk are never modified. pub fn read_shapefile_in(path: &Path, name: &str, crs: Option) -> Result<(Dataset, ReadReport)> { + read_shapefile_with_encoding(path, name, crs, None) +} + +/// Reads a Shapefile with optional CRS and dBASE encoding overrides. +pub fn read_shapefile_with_encoding(path: &Path, name: &str, crs: Option, encoding: Option<&str>) -> Result<(Dataset, ReadReport)> { check_size_with(path, shapefile_size_error)?; let dbf = dbf_sidecar(path); if !dbf.is_file() { @@ -4326,10 +4340,9 @@ pub fn read_shapefile_in(path: &Path, name: &str, crs: Option) -> Result<(D let dbf = crate::provenance::read(dbf)?; // The `.dbf`'s language driver, for what an unreadable `.cpg` falls back to. let ldid = dbf.get(29).copied().unwrap_or(0); - let cpg = crate::dbf::read_cpg(path, ldid, &mut notes)?; - crate::dbf::unused_cst(cpg.as_deref(), ldid, || crate::dbf::has_cst(path), &mut notes); + let cpg = crate::dbf::cpg_for_read(path, ldid, encoding, &mut notes)?; let parts = ShapefileParts { shp, shx, dbf, prj: crate::raster::read_prj(path), cpg }; - let (ds, mut report) = read_shapefile_parts(parts, name, crs)?; + let (ds, mut report) = read_shapefile_parts_with_encoding(parts, name, crs, encoding)?; report.messages.extend(notes.prefixed(name)); Ok((ds, report)) } @@ -4565,7 +4578,12 @@ pub fn read_zip_in(file_name: &str, bytes: &[u8], crs: Option) -> Result Result> { - read_zip_layers_budget(file_name, bytes, opts, &mut csv_memory_budget()) + read_zip_layers_with_encoding(file_name, bytes, opts, None) +} + +/// Reads the layers of a ZIP, optionally overriding the encoding of its dBASE members. +pub fn read_zip_layers_with_encoding(file_name: &str, bytes: &[u8], opts: &CsvOptions, encoding: Option<&str>) -> Result> { + read_zip_layers_budget(file_name, bytes, opts, &mut csv_memory_budget(), encoding) } /// Whether a zip member's path ends as a vector tile set's do, `…///.pbf`. @@ -4578,7 +4596,7 @@ fn is_tile_path(n: &str) -> bool { /// [`read_zip_layers_budget`] without the styles. fn read_zip_budget(file_name: &str, bytes: &[u8], crs: Option, budget: &mut usize) -> Result> { - Ok(read_zip_layers_budget(file_name, bytes, &CsvOptions { crs, ..Default::default() }, budget)? + Ok(read_zip_layers_budget(file_name, bytes, &CsvOptions { crs, ..Default::default() }, budget, None)? .into_iter() .map(|l| (l.dataset, l.report)) .collect()) @@ -4586,7 +4604,13 @@ fn read_zip_budget(file_name: &str, bytes: &[u8], crs: Option, budget: &mut /// Delimited, dBASE, workbook, LandXML and multi-layer members (KML, GPX and the like) share one /// allowance, including gzip members whose text is nested in ZIP. -fn read_zip_layers_budget(file_name: &str, bytes: &[u8], opts: &CsvOptions, budget: &mut usize) -> Result> { +fn read_zip_layers_budget( + file_name: &str, + bytes: &[u8], + opts: &CsvOptions, + budget: &mut usize, + encoding: Option<&str>, +) -> Result> { let crs = opts.crs; // The tables' options: not every member holds the columns given. let member = CsvOptions { columns_optional: true, ..opts.clone() }; @@ -4620,6 +4644,9 @@ fn read_zip_layers_budget(file_name: &str, bytes: &[u8], opts: &CsvOptions, budg return false; } let e = ext_of(n); + if encoding.is_some() && matches!(e.as_str(), "cpg" | "cst") { + return false; + } 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. @@ -4642,6 +4669,11 @@ fn read_zip_layers_budget(file_name: &str, bytes: &[u8], opts: &CsvOptions, budg let stem = |n: &str| lower(n.get(..n.len().saturating_sub(ext_of(n).len() + 1)).unwrap_or(n)); // 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(); + if let Some(encoding) = encoding + && entries.iter().flatten().any(|(name, _)| ext_of(name) == "dbf") + { + crate::dbf::DbfEncoding::parse(encoding)?; + } let mut shps: Vec = entries.iter().flatten().filter(|(n, _)| ext_of(n) == "shp").map(|(n, _)| n.clone()).collect(); shps.sort(); let shp_stems: Vec<_> = shps.iter().map(|n| stem(n)).collect(); @@ -4672,13 +4704,15 @@ fn read_zip_layers_budget(file_name: &str, bytes: &[u8], opts: &CsvOptions, budg 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) { + if encoding.is_none() { + 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_with_encoding(ShapefileParts { shp, shx, dbf, prj, cpg }, &name, crs, encoding) { Ok((mut dataset, mut report)) => { report.messages.extend(advisory.prefixed(&name)); dataset.source = Some(format!("{file_name}/{n}")); @@ -4750,13 +4784,15 @@ fn read_zip_layers_budget(file_name: &str, bytes: &[u8], opts: &CsvOptions, budg 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"); 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)| { + if encoding.is_none() { + 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, encoding).map(|(ds, mut report)| { report.messages.extend(advisory.prefixed(name)); plain(vec![(ds, report)]) }) @@ -4890,6 +4926,15 @@ fn read_zip_layers_budget(file_name: &str, bytes: &[u8], opts: &CsvOptions, budg cap(tables_lacking).join("; ") )); } + if encoding.is_some() + && out.iter().all(|layer| layer.dataset.dbf_encoding.is_none()) + && let Some(first) = out.first_mut() + { + first + .report + .messages + .push(format!("{file_name}: encoding was ignored because the archive has no readable Shapefile or dBASE data")); + } if let Some(first) = out.first_mut() && !skipped.is_empty() { @@ -4954,10 +4999,13 @@ 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]>, name: &str, override_name: Option<&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 = match override_name { + Some(label) => crate::dbf::DbfEncoding::parse(label)?, + None => crate::dbf::encoding(cpg, 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); @@ -5001,9 +5049,16 @@ 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]>, + name: &str, + budget: &mut usize, + override_name: Option<&str>, +) -> Result<(Dataset, ReadReport)> { + let DbfRead { mut reader, fields, decimals, mut report, not_utf8, deleted, encoding } = dbf_reader(bytes, cpg, name, override_name)?; let mut ds = Dataset::new(name, GeometryType::None, fields); + ds.dbf_encoding = override_name.map(str::to_owned); let mut counts = DbfCounts::new(ds.fields.len(), not_utf8, encoding); let allowance = *budget; let mut left = allowance; @@ -5181,18 +5236,24 @@ pub(crate) struct ShapefileParts { /// Decodes attributes and shapes together, tracking geometry lost during CRS conversion so /// a later projection definition cannot silently repair an incomplete layer. -pub(crate) fn read_shapefile_parts(parts: ShapefileParts, name: &str, crs: Option) -> Result<(Dataset, ReadReport)> { +pub(crate) fn read_shapefile_parts_with_encoding( + parts: ShapefileParts, + name: &str, + crs: Option, + override_name: Option<&str>, +) -> Result<(Dataset, ReadReport)> { use shapefile::Shape; 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(), name, override_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)), } .map_err(fmt)?; let mut ds = Dataset::new(name, GeometryType::None, fields); + ds.dbf_encoding = override_name.map(str::to_owned); // A system given or in a `.prj` (even one that can't be used, said on its own) isn't one // RustGIS assumed. let declared = crs.is_some() || parts.prj.is_some(); @@ -11067,11 +11128,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, "small", &mut left, None).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, "small", &mut (cost - 1), None).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(); diff --git a/crates/data/src/lib.rs b/crates/data/src/lib.rs index 1c5044a867..ab2510f818 100644 --- a/crates/data/src/lib.rs +++ b/crates/data/src/lib.rs @@ -477,6 +477,9 @@ pub struct Dataset { /// Where it was read from, if anywhere. #[serde(default)] pub source: Option, + /// Explicit dBASE encoding used to interpret the source text. + #[serde(default)] + pub dbf_encoding: Option, /// The coordinate system it was read in, when that isn't longitude/latitude: what an export /// writes by default. Its geometry is in [`Dataset::held_in`], which is this system for a file /// read now or a project saved by this release, and longitude/latitude for one a project saved @@ -528,6 +531,7 @@ impl Dataset { fields: _, features: _, source: _, + dbf_encoding: _, crs, crs_incomplete: _, zm_dropped: _, @@ -785,7 +789,7 @@ impl Serialize for Dataset { /// Saves CRS recovery and dropped Z/M state with the dataset, but omits disposable streamed rows. fn serialize(&self, s: S) -> std::result::Result { use serde::ser::SerializeStruct; - let mut st = s.serialize_struct("Dataset", 8)?; + let mut st = s.serialize_struct("Dataset", 10)?; st.serialize_field("name", &self.name)?; st.serialize_field("geometry_type", &self.geometry_type)?; st.serialize_field("fields", &self.fields)?; @@ -793,6 +797,11 @@ impl Serialize for Dataset { // In the system it holds them in, exactly, as it reads them back (`held_in`, below). st.serialize_field("features", if self.windowed { none } else { self.features.as_slice() })?; st.serialize_field("source", &self.source)?; + if let Some(encoding) = &self.dbf_encoding { + st.serialize_field("dbf_encoding", encoding)?; + } else { + st.skip_field("dbf_encoding")?; + } if let Some(crs) = &self.crs { st.serialize_field("crs", crs)?; } else { @@ -1147,6 +1156,7 @@ impl Dataset { fields, features: Features::default(), source: None, + dbf_encoding: None, crs: None, crs_incomplete: false, zm_dropped: false, diff --git a/crates/data/src/loss.rs b/crates/data/src/loss.rs index 2f2add709d..1561d6f24d 100644 --- a/crates/data/src/loss.rs +++ b/crates/data/src/loss.rs @@ -183,7 +183,7 @@ loss_codes! { "changed.encoding", Changed, "Text could not be represented in its source or destination encoding, so replacement characters or equivalent ASCII text were used.", - "Give the source's encoding in a form RustGIS reads: a .cpg beside a Shapefile or dBASE file, a DXF saved as UTF-8 or with its $DWGCODEPAGE, or a service that sends UTF-8. TIFF copyright tags hold ASCII only; keep the original credits with the exported file." + "For a Shapefile or dBASE table, set the encoding Add Data parameter or provide a matching .cpg file. Save a DXF as UTF-8 or with its $DWGCODEPAGE, or use a service that sends UTF-8. TIFF copyright tags hold ASCII only. Keep the original credits with the exported file." ), ChangedRounded => ( "changed.rounded", @@ -225,7 +225,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." + "For a Shapefile or dBASE table, set the encoding Add Data parameter or provide a matching .cpg file. Save a DXF as UTF-8." ), } diff --git a/crates/data/src/publish.rs b/crates/data/src/publish.rs index 4c0081e879..7191c954fc 100644 --- a/crates/data/src/publish.rs +++ b/crates/data/src/publish.rs @@ -261,7 +261,10 @@ pub fn shapefile(ds: &Dataset, path: &Path, synced: &Synced) -> Result crate::dbf::DbfEncoding::parse(label)?, + None => crate::dbf::encoding(original.cpg.as_ref().map(|(_, b)| b.as_slice()), ldid, &mut encoding_notes), + }, ldid, columns: table.columns.clone(), }; @@ -273,12 +276,12 @@ pub fn shapefile(ds: &Dataset, path: &Path, synced: &Synced) -> Result Result Some(crate::io::read_shapefile_parts(original.parts(), &name, Some(Crs::LonLat))?.0), + Some(_) => { + Some(crate::io::read_shapefile_parts_with_encoding(original.parts(), &name, Some(Crs::LonLat), ds.dbf_encoding.as_deref())?.0) + } None => None, }; let as_held = raw.as_ref().map(|raw| (&as_read, raw)); @@ -328,7 +333,7 @@ pub fn shapefile(ds: &Dataset, path: &Path, synced: &Synced) -> Result) -> Result { + Self::open_path_with_encoding(path, name, crs, None) + } + + /// Opens a linked Shapefile with optional CRS and dBASE encoding overrides. + pub fn open_path_with_encoding( + path: &Path, + name: &str, + crs: Option, + override_name: Option<&str>, + ) -> Result { if let Some(c) = crs { c.transformer().map_err(DataError::Format)?; } @@ -146,9 +156,13 @@ 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, table.ldid, &mut notes)?; - crate::dbf::unused_cst(cpg.as_deref(), table.ldid, || crate::dbf::has_cst(path), &mut notes); - let encoding = crate::dbf::encoding(cpg.as_deref(), table.ldid, &mut notes); + let encoding = match override_name { + Some(label) => crate::dbf::DbfEncoding::parse(label)?, + None => { + let cpg = crate::dbf::cpg_for_read(path, table.ldid, None, &mut notes)?; + 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) { return Err(bad("the .shp is larger than the format's 4 GB")); diff --git a/crates/data/tests/integration/shapefile_encoding.rs b/crates/data/tests/integration/shapefile_encoding.rs index 2a9a9d1ffc..f3e539b494 100644 --- a/crates/data/tests/integration/shapefile_encoding.rs +++ b/crates/data/tests/integration/shapefile_encoding.rs @@ -74,17 +74,7 @@ fn named_parts(field: &[u8], text: &[u8], ldid: u8, cpg: Option<&[u8]>, rows: us .collect() } -/// 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)"; - -/// 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. -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}"), - } -} +const ENCODING_HINT: &str = "if the file uses another code page, supply it with encoding or a .cpg file"; /// What a read of `places` says of `values` text values of its field `field` that aren't valid in `encoding`. fn invalid_note(values: usize, field: &str, encoding: &str) -> String { @@ -92,14 +82,13 @@ fn invalid_note(values: usize, field: &str, encoding: &str) -> String { 1 => format!("1 text value isn't valid {encoding} and was"), n => format!("{n} text values aren't valid {encoding} and were"), }; - format!("places: {what} read with U+FFFD in place of the bytes that can't be read, in '{field}'; {}", cause(encoding)) + format!("places: {what} read with U+FFFD in place of the bytes that can't be read, in '{field}'; {ENCODING_HINT}") } /// What opening a `.dbf` says of its one field name that isn't valid in `encoding`, the first column. fn invalid_name_note(encoding: &str) -> String { format!( - "1 field name isn't valid {encoding} and was read with U+FFFD in place of the bytes that can't be read, in field 1; {}", - cause(encoding) + "1 field name isn't valid {encoding} and was read with U+FFFD in place of the bytes that can't be read, in field 1; {ENCODING_HINT}" ) } diff --git a/crates/engine/command-surface.txt b/crates/engine/command-surface.txt index 28fb924567..59c9f349fd 100644 --- a/crates/engine/command-surface.txt +++ b/crates/engine/command-surface.txt @@ -213,11 +213,11 @@ labels.resetMoved layer? class? all? labels.scaleRange layer? class? min? max? clear? labels.style layer? class? size? color? halo? haloColor? haloWidth? spacing? stretch? bold? italic? font? background? wrapChar? wrapLength? lineAlign? labels.viewUnplaced on? -layer.addData path name? layer? pdfLayers? paperSpace? blocks? stream? as? crs? x? y? wkt? delimiter? fields? -layer.addDataBytes fileName data zoom? layer? name? x? y? wkt? crs? delimiter? paperSpace? blocks? stream? as? pdfLayers? fields? +layer.addData path name? layer? pdfLayers? paperSpace? blocks? stream? as? crs? encoding? x? y? wkt? delimiter? fields? +layer.addDataBytes fileName data zoom? layer? name? x? y? wkt? crs? encoding? delimiter? paperSpace? blocks? stream? as? pdfLayers? fields? layer.addDataText fileName text name? x? y? wkt? crs? delimiter? layer? paperSpace? blocks? layer.addDatabase database password? layer? crs? name? stream? -layer.addDownload id url name? layer? zoom? x? y? wkt? crs? delimiter? paperSpace? blocks? stream? as? pdfLayers? fields? service? bounds? coverage? coverageCrs? drawingInfo? geolibreProject? geolibreLayer? geolibreZarr? connection? anonymous? request? window? +layer.addDownload id url name? layer? zoom? x? y? wkt? crs? encoding? delimiter? paperSpace? blocks? stream? as? pdfLayers? fields? service? bounds? coverage? coverageCrs? drawingInfo? geolibreProject? geolibreLayer? geolibreZarr? connection? anonymous? request? window? layer.addEncodedPolyline polyline precision? name? layer.addLayerFile path? text? data? group? to? layer.addPhotos paths? folder? name? diff --git a/crates/engine/src/cmd/layer.rs b/crates/engine/src/cmd/layer.rs index a42f7c4212..4f14555b44 100644 --- a/crates/engine/src/cmd/layer.rs +++ b/crates/engine/src/cmd/layer.rs @@ -21,7 +21,7 @@ pub const MAX_LAYER_NAME: usize = 200; pub fn commands() -> Vec { vec![ C::new("layer.addData", "Add Data", "Home › Add", add_data).inputs(add_data_inputs).roles(&[]).effects(crate::policy::Effects::NONE.with(crate::policy::Effect::Files)) - .params(r#"{"path": string, "name"?: "string; for a PDF opened as its layers, the group's (its layers keep the PDF's names)", "layer"?: "GeoPackage, GDAL, DuckDB or DXF layer, or a PDF's page number (the first when left out or blank)", "pdfLayers"?: "bool: a PDF page with layers (optional content groups) as a group of them, one raster each, true by default; false opens the page as one picture", "paperSpace"?: "bool: a DXF's layout entities too", "blocks"?: "bool: a DXF's block (图块) contents, true by default", "stream"?: "bool: true links the file instead of copying it (read in place, a view at a time; the project keeps its path, not its features), false copies it into the project; left out, decided by its size or feature count", "as"?: "scan" (a TIFF, PNG, JPEG or PDF page, even a photo, a GeoTIFF or a GeoPDF, as a picture with no coordinates), "crs"?: "EPSG:… (or WKT) for Shapefile coordinates (overrides .prj), a CSV, a DXF (which never says), a CityJSON or CityGML model (it replaces the system a model file names; in a zip, it is used for a model naming none RustGIS knows), or a GDAL or DuckDB file that doesn't say (GDAL takes an authority code such as EPSG:2263 or the exact names WGS84, WGS72, NAD27, NAD83, not WKT or a file)", "x"?: "CSV or workbook x/longitude column (in a zip, for each CSV and workbook member that has it)", "y"?: "CSV or workbook y/latitude column (as x)", "wkt"?: "CSV or workbook WKT geometry column (as x)", "delimiter"?: ","|";"|"\\t"|"|", "fields"?: "[column names]: of a Parquet file with no geometry column (a standalone table), read only these, in this order (the others are never decoded)"}"#), + .params(r#"{"path": string, "name"?: "string; for a PDF opened as its layers, the group's (its layers keep the PDF's names)", "layer"?: "GeoPackage, GDAL, DuckDB or DXF layer, or a PDF's page number (the first when left out or blank)", "pdfLayers"?: "bool: a PDF page with layers (optional content groups) as a group of them, one raster each, true by default; false opens the page as one picture", "paperSpace"?: "bool: a DXF's layout entities too", "blocks"?: "bool: a DXF's block (图块) contents, true by default", "stream"?: "bool: true links the file instead of copying it (read in place, a view at a time; the project keeps its path, not its features), false copies it into the project; left out, decided by its size or feature count", "as"?: "scan" (a TIFF, PNG, JPEG or PDF page, even a photo, a GeoTIFF or a GeoPDF, as a picture with no coordinates), "crs"?: "EPSG:… (or WKT) for Shapefile coordinates (overrides .prj), a CSV, a DXF (which never says), a CityJSON or CityGML model (it replaces the system a model file names; in a zip, it is used for a model naming none RustGIS knows), or a GDAL or DuckDB file that doesn't say (GDAL takes an authority code such as EPSG:2263 or the exact names WGS84, WGS72, NAD27, NAD83, not WKT or a file)", "encoding"?: "dBASE text code page name or number (such as Shift_JIS or 932), overriding .cpg and the DBF language driver, for Shapefiles and .dbf tables, including in ZIP", "x"?: "CSV or workbook x/longitude column (in a zip, for each CSV and workbook member that has it)", "y"?: "CSV or workbook y/latitude column (as x)", "wkt"?: "CSV or workbook WKT geometry column (as x)", "delimiter"?: ","|";"|"\\t"|"|", "fields"?: "[column names]: of a Parquet file with no geometry column (a standalone table), read only these, in this order (the others are never decoded)"}"#), C::new("layer.addPhotos", "Add Photos", "Home › Add", add_photos).roles(&[]).effects(crate::policy::Effects::NONE.with(crate::policy::Effect::Files)).params( r#"{"paths"?: [JPEG photo files], "folder"?: "a folder of photos (every JPEG in it)", "name"?: "the layer (default Photos; photos join it when it exists)"}"#, ), @@ -54,7 +54,7 @@ pub fn commands() -> Vec { 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 MiB), 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"?, "pdfLayers"?, "fields"? (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); a GeoTIFF in strips, its overviews in strips too when it has some, then takes one strip and column in as many as that size holds on that level", "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"?, "pdfLayers"?, "fields"? (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)}"#), + .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"?, "encoding"?, "delimiter"?, "paperSpace"?, "blocks"?, "stream"?, "as"?, "pdfLayers"?, "fields"? (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)}"#), C::new("layer.addEncodedPolyline", "Add Encoded Polyline", "Home › Add", add_encoded_polyline).roles(&[]).effects(crate::policy::Effects::NONE).params( r#"{"polyline": "encoded polyline text" | [texts] (one line each), "precision"?: 5 (Google) | 6 (OSRM, Valhalla), "name"?: text}"#, ), @@ -2058,11 +2058,42 @@ fn add_data_inputs(_: &super::InputContext<'_>, p: &Value) -> Result Option> { + let value = p.get("encoding").filter(|v| !v.is_null())?; + Some(match value { + Value::String(label) => { + let label = label.trim(); + if label.is_empty() { + return None; + } + std::borrow::Cow::Borrowed(label) + } + Value::Number(page) => std::borrow::Cow::Owned(page.to_string()), + // The DBF reader reports accepted values for an invalid override. Other formats ignore it. + _ => std::borrow::Cow::Borrowed(""), + }) +} + +pub(crate) fn dbf_encoding_ignored(s: &mut Session, encoding: Option<&str>) { + if encoding.is_some() { + s.notify("encoding was ignored because the data has no Shapefile or dBASE text", false); + } +} + +pub(crate) fn takes_dbf_encoding(name: &str) -> bool { + let ext = Path::new(name).extension().and_then(|e| e.to_str()).unwrap_or(""); + ["shp", "dbf", "zip"].iter().any(|format| ext.eq_ignore_ascii_case(format)) +} + /// Opens a file through its format's reader. A Shapefile CRS override is applied before any /// conversion in both whole-file and streamed paths; the source file is never rewritten. /// DBF picks with geometry follow the full Shapefile import path. fn add_data(s: &mut Session, p: &Value) -> CmdResult { let path = s_req(p, "path")?; + if !takes_dbf_encoding(path) { + dbf_encoding_ignored(s, dbf_encoding(p).as_deref()); + } if fields_given(p).is_some() && !is_parquet_name(path) { return Err(format!("{path}: {ONLY_PARQUET_TABLES}")); } @@ -2126,7 +2157,7 @@ fn add_data(s: &mut Session, p: &Value) -> CmdResult { // A Parquet file opened ahead in the desktop app, a table read whole there ([`in_place_ahead`]). #[cfg(not(target_arch = "wasm32"))] if is_parquet_name(path) - && let Some(Opened { source, whole, .. }) = take_opened(s, path, None) + && let Some(Opened { source, whole, .. }) = take_opened(s, path, None, None) { return add_source_read(s, p, Origin::Path(path), Some(source.map_err(|e| format!("{path}: {e}"))?), whole, None); } @@ -2142,7 +2173,7 @@ fn add_data(s: &mut Session, p: &Value) -> CmdResult { let bytes = rustgis_data::provenance::read(path).map_err(|e| format!("{path}: {e}"))?; if rustgis_data::io::is_cityjson(path, &bytes) { let full = std::path::absolute(path).map(|p| p.display().to_string()).unwrap_or_else(|_| path.to_string()); - return add_layers(s, p, &full, &bytes, None, true); + return add_layers(s, p, &full, &bytes, None, true, dbf_encoding(p).as_deref()); } } // A large GeoJSON FeatureCollection (any, with `"stream": true`) is read in place, streamed @@ -2157,7 +2188,7 @@ fn add_data(s: &mut Session, p: &Value) -> CmdResult { { let name = Path::new(path).file_stem().and_then(|n| n.to_str()).unwrap_or("layer"); // Opened ahead in the desktop app ([`in_place_ahead`]). - let Opened { source, whole, .. } = take_opened(s, path, None).unwrap_or_else(|| { + let Opened { source, whole, .. } = take_opened(s, path, None, None).unwrap_or_else(|| { Opened::here(|| Ok(Box::new(rustgis_data::source::geojson::GeoJsonSource::open_path(Path::new(path), name)?))) }); match source { @@ -2187,37 +2218,30 @@ fn add_data(s: &mut Session, p: &Value) -> CmdResult { #[cfg(not(target_arch = "wasm32"))] let p = past_cap.as_ref().unwrap_or(p); #[cfg(not(target_arch = "wasm32"))] - if path.to_ascii_lowercase().ends_with(".shp") - && let Some(crs) = ps(p, "crs").map(str::trim).filter(|c| !c.is_empty()) - { - let crs = super::parse_crs(s, crs)?; + if path.to_ascii_lowercase().ends_with(".shp") { + let system = ps(p, "crs").map(str::trim).filter(|c| !c.is_empty()); + let crs = system.map(|text| super::parse_crs(s, text)).transpose()?; let name = Path::new(path).file_stem().and_then(|n| n.to_str()).unwrap_or("layer"); - let stream = streams_shapefile(p, path); - if stream { - // Opened ahead in the desktop app ([`in_place_ahead`]), in the same system. - let Opened { source, whole, .. } = take_opened(s, path, ps(p, "crs").map(str::trim)).unwrap_or_else(|| { - Opened::here(|| Ok(Box::new(rustgis_data::source::shp::ShpSource::open_path_in(Path::new(path), name, Some(crs))?))) + let encoding = dbf_encoding(p); + if streams_shapefile(p, path) { + let Opened { source, whole, .. } = take_opened(s, path, system, encoding.as_deref()).unwrap_or_else(|| { + Opened::here(|| { + Ok(Box::new(rustgis_data::source::shp::ShpSource::open_path_with_encoding( + Path::new(path), + name, + crs, + encoding.as_deref(), + )?)) + }) }); - return add_source_read(s, p, Origin::Path(path), Some(source.map_err(|e| e.to_string())?), whole, None); + return add_source_read(s, p, Origin::Path(path), Some(source.map_err(|e| format!("{path}: {e}"))?), whole, None); } - // Read ahead in the desktop app ([`add_data_ahead`]). let read = match super::reads::take(s, &whole_key(path)) { Some(read) => read, - None => read_shapefile_with(path, name, crs), + None => read_shapefile_with(path, name, crs, encoding.as_deref()), }?; return add_read(s, p, read, None); } - // A large Shapefile is read in place, as a GeoPackage is; smaller ones are loaded whole. - #[cfg(not(target_arch = "wasm32"))] - if path.to_ascii_lowercase().ends_with(".shp") && streams_shapefile(p, path) { - // Opened ahead in the desktop app ([`in_place_ahead`]). - return match take_opened(s, path, None) { - Some(Opened { source, whole, .. }) => { - add_source_read(s, p, Origin::Path(path), Some(source.map_err(|e| format!("{path}: {e}"))?), whole, None) - } - None => add_source(s, p, Origin::Path(path), None), - }; - } // A PMTiles archive is a tile layer (raster or vector, as its header says). if path.to_ascii_lowercase().ends_with(".pmtiles") { if cfg!(target_arch = "wasm32") { @@ -2311,7 +2335,7 @@ fn add_data(s: &mut Session, p: &Value) -> CmdResult { } let bytes = rustgis_data::provenance::read(path).map_err(|e| format!("{path}: {e}"))?; let full = std::path::absolute(path).map(|p| p.display().to_string()).unwrap_or_else(|_| path.to_string()); - return add_layers(s, p, &full, &bytes, None, true); + return add_layers(s, p, &full, &bytes, None, true, dbf_encoding(p).as_deref()); } let read = match super::reads::take(s, &whole_key(path)) { Some(read) => read, @@ -2416,7 +2440,8 @@ fn read_layers_file(p: &Value, path: &str) -> LayersRead { let reads = match crs { _ if full.to_ascii_lowercase().ends_with(".zip") => { let crs = crs.map(rustgis_data::raster::Crs::parse).transpose()?; - rustgis_data::io::read_zip_layers(&full, &bytes, &zip_options(p, crs)?).map_err(|e| e.to_string())? + rustgis_data::io::read_zip_layers_with_encoding(&full, &bytes, &zip_options(p, crs)?, dbf_encoding(p).as_deref()) + .map_err(|e| e.to_string())? } Some(text) if rustgis_data::io::is_city_model(&full, &bytes) => { city_reads(&full, &bytes, Some(rustgis_data::raster::Crs::parse(text)?))? @@ -2499,7 +2524,8 @@ fn read_whole(p: &Value, path: &str) -> WholeRead { if let Some(read) = delimited { return Ok(read); } - let read = || rustgis_data::io::read_path(Path::new(path)).map_err(|e| whole_read_error(path, e)); + let read = + || rustgis_data::io::read_path_with_encoding(Path::new(path), dbf_encoding(p).as_deref()).map_err(|e| whole_read_error(path, e)); // A file its edits can be written back to: the files as read, to compare with before then. #[cfg(not(target_arch = "wasm32"))] if rustgis_data::sync::is_syncable(path) { @@ -2511,9 +2537,10 @@ fn read_whole(p: &Value, path: &str) -> WholeRead { /// A Shapefile read whole in coordinate system `crs`, which replaces its `.prj`, with the record /// of what was read ([`read_synced`]). #[cfg(not(target_arch = "wasm32"))] -fn read_shapefile_with(path: &str, name: &str, crs: rustgis_data::raster::Crs) -> WholeRead { +fn read_shapefile_with(path: &str, name: &str, crs: Option, encoding: Option<&str>) -> WholeRead { read_synced(path, || { - let mut read = rustgis_data::io::read_shapefile_in(Path::new(path), name, Some(crs)).map_err(|e| e.to_string())?; + let mut read = rustgis_data::io::read_shapefile_with_encoding(Path::new(path), name, crs, encoding) + .map_err(|e| if crs.is_some() { e.to_string() } else { whole_read_error(path, e) })?; read.0.source = Some(path.to_string()); Ok(read) }) @@ -2748,16 +2775,16 @@ fn file_stamp(path: &str) -> Option) -> Option { - let opened = super::reads::take::(s, &in_place_key(path, crs))?; +fn take_opened(s: &mut Session, path: &str, crs: Option<&str>, encoding: Option<&str>) -> Option { + let opened = super::reads::take::(s, &in_place_key(path, crs, encoding))?; (opened.stamp.is_some() && opened.stamp == file_stamp(path)).then_some(opened) } /// The key of Add Data's opening of `path` in place, in the coordinate system `crs` names (see /// [`super::reads`]). #[cfg(not(target_arch = "wasm32"))] -fn in_place_key(path: &str, crs: Option<&str>) -> String { - format!("in-place:{}", json!([path, crs])) +fn in_place_key(path: &str, crs: Option<&str>, encoding: Option<&str>) -> String { + format!("in-place:{}", json!([path, crs, encoding])) } /// The opening of a large Shapefile or GeoJSON file that Add Data reads in place, made ahead on a @@ -2778,7 +2805,7 @@ fn in_place_ahead(p: &Value, path: &str) -> Option { if is_parquet_name(path) { // A "fields" that isn't a list is refused by add_data, not here. let (path, fields) = (path.to_string(), chosen_fields(p).ok()?); - return Some(super::reads::ahead(NAME, in_place_key(&path, None), move || { + return Some(super::reads::ahead(NAME, in_place_key(&path, None, None), move || { let stamp = file_stamp(&path); let mut source = rustgis_data::source::open_path(Path::new(&path), None); let whole = match &mut source { @@ -2800,7 +2827,7 @@ fn in_place_ahead(p: &Value, path: &str) -> Option { && streams_geojson(p, path) { let (path, may_load) = (path.to_string(), b(p, "stream").is_none()); - return Some(super::reads::ahead(NAME, in_place_key(&path, None), move || { + return Some(super::reads::ahead(NAME, in_place_key(&path, None, None), move || { Opened::ahead(&path, may_load, || { Ok(Box::new(rustgis_data::source::geojson::GeoJsonSource::open_path(Path::new(&path), &name)?)) }) @@ -2817,9 +2844,12 @@ fn in_place_ahead(p: &Value, path: &str) -> Option { let text = ps(&q, "crs").map(str::trim).filter(|c| !c.is_empty()); // One add_data can't parse it refuses as it runs. let crs = text.map(rustgis_data::raster::Crs::parse).transpose().ok()?; - let (key, path, may_load) = (in_place_key(path, text), path.to_string(), b(&q, "stream").is_none()); + let encoding = dbf_encoding(&q).map(std::borrow::Cow::into_owned); + let (key, path, may_load) = (in_place_key(path, text, encoding.as_deref()), path.to_string(), b(&q, "stream").is_none()); Some(super::reads::ahead(NAME, key, move || { - Opened::ahead(&path, may_load, || Ok(Box::new(rustgis_data::source::shp::ShpSource::open_path_in(Path::new(&path), &name, crs)?))) + Opened::ahead(&path, may_load, || { + Ok(Box::new(rustgis_data::source::shp::ShpSource::open_path_with_encoding(Path::new(&path), &name, crs, encoding.as_deref())?)) + }) })) } @@ -2901,15 +2931,9 @@ pub(crate) fn add_data_ahead(p: &Value) -> Option { return None; } let key = whole_key(&path); - return match ps(&q, "crs").map(str::trim).filter(|c| !c.is_empty()) { - Some(text) => { - // One add_data can't parse it refuses as it runs. - let crs = rustgis_data::raster::Crs::parse(text).ok()?; - let name = Path::new(&path).file_stem().and_then(|n| n.to_str()).unwrap_or("layer").to_string(); - Some(ahead(NAME, key, move || read_shapefile_with(&path, &name, crs))) - } - None => Some(ahead(NAME, key, move || read_whole(&q, &path))), - }; + let crs = ps(&q, "crs").map(str::trim).filter(|c| !c.is_empty()).map(rustgis_data::raster::Crs::parse).transpose().ok()?; + let name = Path::new(&path).file_stem().and_then(|n| n.to_str()).unwrap_or("layer").to_string(); + return Some(ahead(NAME, key, move || read_shapefile_with(&path, &name, crs, dbf_encoding(&q).as_deref()))); } let (key, q) = (whole_key(&path), p.clone()); if rustgis_data::sheets::is_sheet_name(&path) { @@ -2926,7 +2950,15 @@ pub(crate) fn add_data_ahead(_: &Value) -> Option { /// Adds every layer of a file that holds several: the Shapefiles (and other files) of a zip, a KML /// or KMZ's points, lines and polygons drawn in its styles, a GPX's waypoints, routes, tracks and /// track points. `"layer"` picks one by name; a name given applies to the first. -pub(crate) fn add_layers(s: &mut Session, p: &Value, file_name: &str, bytes: &[u8], zoom: Option, local_file: bool) -> CmdResult { +pub(crate) fn add_layers( + s: &mut Session, + p: &Value, + file_name: &str, + bytes: &[u8], + zoom: Option, + local_file: bool, + encoding: Option<&str>, +) -> CmdResult { // A LandXML file in a coordinate system it doesn't say. let crs = ps(p, "crs").map(str::trim).filter(|c| !c.is_empty()); let landxml = rustgis_data::landxml::is_landxml_name(file_name) @@ -2959,7 +2991,7 @@ pub(crate) fn add_layers(s: &mut Session, p: &Value, file_name: &str, bytes: &[u let reads = match crs.filter(|_| landxml) { _ if lower.ends_with(".zip") => { let crs = crs.map(|text| super::parse_crs(s, text)).transpose()?; - rustgis_data::io::read_zip_layers(file_name, bytes, &zip_options(p, crs)?).map_err(|e| e.to_string())? + rustgis_data::io::read_zip_layers_with_encoding(file_name, bytes, &zip_options(p, crs)?, encoding).map_err(|e| e.to_string())? } // A city model (CityJSON or CityGML) with a coordinate system given, which takes the place // of any it names. @@ -3664,6 +3696,7 @@ fn add_source_read( Origin::Sqlserver(o) => rustgis_map::source::SourceLayer::from_sqlserver((*o).clone(), src), }; if info.format == "Shapefile" { + layer.dbf_encoding = dbf_encoding(p).map(std::borrow::Cow::into_owned); layer.shapefile_crs = ps(p, "crs").map(str::trim).filter(|c| !c.is_empty()).map(rustgis_data::raster::Crs::parse).transpose()?; } @@ -3695,6 +3728,9 @@ fn add_source_read( let (mut ds, report) = whole.take().unwrap_or_else(|| source::materialize(src.as_ref())).map_err(err)?; ds.name = name; ds.source = Some(label.clone()); + if info.format == "Shapefile" { + ds.dbf_encoding = dbf_encoding(p).map(std::borrow::Cow::into_owned); + } features = features.saturating_add(ds.features.len() as u64); let id = add_dataset(s, ds); if let (Some(r), Some(l)) = (style.clone(), s.map_mut().layer_mut(id)) { @@ -4844,6 +4880,7 @@ fn load_all(s: &mut Session, p: &Value) -> CmdResult { let l = s.map().layer(id).ok_or("no such layer")?; // Named as the layer is now: it may have been renamed while the read ran. ds.name = l.dataset.name.clone(); + ds.dbf_encoding = l.source.as_ref().and_then(|source| source.dbf_encoding.clone()); let n = ds.features.len(); unread.say(s); let l = s.map_mut().layer_mut(id).ok_or("no such layer")?; @@ -5711,7 +5748,9 @@ fn add_url_as_given(s: &mut Session, p: &Value) -> CmdResult { let cut = url_name_cut("Add Data From URL", url, p, &bytes); // A WCS coverage's own system it was asked for in, for an answer that doesn't say it. let asked = if b(p, "coverage") == Some(true) { super::raster::coverage_system(s, p, url) } else { None }; - let r = super::raster::add_named_bytes_read(s, p, name, bytes, b(p, "zoom"), None, asked).map_err(named)?; + let r = + super::raster::add_named_bytes_read(s, p, name, bytes, b(p, "zoom"), super::raster::ByteRead { asked, ..Default::default() }) + .map_err(named)?; if let Some(n) = left_out { s.notify(n, false); } @@ -7359,6 +7398,7 @@ fn add_download(s: &mut Session, p: &Value) -> CmdResult { // A window the app read off the frame (#1330). #[cfg(not(target_arch = "wasm32"))] if let Some(i) = s.landed_windows.iter().position(|(d, _)| *d == id) { + dbf_encoding_ignored(s, dbf_encoding(p).as_deref()); let (_, read) = s.landed_windows.remove(i); let r = add_window(s, p, read)?; return added_download(s, p, r, false, &url); @@ -7371,6 +7411,7 @@ fn add_download(s: &mut Session, p: &Value) -> CmdResult { // A download read already (an ArcGIS layer's protocol buffer pages, joined): added as read, // with no axes to check against bounds. if let Some(i) = s.landed_reads.iter().position(|(d, _)| *d == id) { + dbf_encoding_ignored(s, dbf_encoding(p).as_deref()); let (_, read) = s.landed_reads.remove(i); let r = add_read(s, p, *read, b(p, "zoom"))?; return added_download(s, p, r, service || coverage, &url); @@ -7380,6 +7421,7 @@ fn add_download(s: &mut Session, p: &Value) -> CmdResult { let (_, bytes) = s.downloaded.remove(i); let read_at = s.downloaded_reach.iter().position(|(d, _)| *d == id).map(|i| s.downloaded_reach.remove(i).1); if p.get("geolibreProject").and_then(Value::as_bool) == Some(true) { + dbf_encoding_ignored(s, dbf_encoding(p).as_deref()); if bytes.len() > rustgis_map::geolibre::MAX_TEXT { return Err("GeoLibre project exceeds 64 MiB".into()); } @@ -7395,6 +7437,7 @@ fn add_download(s: &mut Session, p: &Value) -> CmdResult { return r; } if p.get("geolibreLayer").is_some() { + dbf_encoding_ignored(s, dbf_encoding(p).as_deref()); let name = if b(p, "geolibreZarr") == Some(true) { "zarr.tif".into() } else { url_file_name(&url, &bytes)? }; return super::geolibre::finish_layer(s, p, name, bytes); } @@ -7435,7 +7478,14 @@ fn add_download(s: &mut Session, p: &Value) -> CmdResult { #[cfg(target_arch = "wasm32")] let drawn = None; let asked = if coverage { super::raster::coverage_system(s, p, &url) } else { None }; - let r = super::raster::add_named_bytes_read(s, p, name, bytes, b(p, "zoom"), drawn, asked)?; + let r = super::raster::add_named_bytes_read( + s, + p, + name, + bytes, + b(p, "zoom"), + super::raster::ByteRead { drawn, asked, encoding: dbf_encoding(p).as_deref() }, + )?; if let Some(n) = left_out { s.notify(n, false); } @@ -7505,7 +7555,7 @@ pub(crate) fn add_data_text_after(s: &mut Session, p: &Value, zoom: Option || (["crs", "layer"].iter().any(|k| ps(p, k).is_some_and(|c| !c.trim().is_empty())) && rustgis_data::io::is_cityjson(name, text.as_bytes())) { - return add_layers(s, p, name, text.as_bytes(), zoom, false); + return add_layers(s, p, name, text.as_bytes(), zoom, false, None); } if let Some(read) = read_delimited(p, name, || Ok(text.as_bytes().to_vec()))? { return add_read(s, p, read, zoom); diff --git a/crates/engine/src/cmd/plugins.rs b/crates/engine/src/cmd/plugins.rs index 119f485383..7fe89ea11e 100644 --- a/crates/engine/src/cmd/plugins.rs +++ b/crates/engine/src/cmd/plugins.rs @@ -616,6 +616,7 @@ impl Bridge<'_> { fields: l.dataset.fields.clone(), features, source: None, + dbf_encoding: None, crs: l.dataset.crs, crs_incomplete: false, zm_dropped: false, diff --git a/crates/engine/src/cmd/raster.rs b/crates/engine/src/cmd/raster.rs index b148c9df80..dfe2a35929 100644 --- a/crates/engine/src/cmd/raster.rs +++ b/crates/engine/src/cmd/raster.rs @@ -38,7 +38,7 @@ pub fn commands() -> Vec { .inputs(crate::cmd::Inputs::single_layer).roles(&[]).effects(crate::policy::Effects::NONE.with(crate::policy::Effect::Files)).view() .params(r#"{"layer"?:name|id}"#), C::new("layer.addDataBytes", "Add Data (from file contents)", "Home › Add", add_bytes::).roles(&[]).effects(crate::policy::Effects::NONE) - .params(r#"{"fileName": "name.tif|.tiff|.asc|.grb|.grib|.grb2|.grib2 (GRIB)|.hgt|.dt0|.dt1|.dt2|.geojson|.csv|.zip|.kml|.kmz|.gpx|.parquet|.fgb|.gpkg|.mbtiles|.jp2|.j2k|.dxf|.pdf (JPEG 2000: desktop, through GDAL; PDF: desktop, command line and Python)", "data": base64, "zoom"?: bool, "layer"?: "one layer of a zip, KML or GPX by name, or a PDF's page number (the first when left out or blank)", "name"?: text, "x"?, "y"?, "wkt"?, "crs"?, "delimiter"?, "paperSpace"?, "blocks"?, "stream"?, "as"?, "pdfLayers"?, "fields"? (as layer.addData)}"#), + .params(r#"{"fileName": "name.tif|.tiff|.asc|.grb|.grib|.grb2|.grib2 (GRIB)|.hgt|.dt0|.dt1|.dt2|.geojson|.csv|.dbf|.zip|.kml|.kmz|.gpx|.parquet|.fgb|.gpkg|.mbtiles|.jp2|.j2k|.dxf|.pdf (JPEG 2000: desktop, through GDAL; PDF: desktop, command line and Python)", "data": base64, "zoom"?: bool, "layer"?: "one layer of a zip, KML or GPX by name, or a PDF's page number (the first when left out or blank)", "name"?: text, "x"?, "y"?, "wkt"?, "crs"?, "encoding"?, "delimiter"?, "paperSpace"?, "blocks"?, "stream"?, "as"?, "pdfLayers"?, "fields"? (as layer.addData)}"#), C::new("raster.symbology", "Symbology", "Style › Rendering", symbology).when(need_raster).roles(&[]).effects(crate::policy::Effects::NONE).params( r#"{"layer"?, "type": "stretch"|"rgb"|"classify"|"unique"|"colormap"|"shadedRelief", "band"?: 1.., "ramp"?, "invert"?: bool, "classes"?: 1..32, "method"?, "azimuth"?, "altitude"?, "zFactor"?, "shadow"?: 0..1 (shadedRelief: how dark the shadows the terrain casts are; left out, kept; 0 casts none), "sky"?: 0..1 (shadedRelief: how much the share of the sky each cell sees dims its ambient light; left out, kept; 0 leaves it whole), "fill"?: 0..1 (shadedRelief: a fill light from the side opposite the sun that lightens the slopes turned toward it; left out, kept; 0 has none), "ambient"?: 0..1|null (shadedRelief: the share of the colour a slope turned fully from the sun keeps; left out, kept; null, the default: 0.25, or 0.5 balanced), "balanced"?: bool (shadedRelief: flat ground keeps the ramp's colour and slopes facing the sun brighten, up to 1.3; left out, kept; false, the default, lights as before), "shadowSoftness"?: 0.5..15|null (shadedRelief: how soft the edges of its cast shadows are, as half the sun's apparent size in degrees; left out, kept; outside 0.5 to 15, refused; null, the default: 5), "aerial"?: 0..1|null (shadedRelief: aerial perspective, low ground on the layer's stretch lit with less contrast and hazed toward #ECECEC, the more the lower; left out, kept; outside 0 to 1, refused; null or 0, the default: none), "terrain"?: -1..1|null (shadedRelief: terrain type, each cell's gradient g reshaped for the sun's light only as tan 30° × (g / tan 30°)^(1 − 0.5 × terrain), steepened at most 8 times: above 0 gentle relief shows, below 0 steep ground stands out; cast shadows, sky, fill light and rock keep the ground's slope; left out, kept; outside -1 to 1, refused; null or 0, the default: lit as before), "flats"?: {"amount"?: 0..1, "size"?: 1..32} | false (shadedRelief: flat ground's detail, each cell's direct light moved by its height above the mean within size cells around it, 40 per unit of height (a metre on most DEMs) within 80, times amount, fading out by 4° of slope; best on a terrain model, as a surface model's trees and roads show too; left out, kept; an object's missing keys keep the current one's, or 1 and 6; amount 0, false or null: none, the default; outside, refused), "generalize"?: 0..10000|null (shadedRelief: generalisation, in metres: the lights read from the slopes (sun, fill light, rock) are worked out from the heights smoothed with a Gaussian of that size, so small landforms fade and large ones stay; the colour ramp keeps each cell's own height; left out, kept; outside 0 to 10000, refused; null or 0, the default: none), "rock"?: {"from"?: 0..90, "to"?: 0..90, "color"?: #RRGGBB} | false (shadedRelief: steep slopes tinted toward a rock colour before the light, from the ground's own slope in degrees, without the Z factor: the ramp below from, the colour above to, blended between; left out, kept; an object's missing keys keep the current rock's, or 25, 40 and #B2ACA4; false or null removes it), "grey"?: bool (shadedRelief without its colour ramp)}"#, ), @@ -1023,7 +1023,14 @@ fn add_bytes(s: &mut Session, p: &Value) -> CmdResult { return Err(rustgis_data::io::file_size_error(&name, LIMIT as u64)); } let bytes = base64::engine::general_purpose::STANDARD.decode(data.as_bytes()).map_err(|e| format!("data: {e}"))?; - add_named_bytes(s, p, name, bytes, b(p, "zoom")) + add_named_bytes_read( + s, + p, + name, + bytes, + b(p, "zoom"), + ByteRead { encoding: super::layer::dbf_encoding(p).as_deref(), ..Default::default() }, + ) } /// The system a WCS coverage was asked for in, for an answer that doesn't say its own: the one @@ -1072,7 +1079,7 @@ pub(crate) fn coverage_system(s: &mut Session, p: &Value, url: &str) -> Option, zoom: Option) -> CmdResult { - add_named_bytes_read(s, p, name, bytes, zoom, None, None) + add_named_bytes_read(s, p, name, bytes, zoom, ByteRead::default()) } /// [`add_named_bytes`] of a WCS coverage's answer asked for in `asked`, its own system: a GeoTIFF @@ -1085,21 +1092,30 @@ pub(crate) fn add_coverage_bytes( bytes: Vec, asked: Option, ) -> CmdResult { - add_named_bytes_read(s, p, name, bytes, None, None, asked) + add_named_bytes_read(s, p, name, bytes, None, ByteRead { asked, ..Default::default() }) } -/// [`add_named_bytes`], with a PDF's page drawn already off the frame (a download's, -/// [`read_download_shared_page`]) instead of here, and a WCS coverage's own system it was asked -/// for in (`asked`, for an answer that doesn't say it). +/// Options supplied by the command that imports these bytes. +#[derive(Default)] +pub(crate) struct ByteRead<'a> { + pub drawn: Option, + pub asked: Option, + pub encoding: Option<&'a str>, +} + +/// Like [`add_named_bytes`], also accepts a PDF page drawn off the frame, a WCS coverage's +/// requested CRS for an answer that doesn't say it, and an explicit dBASE encoding. pub(crate) fn add_named_bytes_read( s: &mut Session, p: &Value, name: String, bytes: Vec, zoom: Option, - drawn: Option, - asked: Option, + ByteRead { drawn, asked, encoding }: ByteRead<'_>, ) -> CmdResult { + if !super::layer::takes_dbf_encoding(&name) { + super::layer::dbf_encoding_ignored(s, encoding); + } // A downloaded file of another kind would be read whole, its "fields" unheard (#3539). if super::layer::fields_given(p).is_some() && !super::layer::is_parquet_name(&name) { return Err(format!("{name}: {}", super::layer::ONLY_PARQUET_TABLES)); @@ -1173,7 +1189,7 @@ pub(crate) fn add_named_bytes_read( } // Files of several layers: zipped Shapefiles, KML/KMZ, GPX, GeoRSS, LandXML, CityJSON, CityGML. if rustgis_data::io::is_multi_layer_name(&name) { - return super::layer::add_layers(s, p, &name, &bytes, zoom, false); + return super::layer::add_layers(s, p, &name, &bytes, zoom, false, encoding); } // GeoParquet and FlatGeobuf uploads (binary vector files). if rustgis_data::source::is_source_name(&name) { @@ -1181,7 +1197,7 @@ pub(crate) fn add_named_bytes_read( } // A standalone dBASE table is binary too, and uses the usual non-spatial table path. if name.to_ascii_lowercase().ends_with(".dbf") { - let read = rustgis_data::io::read_bytes(&name, &bytes).map_err(|e| e.to_string())?; + let read = rustgis_data::io::read_bytes_with_encoding(&name, &bytes, encoding).map_err(|e| e.to_string())?; return super::layer::add_read(s, p, read, zoom); } if name.to_ascii_lowercase().ends_with(".gz") && !rustgis_data::io::is_gzip_text_name(&name) { diff --git a/crates/engine/src/cmd/repair.rs b/crates/engine/src/cmd/repair.rs index fd614a1cc3..4ee258b296 100644 --- a/crates/engine/src/cmd/repair.rs +++ b/crates/engine/src/cmd/repair.rs @@ -356,6 +356,7 @@ fn install(s: &mut Session, prepared: Prepared) -> Result<(), String> { || current.path != prior.path || current.table != prior.table || current.shapefile_crs != prior.shapefile_crs + || current.dbf_encoding != prior.dbf_encoding || current.embedded != prior.embedded || current.file_name != prior.file_name || current.gdal != prior.gdal diff --git a/crates/engine/src/peer.rs b/crates/engine/src/peer.rs index 92221fd67b..6ee9a32177 100644 --- a/crates/engine/src/peer.rs +++ b/crates/engine/src/peer.rs @@ -170,6 +170,7 @@ fn source_choice(layer: Option<&rustgis_map::Layer>) -> Result, ( &s.file_name, &s.table, &s.shapefile_crs, + &s.dbf_encoding, s.embedded.as_deref(), s.gdal.as_ref().map(|g| (public(&g.path), &g.layer, g.family, &g.crs)), s.duckdb.as_ref().map(|d| { diff --git a/crates/engine/src/project.rs b/crates/engine/src/project.rs index 47bf4fee7c..068ca72fe3 100644 --- a/crates/engine/src/project.rs +++ b/crates/engine/src/project.rs @@ -141,6 +141,7 @@ pub const CAPABILITIES: &[&str] = &[ "layout-legend-column-breaks", "layout-legend-one-row", "layout-picture-source", + DBF_ENCODING, "layout-scale-bar-details", "label-guide", "label-weight", @@ -178,6 +179,8 @@ pub(crate) const PROJECT_CRS: &str = "project-crs"; /// A project saved with a layout open (`Project::open_layout`, #3446): an older reader would /// save it again without it. pub(crate) const PROJECT_OPEN_LAYOUT: &str = "project-open-layout"; +/// A layer or table keeping the explicit encoding used to read its dBASE text. +pub(crate) const DBF_ENCODING: &str = "dbf-encoding"; /// Independent marker sizes alongside classified point colours (`Layer::size_by`). pub(crate) const SIZE_BY_CAPABILITY: &str = "classified-point-size"; /// The most entries a document's `requires` may list: past it the document is refused without @@ -630,6 +633,8 @@ struct TableFile { #[serde(default)] source: Option, #[serde(default)] + dbf_encoding: Option, + #[serde(default)] crs: Option, #[serde(default)] crs_incomplete: bool, @@ -643,7 +648,7 @@ struct TableFile { impl From for Table { /// Loads stored data under a fresh runtime identity, never one supplied by the file. fn from(t: TableFile) -> Self { - let TableFile { id, name, geometry_type, fields, features, source, crs, crs_incomplete, zm_dropped, held_in } = t; + let TableFile { id, name, geometry_type, fields, features, source, dbf_encoding, crs, crs_incomplete, zm_dropped, held_in } = t; Table { id, instance_id: next_table_instance(), @@ -653,6 +658,7 @@ impl From for Table { fields, features: features.into(), source, + dbf_encoding, crs, crs_incomplete, zm_dropped, @@ -3038,6 +3044,7 @@ impl Durable for Table { fields: _, features: _, source: provenance, + dbf_encoding: _, crs: _, crs_incomplete: _, zm_dropped: _, diff --git a/crates/engine/src/project_capabilities.rs b/crates/engine/src/project_capabilities.rs index 21cc6ceef4..c6b2820184 100644 --- a/crates/engine/src/project_capabilities.rs +++ b/crates/engine/src/project_capabilities.rs @@ -63,6 +63,9 @@ impl Project { if !required.contains(&super::NATIVE_COORDINATES) && self.tables.iter().any(|t| held_natively(&t.dataset)) { required.push(super::NATIVE_COORDINATES); } + if !required.contains(&super::DBF_ENCODING) && self.tables.iter().any(|t| t.dataset.dbf_encoding.is_some()) { + required.push(super::DBF_ENCODING); + } if self.coordinate_system.is_some() || self.crs_from_first_layer { required.push(super::PROJECT_CRS); } @@ -481,6 +484,7 @@ const COMMAND_CAPABILITIES: &[(&str, CommandCheck)] = &[ ("layout-legend-column-breaks", command_uses_legend_column_breaks), ("layout-legend-one-row", command_uses_legend_one_row), ("layout-picture-source", command_uses_picture_source), + (super::DBF_ENCODING, command_uses_dbf_encoding), ("layout-scale-bar-details", command_uses_scale_bar_details), ("dggs-system", command_uses_dggs_system), ("label-weight", command_weighs_labels), @@ -1900,6 +1904,10 @@ fn shares_embedded_files(map: &Map) -> bool { map.layers.iter().filter_map(|l| l.raster.as_ref()?.embedded.as_ref()).any(|f| !seen.insert(std::sync::Arc::as_ptr(f))) } +fn has_dbf_encoding(layer: &Layer) -> bool { + layer.dataset.dbf_encoding.is_some() || layer.source.as_ref().is_some_and(|s| s.dbf_encoding.is_some()) +} + /// The capabilities a layer needs, in [`map_capabilities`]'s order. fn layer_capabilities(layer: &Layer) -> Vec<&'static str> { [ @@ -1923,6 +1931,7 @@ fn layer_capabilities(layer: &Layer) -> Vec<&'static str> { (label_clearance(layer), "label-clearance"), (removes_duplicate_labels(layer), "label-duplicates"), (held_natively(&layer.dataset), super::NATIVE_COORDINATES), + (has_dbf_encoding(layer), super::DBF_ENCODING), ] .into_iter() .filter_map(|(used, name)| used.then_some(name)) @@ -1951,6 +1960,7 @@ fn map_capabilities<'a>(maps: impl IntoIterator) -> Vec<&'static let (mut offline_area_id, mut paper, mut native, mut guided, mut weighed, mut cleared, mut deduped) = (false, false, false, false, false, false, false); let mut obstructing = false; + let mut dbf_encoding = false; let (mut crisp, mut bed, mut walls_top, mut soft, mut aerial, mut terrain_type, mut flats, mut generalize) = (false, false, false, false, false, false, false, false); for map in maps { @@ -1962,6 +1972,7 @@ fn map_capabilities<'a>(maps: impl IntoIterator) -> Vec<&'static obstructing |= map.layers.iter().any(label_obstacle); cleared |= map.layers.iter().any(label_clearance); deduped |= map.layers.iter().any(removes_duplicate_labels); + dbf_encoding |= map.layers.iter().any(has_dbf_encoding); // A tile layer drawn nearest (#2804), which an older reader would draw and save blended. crisp |= map.tiles.iter().any(|t| t.resampling != rustgis_map::raster::Resampling::Bilinear); // An older reader doesn't know the MGRS graticule (#1042 piece 8): it refuses the @@ -2040,6 +2051,7 @@ fn map_capabilities<'a>(maps: impl IntoIterator) -> Vec<&'static (offline_area_id, "offline-map-area-id"), (paper, "blank-paper"), (native, super::NATIVE_COORDINATES), + (dbf_encoding, super::DBF_ENCODING), (mgrs, "graticule-mgrs"), (on_top, "graticule-on-top"), (grid_color, "graticule-color"), @@ -2258,6 +2270,14 @@ fn group_file_requires(layers: &[Layer]) -> Vec<&'static str> { requires } +fn command_uses_dbf_encoding(id: &str, params: &Value) -> bool { + match id { + "layer.addData" | "layer.addDataBytes" | "layer.addDownload" => crate::cmd::layer::dbf_encoding(params).is_some(), + "script.run" => params.get("script").and_then(Value::as_str).is_some_and(|s| script_uses(s, command_uses_dbf_encoding)), + _ => false, + } +} + /// Only executable export options require the capability, not fields in unrelated data. /// Models and web tools run analysis tools, so cannot execute share.exportTable. fn command_uses_table_export_order(id: &str, params: &serde_json::Value) -> bool { @@ -3075,6 +3095,7 @@ mod tests { (&["layout-legend-column-breaks"], "layout.update", json!({"element": 1, "columnBreaks": ["a"]})), (&["layout-legend-one-row"], "layout.update", json!({"element": 1, "oneRow": true})), (&["layout-picture-source"], "layout.update", json!({"element": 1, "path": "logo.png"})), + (&[crate::project::DBF_ENCODING], "layer.addData", json!({"path": "places.shp", "encoding": 932})), (&["dggs-system"], "a5Grid", json!({"system": "H3"})), (&["dggs-system"], "a5Aggregate", json!({"system": "S2"})), (&["label-weight"], "labels.placement", json!({"weight": 9})), diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index 9ec6a43f0b..0638f6e502 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -2324,11 +2324,8 @@ 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. let says = |t: &str, encoding: &str| { - let why = if encoding == "UTF-8" { "no .cpg 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)) + ["1 text value", "'NAME'", "U+FFFD", ".cpg", &format!("isn't valid {encoding}")].iter().all(|k| t.contains(k)) }; // 臺北101 in Big5, and as many bytes of ASCII. The last value is named Big5 by its language // driver (0x4F) and ends in a lead byte; the one before it is valid Big5 and says nothing. @@ -67778,3 +67775,96 @@ fn a_linked_geoparquet_that_lost_its_geometry_is_not_reopened() { assert!(!linked.is_open() && e.contains("no geometry column"), "{e}"); std::fs::remove_dir_all(&dir).ok(); } + +#[test] +fn dbf_encoding_override_is_kept_across_add_data_routes() { + use base64::Engine; + use rustgis_data::{Coord, Dataset, Field, FieldType, Geometry, GeometryType, Value as Cell, loss::LossCode}; + + struct Dir(std::path::PathBuf); + impl Drop for Dir { + fn drop(&mut self) { + let _ = std::fs::remove_dir_all(&self.0); + } + } + let nanos = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).unwrap().as_nanos(); + let dir = Dir(std::env::temp_dir().join(format!("rustgis-dbf-encoding-{}-{nanos}", std::process::id()))); + std::fs::create_dir(&dir.0).unwrap(); + let dbf_path = dir.0.join("places.dbf"); + let project_path = dir.0.join("places.rgis"); + let expected = Cell::Text("東京".into()); + let mut data = Dataset::new("places", GeometryType::Point, vec![Field::new("name", FieldType::Text)]); + data.push_next(Some(Geometry::Point(Coord::new(139.0, 35.0))), vec![Cell::Text("test".into())]); + let (mut parts, _) = rustgis_data::io::shapefile_parts(&data).unwrap(); + let dbf = &mut parts.iter_mut().find(|(ext, _)| *ext == "dbf").unwrap().1; + dbf[29] = 0; + let row = u16::from_le_bytes([dbf[8], dbf[9]]) as usize; + dbf[row + 1..row + 5].copy_from_slice(&[0x93, 0x8c, 0x8b, 0x9e]); + let dbf = dbf.clone(); + std::fs::write(&dbf_path, &dbf).unwrap(); + + let mut s = Session::new(Project::default()); + for encoding in [json!(null), json!("UTF-8"), json!(" ")] { + let mark = s.notice_mark(); + let added = s.run("layer.addData", &json!({"path": dbf_path, "encoding": encoding})).unwrap(); + let fallback = &s.project.table(added["id"].as_u64().unwrap() as u32).unwrap().dataset; + assert_ne!(fallback.value(0, 0), &expected); + let losses: Vec<_> = s.notices_since(mark).iter().filter(|n| n.loss().is_some()).collect(); + assert_eq!(losses.len(), 1, "{losses:?}"); + assert_eq!(losses[0].loss(), Some(LossCode::ChangedEncoding)); + assert!(losses[0].text.contains("name") && losses[0].text.contains("1 text")); + } + + // An unusable declaration reports an assumption only when it must be consulted. + std::fs::write(dbf_path.with_extension("cpg"), "x-unknown").unwrap(); + let mark = s.notice_mark(); + s.run("layer.addData", &json!({"path": dbf_path})).unwrap(); + assert_eq!(s.notices_since(mark).iter().filter(|n| n.loss() == Some(LossCode::AssumedEncoding)).count(), 1); + let mark = s.notice_mark(); + let added = s.run("layer.addData", &json!({"path": dbf_path, "encoding": "CP932"})).unwrap(); + let error = s.run("layer.addData", &json!({"path": dbf_path, "encoding": "unknown"})).unwrap_err(); + assert!(error.contains("unsupported dBASE encoding") && error.contains("932"), "{error}"); + assert!(s.notices_since(mark).iter().all(|n| n.loss().is_none())); + s.project.save(&project_path).unwrap(); + let reopened = Project::load(&project_path).unwrap(); + let decoded = &reopened.table(added["id"].as_u64().unwrap() as u32).unwrap().dataset; + assert_eq!(decoded.value(0, 0), &expected); + assert_eq!(decoded.dbf_encoding.as_deref(), Some("CP932")); + + // A conflicting .cpg in the archive also loses to the supplied code page. + let zip = + rustgis_data::zip::write(&parts.iter().map(|(ext, bytes)| (format!("places.{ext}"), bytes.clone())).collect::>()).unwrap(); + let mut s = Session::new(Project::default()); + let mark = s.notice_mark(); + s.run( + "layer.addDataBytes", + &json!({"fileName": "places.zip", "data": base64::engine::general_purpose::STANDARD.encode(&zip), "encoding": 932}), + ) + .unwrap(); + let id = s.download_started(); + assert!(s.download_landed(id, dbf)); + s.run("layer.addDownload", &json!({"id": id, "url": "https://example.org/places.dbf", "encoding": 932})).unwrap(); + assert_eq!(s.map().layers[0].dataset.value(0, 0), &expected); + assert_eq!(s.project.tables[0].dataset.value(0, 0), &expected); + assert!(s.notices_since(mark).iter().all(|n| n.loss().is_none())); + + let mark = s.notice_mark(); + s.run("layer.addDataBytes", &json!({"fileName": "point.geojson", "data": base64::engine::general_purpose::STANDARD.encode(br#"{"type":"Point","coordinates":[1,2]}"#), "encoding": "unknown"})).unwrap(); + assert!(s.notices_since(mark).iter().any(|n| n.loss().is_none() && n.text.contains("encoding was ignored"))); + + for (ext, bytes) in &parts { + std::fs::write(dbf_path.with_extension(ext), bytes).unwrap(); + } + let mut s = Session::new(Project::default()); + let params = json!({"path": dbf_path.with_extension("shp"), "stream": true, "encoding": "Shift_JIS"}); + let read = crate::cmd::reads::read_ahead(&mut s, "layer.addData", ¶ms).unwrap(); + assert!(read.reads()); + let read = read.run(&rustgis_analysis::control::Control::new()).unwrap(); + crate::cmd::reads::read_land(&mut s, read).unwrap(); + s.project.save(&project_path).unwrap(); + let reopened = Project::load(&project_path).unwrap(); + let source = reopened.maps[0].layers[0].source.as_ref().unwrap(); + let (decoded, report) = source.read_all().unwrap(); + assert_eq!(decoded.value(0, 0), &expected); + assert!(report.messages.iter().all(|note| note.loss.is_none())); +} diff --git a/crates/map/src/lib.rs b/crates/map/src/lib.rs index da663228d6..d00c17da90 100644 --- a/crates/map/src/lib.rs +++ b/crates/map/src/lib.rs @@ -4228,6 +4228,7 @@ impl Layer { fields: _, features: _, source: provenance, + dbf_encoding: _, crs: _, crs_incomplete: _, zm_dropped: _, diff --git a/crates/map/src/look.rs b/crates/map/src/look.rs index 9c641a9f13..00e4baf8f9 100644 --- a/crates/map/src/look.rs +++ b/crates/map/src/look.rs @@ -351,7 +351,20 @@ fn same_time(a: Option<&crate::time::TimeBinding>, b: Option<&crate::time::TimeB /// Whether two datasets hold what a frame draws alike, their rows aside (compared by allocation). fn same_dataset(a: &Dataset, b: &Dataset) -> bool { - let Dataset { name, geometry_type, fields, features: _, source, crs, crs_incomplete, zm_dropped, windowed, held_in, shown_in } = a; + let Dataset { + name, + geometry_type, + fields, + features: _, + source, + dbf_encoding: _, + crs, + crs_incomplete, + zm_dropped, + windowed, + held_in, + shown_in, + } = a; *name == b.name && *geometry_type == b.geometry_type && *fields == b.fields diff --git a/crates/map/src/source.rs b/crates/map/src/source.rs index 4384299fc3..8dd932ec9b 100644 --- a/crates/map/src/source.rs +++ b/crates/map/src/source.rs @@ -132,6 +132,9 @@ pub struct SourceLayer { /// A Shapefile's source CRS override, reapplied when its path is reopened. #[serde(default, skip_serializing_if = "Option::is_none")] pub shapefile_crs: Option, + /// A Shapefile's dBASE encoding override, reapplied when its path is reopened. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub dbf_encoding: Option, /// The original file, kept in the project when there is no path (a browser upload). #[serde(default, skip_serializing_if = "Option::is_none", with = "crate::raster::b64")] pub embedded: Option>>, @@ -898,6 +901,7 @@ impl SourceLayer { file_name: _, table: _, shapefile_crs, + dbf_encoding: _, embedded: _, handle: _, conversion_info: _, @@ -1162,8 +1166,13 @@ impl SourceLayer { if self.embedded.is_some() || self.postgis.is_some() || self.mysql.is_some() || self.sqlserver.is_some() { return Err("the layer reads a database or data kept in the project: there's no file to repair".into()); } - let mut new = - SourceLayer { shapefile_crs: self.shapefile_crs, limit: self.limit, byte_budget: self.byte_budget, ..Default::default() }; + let mut new = SourceLayer { + shapefile_crs: self.shapefile_crs, + dbf_encoding: self.dbf_encoding.clone().filter(|_| path.to_ascii_lowercase().ends_with(".shp")), + limit: self.limit, + byte_budget: self.byte_budget, + ..Default::default() + }; let mut conversion_notes = rustgis_data::loss::Notes::new(); let declared_empty; let conversion_zm_dropped; @@ -1627,7 +1636,7 @@ impl SourceLayer { } } #[cfg(not(target_arch = "wasm32"))] - let overridden = self.shapefile_crs.filter(|_| p.to_ascii_lowercase().ends_with(".shp")); + let overridden = (self.shapefile_crs.is_some() || self.dbf_encoding.is_some()) && p.to_ascii_lowercase().ends_with(".shp"); #[cfg(not(target_arch = "wasm32"))] if p.to_ascii_lowercase().ends_with(".fgb") { let path = std::path::Path::new(p); @@ -1651,10 +1660,15 @@ impl SourceLayer { let path = std::path::Path::new(p); let name = path.file_stem().and_then(|s| s.to_str()).unwrap_or("layer"); ParquetSource::open_converted_path(path, name, original, None).map(|src| Box::new(src) as Box) - } else if let Some(crs) = overridden { + } else if overridden { let name = std::path::Path::new(p).file_stem().and_then(|s| s.to_str()).unwrap_or("layer"); - rustgis_data::source::shp::ShpSource::open_path_in(std::path::Path::new(p), name, Some(crs)) - .map(|src| Box::new(src) as Box) + rustgis_data::source::shp::ShpSource::open_path_with_encoding( + std::path::Path::new(p), + name, + self.shapefile_crs, + self.dbf_encoding.as_deref(), + ) + .map(|src| Box::new(src) as Box) } else { rustgis_data::source::open_path_for_fields(std::path::Path::new(p), self.table.as_deref(), fields) } @@ -2452,6 +2466,7 @@ impl SourceLayer { file_name: _, table: _, shapefile_crs: _, + dbf_encoding: _, embedded, handle: _, window: _, diff --git a/crates/plugins/src/tools.rs b/crates/plugins/src/tools.rs index d17c4753ab..38c679b670 100644 --- a/crates/plugins/src/tools.rs +++ b/crates/plugins/src/tools.rs @@ -206,6 +206,7 @@ fn layer_geojson(inputs: &dyn Inputs, name: &str) -> Result { fields: ds.fields.clone(), features: sel.iter().filter_map(|&i| ds.features.get(i).cloned()).collect(), source: None, + dbf_encoding: None, crs: None, crs_incomplete: false, zm_dropped: false, diff --git a/crates/ui-egui/src/layerchooser.rs b/crates/ui-egui/src/layerchooser.rs index 5b486e793b..bdc820c9dc 100644 --- a/crates/ui-egui/src/layerchooser.rs +++ b/crates/ui-egui/src/layerchooser.rs @@ -16,6 +16,7 @@ pub struct Chooser { /// Its layers, and whether each is ticked. layers: Vec<(String, bool)>, filter: String, + encoding: String, /// Whether its layers are chosen (Ask Which Layers to Add on, and a file that lists them). pick: bool, /// Copy into the project or link to the file, for a file Add Data can link (`"link"`). @@ -121,6 +122,7 @@ pub fn add_file(app: &mut RustGisApp, path: &str) -> Result { listing: Some(slot), layers: Vec::new(), filter: String::new(), + encoding: String::new(), pick, link: None, opened, @@ -170,11 +172,14 @@ pub(crate) fn add(app: &mut RustGisApp, p: Value) -> Result { /// Adds the layers ticked, each by name (a failure is told, by the command, and the rest still /// added), or the whole file when none are listed; `linked` as the user answered (#2350). -fn add_chosen(app: &mut RustGisApp, path: &str, layers: &[String], linked: Option) { +fn add_chosen(app: &mut RustGisApp, path: &str, layers: &[String], linked: Option, encoding: &str) { let with = |mut p: Value| { if let Some(linked) = linked { p["stream"] = json!(linked); } + if !encoding.is_empty() { + p["encoding"] = json!(encoding); + } p }; if layers.is_empty() { @@ -262,6 +267,14 @@ pub fn show(app: &mut RustGisApp, ctx: &egui::Context) { && c.layers.is_empty() { link_choice(ui, link, &t); + if c.path.to_ascii_lowercase().ends_with(".shp") { + ui.horizontal_wrapped(|ui| { + let label = ui.label(tl!("dBASE encoding")); + ui.add(egui::TextEdit::singleline(&mut c.encoding).hint_text(tl!("Automatic")).desired_width(144.0)) + .labelled_by(label.id) + .on_hover_text(tl!("Enter a code page name or number, such as Shift_JIS or 932.")); + }); + } ui.horizontal(|ui| { if crate::widgets::dialog_button(ui, tl!("Add"), Some(t.accent), egui::vec2(84.0, 28.0)).clicked() || (keys_free && ui.input_mut(|i| i.consume_key(egui::Modifiers::NONE, egui::Key::Enter))) @@ -322,8 +335,9 @@ pub fn show(app: &mut RustGisApp, ctx: &egui::Context) { // would decide by its count once it is read in place. let geojson = path.trim().to_ascii_lowercase().ends_with(".geojson"); let linked = c.link.as_ref().filter(|l| geojson || l.answered || l.linked != l.rule).map(|l| l.linked); + let encoding = c.encoding.trim().to_owned(); app.ui.choosing.remove(0); - add_chosen(app, &path, &layers, linked); + add_chosen(app, &path, &layers, linked, &encoding); } else if cancel || !open { app.ui.choosing.remove(0); } @@ -406,6 +420,7 @@ mod tests { listing: Some(slot), layers: Vec::new(), filter: String::new(), + encoding: String::new(), pick: true, link: None, opened, diff --git a/docs/maintaining.md b/docs/maintaining.md index 5707d26073..cdeeb7f06f 100644 --- a/docs/maintaining.md +++ b/docs/maintaining.md @@ -310,6 +310,10 @@ Projects saved with a layout open (`open_layout`) require `project-open-layout`, reader refuses them instead of saving them again without it (#3446). A project saved on the map view has no such key and requires nothing for it. +Projects with a dBASE encoding override in a layer, table or saved command require +`dbf-encoding`. Older readers refuse the project before they can drop the setting or read +a linked Shapefile with a different decoder. + Projects with a layout table whose columns are chosen (`fields` on a table element), whose text isn't 8 points (`text_size`) or whose header is off (`header`) require `layout-table-look`, so an older reader refuses them instead of drawing the whole table and saving it again without (#3409). diff --git a/docs/user-guide/data-formats.md b/docs/user-guide/data-formats.md index 886a37188e..8db3167e68 100644 --- a/docs/user-guide/data-formats.md +++ b/docs/user-guide/data-formats.md @@ -55,8 +55,12 @@ 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. +For Shapefile and standalone dBASE text, an explicit `encoding` (for example, `"Shift_JIS"` +or `932`) takes precedence over file metadata. Use it in `layer.addData` or `layer.addDataBytes` +for loose or zipped dBASE data. The host can also supply it in the internal +`layer.addDownload` completion command. Other formats report that they ignored the option. +Without an override, Shapefile text uses a supported `.cpg` first, then the language-driver +code in the `.dbf` header. Include the `.cpg` when picking or dropping loose files in the web app. 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 diff --git a/docs/user-guide/data.md b/docs/user-guide/data.md index 982b964ee8..16831e4225 100644 --- a/docs/user-guide/data.md +++ b/docs/user-guide/data.md @@ -304,7 +304,15 @@ 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 +For a loose Shapefile on the desktop, enter a **dBASE encoding** in the Add Data dialog to +override the file's encoding. Leave it blank to use the file metadata. The `encoding` command +parameter also works for standalone dBASE tables and Shapefiles or dBASE tables inside a ZIP. +For example, add a Japanese Shapefile without encoding metadata using +`layer.addData {"path":"places.shp","encoding":932}` or Python +`project.add_data("places.shp", encoding="Shift_JIS")`. For a browser upload, pass `encoding` +to `layer.addDataBytes` with the dBASE file or zipped Shapefile. Saved projects keep the choice. + +Without an override, 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, write that label to a diff --git a/docs/user-guide/loss-codes.md b/docs/user-guide/loss-codes.md index d586525032..6e2850a1d5 100644 --- a/docs/user-guide/loss-codes.md +++ b/docs/user-guide/loss-codes.md @@ -186,7 +186,7 @@ Text could not be represented in its source or destination encoding, so replacem **Where you see it:** reading a Shapefile or dBASE file, a DXF drawing, or feature service answers in PBF; exporting copyright text in a GeoTIFF or COG. -**What to do:** Give the source's encoding in a form RustGIS reads: a .cpg beside a Shapefile or dBASE file, a DXF saved as UTF-8 or with its $DWGCODEPAGE, or a service that sends UTF-8. TIFF copyright tags hold ASCII only; keep the original credits with the exported file. +**What to do:** For a Shapefile or dBASE table, set the encoding Add Data parameter or provide a matching .cpg file. Save a DXF as UTF-8 or with its $DWGCODEPAGE, or use a service that sends UTF-8. TIFF copyright tags hold ASCII only. Keep the original credits with the exported file. ### `changed.rounded` { #changed.rounded } @@ -252,4 +252,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 file, 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:** For a Shapefile or dBASE table, set the encoding Add Data parameter or provide a matching .cpg file. Save a DXF as UTF-8. diff --git a/docs/user-guide/shapefile-encoding.md b/docs/user-guide/shapefile-encoding.md index 03a761bd3d..6a1efb5a03 100644 --- a/docs/user-guide/shapefile-encoding.md +++ b/docs/user-guide/shapefile-encoding.md @@ -1,6 +1,7 @@ # Shapefile DBF language drivers -A valid `.cpg` takes precedence over the language driver ID (LDID, byte 29 of the `.dbf` +An explicit `encoding` in Add Data takes precedence over both declarations. Otherwise, +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. All numbers in the marker column are hexadecimal. These are language-driver identifiers, not the numeric code-page labels accepted in a `.cpg`. @@ -65,8 +66,7 @@ fields, and another counts such field names. A file whose text is all valid UTF- 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 +notices name the encoding, the affected fields and the count of changed values and field names. 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, diff --git a/schema/fixtures/dbf_encoding.rgis b/schema/fixtures/dbf_encoding.rgis new file mode 100644 index 0000000000..888068750a --- /dev/null +++ b/schema/fixtures/dbf_encoding.rgis @@ -0,0 +1,18 @@ +{ + "format": 2, + "requires": ["dbf-encoding"], + "name": "dBASE encoding override", + "maps": [], + "active_map": 0, + "tables": [ + { + "id": 1, + "name": "Places", + "geometry_type": "None", + "fields": [{"name": "name", "ty": "Text"}], + "features": [{"id": 1, "geometry": null, "attrs": [{"Text": "東京"}]}], + "source": "places.dbf", + "dbf_encoding": "932" + } + ] +} diff --git a/schema/project.schema.json b/schema/project.schema.json index 55d1114138..31747f9956 100644 --- a/schema/project.schema.json +++ b/schema/project.schema.json @@ -872,6 +872,13 @@ "default": false, "type": "boolean" }, + "dbf_encoding": { + "default": null, + "type": [ + "string", + "null" + ] + }, "features": { "items": { "$ref": "#/$defs/Feature" @@ -1310,6 +1317,7 @@ "layout-legend-column-breaks", "layout-legend-one-row", "layout-picture-source", + "dbf-encoding", "layout-scale-bar-details", "label-guide", "label-weight", @@ -1461,6 +1469,7 @@ "layout-legend-column-breaks", "layout-legend-one-row", "layout-picture-source", + "dbf-encoding", "layout-scale-bar-details", "label-guide", "label-weight",