diff --git a/crates/data/src/io.rs b/crates/data/src/io.rs index 717581ad33..2dfc8ab8c2 100644 --- a/crates/data/src/io.rs +++ b/crates/data/src/io.rs @@ -20,6 +20,7 @@ pub const READ_EXTENSIONS: &[&str] = &[ "dat", "gz", "shp", + "dbf", "zip", "kml", "kmz", @@ -269,7 +270,8 @@ 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" | "shx" | "prj" | "cpg" => { + "dbf" => read_dbf(bytes.to_vec(), None, &name, &mut csv_memory_budget())?, + "shx" | "prj" | "cpg" => { return Err(DataError::Unsupported(format!("{ext} on its own: it is part of a Shapefile; add it together with its .shp"))); } // The first layer (`read_layers` reads them all), saying what else the file holds. @@ -305,6 +307,9 @@ 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)> { + if let Some(shp) = shapefile_for_dbf(path) { + return read_path(&shp); + } 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(); let mut out = match ext.as_str() { @@ -328,6 +333,14 @@ pub fn read_path(path: &Path) -> Result<(Dataset, ReadReport)> { check_size(path)?; read_gzip_text(std::io::BufReader::new(std::fs::File::open(path)?), &path.display().to_string(), &CsvOptions::default())? } + "dbf" => { + check_size(path)?; + let mut notes = Vec::new(); + let cpg = crate::dbf::read_cpg(path, &mut notes); + let (ds, mut report) = read_dbf(std::fs::read(path)?, cpg.as_deref(), &name, &mut csv_memory_budget())?; + report.messages.extend(notes); + (ds, report) + } "shp" => { check_size(path)?; let dbf = path.with_extension("dbf"); @@ -2418,6 +2431,25 @@ impl CsvWriter { // --------------------------------------------------------------------------------------------- // Shapefile +/// A DBF picked by its path opens the Shapefile beside it when present. Try every ASCII +/// spelling of the extension without scanning a directory; standalone tables return `None`. +pub fn shapefile_for_dbf(path: &Path) -> Option { + if !path.extension().is_some_and(|e| e.eq_ignore_ascii_case("dbf")) { + return None; + } + ["shp", "SHP", "Shp", "sHp", "shP", "SHp", "ShP", "sHP"].iter().map(|e| path.with_extension(e)).find(|p| p.is_file()) +} + +/// Finds the attributes beside a Shapefile, accepting every ASCII case of `.dbf` in whole +/// and streamed reads. A missing sidecar keeps the usual lowercase path for the error. +pub(crate) fn dbf_sidecar(path: &Path) -> std::path::PathBuf { + ["dbf", "DBF", "Dbf", "dBf", "dbF", "DBf", "DbF", "dBF"] + .iter() + .map(|e| path.with_extension(e)) + .find(|p| p.is_file()) + .unwrap_or_else(|| path.with_extension("dbf")) +} + /// Reads a loose Shapefile using its sidecar CRS, retaining the default reader's behavior. fn read_shapefile(path: &Path, name: &str) -> Result<(Dataset, ReadReport)> { read_shapefile_in(path, name, None) @@ -2427,7 +2459,7 @@ fn read_shapefile(path: &Path, name: &str) -> Result<(Dataset, ReadReport)> { /// 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)> { check_size(path)?; - let dbf = path.with_extension("dbf"); + let dbf = dbf_sidecar(path); if !dbf.is_file() { return Err(DataError::Format(format!("Shapefile: {} is missing", dbf.display()))); } @@ -2456,9 +2488,9 @@ const SHAPEFILE_SIDECARS: [&str; 4] = ["dbf", "shx", "prj", "cpg"]; /// dropped at once) into a zip that reads as a zipped Shapefile: a `.shp` with the `.dbf` of the /// same base name, ignoring case, and its `.shx`, `.prj` and `.cpg` when they are there. The zip, /// named after the `.shp`, takes its place; its parts go. Other files, and a `.shp` without its -/// `.dbf`, pass through as they came. A Shapefile whose parts are too large to read together (more -/// than [`MAX_BYTES`], or the zip reader's limit) is left out, and said why in the messages -/// returned with the files. +/// `.dbf`, pass through as they came. A standalone `.dbf` with a `.cpg` is zipped with it too. +/// Files whose parts are too large to read together (more than [`MAX_BYTES`], or the zip +/// reader's limit) are left out, with an explanation in the messages returned with the files. pub fn gather_shapefiles(files: Vec<(String, Vec)>) -> (Vec<(String, Vec)>, Vec) { let ext_of = |n: &str| Path::new(n).extension().and_then(|e| e.to_str()).map(|e| e.to_ascii_lowercase()).unwrap_or_default(); let stem = |n: &str| Path::new(n).file_stem().and_then(|s| s.to_str()).unwrap_or("").to_ascii_lowercase(); @@ -2486,6 +2518,18 @@ pub fn gather_shapefiles(files: Vec<(String, Vec)>) -> (Vec<(String, Vec *slot = Some(parts); } } + // A standalone DBF's .cpg travels through the browser's Services inbox in the same zip. + for i in 0..files.len() { + let Some(base) = files.get(i).and_then(Option::as_ref).filter(|(n, _)| ext_of(n) == "dbf").map(|(n, _)| stem(n)) else { + continue; + }; + let Some(j) = sidecar(&files, &base, "cpg") else { continue }; + let mut parts: Vec<_> = files.get_mut(i).and_then(Option::take).into_iter().collect(); + parts.extend(files.get_mut(j).and_then(Option::take)); + if let Some(slot) = zips.get_mut(i) { + *slot = Some(parts); + } + } // The zip must open again: within the read size and the zip reader's inflated total. let limit = crate::zip::MAX_TOTAL.min(usize::try_from(MAX_BYTES).unwrap_or(usize::MAX)); let (mut out, mut problems) = (Vec::new(), Vec::new()); @@ -2497,8 +2541,7 @@ pub fn gather_shapefiles(files: Vec<(String, Vec)>) -> (Vec<(String, Vec let shp = parts.first().map(|(n, _)| n.clone()).unwrap_or_else(|| "layer.shp".into()); let zip_name = format!("{}.zip", Path::new(&shp).file_stem().and_then(|s| s.to_str()).unwrap_or("layer")); let total = parts.iter().fold(0usize, |sum, (_, b)| sum.saturating_add(b.len())); - let too_large = - || format!("{shp}: its Shapefile's files hold {} MB in all; at most {} MB can be read together", total >> 20, limit >> 20); + let too_large = || format!("{shp}: its data files hold {} MB in all; at most {} MB can be read together", total >> 20, limit >> 20); if total > limit { problems.push(too_large()); continue; @@ -2597,7 +2640,7 @@ pub fn shapefile_zip_lacks(bytes: &[u8]) -> Vec<(String, Vec<&'static str>)> { .collect() } -/// Most layers read from one zip archive. +/// Most layers and standalone tables read together from one zip archive. pub const MAX_ZIP_LAYERS: usize = 32; /// A text table has matching CSV records, or an identifier-only header for an empty table. @@ -2624,8 +2667,9 @@ fn delimited_table_columns(text: &str) -> usize { /// Reads the vector data in a zip archive: each Shapefile in it (its `.shp` with the `.dbf`, /// `.shx` and `.prj` beside it), then every other file the readers understand (GeoJSON, CSV, -/// GeoParquet, FlatGeobuf…; `.txt` files that sniff as delimited text become tables or points), at most -/// [`MAX_ZIP_LAYERS`]. Folders inside are fine; macOS +/// GeoParquet, FlatGeobuf…; unpaired `.dbf` files become tables, and `.txt` files that sniff as +/// delimited text become tables or points), at most [`MAX_ZIP_LAYERS`] layers and tables together. +/// Folders inside are fine; macOS /// resource forks (`__MACOSX/`, `._*`) are ignored. pub fn read_zip(file_name: &str, bytes: &[u8]) -> Result> { read_zip_in(file_name, bytes, None) @@ -2674,6 +2718,7 @@ fn read_zip_budget(file_name: &str, bytes: &[u8], crs: Option, budget: &mut let mut entries: Vec)>> = entries.into_iter().map(Some).collect(); let mut shps: Vec = entries.iter().flatten().filter(|(n, _)| ext_of(n) == "shp").map(|(n, _)| n.clone()).collect(); shps.sort(); + let shp_stems: Vec<_> = shps.iter().map(|n| stem(n)).collect(); let take = |entries: &mut Vec)>>, base: &str, ext: &str| -> Option<(String, Vec)> { entries.iter_mut().find(|e| e.as_ref().is_some_and(|(n, _)| ext_of(n) == ext && stem(n) == base))?.take() }; @@ -2712,7 +2757,8 @@ fn read_zip_budget(file_name: &str, bytes: &[u8], crs: Option, budget: &mut for n in mifs { // The `.mif` files not taken stay in `entries`, so the loop below names them as past the limit. if out.len() >= MAX_ZIP_LAYERS { - break; + let _ = take(&mut entries, &stem(&n), "mid"); + continue; } let base = stem(&n); let name = Path::new(&n).file_stem().and_then(|s| s.to_str()).unwrap_or("layer").to_string(); @@ -2727,12 +2773,19 @@ fn read_zip_budget(file_name: &str, bytes: &[u8], crs: Option, budget: &mut Err(e) => skipped.push(format!("{n} ({e})")), } } - let mut others: Vec<(String, Vec)> = - entries.into_iter().flatten().filter(|(n, _)| !matches!(ext_of(n).as_str(), "shp" | "shx" | "prj" | "cpg" | "mid")).collect(); + let mut others: Vec<(String, Vec)> = entries + .iter_mut() + .filter(|e| e.as_ref().is_some_and(|(n, _)| !matches!(ext_of(n).as_str(), "shp" | "shx" | "prj" | "cpg"))) + .filter_map(Option::take) + .collect(); others.sort_by(|a, b| a.0.cmp(&b.0)); for (n, b) in others { - if ext_of(&n) == "dbf" { - skipped.push(format!("{n} (a .dbf table without a .shp is not read)")); + if ext_of(&n) == "mid" { + skipped.push(format!("{n} (no .mif beside it)")); + continue; + } + if ext_of(&n) == "dbf" && shp_stems.contains(&stem(&n)) { + skipped.push(format!("{n} (an extra .dbf sidecar of a Shapefile)")); continue; } // Prose readmes aren't tables; optional empty GTFS tables still have headers. @@ -2750,7 +2803,11 @@ fn read_zip_budget(file_name: &str, bytes: &[u8], crs: Option, budget: &mut } let leaf = n.rsplit('/').next().unwrap_or(&n); // A city model has many layers. - let read = if is_city_model(leaf, &b) { + let read = if ext_of(&n) == "dbf" { + let cpg = take(&mut entries, &stem(&n), "cpg").map(|(_, b)| b); + let name = Path::new(leaf).file_stem().and_then(|s| s.to_str()).unwrap_or("table"); + read_dbf(b, cpg.as_deref(), name, budget).map(|r| vec![r]) + } else if is_city_model(leaf, &b) { read_city_member(leaf, &b, crs) } else if is_delimited_name(leaf) { read_delimited_bytes_budget(leaf, &b, &CsvOptions { crs, ..Default::default() }, budget).map(|r| vec![r]) @@ -2803,33 +2860,28 @@ fn read_zip_budget(file_name: &str, bytes: &[u8], crs: Option, budget: &mut Ok(out) } -/// The files of a Shapefile, read into memory. -pub(crate) struct ShapefileParts { - pub shp: Vec, - pub shx: Option>, - pub dbf: Vec, - pub prj: Option, - pub cpg: Option>, +/// The same schema, decoder and numeric declarations for loose tables and Shapefile attributes. +struct DbfRead { + reader: shapefile::dbase::Reader>>, + fields: Vec, + decimals: Vec, + report: ReadReport, } -/// 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(mut parts: ShapefileParts, name: &str, crs: Option) -> Result<(Dataset, ReadReport)> { - use shapefile::Shape; - use shapefile::dbase::FieldValue; +/// Opens dBASE attributes with the Shapefile reader's code-page and date/number handling. +fn dbf_reader(mut bytes: Vec, cpg: Option<&[u8]>) -> Result { use std::io::Cursor; - let fmt = |e: shapefile::Error| DataError::Format(format!("Shapefile: {e}")); let mut encoding_notes = Vec::new(); - let encoding = crate::dbf::encoding(parts.cpg.as_deref(), parts.dbf.get(29).copied().unwrap_or(0), &mut encoding_notes); - crate::dbf::readable_header_date(&mut parts.dbf); - let date_columns = crate::dbf::dates_as_text(&mut parts.dbf); - crate::dbf::floats_as_numeric(&mut parts.dbf); - let decimals = crate::dbf::field_decimals(&parts.dbf); + let encoding = crate::dbf::encoding(cpg, bytes.get(29).copied().unwrap_or(0), &mut encoding_notes); + crate::dbf::readable_header_date(&mut bytes); + let date_columns = crate::dbf::dates_as_text(&mut bytes); + crate::dbf::floats_as_numeric(&mut bytes); + let decimals = crate::dbf::field_decimals(&bytes); let dbf = shapefile::dbase::ReaderBuilder::new() .with_encoding(encoding.decoder()) // A date's year may be padded with spaces on the left (` 10101`): keep them. .with_options(shapefile::dbase::ReadingOptions::default().character_trim(shapefile::dbase::TrimOption::End)) - .build(Cursor::new(parts.dbf)) + .build(Cursor::new(bytes)) .map_err(|e| DataError::Format(format!("Shapefile: the .dbf: {e}")))?; // Field order comes from the .dbf header (records are unordered maps). let order: Vec<(String, FieldType)> = dbf @@ -2849,16 +2901,136 @@ pub(crate) fn read_shapefile_parts(mut parts: ShapefileParts, name: &str, crs: O (f.name().to_string(), ty) }) .collect(); + let fields = order.into_iter().map(|(n, t)| Field::new(n, t)).collect(); + Ok(DbfRead { reader: dbf, fields, decimals, report: ReadReport { messages: encoding_notes, ..Default::default() } }) +} + +/// Reads a geometry-free dBASE table, checking cancellation and counting progress per record. +/// Charges retained rows and cell allocations, with room for vector capacity, against the +/// same budget as delimited tables; archive members share the remaining allowance. +/// The bounded file read and header decoding finish before cancellation can be observed. +fn read_dbf(bytes: Vec, cpg: Option<&[u8]>, name: &str, budget: &mut usize) -> Result<(Dataset, ReadReport)> { + let DbfRead { mut reader, fields, decimals, mut report } = dbf_reader(bytes, cpg)?; + let mut ds = Dataset::new(name, GeometryType::None, fields); + let mut unread_dates = vec![0; ds.fields.len()]; + let mut nonfinite = vec![0; ds.fields.len()]; + let allowance = *budget; + let mut left = allowance; + crate::progress::begin(reader.header().num_records as usize); + for record in reader.iter_records() { + crate::progress::step(1)?; + match record { + Ok(record) => { + let attrs = dbf_attrs(&record, &ds.fields, &mut unread_dates, &mut nonfinite); + let cost = attrs + .iter() + .fold( + std::mem::size_of::().saturating_add(attrs.capacity().saturating_mul(std::mem::size_of::())), + |sum, value| { + sum.saturating_add(match value { + Value::Text(s) => s.capacity(), + _ => 0, + }) + }, + ) + .saturating_mul(2); + left = left.checked_sub(cost).ok_or_else(|| { + DataError::Format(format!( + "{name}: dBASE retained table exceeds the {allowance}-byte remaining memory budget; import a smaller file" + )) + })?; + ds.push_next(None, attrs); + } + // An I/O failure can leave dbase's iterator at the same record forever. + Err(e) if matches!(e.kind(), shapefile::dbase::ErrorKind::IoError(_)) => { + return Err(DataError::Format(format!("{name}: the .dbf: {e}"))); + } + Err(_) => report.skipped += 1, + } + } + // The iterator passes over records marked deleted; the header still counts them. + let deleted = (reader.header().num_records as usize).saturating_sub(ds.features.len() + report.skipped); + if deleted > 0 { + report.messages.push(format!("{name}: {deleted} dBASE records marked deleted were left out")); + } + dbf_notices(&ds, &mut report, &unread_dates, &nonfinite); + integral_numeric_to_integer(&mut ds, &decimals); + if report.skipped > 0 { + report.messages.push(format!("{name}: {} dBASE records were unreadable and left out", report.skipped)); + } + *budget = left; + Ok((ds, report)) +} + +/// Converts one record to typed values, sharing loss counts with the containing dataset. +fn dbf_attrs(record: &shapefile::dbase::Record, fields: &[Field], unread_dates: &mut [usize], nonfinite: &mut [usize]) -> Vec { + use shapefile::dbase::FieldValue; + fields + .iter() + .zip(unread_dates.iter_mut().zip(nonfinite.iter_mut())) + .map(|(f, (unread, nonfinite))| match record.get(&f.name) { + Some(FieldValue::Character(Some(s))) if f.ty == FieldType::Date => match crate::dbf::date(s.as_bytes()) { + Ok(d) => d.map_or(Value::Null, Value::Date), + Err(()) => { + *unread += 1; + Value::Null + } + }, + Some(FieldValue::Character(Some(s))) => Value::Text(s.trim().to_string()), + Some(FieldValue::Numeric(Some(n))) if n.is_finite() => Value::Float(*n), + Some(FieldValue::Numeric(Some(_))) => { + *nonfinite += 1; + Value::Null + } + Some(FieldValue::Integer(i)) => Value::Int(i64::from(*i)), + Some(FieldValue::Double(d)) => Value::Float(*d), + Some(FieldValue::Currency(d)) => Value::Float(*d), + Some(FieldValue::Logical(Some(b))) => Value::Bool(*b), + Some(FieldValue::Memo(s)) => Value::Text(s.clone()), + _ => Value::Null, + }) + .collect() +} + +/// Reports date and numeric cells read as null, identically for tables and Shapefiles. +fn dbf_notices(ds: &Dataset, report: &mut ReadReport, unread_dates: &[usize], nonfinite: &[usize]) { + let name = &ds.name; + report.unread_dates = crate::source::unread_dates_note(&ds.fields, unread_dates); + report.messages.extend(report.unread_dates.iter().map(|n| format!("{name}: {n}"))); + let nonfinite_total: usize = nonfinite.iter().sum(); + if nonfinite_total > 0 { + let what = if nonfinite_total == 1 { + "1 number isn't finite (nan or inf) and was".to_string() + } else { + format!("{nonfinite_total} numbers aren't finite (nan or inf) and were") + }; + report.messages.push(format!("{name}: {what} read as empty, in {}", named_fields(&ds.fields, nonfinite))); + } +} + +/// The files of a Shapefile, read into memory. +pub(crate) struct ShapefileParts { + pub shp: Vec, + pub shx: Option>, + pub dbf: Vec, + pub prj: Option, + pub cpg: Option>, +} + +/// 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)> { + use shapefile::Shape; + use std::io::Cursor; + let fmt = |e: shapefile::Error| DataError::Format(format!("Shapefile: {e}")); + let DbfRead { reader: dbf, fields, decimals, mut report } = dbf_reader(parts.dbf, parts.cpg.as_deref())?; let 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 reader = shapefile::Reader::new(shapes, dbf); - let fields: Vec = order.iter().map(|(n, t)| Field::new(n.clone(), *t)).collect(); let mut ds = Dataset::new(name, GeometryType::None, fields); - let mut report = ReadReport::default(); - report.messages.extend(encoding_notes); let to_lonlat = match crs { Some(c) => { ds.crs = Some(c); @@ -2935,46 +3107,11 @@ pub(crate) fn read_shapefile_parts(mut parts: ShapefileParts, name: &str, crs: O } (_, g) => g, }; - let attrs = ds - .fields - .iter() - .zip(unread_dates.iter_mut().zip(nonfinite.iter_mut())) - .map(|(f, (unread, nonfinite))| match record.get(&f.name) { - Some(FieldValue::Character(Some(s))) if f.ty == FieldType::Date => match crate::dbf::date(s.as_bytes()) { - Ok(d) => d.map_or(Value::Null, Value::Date), - Err(()) => { - *unread += 1; - Value::Null - } - }, - Some(FieldValue::Character(Some(s))) => Value::Text(s.trim().to_string()), - Some(FieldValue::Numeric(Some(n))) if n.is_finite() => Value::Float(*n), - Some(FieldValue::Numeric(Some(_))) => { - *nonfinite += 1; - Value::Null - } - Some(FieldValue::Integer(i)) => Value::Int(i64::from(*i)), - Some(FieldValue::Double(d)) => Value::Float(*d), - Some(FieldValue::Currency(d)) => Value::Float(*d), - Some(FieldValue::Logical(Some(b))) => Value::Bool(*b), - Some(FieldValue::Memo(s)) => Value::Text(s.clone()), - _ => Value::Null, - }) - .collect(); + let attrs = dbf_attrs(&record, &ds.fields, &mut unread_dates, &mut nonfinite); ds.push_next(geom, attrs); } ds.drop_zm(&mut report, zm_shapes); - report.unread_dates = crate::source::unread_dates_note(&ds.fields, &unread_dates); - report.messages.extend(report.unread_dates.iter().map(|n| format!("{name}: {n}"))); - let nonfinite_total: usize = nonfinite.iter().sum(); - if nonfinite_total > 0 { - let what = if nonfinite_total == 1 { - "1 number isn't finite (nan or inf) and was".to_string() - } else { - format!("{nonfinite_total} numbers aren't finite (nan or inf) and were") - }; - report.messages.push(format!("{name}: {what} read as empty, in {}", named_fields(&ds.fields, &nonfinite))); - } + dbf_notices(&ds, &mut report, &unread_dates, &nonfinite); ds.geometry_type = dominant_type(&ds); // A bad .prj must not turn a spatial layer into an attribute-only table and hide the // conversion warning. Its shapes can be recovered by importing with an override. @@ -6033,10 +6170,10 @@ mod tests { assert!(layers[0].1.messages.iter().any(|m| m.contains(".gdb folder"))); } - /// A DBF in another folder isn't a Shapefile sidecar, even with the same base name. Name - /// the unsupported table instead of losing it silently; paired sidecars need no notice. + /// A DBF in another folder is a table, even with the Shapefile's base name. Both read; + /// paired sidecars and resource forks never become extra tables. #[test] - fn zipped_standalone_dbf_is_named_in_notice() { + fn zipped_standalone_dbf_opens_as_table() { let mut ds = Dataset::new("places", GeometryType::Point, vec![Field::new("name", FieldType::Text)]); ds.push_next(Some(Geometry::Point(Coord::new(1.0, 2.0))), vec![Value::Text("one".into())]); ds.push_next(Some(Geometry::Point(Coord::new(3.0, 4.0))), vec![Value::Text("two".into())]); @@ -6054,22 +6191,138 @@ mod tests { entries.push(("tables/Places.DBF".into(), dbf.clone())); entries.push(("__MACOSX/._table.dbf".into(), dbf.clone())); let mixed = read_zip("county.zip", &crate::zip::write(&entries).unwrap()).unwrap(); - assert_eq!(mixed.len(), 1); + assert_eq!(mixed.len(), 2); + assert_eq!(mixed[0].0.geometry_type, GeometryType::Point); + assert_eq!(mixed[1].0.geometry_type, GeometryType::None); + assert_eq!(mixed[1].0.features.len(), 2); + assert_eq!(mixed[1].0.source.as_deref(), Some("county.zip/tables/Places.DBF")); + assert_eq!(mixed[1].0.value(1, 0), &Value::Text("two".into())); assert_eq!(mixed[0].0.features.len(), 2); assert_eq!(mixed[0].0.value(1, 0), &Value::Text("two".into())); - assert_eq!(mixed[0].1.messages, ["county.zip: skipped tables/Places.DBF (a .dbf table without a .shp is not read)"]); + assert!(mixed.iter().all(|(_, r)| r.messages.is_empty())); // A second `.dbf` beside the Shapefile, its name differing only in case, isn't its table. entries.push(("shapes/PLACES.dbf".into(), dbf.clone())); let twice = read_zip("county.zip", &crate::zip::write(&entries).unwrap()).unwrap(); assert!( - twice[0].1.messages.iter().any(|m| m.contains("shapes/PLACES.dbf (a .dbf table without a .shp is not read)")), + twice[0].1.messages.iter().any(|m| m.contains("shapes/PLACES.dbf (an extra .dbf sidecar of a Shapefile)")), "{:?}", twice[0].1.messages ); - // With only an unsupported table, the archive refuses to open and names it too. - let only_table = crate::zip::write(&[("tables/Places.DBF".into(), dbf)]).unwrap(); - let error = read_zip("county.zip", &only_table).unwrap_err().to_string(); - assert!(error.contains("tables/Places.DBF") && error.contains("a .dbf table without a .shp"), "{error}"); + // Tables count toward the same 32-item budget as layers. + let entries: Vec<_> = (0..33).map(|i| (format!("tables/table{i:02}.dbf"), dbf.clone())).collect(); + let limited = read_zip("tables.zip", &crate::zip::write(&entries).unwrap()).unwrap(); + assert_eq!(limited.len(), MAX_ZIP_LAYERS); + assert_eq!(limited[0].1.messages, ["tables.zip: skipped tables/table32.dbf (past the 32-layer limit)"]); + } + + /// A small file can expand into many owned rows; both loose and zipped tables must fit + /// the retained-memory allowance, shared with other archive tables. + #[test] + fn standalone_dbf_rows_share_the_zip_memory_budget() { + let mut ds = Dataset::new("small", GeometryType::Point, vec![Field::new("name", FieldType::Text)]); + for _ in 0..32 { + ds.push_next(Some(Geometry::Point(Coord::new(1.0, 2.0))), vec![Value::Text("one".into())]); + } + 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(); + 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(); + 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(); + assert_eq!(limited.len(), 1); + assert!(limited[0].1.messages.iter().any(|m| m.contains("b.dbf") && m.contains("memory budget"))); + let clean = read_zip_budget("tables.zip", &zip, None, &mut (cost * 2)).unwrap(); + assert_eq!(clean.len(), 2); + assert!(clean.iter().all(|(_, report)| report.messages.is_empty())); + } + + /// Standalone tables share Shapefile typing and loss notices; .cpg wins over the header, + /// including when loose files are gathered for a browser upload. + #[test] + fn standalone_dbf_keeps_typed_rows_and_cpg() { + use shapefile::dbase::{FieldValue, Record, TableWriterBuilder}; + use std::io::Cursor; + let mut bytes = Cursor::new(Vec::new()); + let table = TableWriterBuilder::with_encoding(shapefile::dbase::encoding::EncodingRs::from(encoding_rs::WINDOWS_1252)) + .add_character_field("name".try_into().unwrap(), 12) + .add_numeric_field("count".try_into().unwrap(), 8, 0) + .add_numeric_field("amount".try_into().unwrap(), 12, 2) + .add_logical_field("active".try_into().unwrap()) + .add_date_field("day".try_into().unwrap()); + { + let mut writer = table.build_with_dest(&mut bytes); + let mut row = Record::default(); + row.insert("name".into(), FieldValue::Character(Some("Málaga".into()))); + row.insert("count".into(), FieldValue::Numeric(Some(7.0))); + // A whole value with decimals declared still has Double type. + row.insert("amount".into(), FieldValue::Numeric(Some(2.0))); + row.insert("active".into(), FieldValue::Logical(Some(true))); + row.insert("day".into(), FieldValue::Date(Some(shapefile::dbase::Date::new(14, 11, 2026).unwrap()))); + writer.write_record(&row).unwrap(); + writer.finalize().unwrap(); + } + let mut bytes = bytes.into_inner(); + bytes[29] = 0; // No language driver: the .cpg must be used. + let dir = std::env::temp_dir().join(format!("rustgis-lone-dbf-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let path = dir.join("communities.DBF"); + std::fs::write(&path, &bytes).unwrap(); + std::fs::write(path.with_extension("cPg"), b"1252").unwrap(); + let (ds, report) = read_path(&path).unwrap(); + assert_eq!(ds.geometry_type, GeometryType::None); + assert_eq!(ds.features.len(), 1); + assert_eq!( + ds.fields.iter().map(|f| f.ty).collect::>(), + [FieldType::Text, FieldType::Integer, FieldType::Double, FieldType::Boolean, FieldType::Date] + ); + assert_eq!( + ds.features[0].attrs, + [ + Value::Text("Málaga".into()), + Value::Int(7), + Value::Float(2.0), + Value::Bool(true), + Value::Date(crate::date::Date::from_ymd(2026, 11, 14).unwrap()) + ] + ); + assert!(report.messages.is_empty(), "{:?}", report.messages); + let (uploads, notes) = + gather_shapefiles(vec![("communities.DBF".into(), bytes.clone()), ("communities.CPG".into(), b"1252".to_vec())]); + assert!(notes.is_empty()); + assert_eq!(uploads.len(), 1); + let read = read_layers(&uploads[0].0, &uploads[0].1).unwrap(); + assert_eq!(read[0].dataset.features, ds.features); + assert!(read[0].report.messages.is_empty()); + // Unknown metadata and an invalid date are counted just as in Shapefile attributes. + let offset = u16::from_le_bytes([bytes[8], bytes[9]]) as usize + 1 + 12 + 8 + 12 + 1; + bytes[offset..offset + 8].copy_from_slice(b"20260230"); + std::fs::write(&path, &bytes).unwrap(); + std::fs::write(path.with_extension("cPg"), b"unknown-page").unwrap(); + let (bad, report) = read_path(&path).unwrap(); + assert_eq!(bad.value(0, 4), &Value::Null); + assert!(report.messages.iter().any(|m| m.contains(".cpg")), "{:?}", report.messages); + assert!(report.messages.iter().any(|m| m.contains("1") && m.contains("day")), "{:?}", report.messages); + // A cut-short record must stop with an error; dbase can repeat the same I/O error. + bytes.truncate(u16::from_le_bytes([bytes[8], bytes[9]]) as usize + 2); + assert!(read_bytes("short.dbf", &bytes).is_err()); + std::fs::remove_dir_all(dir).unwrap(); + } + + #[test] + fn zipped_orphan_mid_is_named_in_notice() { + let mut entries = vec![("counts.csv".into(), b"id,n\nA,12\n".to_vec())]; + let clean = read_zip("map.zip", &crate::zip::write(&entries).unwrap()).unwrap(); + assert!(clean[0].1.messages.is_empty()); + entries.push(("tables/Addresses.MID".into(), b"1,Main St".to_vec())); + let mixed = read_zip("map.zip", &crate::zip::write(&entries).unwrap()).unwrap(); + assert_eq!(mixed[0].1.messages, ["map.zip: skipped tables/Addresses.MID (no .mif beside it)"]); + let error = read_zip("map.zip", &crate::zip::write(&entries[1..]).unwrap()).unwrap_err().to_string(); + assert!(error.contains("tables/Addresses.MID (no .mif beside it)"), "{error}"); } /// Zipped Shapefiles are read from memory (the web app's way to open them), with their `.prj`, diff --git a/crates/data/src/publish.rs b/crates/data/src/publish.rs index 0944ae017b..6705523c86 100644 --- a/crates/data/src/publish.rs +++ b/crates/data/src/publish.rs @@ -139,6 +139,8 @@ struct Original { shp: Vec, shx: Option>, dbf: Vec, + /// Where its table is, in whichever case the reader found it, so it is written back there. + dbf_path: PathBuf, prj: Option>, cpg: Option<(PathBuf, Vec)>, } @@ -159,7 +161,8 @@ impl Original { fn read(path: &Path) -> Result { let missing = |ext: &str| refused(path, format!("its .{ext} isn't there")); let shp = read_part(path)?.ok_or_else(|| missing("shp"))?; - let dbf = read_part(&path.with_extension("dbf"))?.ok_or_else(|| missing("dbf"))?; + let dbf_path = crate::io::dbf_sidecar(path); + let dbf = read_part(&dbf_path)?.ok_or_else(|| missing("dbf"))?; let shx = read_part(&path.with_extension("shx"))?; let prj = read_part(&path.with_extension("prj"))?; let mut cpg = None; @@ -170,7 +173,7 @@ impl Original { break; } } - Ok(Original { shp, shx, dbf, prj, cpg }) + Ok(Original { shp, shx, dbf, dbf_path, prj, cpg }) } /// Its parts as the reader takes them. @@ -207,6 +210,7 @@ pub fn shapefile(ds: &Dataset, path: &Path, synced: &Synced) -> Result Result)> = parts.into_iter().map(|(e, bytes)| (crate::io::shapefile_part(path, e), bytes)).collect(); + let mut targets: Vec<(PathBuf, Vec)> = parts + .into_iter() + .map(|(e, bytes)| (if e == "dbf" { original.dbf_path.clone() } else { crate::io::shapefile_part(path, e) }, bytes)) + .collect(); if let Some((cpg, bytes)) = &original.cpg { targets.push((cpg.clone(), bytes.clone())); } @@ -828,6 +835,35 @@ mod tests { assert!(names.iter().all(|n| !n.starts_with('.') || n == ".parcels.shp.rustgis-lock"), "{names:?}"); } + /// A table named in upper case (`parcels.DBF`) is written back under that name, and an edit + /// made to it afterwards outside RustGIS is seen. + #[test] + fn an_upper_case_table_is_published_under_its_own_name() { + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("parcels.shp"); + crate::io::write_path(&parcels(), &path).unwrap(); + let upper = path.with_extension("DBF"); + std::fs::rename(path.with_extension("dbf"), &upper).unwrap(); + // On a case-insensitive file system the two names are one file; nothing to check there. + if path.with_extension("dbf").exists() { + return; + } + let (mut ds, sync) = read(&path); + let mut rows: Vec<_> = ds.features.iter().cloned().collect(); + rows[0].attrs[0] = Value::Text("Smyth".into()); + ds.features = rows.into(); + let published = shapefile(&ds, &path, &sync).unwrap(); + assert!(!path.with_extension("dbf").exists()); + let (back, _) = crate::io::read_path(&path).unwrap(); + assert_eq!(back.features.iter().next().unwrap().attrs[0], Value::Text("Smyth".into())); + assert!(published.files.changed(&path).unwrap().is_empty()); + let mut bytes = std::fs::read(&upper).unwrap(); + let last = bytes.len() - 2; + bytes[last] ^= 1; + std::fs::write(&upper, bytes).unwrap(); + assert_eq!(published.files.changed(&path).unwrap(), ["parcels.DBF"]); + } + /// Reads follow symlinks, but replacement would sever them and leave the target stale. #[cfg(unix)] #[test] diff --git a/crates/data/src/source/shp.rs b/crates/data/src/source/shp.rs index 8cfaeaa4de..4d8d2b07dc 100644 --- a/crates/data/src/source/shp.rs +++ b/crates/data/src/source/shp.rs @@ -89,7 +89,7 @@ impl ShpSource { if let Some(c) = crs { c.transformer().map_err(DataError::Format)?; } - let dbf = path.with_extension("dbf"); + let dbf = crate::io::dbf_sidecar(path); if !dbf.is_file() { return Err(bad(format!("{} is missing", dbf.display()))); } diff --git a/crates/data/src/sync.rs b/crates/data/src/sync.rs index 014b95becb..e67ea7b919 100644 --- a/crates/data/src/sync.rs +++ b/crates/data/src/sync.rs @@ -103,9 +103,8 @@ mod native { fn parts(path: &Path) -> Vec<(String, PathBuf)> { let mut paths = vec![path.to_path_buf()]; if path.extension().and_then(|e| e.to_str()).is_some_and(|e| e.eq_ignore_ascii_case("shp")) { - for ext in ["shx", "dbf", "prj"] { - paths.push(path.with_extension(ext)); - } + // The table in whichever case the reader finds it. + paths.extend([path.with_extension("shx"), crate::io::dbf_sidecar(path), path.with_extension("prj")]); let cpg = crate::dbf::CPG_SPELLINGS .iter() .map(|e| path.with_extension(e)) diff --git a/crates/engine/src/cmd/layer.rs b/crates/engine/src/cmd/layer.rs index e94c0b4ba7..6d401e0632 100644 --- a/crates/engine/src/cmd/layer.rs +++ b/crates/engine/src/cmd/layer.rs @@ -1630,8 +1630,26 @@ fn add_geodatabase(s: &mut Session, p: &Value, path: &str) -> CmdResult { /// 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")?; + #[cfg(not(target_arch = "wasm32"))] + if Path::new(path).extension().is_some_and(|e| e.eq_ignore_ascii_case("dbf")) { + if let Some(read) = super::reads::take::(s, &dbf_shapefile_key(path)) { + if let Some(crs) = ps(p, "crs").map(str::trim).filter(|c| !c.is_empty()) { + super::parse_crs(s, crs)?; + } + return add_read(s, p, read?, None); + } + // A standalone table already read stays a table if a companion appears meanwhile. + if !super::reads::placed_for(s, &whole_key(path)) + && let Some(shp) = rustgis_data::io::shapefile_for_dbf(Path::new(path)) + { + let mut q = p.clone(); + q["path"] = json!(shp.display().to_string()); + return add_data(s, &q); + } + } let path = &*gdb_path(path); // `"as": "scan"` opens a TIFF, PNG or JPEG as a picture with no coordinates, a photo too. let scan = super::raster::wants_scan(p, path)?; @@ -1823,6 +1841,12 @@ fn add_data(s: &mut Session, p: &Value) -> CmdResult { /// A file Add Data reads whole: the features, and what reading them said. type WholeRead = Result<(rustgis_data::Dataset, rustgis_data::ReadReport), String>; +/// A companion Shapefile read belongs to the initiating DBF pick even if the files go away. +#[cfg(not(target_arch = "wasm32"))] +fn dbf_shapefile_key(path: &str) -> String { + format!("dbf-shapefile:{path}") +} + /// The key Add Data's whole read of `path` is taken by (see [`super::reads`]). fn whole_key(path: &str) -> String { format!("whole:{path}") @@ -2015,8 +2039,8 @@ fn read_synced(path: &str, read: impl FnOnce() -> WholeRead) -> WholeRead { /// Add Data's read of the file `p` names, made before it runs ([`super::reads`]): a raster read /// whole or converted by GDAL, a GeoJSON read whole, delimited text, a spreadsheet or a city model -/// (CityJSON or CityGML) or DXF drawing read into its layers, a Shapefile read whole. `None` for -/// any other file, which [`add_data`] reads as it adds it. Each is picked only where `add_data` +/// (CityJSON or CityGML) or DXF drawing read into its layers, a Shapefile read whole, or a +/// standalone dBASE table. `None` for any other file, which [`add_data`] reads as it adds it. Each is picked only where `add_data` /// takes that read, so a read made is never wasted; a few it makes whole are left to it (a `.json` /// with a coordinate system or layer given, a large GeoJSON that isn't a FeatureCollection). #[cfg(not(target_arch = "wasm32"))] @@ -2024,6 +2048,11 @@ pub(crate) fn add_data_ahead(p: &Value) -> Option { use super::reads::ahead; const NAME: &str = "Add Data"; let path = gdb_path(ps(p, "path")?).into_owned(); + if let Some(shp) = rustgis_data::io::shapefile_for_dbf(Path::new(&path)) { + let mut q = p.clone(); + q["path"] = json!(shp.display().to_string()); + return add_data_ahead(&q).map(|work| work.with_key(dbf_shapefile_key(&path))); + } let scan = super::raster::wants_scan(p, &path).ok()?; if !scan && rustgis_data::photo::is_photo_name(&path) && !rustgis_data::raster::world::places(Path::new(&path)) { return None; @@ -2086,7 +2115,7 @@ pub(crate) fn add_data_ahead(p: &Value) -> Option { if rustgis_data::sheets::is_sheet_name(&path) { return Some(ahead(NAME, key, move || read_sheet_file(&q, &path))); } - (geojson || is_delimited_name(&path)).then(|| ahead(NAME, key, move || read_whole(&q, &path))) + (geojson || is_delimited_name(&path) || lower.ends_with(".dbf")).then(|| ahead(NAME, key, move || read_whole(&q, &path))) } #[cfg(target_arch = "wasm32")] diff --git a/crates/engine/src/cmd/raster.rs b/crates/engine/src/cmd/raster.rs index 2d6215f3e0..0f8614ca1f 100644 --- a/crates/engine/src/cmd/raster.rs +++ b/crates/engine/src/cmd/raster.rs @@ -723,6 +723,11 @@ pub(crate) fn add_named_bytes(s: &mut Session, p: &Value, name: String, bytes: V if rustgis_data::source::is_source_name(&name) { return super::layer::add_source(s, p, super::layer::Origin::Bytes(&name, std::sync::Arc::new(bytes)), zoom); } + // 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())?; + 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) { return Err(format!("{name}: decompress it first, then add the supported file inside")); } diff --git a/crates/engine/src/cmd/reads.rs b/crates/engine/src/cmd/reads.rs index 60e0e28aee..755c160acd 100644 --- a/crates/engine/src/cmd/reads.rs +++ b/crates/engine/src/cmd/reads.rs @@ -36,6 +36,16 @@ pub(crate) struct ReadWork { work: Box Box + Send>, } +#[cfg(not(target_arch = "wasm32"))] +impl ReadWork { + /// Lets an alternate file pick consume the same prepared value without choosing its + /// reader again when the result lands (a DBF pick routed to its companion Shapefile). + pub(crate) fn with_key(mut self, key: String) -> Self { + self.key = key; + self + } +} + /// A read started for a command, to run on a thread of its own. pub struct ReadAhead { /// What the read is called, for its progress and a cancelled run's error. diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index edf8d43784..f78963a9b8 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -50878,3 +50878,89 @@ fn bookmark_layout_map_names_over_their_limit_are_refused() { s.run("map.rename", &json!({"name": long(200)})).unwrap(); assert_eq!(s.map().name.chars().count(), 200); } +/// DBF imports land in the same table path as non-spatial CSV/GPKG, through desktop read-ahead +/// and uploaded bytes. Picking attributes with a companion SHP still opens the spatial layer. +#[test] +fn standalone_dbf_add_data_uses_tables_and_companion_shapefile() { + use base64::Engine; + use rustgis_data::{Coord, Dataset, Field, FieldType, Geometry, GeometryType, Value as Cell}; + let mut data = + Dataset::new("places", GeometryType::Point, vec![Field::new("name", FieldType::Text), Field::new("count", FieldType::Integer)]); + data.push_next(Some(Geometry::Point(Coord::new(1.0, 2.0))), vec![Cell::Text("one".into()), Cell::Int(7)]); + data.push_next(Some(Geometry::Point(Coord::new(3.0, 4.0))), vec![Cell::Text("two".into()), Cell::Int(12)]); + let (parts, _) = rustgis_data::io::shapefile_parts(&data).unwrap(); + let dbf = parts.iter().find(|(e, _)| *e == "dbf").unwrap().1.clone(); + let dir = std::env::temp_dir().join(format!("rustgis-add-dbf-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + let path = dir.join("places.DBF"); + std::fs::write(&path, &dbf).unwrap(); + let p = json!({"path": path}); + let mut s = Session::new(Project::default()); + let ahead = crate::cmd::reads::read_ahead(&mut s, "layer.addData", &p).unwrap(); + assert!(ahead.reads()); + let control = rustgis_analysis::control::Control::cancelled_once_started(); + assert!(crate::cmd::reads::read_ahead(&mut s, "layer.addData", &p).unwrap().run(&control).is_err()); + assert!(control.looked() > 0); + let read = ahead.run(&rustgis_analysis::control::Control::new()).unwrap(); + // A new companion after the read must not turn the prepared table into a layer. + let shp = path.with_extension("ShP"); + let shape_bytes = &parts.iter().find(|(e, _)| *e == "shp").unwrap().1; + std::fs::write(&shp, shape_bytes).unwrap(); + crate::cmd::reads::read_land(&mut s, read).unwrap(); + std::fs::remove_file(&shp).unwrap(); + assert!(s.map().layers.is_empty()); + assert_eq!(s.project.tables.len(), 1); + let table = &s.project.tables[0].dataset; + assert_eq!(table.features.len(), 2); + assert_eq!(table.fields[1].ty, FieldType::Integer); + assert_eq!(table.value(1, 1), &Cell::Int(12)); + let mut uploaded = Session::new(Project::default()); + uploaded + .run("layer.addDataBytes", &json!({"fileName": "places.dbf", "data": base64::engine::general_purpose::STANDARD.encode(&dbf)})) + .unwrap(); + assert_eq!(uploaded.project.tables[0].dataset.features, table.features); + let zip = rustgis_data::zip::write( + &parts + .iter() + .map(|(e, b)| (format!("places.{e}"), b.clone())) + .chain(std::iter::once(("L_COMM_INFO.dbf".into(), dbf))) + .collect::>(), + ) + .unwrap(); + let mut mixed = Session::new(Project::default()); + mixed + .run("layer.addDataBytes", &json!({"fileName": "county.zip", "data": base64::engine::general_purpose::STANDARD.encode(zip)})) + .unwrap(); + assert_eq!(mixed.map().layers.len(), 1); + assert_eq!(mixed.project.tables.len(), 1); + assert_eq!(mixed.project.tables[0].dataset.name, "L_COMM_INFO"); + for (ext, bytes) in &parts { + std::fs::write( + path.with_extension(match *ext { + "shp" => "ShP", + "dbf" => "DBF", + ext => ext, + }), + bytes, + ) + .unwrap(); + } + // Read-ahead and dispatch must agree on the SHP path, including the streamed route. + for stream in [false, true] { + let mut paired = Session::new(Project::default()); + let p = json!({"path": path, "stream": stream}); + let ahead = crate::cmd::reads::read_ahead(&mut paired, "layer.addData", &p).unwrap(); + assert_eq!(ahead.reads(), !stream); + let read = ahead.run(&rustgis_analysis::control::Control::new()).unwrap(); + if !stream { + std::fs::remove_file(&shp).unwrap(); + } + crate::cmd::reads::read_land(&mut paired, read).unwrap(); + std::fs::write(&shp, shape_bytes).unwrap(); + assert_eq!(paired.map().layers.len(), 1); + assert!(paired.project.tables.is_empty()); + assert_eq!(paired.map().layers[0].dataset.geometry_type, GeometryType::Point); + } + std::fs::remove_dir_all(dir).unwrap(); +} diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index d2baea6aa3..d9df59cbd9 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -2033,6 +2033,7 @@ impl RustGisApp { || rustgis_engine::data::source::is_source_name(name) || rustgis_engine::data::io::is_multi_layer_name(name) || rustgis_engine::data::sheets::is_sheet_name(name) + || lower.ends_with(".dbf") || lower.ends_with(".gz") || (lower.ends_with(".dat") && std::str::from_utf8(bytes).is_err()) { @@ -3962,6 +3963,7 @@ impl RustGisApp { "jpg", "jpeg", "shp", + "dbf", "zip", "gpkg", "parquet", diff --git a/crates/ui-egui/tests/picker_admission.rs b/crates/ui-egui/tests/picker_admission.rs index 437ec0d6b4..6447e55b6b 100644 --- a/crates/ui-egui/tests/picker_admission.rs +++ b/crates/ui-egui/tests/picker_admission.rs @@ -25,3 +25,32 @@ fn two_requests_in_one_frame_keep_the_first_admitted_options() { assert!(candidate.lock().unwrap().is_none()); assert_eq!(*admitted.lock().unwrap(), Some(options)); } + +/// A lone binary DBF from the platform inbox must reach the table reader without decoding +/// the file as UTF-8 text first, including when no CPG is selected alongside it. +#[test] +fn standalone_dbf_inbox_opens_as_a_table() { + use rustgis_engine::{ + Project, Session, + data::{Coord, Dataset, Field, FieldType, Geometry, GeometryType, Value as Cell}, + }; + let name = "x".repeat(130); + let mut ds = Dataset::new("places", GeometryType::Point, vec![Field::new("name", FieldType::Text)]); + ds.push_next(Some(Geometry::Point(Coord::new(1.0, 2.0))), vec![Cell::Text(name.clone())]); + let (parts, _) = rustgis_engine::data::io::shapefile_parts(&ds).unwrap(); + let dbf = parts.into_iter().find(|(ext, _)| *ext == "dbf").unwrap().1; + assert!(std::str::from_utf8(&dbf).is_err(), "the DBF header's field width is binary"); + let inbox = Arc::new(Mutex::new(vec![("places.DBF".into(), dbf)])); + let app = RustGisApp::new(Session::new(Project::default())).with_services(Services { inbox: Some(inbox), ..Default::default() }); + let mut h = egui_kittest::Harness::builder().with_size(egui::vec2(1200.0, 900.0)).build_ui_state( + |ui, app: &mut RustGisApp| { + app.logic(ui.ctx()); + app.ui(ui); + }, + app, + ); + h.step(); + assert!(h.state().session.map().layers.is_empty()); + assert_eq!(h.state().session.project.tables.len(), 1); + assert_eq!(h.state().session.project.tables[0].dataset.value(0, 0), &Cell::Text(name)); +} diff --git a/docs/user-guide/data-formats.md b/docs/user-guide/data-formats.md index 4f36dcf1d8..30514e89bf 100644 --- a/docs/user-guide/data-formats.md +++ b/docs/user-guide/data-formats.md @@ -20,7 +20,8 @@ export names its feature. | --- | --- | --- | --- | | GeoJSON | `.geojson`, `.json` | Home › Add › Add Data, or drop the file | Features with typed attributes; a single-member `GeometryCollection` is unwrapped (including nested single-member collections). Empty or multi-member collections are unsupported: the whole feature, including its attributes, is skipped and counted in an unreadable-geometry notice. A FeatureCollection's legacy `crs` member (`{"type": "name", "properties": {"name": "urn:ogc:def:crs:EPSG::28992"}}`) is honoured for EPSG codes (`EPSG:28992`, `urn:ogc:def:crs:EPSG::28992`, `urn:ogc:def:crs:EPSG:6.6:28992`) and for `CRS84`: a projected or other non-WGS 84 system converts the coordinates to longitude/latitude and the layer keeps it as its coordinate system (Layer properties, export in it, Define Projection); `CRS84` and `EPSG:4326` are longitude/latitude already, so the coordinates stay as they are and the layer has no other coordinate system. Coordinates are x/y (easting/northing, or longitude/latitude) whatever the EPSG axis order. A `crs` that isn't understood (a `link`, WKT or PROJ text, any other name, an unknown code) is named in a notice and the coordinates are read as longitude/latitude. A feature whose coordinates can't be converted, or convert to beyond ±180.5° longitude or ±90.5° latitude (the declared system doesn't fit the numbers), is left out and counted in a notice, and Define Projection then asks for the file to be added again. A feature read as longitude/latitude (no `crs`, `CRS84` or `EPSG:4326`, or a `crs` that isn't understood) with a position whose longitude is within ±180.5° but whose latitude is past ±90.5° is kept, and one notice counts them: longitude and latitude may be swapped. A `crs` on a feature, a geometry or a lone Feature is ignored. GeoJSON is always written in WGS 84 without a `crs`. Desktop FeatureCollections larger than 32 MiB use an in-place reader (which honours `crs` too, reading the file once more to check the features convert); layers with more than 100,000 features stream a view at a time. Other GeoJSON files load whole, up to 256 MiB. | | Delimited text | `.csv`, `.tsv`, `.txt`, recognised `.dat`; UTF-8 `.csv.gz`, `.tsv.gz`, `.txt.gz`, `.dat.gz` | Add Data, or Home › Add › Add Data › Delimited Text… to choose the columns from the file's header | Comma, semicolon, tab or pipe separated (found from the header, or `"delimiter"`); `info.fileColumns` lists the columns and the ones found. Points from x/y columns (named like longitude/latitude, GTFS `stop_lon`/`stop_lat` or easting/northing, or chosen with `"x"` and `"y"`), or any geometry from a WKT/EWKT column (named like `wkt` or `geometry`, or `"wkt"`). When an inferred pair exceeds degree ranges, a recognised longitude/latitude pair is preferred only if its in-range, non-0,0 points cover at least as many rows as the first pair can place, unless a projected `"crs"` is given (see [Delimited Text](data.md) for aliases and sampling). Coordinates in another system are converted from `"crs"` (`EPSG:2263`, or WKT) or an EWKT `SRID=`; rows still read outside longitude/latitude are counted in a notice. Points placed at exactly 0,0 are kept and counted in a notice, as they may represent missing coordinates. Uncompressed text is UTF-8, or UTF-16 with its byte-order mark; other uncompressed files are read as Windows-1252 (Latin-1, as many public sources still publish CSV), with a notice saying so. Gzip input is UTF-8 only, streamed within 256 MiB of expanded text; decompress other encodings and add as `.txt`. Retained CSV rows and cells have a separate estimated memory budget (256 MiB in the browser; a quarter of physical memory between 256 MiB and 4 GiB on desktop). A file without coordinates opens as a standalone table. | -| Shapefile | `.shp` with `.dbf` (and `.shx`), or zipped (`.zip`) | Add Data or drop the file; in the web app, pick or drop the `.shp` and `.dbf` together, with the `.shx` and `.prj` if there are (they open as one layer), or the zip | A zip may hold several Shapefiles, in folders, and other vector files (GeoJSON, CSV, GeoParquet, FlatGeobuf); each becomes a layer, at most 32 for the whole archive (Shapefiles first, so other files are left out when Shapefiles fill it). A `.dbf` table without a `.shp` of the same name in its folder (such as a flood map's `L_` tables) isn't read, and a notice names it. Delimited `.txt` members (including GTFS tables) are read; unrecognised text members and single-column `README.txt` documentation are skipped with a notice and macOS `__MACOSX` entries are passed over, and a member that can't be read is skipped and named in a notice. Converted to longitude/latitude from the coordinate system in its `.prj` (EPSG, Esri or OGC WKT, or WKT2 as PROJ and QGIS write it; Web Mercator, UTM, State Plane and other common projections); without a `.prj` it must be in longitude/latitude. On the desktop, one with more than 100,000 shapes (counted from its `.shx`) is read in place, a view at a time. Numeric (`N`) and floating point (`F`) fields are read at full double precision; on whole-file reads, `nan` or `inf` becomes empty and is counted in a notice. Date (`D`) fields are read as dates; a blank or zero date is empty, and one that isn't a date (`20260230`) is empty and counted in a notice. | +| Shapefile | `.shp` with `.dbf` (and `.shx`), or zipped (`.zip`) | Add Data or drop the file; in the web app, pick or drop the `.shp` and `.dbf` together, with the `.shx` and `.prj` if there are (they open as one layer), or the zip | A zip may hold several Shapefiles, in folders, and other vector files (GeoJSON, CSV, GeoParquet, FlatGeobuf); each becomes a layer or standalone table, at most 32 layers and tables together for the whole archive (Shapefiles first, so other files are left out when Shapefiles fill it). A `.dbf` without a `.shp` of the same name in its folder (such as a flood map's `L_` tables) opens as a standalone table, with its `.cpg` when present. An orphan MapInfo `.mid` without its `.mif` is skipped and named in the archive's notice. Delimited `.txt` members (including GTFS tables) are read; unrecognised text members and single-column `README.txt` documentation are skipped with a notice and macOS `__MACOSX` entries are passed over, and a member that can't be read is skipped and named in a notice. Converted to longitude/latitude from the coordinate system in its `.prj` (EPSG, Esri or OGC WKT, or WKT2 as PROJ and QGIS write it; Web Mercator, UTM, State Plane and other common projections); without a `.prj` it must be in longitude/latitude. On the desktop, one with more than 100,000 shapes (counted from its `.shx`) is read in place, a view at a time. Numeric (`N`) and floating point (`F`) fields are read at full double precision; on whole-file reads, `nan` or `inf` becomes empty and is counted in a notice. Date (`D`) fields are read as dates; a blank or zero date is empty, and one that isn't a date (`20260230`) is empty and counted in a notice. | +| dBASE table | `.dbf`, with `.cpg` when present | Add Data or drop the file; in the browser, pick or drop the `.dbf` and `.cpg` together, or zip them | Without a `.shp` beside it, opens as an editable standalone table. Uses the same code page, field types and loss notices as Shapefile attributes (including integer, double, Boolean and date fields). On the desktop, picking a `.dbf` with a `.shp` beside it opens that Shapefile instead; in the browser pick its parts together. ZIP tables share the archive's 32-layer/table budget. | | KML / KMZ | `.kml`, `.kmz` | Add Data, drop the file, or upload it in the web app | A layer for each kind of geometry (points, lines, polygons), with each placemark's name, description, folder path and extended data (a key named like the `name`, `description`, `folder` or `style` column, ignoring case, gets a column of its own, such as `NAME_1`, unless it only repeats that column). Styles are kept: the layer is drawn by unique values of its `style` field, with each KML style's line and fill colours, widths and icon colours (up to 64 styles). Multi-geometries and `gx:Track`s are read. Ground overlays (pictures on a `LatLonBox`, turned by its `rotation`) are raster layers kept in the project: the picture inside a KMZ, or a file beside a KML (not a web address, nor outside its folder); a `gx:LatLonQuad` isn't drawn. | | GPX | `.gpx` | Add Data, drop the file, or upload it in the web app | Waypoints, routes, tracks (one line per track, its segments as parts) and track points (with elevation and time) as separate layers. | | Spreadsheets | `.xlsx`, `.xlsm`, `.xlsb`, `.xls`, `.ods` | Add Data (or Delimited Text… to choose the columns), drop the file, or upload it in the web app | One sheet at a time, read like delimited text: the first non-empty row names the columns, and x/y or WKT columns (found, or given with `"x"`, `"y"`, `"wkt"` and `"crs"`) make the geometry; a sheet without them is a table. The first sheet is added and the others named in a notice; `"layer"` picks one, and `info.fileLayers` lists them. Dates read as ISO 8601. |