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
1 change: 1 addition & 0 deletions crates/assistant/skills/add-data/SKILL.md
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ and its limits are listed in `user-guide/data-formats.md`.
- **CSV / TSV:** points come from `"x"` and `"y"` columns, or a `"wkt"` column. When the
coordinates aren't longitude/latitude, give their `"crs"` (`"EPSG:2271"`). Without it, projected
coordinates land in the wrong place. Use `"delimiter"` when it isn't a comma.
In a zip, its CSVs and workbooks that have those columns take `"x"`, `"y"` and `"wkt"` too, and its CSVs the `"delimiter"`; one notice names the tables that lack a column and were read without them.
- **A web address:** `layer.addUrl` `{"url": U}` for GeoJSON, CSV, GeoParquet, FlatGeobuf,
GeoPackage, zipped Shapefiles, KML/KMZ, GPX, GeoTIFF, GRIB or a PMTiles archive. This uses the
network, so the user is asked first. One record of a large GRIB file: `"bytes": [first, last]`,
Expand Down
234 changes: 212 additions & 22 deletions crates/data/src/io.rs

Large diffs are not rendered by default.

4 changes: 4 additions & 0 deletions crates/data/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -771,6 +771,10 @@ pub struct ReadReport {
/// The extrusion the reader suggests for the layer (a city model's volumes): applied when the
/// layer is added, and only then; a reload keeps the layer's own.
pub extrusion: Option<SuggestedExtrusion>,
/// A zip's table read with `CsvOptions::columns_optional` that lacked a column named (`x`, `y` or
/// `WKT`, and its name): read without the columns given. Not in `messages`: the zip reader takes it
/// and says it once for all its tables.
pub columns_lacking: Option<Box<(&'static str, String)>>,
}

/// An extrusion a reader suggests for a layer of polygons: heights from one field, on a base from
Expand Down
1 change: 1 addition & 0 deletions crates/data/src/source/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -841,6 +841,7 @@ fn materialize_within(src: &dyn FeatureSource, budget: u64) -> Result<(Dataset,
unread_dates: unread_dates.clone(),
rounded_dates: rounded.clone(),
extrusion: None,
columns_lacking: None,
};
let null_text = null_text_note(&info.fields, &null_text);
let not_utf8 = not_utf8_note(&info.fields, &not_utf8, src.text_encoding());
Expand Down
57 changes: 51 additions & 6 deletions crates/engine/src/cmd/layer.rs
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ pub const MAX_LAYER_NAME: usize = 200;
pub fn commands() -> Vec<C> {
vec![
C::new("layer.addData", "Add Data", "Home › Add", add_data).roles(&[]).effects(crate::policy::Effects::NONE.with(crate::policy::Effect::Files))
.params(r#"{"path": string, "name"?: string, "layer"?: "GeoPackage, GDAL, DuckDB or DXF layer, or a PDF's page number (the first when left out or blank)", "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 x/longitude column", "y"?: "CSV y/latitude column", "wkt"?: "CSV WKT geometry column", "delimiter"?: ","|";"|"\\t"|"|"}"#),
.params(r#"{"path": string, "name"?: string, "layer"?: "GeoPackage, GDAL, DuckDB or DXF layer, or a PDF's page number (the first when left out or blank)", "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"|"|"}"#),
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)"}"#,
),
Expand Down Expand Up @@ -2347,8 +2347,9 @@ fn read_layers_file(p: &Value, path: &str) -> LayersRead {
let full = std::path::absolute(path).map(|p| p.display().to_string()).unwrap_or_else(|_| path.to_string());
let crs = ps(p, "crs").map(str::trim).filter(|c| !c.is_empty());
let reads = match crs {
Some(text) if full.to_ascii_lowercase().ends_with(".zip") => {
rustgis_data::io::read_zip_layers(&full, &bytes, Some(rustgis_data::raster::Crs::parse(text)?)).map_err(|e| e.to_string())?
_ 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())?
}
Some(text) if rustgis_data::io::is_city_model(&full, &bytes) => {
city_reads(&full, &bytes, Some(rustgis_data::raster::Crs::parse(text)?))?
Expand Down Expand Up @@ -2833,9 +2834,9 @@ pub(crate) fn add_layers(s: &mut Session, p: &Value, file_name: &str, bytes: &[u
// A DXF drawing: its coordinate system (it never says) and one of its own layers.
let dxf = rustgis_data::dxf::is_dxf_name(file_name);
let reads = match crs.filter(|_| landxml) {
_ if lower.ends_with(".zip") && crs.is_some() => {
_ 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, crs).map_err(|e| e.to_string())?
rustgis_data::io::read_zip_layers(file_name, bytes, &zip_options(p, crs)?).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.
Expand Down Expand Up @@ -4850,7 +4851,13 @@ pub(crate) fn csv_options(p: &Value) -> Result<Option<rustgis_data::io::CsvOptio
}
let crs = crs.map(|c| rustgis_data::raster::Crs::parse(&c)).transpose()?;
let delimiter = parse_delimiter(delimiter)?;
Ok(Some(rustgis_data::io::CsvOptions { x, y, wkt, crs, delimiter }))
Ok(Some(rustgis_data::io::CsvOptions { x, y, wkt, crs, delimiter, ..Default::default() }))

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.

csv_options (line 4848, outside this hunk) drops a blank x, y, wkt and crs, but passes delimiter through as given. Before this PR a zip ignored delimiter, so "delimiter": "" (a blank form field or an empty default from a caller) read fine. Now parse_delimiter refuses the whole archive with delimiter '': give one character. Blanking it like the other keys makes a blank delimiter mean the default. That also changes a single CSV, where a blank delimiter now auto-detects instead of erroring, which matches how the other blank keys already behave. Change on line 4848:

    let (x, y, wkt, crs, delimiter) = (text("x"), text("y"), text("wkt"), text("crs"), ps(p, "delimiter").map(str::trim).filter(|d| !d.is_empty()));

Category: quality

}

/// What a zip's delimited and workbook members are read with: the `x`, `y`, `wkt` and `delimiter`
/// given (as [`csv_options`]), and the coordinate system `crs`.
fn zip_options(p: &Value, crs: Option<rustgis_data::raster::Crs>) -> Result<rustgis_data::io::CsvOptions, String> {
Ok(rustgis_data::io::CsvOptions { crs, ..csv_options(p)?.unwrap_or_default() })
}

/// A `delimiter` parameter: one character, or `\t`/`tab`.
Expand Down Expand Up @@ -8415,6 +8422,44 @@ mod tests {
std::fs::remove_dir_all(dir).unwrap();
}

/// The desktop reads a zip ahead, off the UI thread, with the columns given as Add Data does (#3062).
#[cfg(not(target_arch = "wasm32"))]
#[test]
fn the_read_ahead_of_a_zip_gives_its_tables_the_columns_given() {
let dir = std::env::temp_dir().join(format!("rustgis-read-ahead-zip-columns-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
std::fs::create_dir_all(&dir).unwrap();
let path = dir.join("x.zip");
let zip = rustgis_data::zip::write(&[
("a.csv".into(), b"id,LongitudeOR,LatitudeOR\n1,10,20\n2,11,21\n".to_vec()),
("notes.csv".into(), b"id,name\n5,x\n".to_vec()),
])
.unwrap();
std::fs::write(&path, zip).unwrap();
let path = path.display().to_string();
let (_, reads) = super::read_layers_file(&json!({"path": path, "x": "LongitudeOR", "y": "LatitudeOR"}), &path).unwrap();
let points: Vec<(String, usize)> = reads
.iter()
.filter(|r| r.dataset.geometry_type == rustgis_data::GeometryType::Point)
.map(|r| (r.dataset.name.clone(), r.dataset.features.len()))
.collect();
assert_eq!(points, [("a".to_string(), 2)]);
assert!(
reads
.iter()
.flat_map(|r| r.report.messages.iter())
.any(|m| m.as_str().contains("used by 1 of 2 tables") && m.as_str().contains("notes.csv")),
"the notice stays"
);
// With a coordinate system too, and without any option, a zip reads as before.
let (_, with_crs) =
super::read_layers_file(&json!({"path": path, "x": "LongitudeOR", "y": "LatitudeOR", "crs": "EPSG:4326"}), &path).unwrap();
assert!(with_crs.iter().any(|r| r.dataset.geometry_type == rustgis_data::GeometryType::Point));
let (_, plain) = super::read_layers_file(&json!({"path": path}), &path).unwrap();
assert!(plain.iter().all(|r| r.dataset.geometry_type == rustgis_data::GeometryType::None));
std::fs::remove_dir_all(dir).unwrap();
}

/// A URL a web document restricted to public addresses stays restricted when a later request
/// comes from a local origin: its blocking download goes through the public agent, which
/// refuses a local address before connecting (#2055).
Expand Down
27 changes: 27 additions & 0 deletions crates/engine/src/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -25233,6 +25233,33 @@ pub(crate) fn serve(body: &'static [u8], n: usize) -> String {
format!("http://{addr}")
}

/// The `x` and `y` given to `layer.addUrl` reach the tables of a zip it answers with (#3062).
#[test]
fn add_url_of_a_zip_gives_its_tables_the_columns_given() {
let book = rustgis_data::sheets::xlsx(&[("ALL", &[&["id", "LongitudeOR", "LatitudeOR"], &["4", "13", "23"]])]);
let zip = rustgis_data::zip::write(&[
("a.csv".into(), b"id,LongitudeOR,LatitudeOR\n1,10,20\n2,11,21\n".to_vec()),
("book.xlsx".into(), book),
("notes.csv".into(), b"id,name\n5,x\n".to_vec()),
])
.unwrap();
let (base, _) = serve_files(vec![("/d/x.zip".into(), zip)]);
let mut s = Session::new(Project::default());
let mark = s.notice_mark();
s.run("layer.addUrl", &json!({"url": format!("{base}/d/x.zip"), "x": "LongitudeOR", "y": "LatitudeOR"})).unwrap();
let mut layers: Vec<(String, usize)> = s.map().layers.iter().map(|l| (l.dataset.name.clone(), l.dataset.features.len())).collect();
layers.sort();
assert_eq!(layers.iter().map(|(_, n)| *n).collect::<Vec<_>>(), [2, 1], "{layers:?}");
assert!(s.project.tables.iter().any(|t| t.dataset.name == "notes"));
let said = s.notices_since(mark);
assert!(
said.iter().any(|n| n.text.contains(
"used by 2 of 3 tables; the rest were read without them, lacking a column named: notes.csv (no x column 'LongitudeOR')"
)),
"{said:?}"
);
}

/// Serves each file by its exact path and query (others are 404) on a local port, keeping the
/// paths asked for; returns the base address and them.
fn serve_files(files: Vec<(String, Vec<u8>)>) -> (String, std::sync::Arc<std::sync::Mutex<Vec<String>>>) {
Expand Down
1 change: 1 addition & 0 deletions crates/engine/tests/integration/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -25,3 +25,4 @@ mod snap_boxes;
mod snapping_point_types;
mod vertex_snap_identity;
mod workflows;
mod zip_columns;
Loading
Loading