diff --git a/crates/assistant/skills/add-data/SKILL.md b/crates/assistant/skills/add-data/SKILL.md index 071ef10632..966b8905ea 100644 --- a/crates/assistant/skills/add-data/SKILL.md +++ b/crates/assistant/skills/add-data/SKILL.md @@ -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]`, diff --git a/crates/data/src/io.rs b/crates/data/src/io.rs index d84245a2e6..1dfab7d705 100644 --- a/crates/data/src/io.rs +++ b/crates/data/src/io.rs @@ -293,7 +293,7 @@ pub fn read_layers(file_name: &str, bytes: &[u8]) -> Result> { let plain = |v: Vec<(Dataset, ReadReport)>| v.into_iter().map(|(dataset, report)| LayerRead { dataset, report, styles: Vec::new() }).collect(); let mut out: Vec = match ext.as_str() { - "zip" => read_zip_layers(file_name, bytes, None)?, + "zip" => read_zip_layers(file_name, bytes, &CsvOptions::default())?, "kml" | "kmz" => crate::kml::read(file_name, bytes)? .into_iter() .map(|l| LayerRead { dataset: l.dataset, report: l.report, styles: l.styles }) @@ -2530,6 +2530,9 @@ pub struct CsvOptions { pub crs: Option, /// The field separator (otherwise the most common of `,`, `;`, tab and `|` in the header). pub delimiter: Option, + /// For a zip's members, which don't all hold the columns named: a table that lacks a named `x`, `y` or `wkt` column is read as it would be + /// without them, and says so, instead of being refused. Set by the zip reader; false elsewhere, where a column that isn't there is an error. + pub columns_optional: bool, } /// The separator of a delimited text file: the most common of `,`, `;`, tab and `|` in its first @@ -3055,16 +3058,33 @@ pub(crate) fn read_rows( workbook: Option<(&[Option], &[usize])>, ) -> Result<(Dataset, ReadReport)> { let types = workbook.map(|(types, _)| types); + let position = |n: &str| headers.iter().position(|h| h.trim().eq_ignore_ascii_case(n)); let named = |n: &Option, what: &str| -> Result> { match n.as_deref().map(str::trim).filter(|n| !n.is_empty()) { - Some(n) => headers - .iter() - .position(|h| h.trim().eq_ignore_ascii_case(n)) - .map(Some) - .ok_or_else(|| DataError::Format(format!("no {what} column '{n}' (columns: {})", headers.join(", ")))), + Some(n) => { + position(n).map(Some).ok_or_else(|| DataError::Format(format!("no {what} column '{n}' (columns: {})", headers.join(", ")))) + } None => Ok(None), } }; + // A zip's members don't all hold the columns the caller named: one that lacks any is read as it would be without them, and its report says + // which (`ReadReport::columns_lacking`), for the zip to say once for all its members. + let lacking = opts + .columns_optional + .then(|| { + [("x", &opts.x), ("y", &opts.y), ("WKT", &opts.wkt)].into_iter().find_map(|(what, n)| { + let n = n.as_deref().map(str::trim).filter(|n| !n.is_empty())?; + position(n).is_none().then(|| (what, n.to_string())) + }) + }) + .flatten(); + let without; + let opts = if lacking.is_some() { + without = CsvOptions { x: None, y: None, wkt: None, ..opts.clone() }; + &without + } else { + opts + }; let (x, y) = (named(&opts.x, "x")?, named(&opts.y, "y")?); let wkt_given = named(&opts.wkt, "WKT")?; if wkt_given.is_some() && (x.is_some() || y.is_some()) { @@ -3096,6 +3116,7 @@ pub(crate) fn read_rows( }) .collect(); let mut report = ReadReport { skipped: malformed, ..ReadReport::default() }; + report.columns_lacking = lacking.map(Box::new); if xy.is_none() && wkt.is_none() && let Some(note) = unmatched_coordinates_note(headers) @@ -3836,7 +3857,7 @@ pub fn read_zip(file_name: &str, bytes: &[u8]) -> Result) -> Result) -> Result> { - read_zip_layers_budget(file_name, bytes, crs, &mut csv_memory_budget()) +/// [`read_zip_in`] with each layer's KML styles, for adding the layers drawn as their files say, +/// and with `opts` for the zip's delimited members and its workbooks' first sheets: the `x`, `y` +/// and `wkt` columns and the `delimiter` apply as when the member is added by itself, and `crs` +/// as [`read_zip_in`] says. A table that lacks a column named is read without them, with a notice +/// naming it and the column; other members ignore the columns and the delimiter. +pub fn read_zip_layers(file_name: &str, bytes: &[u8], opts: &CsvOptions) -> Result> { + read_zip_layers_budget(file_name, bytes, opts, &mut csv_memory_budget()) } /// [`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, crs, budget)?.into_iter().map(|l| (l.dataset, l.report)).collect()) + Ok(read_zip_layers_budget(file_name, bytes, &CsvOptions { crs, ..Default::default() }, budget)? + .into_iter() + .map(|l| (l.dataset, l.report)) + .collect()) } /// Delimited, dBASE and workbook members share one allowance, including gzip members whose text /// is nested in ZIP. -fn read_zip_layers_budget(file_name: &str, bytes: &[u8], crs: Option, budget: &mut usize) -> Result> { +fn read_zip_layers_budget(file_name: &str, bytes: &[u8], opts: &CsvOptions, budget: &mut usize) -> Result> { + let crs = opts.crs; + // The tables' options: not every member holds the columns given. + let member = CsvOptions { columns_optional: true, ..opts.clone() }; + let columns_given = [&opts.x, &opts.y, &opts.wkt].into_iter().any(|n| n.as_deref().is_some_and(|n| !n.trim().is_empty())); + // The tables read with columns given, and those of them that lacked a column named, each with which. + let mut tables_given = 0usize; + let mut tables_lacking: Vec = Vec::new(); let max = max_bytes(); if bytes.len() as u64 > max { return Err(DataError::Format(file_size_error(file_name, max))); @@ -3980,6 +4015,7 @@ fn read_zip_layers_budget(file_name: &str, bytes: &[u8], crs: Option, budge let plain = |reads: Vec<(Dataset, ReadReport)>| { reads.into_iter().map(|(dataset, report)| LayerRead { dataset, report, styles: Vec::new() }).collect::>() }; + let mut table = false; // A city model has many layers. let read = if ext_of(&n) == "dbf" { let cpg = take(&mut entries, &stem(&n), "cpg").map(|(_, b)| b); @@ -3988,12 +4024,13 @@ fn read_zip_layers_budget(file_name: &str, bytes: &[u8], crs: Option, budge } else if is_city_model(leaf, &b) { read_city_member(leaf, &b, crs).map(plain) } else if is_delimited_name(leaf) { - read_delimited_bytes_budget(leaf, &b, &CsvOptions { crs, ..Default::default() }, budget).map(|r| plain(vec![r])) + table = true; + read_delimited_bytes_budget(leaf, &b, &member, budget).map(|r| plain(vec![r])) } else if crate::sheets::is_sheet_name(leaf) { + table = true; // A workbook's first sheet, as a workbook added by itself is read, within the allowance. let name = Path::new(leaf).file_stem().and_then(|s| s.to_str()).unwrap_or("sheet"); - crate::sheets::read(&b, name, None, &CsvOptions { crs, ..Default::default() }) - .and_then(|r| charge_retained([&r.0], leaf, budget).map(|()| plain(vec![r]))) + crate::sheets::read(&b, name, None, &member).and_then(|r| charge_retained([&r.0], leaf, budget).map(|()| plain(vec![r]))) } else if let Some(crs) = crs.filter(|_| { crate::landxml::is_landxml_name(leaf) || (ext_of(&n) == "xml" @@ -4039,6 +4076,12 @@ fn read_zip_layers_budget(file_name: &str, bytes: &[u8], crs: Option, budge continue; } layer.dataset.source = Some(format!("{file_name}/{n}")); + if table && columns_given { + tables_given += 1; + if let Some((what, column)) = layer.report.columns_lacking.take().map(|b| *b) { + tables_lacking.push(format!("{n} (no {what} column '{column}')")); + } + } out.push(layer); } } @@ -4049,14 +4092,17 @@ fn read_zip_layers_budget(file_name: &str, bytes: &[u8], crs: Option, budge } // At most this many skipped members are named; the rest are counted. const NAMED_SKIPPED: usize = 20; - let mut skipped = if skipped.len() > NAMED_SKIPPED { - let more = skipped.len() - NAMED_SKIPPED; - let mut named: Vec = skipped.into_iter().take(NAMED_SKIPPED).collect(); - named.push(format!("and {more} more")); - named - } else { - skipped + let cap = |list: Vec| { + if list.len() > NAMED_SKIPPED { + let more = list.len() - NAMED_SKIPPED; + let mut named: Vec = list.into_iter().take(NAMED_SKIPPED).collect(); + named.push(format!("and {more} more")); + named + } else { + list + } }; + let mut skipped = cap(skipped); if geodatabase.get() { skipped.push("File Geodatabase contents (unzip the archive and add the .gdb folder on the desktop)".into()); } @@ -4087,6 +4133,17 @@ fn read_zip_layers_budget(file_name: &str, bytes: &[u8], crs: Option, budge { first.report.messages.push(format!("{file_name}: {overlays}")); } + // One notice for every table that lacked a column named, with how many took the columns given. + if let Some(first) = out.first_mut() + && !tables_lacking.is_empty() + { + let took = tables_given.saturating_sub(tables_lacking.len()); + let tables = if tables_given == 1 { "table" } else { "tables" }; + first.report.messages.push(format!( + "{file_name}: the x, y or WKT columns given were used by {took} of {tables_given} {tables}; the rest were read without them, lacking a column named: {}", + cap(tables_lacking).join("; ") + )); + } if let Some(first) = out.first_mut() && !skipped.is_empty() { @@ -9397,6 +9454,139 @@ mod tests { assert!(read_zip("p.zip", &plain).unwrap().iter().all(|(_, r)| r.messages.is_empty())); } + /// A zip's tables read as they do by themselves with the same options, on edge values too. + #[test] + fn a_zips_tables_read_as_they_do_alone_with_the_options() { + let csv = "id,LongitudeOR,LatitudeOR\n1,10,20\n2,1e400,5\n3,NaN,5\n4,,5\n5,12,22\n"; + let opts = CsvOptions { x: Some("LongitudeOR".into()), y: Some(" latitudeor ".into()), ..Default::default() }; + let book = crate::sheets::xlsx(&[("ALL", &[&["id", "LongitudeOR", "LatitudeOR"], &["1", "10", "20"], &["2", "1e400", "5"]])]); + let zip = crate::zip::write(&[ + ("a.csv".into(), csv.as_bytes().to_vec()), + ("b.csv.gz".into(), gzip_csv(csv.as_bytes())), + ("c.xlsx".into(), book.clone()), + ("empty.csv".into(), b"id,LongitudeOR,LatitudeOR\n".to_vec()), + ]) + .unwrap(); + let read = read_zip_layers("t.zip", &zip, &opts).unwrap(); + assert_eq!(read.len(), 4); + let alone = [ + read_delimited_bytes("a.csv", csv.as_bytes(), &opts).unwrap(), + read_delimited_bytes("b.csv.gz", &gzip_csv(csv.as_bytes()), &opts).unwrap(), + crate::sheets::read(&book, "c", None, &opts).unwrap(), + ]; + for (layer, (ds, report)) in read.iter().zip(&alone) { + assert_eq!(layer.dataset.features, ds.features, "{}", layer.dataset.name); + assert_eq!(layer.dataset.fields, ds.fields); + assert_eq!(layer.report.messages, report.messages); + assert_eq!(layer.report.skipped, report.skipped); + } + // The rows at 1e400 (infinity), NaN and the empty cell stay without a point, and are counted. + let first = read.first(); + assert_eq!(first.map(|l| l.dataset.features.iter().filter(|f| f.geometry.is_some()).count()), Some(2)); + assert_eq!(first.map(|l| l.report.skipped), Some(3)); + // A header with the columns and no rows gives no point and nothing to say about columns. + assert!( + read.last().is_some_and(|l| l.dataset.features.is_empty() && !l.report.messages.iter().any(|m| m.contains("read without"))) + ); + } + + /// A table without the column named is read without the columns given, and says so; the + /// others take them. Clean input says nothing. + #[test] + fn a_zip_member_lacking_a_column_given_is_read_without_the_columns_and_says_so() { + let have = b"id,LongitudeOR,LatitudeOR\n1,10,20\n".to_vec(); + let only_x = b"id,longitude,latitude,LongitudeOR\n1,10,20,30\n".to_vec(); + let zip = + crate::zip::write(&[("a.csv".into(), have.clone()), ("b.csv".into(), only_x), ("c.csv".into(), b"id,name\n1,x\n".to_vec())]) + .unwrap(); + let opts = CsvOptions { x: Some("LongitudeOR".into()), y: Some("LatitudeOR".into()), ..Default::default() }; + let read = read_zip_layers("t.zip", &zip, &opts).unwrap(); + let said = |name: &str| { + read.iter() + .find(|l| l.dataset.name == name) + .map(|l| l.report.messages.iter().map(|m| m.as_str().to_string()).collect::>()) + }; + // One notice for the zip, on its first layer, with how many tables took the columns and the others named. + let all: Vec = read.iter().flat_map(|l| l.report.messages.iter().map(|m| m.as_str().to_string())).collect(); + let lacking: Vec<&String> = all.iter().filter(|m| m.contains("lacking a column named")).collect(); + assert_eq!( + lacking, + [ + "t.zip: the x, y or WKT columns given were used by 1 of 3 tables; the rest were read without them, lacking a column named: b.csv (no y column 'LatitudeOR'); c.csv (no x column 'LongitudeOR')" + ], + "{all:?}" + ); + assert!(read.first().is_some_and(|l| l.report.messages.iter().any(|m| m.as_str().contains("lacking a column named")))); + assert_eq!(said("c"), Some(vec![]), "the other layers say nothing of it"); + assert!(read.iter().all(|l| l.report.columns_lacking.is_none())); + // By detection `b` is still points, as it is without the columns given. + assert_eq!(read.iter().find(|l| l.dataset.name == "b").map(|l| l.dataset.geometry_type), Some(GeometryType::Point)); + assert_eq!(read.iter().find(|l| l.dataset.name == "c").map(|l| l.dataset.geometry_type), Some(GeometryType::None)); + // Alone, a missing column is still an error. + assert!(read_delimited_bytes("c.csv", b"id,name\n1,x\n", &opts).is_err()); + // The same zip without the columns given reads as before. + let plain = read_zip("t.zip", &zip).unwrap(); + assert!(plain.iter().all(|(_, r)| !r.messages.iter().any(|m| m.contains("lacking a column named")))); + // Every table having them says nothing about them. + let clean = crate::zip::write(&[("a.csv".into(), have.clone()), ("b.csv".into(), have)]).unwrap(); + let read = read_zip_layers("t.zip", &clean, &opts).unwrap(); + assert!(read.iter().all(|l| l.report.messages.is_empty()), "{:?}", read.iter().map(|l| &l.report.messages).collect::>()); + } + + /// A WKT column missing from some tables, or from all, is said once; the tables are still read. + #[test] + fn a_zips_missing_wkt_column_is_said_once_for_some_or_all_tables() { + let opts = CsvOptions { wkt: Some("footprint".into()), ..Default::default() }; + let notices = |zip: &[u8]| -> (usize, Vec) { + let read = read_zip_layers("t.zip", zip, &opts).unwrap(); + let all = read.iter().flat_map(|l| l.report.messages.iter().map(|m| m.as_str().to_string())).collect::>(); + (read.len(), all.into_iter().filter(|m| m.contains("lacking a column named")).collect()) + }; + let some = + crate::zip::write(&[("a.csv".into(), b"id,footprint\n1,POINT (1 2)\n".to_vec()), ("b.csv".into(), b"id,name\n1,x\n".to_vec())]) + .unwrap(); + assert_eq!( + notices(&some), + (2, vec!["t.zip: the x, y or WKT columns given were used by 1 of 2 tables; the rest were read without them, lacking a column named: b.csv (no WKT column 'footprint')".to_string()]) + ); + let none = + crate::zip::write(&[("a.csv".into(), b"id,name\n1,x\n".to_vec()), ("b.csv".into(), b"id,name\n2,y\n".to_vec())]).unwrap(); + assert_eq!( + notices(&none), + (2, vec!["t.zip: the x, y or WKT columns given were used by 0 of 2 tables; the rest were read without them, lacking a column named: a.csv (no WKT column 'footprint'); b.csv (no WKT column 'footprint')".to_string()]) + ); + // Many tables, one notice: the names are capped as the skipped members' are. + let many: Vec<(String, Vec)> = (0..MAX_ZIP_LAYERS).map(|i| (format!("t{i:02}.csv"), b"id,name\n1,x\n".to_vec())).collect(); + let (read, said) = notices(&crate::zip::write(&many).unwrap()); + assert_eq!((read, said.len()), (MAX_ZIP_LAYERS, 1)); + assert!(said[0].contains("used by 0 of 32 tables") && said[0].contains("and 12 more"), "{said:?}"); + } + + /// `wkt` and `delimiter` reach a zip's tables; the other members ignore them. + #[test] + fn a_zips_wkt_and_delimiter_reach_its_tables() { + let zip = crate::zip::write(&[ + ("a.csv".into(), b"id,footprint\n1,POINT (1 2)\n".to_vec()), + ("b.csv".into(), b"a,b\tc\n1,2\t3\n".to_vec()), + ]) + .unwrap(); + let wkt = CsvOptions { wkt: Some("footprint".into()), delimiter: Some(b','), ..Default::default() }; + let read = read_zip_layers("t.zip", &zip, &wkt).unwrap(); + assert_eq!(read.iter().find(|l| l.dataset.name == "a").map(|l| l.dataset.features.len()), Some(1)); + assert_eq!(read.iter().find(|l| l.dataset.name == "a").map(|l| l.dataset.geometry_type), Some(GeometryType::Point)); + let tab = CsvOptions { delimiter: Some(b'\t'), ..Default::default() }; + let read = read_zip_layers("t.zip", &zip, &tab).unwrap(); + let names = |name: &str| { + read.iter().find(|l| l.dataset.name == name).map(|l| l.dataset.fields.iter().map(|f| f.name.clone()).collect::>()) + }; + assert_eq!(names("b"), Some(vec!["a,b".to_string(), "c".to_string()])); + // `x` without `y` skips a table that has it, and names it, rather than reading it as something else. + let lone = CsvOptions { x: Some("id".into()), ..Default::default() }; + let read = read_zip_layers("t.zip", &zip, &lone).unwrap_or_default(); + let said: Vec = read.iter().flat_map(|l| l.report.messages.iter().map(|m| m.as_str().to_string())).collect(); + assert!(said.iter().any(|m| m.contains("a.csv") && m.contains("give both the x and the y column")), "{said:?}"); + } + /// A zipped LandXML file is read in the system the zip is given, as it is by itself. #[test] fn a_zipped_landxml_file_takes_the_zips_system() { diff --git a/crates/data/src/lib.rs b/crates/data/src/lib.rs index e9319f24c3..88bee1a423 100644 --- a/crates/data/src/lib.rs +++ b/crates/data/src/lib.rs @@ -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, + /// 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>, } /// An extrusion a reader suggests for a layer of polygons: heights from one field, on a base from diff --git a/crates/data/src/source/mod.rs b/crates/data/src/source/mod.rs index 3af146d1ac..f6c932ef71 100644 --- a/crates/data/src/source/mod.rs +++ b/crates/data/src/source/mod.rs @@ -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, ¬_utf8, src.text_encoding()); diff --git a/crates/engine/src/cmd/layer.rs b/crates/engine/src/cmd/layer.rs index 0e80688dcc..be221331bc 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).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)"}"#, ), @@ -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)?))? @@ -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. @@ -4850,7 +4851,13 @@ pub(crate) fn csv_options(p: &Value) -> Result) -> Result { + Ok(rustgis_data::io::CsvOptions { crs, ..csv_options(p)?.unwrap_or_default() }) } /// A `delimiter` parameter: one character, or `\t`/`tab`. @@ -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). diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index 63607f5548..848113a0de 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -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::>(), [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)>) -> (String, std::sync::Arc>>) { diff --git a/crates/engine/tests/integration/main.rs b/crates/engine/tests/integration/main.rs index 430cf68fe5..85153b6440 100644 --- a/crates/engine/tests/integration/main.rs +++ b/crates/engine/tests/integration/main.rs @@ -25,3 +25,4 @@ mod snap_boxes; mod snapping_point_types; mod vertex_snap_identity; mod workflows; +mod zip_columns; diff --git a/crates/engine/tests/integration/zip_columns.rs b/crates/engine/tests/integration/zip_columns.rs new file mode 100644 index 0000000000..28df8df0d6 --- /dev/null +++ b/crates/engine/tests/integration/zip_columns.rs @@ -0,0 +1,182 @@ +//! The `x`, `y`, `wkt` and `delimiter` given when adding a zip reach its delimited and workbook +//! members (#3062), by path, as bytes and as a finished download. +use base64::Engine; +use rustgis_engine::data::{sheets, zip}; +use rustgis_engine::{Project, Session}; +use serde_json::{Value, json}; + +/// A zip of three tables that hold the columns `LongitudeOR`/`LatitudeOR` (which name detection +/// doesn't take) and one that doesn't. +fn members(with_notes: bool) -> Vec { + let mut entries = vec![ + ("d/2023.csv".to_string(), b"id,LongitudeOR,LatitudeOR\n1,10,20\n2,11,21\n".to_vec()), + ("d/2024.csv".to_string(), b"id;LongitudeOR;LatitudeOR\n3;12;22\n".to_vec()), + ("book.xlsx".to_string(), sheets::xlsx(&[("ALL", &[&["id", "LongitudeOR", "LatitudeOR"], &["4", "13", "23"]])])), + ]; + if with_notes { + entries.push(("notes.csv".to_string(), b"id,name\n5,x\n".to_vec())); + } + zip::write(&entries).unwrap() +} + +/// A folder of its own for each read: the tests run side by side. +fn unique_dir() -> std::path::PathBuf { + static NEXT: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0); + std::env::temp_dir().join(format!( + "rustgis-zip-columns-{}-{}", + std::process::id(), + NEXT.fetch_add(1, std::sync::atomic::Ordering::Relaxed) + )) +} + +/// Adds `bytes` named `x.zip` by `route` with `extra` parameters; the session and its notices. +fn add(route: &str, bytes: &[u8], extra: Value) -> (Session, Vec) { + let dir = unique_dir(); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + let mut s = Session::new(Project::default()); + let mark = s.notice_mark(); + let mut p = extra; + match route { + "path" => { + let path = dir.join("x.zip"); + std::fs::write(&path, bytes).unwrap(); + p["path"] = json!(path); + s.run("layer.addData", &p).unwrap(); + } + "bytes" => { + p["fileName"] = json!("x.zip"); + p["data"] = json!(base64::engine::general_purpose::STANDARD.encode(bytes)); + s.run("layer.addDataBytes", &p).unwrap(); + } + _ => { + let id = s.download_started(); + s.download_landed(id, bytes.to_vec()); + p["id"] = json!(id); + p["url"] = json!("https://example.org/x.zip"); + s.run("layer.addDownload", &p).unwrap(); + } + } + let said = s.notices_since(mark).iter().map(|n| n.text.to_string()).collect(); + let _ = std::fs::remove_dir_all(&dir); + (s, said) +} + +fn columns() -> Value { + json!({"x": "LongitudeOR", "y": "LatitudeOR"}) +} + +/// Each point layer's name and features' count, in name order, and the tables' names. +fn shape(s: &Session) -> (Vec<(String, usize)>, Vec) { + let mut layers: Vec<_> = s.map().layers.iter().map(|l| (l.dataset.name.clone(), l.dataset.features.len())).collect(); + layers.sort(); + let mut tables: Vec<_> = s.project.tables.iter().map(|t| t.dataset.name.clone()).collect(); + tables.sort(); + (layers, tables) +} + +#[test] +fn a_zips_csv_and_workbook_members_take_the_columns_given() { + for route in ["path", "bytes", "download"] { + let (s, said) = add(route, &members(true), columns()); + let (layers, tables) = shape(&s); + assert_eq!(layers.iter().map(|(_, n)| *n).collect::>(), [2, 1, 1], "{route}: {layers:?}"); + assert_eq!(tables, ["notes"], "{route}"); + // One notice for the zip, with how many tables took the columns and the one that didn't. + let lacking: Vec<_> = said.iter().filter(|t| t.contains("lacking a column named")).collect(); + assert_eq!(lacking.len(), 1, "{route}: {said:?}"); + assert!( + lacking.iter().all(|t| t.contains( + "the x, y or WKT columns given were used by 3 of 4 tables; the rest were read without them, lacking a column named: notes.csv (no x column 'LongitudeOR')" + )), + "{route}: {said:?}" + ); + } +} + +#[test] +fn a_zip_whose_members_all_have_the_columns_says_nothing_about_them() { + let (s, said) = add("path", &members(false), columns()); + assert_eq!(shape(&s).0.len(), 3); + assert!(!said.iter().any(|t| t.contains("lacking a column named")), "{said:?}"); + // Without the columns given, the zip reads as before: tables only, and nothing new said. + let (s, said) = add("path", &members(true), json!({})); + let (layers, tables) = shape(&s); + assert!(layers.is_empty(), "{layers:?}"); + assert_eq!(tables.len(), 4, "{tables:?}"); + assert!(!said.iter().any(|t| t.contains("lacking a column named")), "{said:?}"); +} + +#[test] +fn a_zips_wkt_column_and_delimiter_reach_its_tables() { + let entries = + vec![("a.csv".to_string(), b"id,footprint\n1,POINT (1 2)\n".to_vec()), ("b.csv".to_string(), b"a,b\tc\n1,2\t3\n".to_vec())]; + let bytes = zip::write(&entries).unwrap(); + let (s, said) = add("path", &bytes, json!({"wkt": "footprint", "delimiter": "tab"})); + // `a.csv` has no tab, so it is one column without `footprint`: read without the column given. + let fields = |name: &str| { + s.project + .tables + .iter() + .find(|t| t.dataset.name == name) + .map(|t| t.dataset.fields.iter().map(|f| f.name.clone()).collect::>()) + }; + assert_eq!(fields("b"), Some(vec!["a,b".to_string(), "c".to_string()]), "{said:?}"); + // Read by commas, `a.csv`'s footprint becomes geometry. + let (s, _) = add("path", &bytes, json!({"wkt": "footprint", "delimiter": ","})); + assert!(s.map().layers.iter().any(|l| l.dataset.name == "a" && l.dataset.features.len() == 1)); +} + +#[test] +fn a_zips_other_members_ignore_the_columns_and_keep_their_notices() { + let kml = br#"p1,2op.png1010"#; + let entries = vec![ + ("a.csv".to_string(), b"id,LongitudeOR,LatitudeOR\n1,10,20\n".to_vec()), + ("o.kml".to_string(), kml.to_vec()), + ("junk.txt".to_string(), b"just some prose".to_vec()), + ]; + let bytes = zip::write(&entries).unwrap(); + let (s, said) = add("path", &bytes, columns()); + assert!(s.map().layers.iter().any(|l| l.dataset.name == "a" && l.dataset.features.len() == 1)); + assert!(s.map().layers.len() >= 2, "the KML's own layer stays"); + assert!(said.iter().any(|t| t.contains("skipped") && t.contains("junk.txt")), "{said:?}"); + assert!(said.iter().any(|t| t.contains("1 ground overlays (pictures) aren't drawn from inside a zip, in o.kml (1)")), "{said:?}"); + // Every notice but the columns' (there is none here) is what the zip says without the columns given. + let (_, before) = add("path", &bytes, json!({})); + let strip = + |said: &[String]| said.iter().map(|t| t.rsplit_once(": ").map_or(t.clone(), |(_, rest)| rest.to_string())).collect::>(); + assert_eq!(strip(&said), strip(&before)); +} + +#[test] +fn a_zips_picked_layer_keeps_the_zips_notices() { + let mut entries = vec![("a.csv".to_string(), b"id,LongitudeOR,LatitudeOR\n1,10,20\n".to_vec())]; + entries.push(("junk.txt".to_string(), b"just some prose".to_vec())); + let (s, said) = add("path", &zip::write(&entries).unwrap(), json!({"x": "LongitudeOR", "y": "LatitudeOR", "layer": "a"})); + assert_eq!(shape(&s).0, [("a".to_string(), 1)]); + assert!(said.iter().any(|t| t.contains("skipped") && t.contains("junk.txt")), "{said:?}"); +} + +#[test] +fn a_zip_given_x_without_y_or_both_kinds_of_geometry_is_refused_or_said() { + let bytes = members(false); + for p in [json!({"x": "LongitudeOR"}), json!({"x": "LongitudeOR", "y": "LatitudeOR", "wkt": "LongitudeOR"})] { + let mut s = Session::new(Project::default()); + let dir = unique_dir(); + std::fs::create_dir_all(&dir).unwrap(); + let path = dir.join("x.zip"); + std::fs::write(&path, &bytes).unwrap(); + let mut q = p; + q["path"] = json!(path); + let ran = s.run("layer.addData", &q); + let _ = std::fs::remove_dir_all(&dir); + assert!(ran.is_err(), "{ran:?}"); + } +} + +#[test] +fn a_zips_columns_notice_goes_with_a_picked_layer_that_is_not_the_first() { + let (s, said) = add("path", &members(true), json!({"x": "LongitudeOR", "y": "LatitudeOR", "layer": "2024"})); + assert_eq!(shape(&s).0, [("2024".to_string(), 1)]); + assert!(said.iter().any(|t| t.contains("used by 3 of 4 tables") && t.contains("notes.csv")), "{said:?}"); +} diff --git a/docs/user-guide/data-formats.md b/docs/user-guide/data-formats.md index 1dd3a1be58..80a7942554 100644 --- a/docs/user-guide/data-formats.md +++ b/docs/user-guide/data-formats.md @@ -20,7 +20,7 @@ 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 is the layer's own: its coordinates are kept as the file holds them and drawn in the map's projection (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 is kept as the file holds it and counted in a notice; it doesn't draw. One whose coordinates convert to beyond ±180.5° longitude or ±90.5° latitude (the declared system doesn't fit the numbers) is kept too, and a notice says it may draw out of place (see [Places with no longitude/latitude](#places-with-no-longitudelatitude)). 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: a FeatureCollection up to 32 MiB, or any with `"stream": false`, up to the size read into memory (256 MiB in the web app; on the desktop about 512 MiB for every 16 GiB of memory, up to 4 GiB: `fileBytes` in [Environments](analysis.md)); another GeoJSON document larger than 32 MiB up to 256 MiB, as it is read as it is added. A GeoJSON read whole whose attribute table (a cell for every field in every feature) would take more than 8 times that size is refused, saying the table's size: many features with properties spread over many fields. | | 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, in English or another language such as `經度`/`緯度`, 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 the size read into memory of expanded text (256 MiB in the web app); 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 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. A shape with a coordinate that isn't a number (NaN, infinity) keeps its attributes without geometry when the whole layer is read, in place too, and is counted in a notice; a view of an area, which holds no feature without geometry, leaves it out. 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. `"x"`, `"y"` and `"wkt"` given to Add Data apply to a zip's delimited members and to the first sheet of its workbooks, as to the file by itself, and `"delimiter"` to its delimited members only, so a zip of several tables with the same columns gives points together. A member that lacks a column given is read without them; one notice says how many members took the columns and names those that didn't, with the column each lacks. Other members ignore all of them. 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. A shape with a coordinate that isn't a number (NaN, infinity) keeps its attributes without geometry when the whole layer is read, in place too, and is counted in a notice; a view of an area, which holds no feature without geometry, leaves it out. 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). For descriptions, only the exact `description` key is treated as a repeated copy; case variants keep a separate column and report the rename. Description text, including surrounding whitespace, is kept as written; an empty description is empty text and an absent one is null. 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. |