Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
423 changes: 338 additions & 85 deletions crates/data/src/io.rs

Large diffs are not rendered by default.

42 changes: 39 additions & 3 deletions crates/data/src/publish.rs
Original file line number Diff line number Diff line change
Expand Up @@ -139,6 +139,8 @@ struct Original {
shp: Vec<u8>,
shx: Option<Vec<u8>>,
dbf: Vec<u8>,
/// Where its table is, in whichever case the reader found it, so it is written back there.
dbf_path: PathBuf,
prj: Option<Vec<u8>>,
cpg: Option<(PathBuf, Vec<u8>)>,
}
Expand All @@ -159,7 +161,8 @@ impl Original {
fn read(path: &Path) -> Result<Original> {
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;
Expand All @@ -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.
Expand Down Expand Up @@ -207,6 +210,7 @@ pub fn shapefile(ds: &Dataset, path: &Path, synced: &Synced) -> Result<Published
for ext in ["shx", "dbf", "prj"].into_iter().chain(crate::dbf::CPG_SPELLINGS) {
refuse_link(path, &path.with_extension(ext))?;
}
refuse_link(path, &crate::io::dbf_sidecar(path))?;
let changed = synced.files.changed(path)?;
if changed.is_empty() {
return Ok(());
Expand Down Expand Up @@ -366,7 +370,10 @@ pub fn shapefile(ds: &Dataset, path: &Path, synced: &Synced) -> Result<Published
notes.push(format!("{}: its .prj now says {}, the system the layer is in", path.display(), written_crs.label()));
parts.push(("prj", prj.into_bytes()));
}
let mut targets: Vec<(PathBuf, Vec<u8>)> = parts.into_iter().map(|(e, bytes)| (crate::io::shapefile_part(path, e), bytes)).collect();
let mut targets: Vec<(PathBuf, Vec<u8>)> = 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()));
}
Expand Down Expand Up @@ -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]
Expand Down
2 changes: 1 addition & 1 deletion crates/data/src/source/shp.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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())));
}
Expand Down
5 changes: 2 additions & 3 deletions crates/data/src/sync.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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")) {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Bug (low, confidence medium): parts adds the .cpg only for a .shp. A standalone .dbf table is read with its .cpg (read_path calls read_cpg, and read_dbf decodes text with it), so a .cpg edit changes the table's text but leaves the table's sync record clean. Add the same companions for a .dbf that a .shp gets, so changed reports them.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Tracking a standalone table's .cpg for changes is a refinement; left for the release quality pass.

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))
Expand Down
35 changes: 32 additions & 3 deletions crates/engine/src/cmd/layer.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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::<WholeRead>(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)?;
Expand Down Expand Up @@ -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}")
Expand Down Expand Up @@ -2015,15 +2039,20 @@ 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"))]
pub(crate) fn add_data_ahead(p: &Value) -> Option<super::reads::ReadWork> {
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;
Expand Down Expand Up @@ -2086,7 +2115,7 @@ pub(crate) fn add_data_ahead(p: &Value) -> Option<super::reads::ReadWork> {
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")]
Expand Down
5 changes: 5 additions & 0 deletions crates/engine/src/cmd/raster.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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())?;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Performance (low, confidence low): this branch decodes the whole DBF synchronously on the calling thread, with no Cancel and no progress. Desktop Add Data runs DBF reads through read-ahead, so this matters only if a large DBF reaches here on the desktop, for example through open_picked. The .gz and delimited-bytes branches below it already work this way, so this follows an existing pattern. If the desktop can reach it, route it through the read-ahead path the same way add_data_ahead does.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

As you note, desktop Add Data reads .dbf through read-ahead with Cancel; this path is the synchronous fallback other formats share. Left for the release quality pass.

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"));
}
Expand Down
10 changes: 10 additions & 0 deletions crates/engine/src/cmd/reads.rs
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,16 @@ pub(crate) struct ReadWork {
work: Box<dyn FnOnce() -> Box<dyn Any + Send> + 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.
Expand Down
86 changes: 86 additions & 0 deletions crates/engine/src/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
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::<Vec<_>>(),
)
.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();
}
2 changes: 2 additions & 0 deletions crates/ui-egui/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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())
{
Expand Down Expand Up @@ -3962,6 +3963,7 @@ impl RustGisApp {
"jpg",
"jpeg",
"shp",
"dbf",
"zip",
"gpkg",
"parquet",
Expand Down
29 changes: 29 additions & 0 deletions crates/ui-egui/tests/picker_admission.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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));
}
Loading
Loading