From 0751a8c9437b43819e0287ede996fa19d469cb06 Mon Sep 17 00:00:00 2001 From: Cory Douglas Martin <4108748+flight1973@users.noreply.github.com> Date: Wed, 18 Nov 2026 08:40:51 -0600 Subject: [PATCH 01/12] fix(data): exports say text that reading the file back trims or reads as null (#1907) CSV, Shapefile, KML and GPX exports now count, per field, text whose spaces the reader drops, blank text it reads as null, and (KML, GPX) fields with no value, which come back without a column. One notice per kind with a count and the fields, on every export path; a streamed CSV export adds up its chunks and types each column over all of them. --- crates/data/src/export.rs | 6 + crates/data/src/export/tests.rs | 5 + crates/data/src/interop.rs | 9 +- crates/data/src/io.rs | 382 +++++++++++++++++++++++++++-- crates/engine/src/cmd/share.rs | 9 +- crates/engine/src/cmd/workflows.rs | 3 +- crates/engine/src/tests.rs | 19 +- crates/ui-egui/src/lib.rs | 2 +- 8 files changed, 407 insertions(+), 28 deletions(-) diff --git a/crates/data/src/export.rs b/crates/data/src/export.rs index 91ab2a446b..927cec3524 100644 --- a/crates/data/src/export.rs +++ b/crates/data/src/export.rs @@ -43,6 +43,8 @@ pub struct Exported { pub beyond_web_mercator: usize, /// Geometry a CSV can't hold, counted over all chunks (none for the other formats). pub csv: crate::io::CsvLosses, + /// Text a CSV changes when read back, counted over all chunks (none for the other formats). + pub text: crate::io::TextLosses, /// Per field of the layer, values of the source's date fields that weren't dates, so are /// written as null ([`crate::source::Batch::unread_dates`], said by /// [`crate::source::unread_dates_note`]). @@ -149,6 +151,7 @@ fn write_chunks_as( let mut beyond_web_mercator = 0usize; let mut null_numbers = 0usize; let mut csv = crate::io::CsvLosses::default(); + let mut text = crate::io::TextLosses::default(); let mut unread_dates = Vec::new(); let mut rounded_dates = Vec::new(); let mut null_text = Vec::new(); @@ -162,6 +165,7 @@ fn write_chunks_as( beyond_web_mercator = 0; null_numbers = 0; csv = crate::io::CsvLosses::default(); + text = crate::io::TextLosses::default(); utc_dates.clear(); fine_dates.clear(); written_values.clear(); @@ -184,6 +188,7 @@ fn write_chunks_as( null_numbers = null_numbers.saturating_add(numbers_written_as_null(&chunk, &layer.fields, ext)); if ext == "csv" { csv += crate::io::CsvLosses::of(&chunk, geometry_type); + text += crate::io::TextLosses::of(&chunk, &layer.fields, geometry_type, ext, None); } if ext == "gpkg" { crate::source::add_unread_dates(&mut utc_dates, &crate::io::offset_dates(chunk.iter(), &layer.fields)); @@ -248,6 +253,7 @@ fn write_chunks_as( unfit, beyond_web_mercator, csv, + text, unread_dates, rounded_dates, null_text, diff --git a/crates/data/src/export/tests.rs b/crates/data/src/export/tests.rs index 293eee1861..aa21fdf7d8 100644 --- a/crates/data/src/export/tests.rs +++ b/crates/data/src/export/tests.rs @@ -205,6 +205,11 @@ fn a_streamed_export_writes_what_a_whole_export_writes() { beyond_web_mercator: 0, // Counted over the chunks as the whole layer counts it. csv: if ext == "csv" { crate::io::CsvLosses::of(&whole.features, whole.geometry_type) } else { Default::default() }, + text: if ext == "csv" { + crate::io::TextLosses::of(&whole.features, &whole.fields, whole.geometry_type, ext, None) + } else { + Default::default() + }, unread_dates: Vec::new(), rounded_dates: Vec::new(), null_text: Vec::new(), diff --git a/crates/data/src/interop.rs b/crates/data/src/interop.rs index a2a97b6803..2e5476e26d 100644 --- a/crates/data/src/interop.rs +++ b/crates/data/src/interop.rs @@ -497,11 +497,16 @@ impl WktParser { } } +/// A [`to_wkt_csv`] cell's text before quoting: text starting like a formula is prefixed with `'` +/// so spreadsheets show it rather than run it. +pub(crate) fn wkt_csv_text(s: &str) -> String { + if s.starts_with(['=', '+', '-', '@']) && s.parse::().is_err() { format!("'{s}") } else { s.to_string() } +} + /// CSV with a `wkt` geometry column and every attribute; cancellable between features. pub fn to_wkt_csv(ds: &Dataset) -> crate::Result { - // Text starting like a formula is prefixed with ' so spreadsheets show it rather than run it. let q = |s: &str| { - let s = if s.starts_with(['=', '+', '-', '@']) && s.parse::().is_err() { format!("'{s}") } else { s.to_string() }; + let s = wkt_csv_text(s); if s.contains([',', '"', '\n', '\r']) { format!("\"{}\"", s.replace('"', "\"\"")) } else { s } }; let mut out = String::from("wkt"); diff --git a/crates/data/src/io.rs b/crates/data/src/io.rs index 773b39a1d9..056bdcc5c7 100644 --- a/crates/data/src/io.rs +++ b/crates/data/src/io.rs @@ -2243,30 +2243,56 @@ fn out_of_lonlat(g: &Geometry) -> bool { /// otherwise (or with no values) Text. A number whose digits a Double doesn't keep, such as a /// 20-digit identifier, keeps its column Text, so no digit is rounded away ([`double_holds`]). pub(crate) fn text_type<'a>(vals: impl Iterator) -> FieldType { - let mut ty: Option = None; - // A whole number a Double can't hold: fine in an Integer column, not in a Double one. - let mut whole_past_double = false; - for v in vals.map(str::trim).filter(|s| !s.is_empty()) { + let mut column = TextColumn::default(); + vals.for_each(|v| column.add(v)); + column.ty() +} + +/// [`text_type`] a value at a time, so a column written a chunk at a time is typed as one. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +struct TextColumn { + ty: Option, + /// A whole number a Double can't hold: fine in an Integer column, not in a Double one. + whole_past_double: bool, +} + +impl TextColumn { + /// Adds a value's text; one that is empty once trimmed types nothing. + fn add(&mut self, v: &str) { + let v = v.trim(); + if v.is_empty() { + return; + } let t = if has_leading_zero(v) { // Identifiers such as ZIP codes keep their leading zeros. FieldType::Text } else if let Ok(i) = v.parse::() { // A whole number is held when its Double is the same number (in i128: no saturation). - whole_past_double |= (i as f64) as i128 != i128::from(i); + self.whole_past_double |= (i as f64) as i128 != i128::from(i); FieldType::Integer } else if double_holds(v) { FieldType::Double } else { FieldType::Text }; - ty = Some(match ty { - None => t, - Some(prev) => widen(prev, Some(t)), - }); + self.ty = Some(self.ty.map_or(t, |prev| widen(prev, Some(t)))); } - match ty { - Some(FieldType::Double) if whole_past_double => FieldType::Text, - ty => ty.unwrap_or(FieldType::Text), + + /// Adds another chunk of the column. + fn merge(&mut self, other: Self) { + self.whole_past_double |= other.whole_past_double; + self.ty = match self.ty { + None => other.ty, + Some(prev) => Some(widen(prev, other.ty)), + }; + } + + /// The column's type: Text without values. + fn ty(self) -> FieldType { + match self.ty { + Some(FieldType::Double) if self.whole_past_double => FieldType::Text, + ty => ty.unwrap_or(FieldType::Text), + } } } @@ -3804,11 +3830,215 @@ impl std::ops::AddAssign for CsvLosses { } } -/// What a CSV or GPX file (extension `ext`) of the whole dataset `ds` can't hold, written to -/// `target`: [`CsvLosses`]' notices, or [`gpx_notes`] with each feature named from `name_field`; +/// What reading a CSV, Shapefile, KML or GPX export back does to its text, counted for each field +/// over the features the writer writes: spaces around text dropped, blank text read as null, and +/// (KML, GPX) a field without a value left without a column. Readers, as they are: +/// - CSV (and Data Interop's WKT CSV) keeps a cell as it is; an empty one reads as null, and so +/// does one of spaces in a column read as numbers ([`Value::parse_file`]). +/// - dBase drops the spaces after text, and reads text of spaces only as null ([`read_dbf`]). +/// - KML and GPX trim each value; a blank name reads as null, and a blank KML extended data +/// value too in a column read as numbers ([`type_text_columns`]). A KML description is kept as +/// it is. A value that is null isn't written, so a field without one has no column. +/// +/// A streamed export adds up its chunks' (`+=`): whether reading takes a column as numbers, which +/// decides what its blanks become, is settled over all of them. +#[derive(Clone, Debug, Default, PartialEq, Eq)] +pub struct TextLosses { + /// For each field, in the layer's order. + fields: Vec, + /// Only the spaces after text are dropped (dBase). + ends_only: bool, +} + +/// One field's [`TextLosses`]. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +struct FieldText { + /// Text with spaces around it that reading drops, unless its column reads as numbers (the + /// text is then a number, and read as one). + padded: usize, + /// Blank text, read as null. + blank: usize, + /// Blank text read as null in a column read as numbers, else read as it is. + blank_in_numbers: usize, + /// Text of spaces only: read as null in a column read as numbers, else as empty text. + spaces: usize, + /// The column's written text, when reading types the column from its values. + column: Option, + /// A value of the field is written. + valued: bool, + /// Reading the file back has no column for the field when it has no value (KML, GPX). + needs_value: bool, +} + +/// The columns the KML reader gives every layer. +const KML_COLUMNS: [&str; 4] = ["name", "description", "folder", "style"]; +/// The columns the GPX reader gives waypoints, and tracks. +const GPX_POINT_COLUMNS: [&str; 7] = ["name", "ele", "time", "desc", "cmt", "sym", "type"]; +const GPX_TRACK_COLUMNS: [&str; 6] = ["name", "desc", "cmt", "type", "number", "points"]; + +impl TextLosses { + /// The losses of `features`, with `fields`, in a layer of type `gt` written to a file of + /// extension `ext` (lowercase), each KML or GPX feature named from field `name_field`; none + /// for another format. + pub fn of(features: &[crate::Feature], fields: &[Field], gt: GeometryType, ext: &str, name_field: Option) -> Self { + let (csv, shp, kml, gpx) = (matches!(ext, "csv" | "wkt"), matches!(ext, "shp" | "zip"), matches!(ext, "kml" | "kmz"), ext == "gpx"); + if !(csv || shp || kml || gpx) { + return Self::default(); + } + let gpx_columns: &[&str] = if gt == GeometryType::Point { &GPX_POINT_COLUMNS } else { &GPX_TRACK_COLUMNS }; + let mut out: Vec = (fields.iter().enumerate()) + .map(|(k, f)| { + let named = Some(k) == name_field; + let fixed = |columns: &[&str]| columns.iter().any(|c| f.name.eq_ignore_ascii_case(c)); + // A KML description is text as it is, not typed. + let typed = csv || kml && !named && f.name != "description"; + let needs_value = !named && (kml && !fixed(&KML_COLUMNS) || gpx && !fixed(gpx_columns)); + FieldText { column: typed.then(TextColumn::default), needs_value, ..FieldText::default() } + }) + .collect(); + let written = |f: &crate::Feature| match &f.geometry { + _ if csv => true, + g if shp => shapefile_keeps(g.as_ref(), gt), + Some(Geometry::MultiPoint(v)) if gpx => !v.is_empty(), + g => (kml || gpx) && g.is_some(), + }; + for feature in features.iter().filter(|f| written(f)) { + for (k, (field, v)) in fields.iter().zip(&feature.attrs).enumerate() { + let Some(loss) = out.get_mut(k) else { continue }; + if v.is_null() { + continue; + } + loss.valued = true; + if let Some(column) = &mut loss.column { + let text = match ext { + "csv" => csv_cell(v), + "wkt" => crate::interop::wkt_csv_text(&v.to_file_text()), + _ => v.to_file_text(), + }; + // CSV's `` reads as null, so it types a column no more than an empty cell. + if !(csv && Value::is_null_marker(&text)) { + column.add(&text); + } + } + let Value::Text(s) = v else { continue }; + let trimmed = s.trim(); + let count = if csv { + if s.is_empty() { + &mut loss.blank + } else if trimmed.is_empty() { + &mut loss.blank_in_numbers + } else { + continue; + } + } else if shp { + // A Character column; text cut to 254 bytes is said as cut. + if !matches!(field.ty, FieldType::Text | FieldType::DateTime) || s.len() > 254 { + continue; + } + let kept = s.trim_end_matches(' '); + if kept.is_empty() { + &mut loss.blank + } else if kept.len() < s.len() { + &mut loss.padded + } else { + continue; + } + } else if (kml || gpx) && Some(k) == name_field { + if trimmed.is_empty() { + &mut loss.blank + } else if trimmed.len() < s.len() { + &mut loss.padded + } else { + continue; + } + } else if kml && field.name != "description" { + if s.is_empty() { + &mut loss.blank_in_numbers + } else if trimmed.is_empty() { + &mut loss.spaces + } else if trimmed.len() < s.len() { + &mut loss.padded + } else { + continue; + } + } else { + continue; + }; + *count += 1; + } + } + Self { fields: out, ends_only: shp } + } + + /// One notice for each loss of a layer with `fields` written to `target`, with a count and + /// the fields; none without loss. + pub fn notes(&self, fields: &[Field], target: &str) -> Vec { + let numbers = |t: &FieldText| t.column.is_some_and(|c| c.ty() != FieldType::Text); + let trimmed = |t: &FieldText| if numbers(t) { 0 } else { t.padded + t.spaces }; + let blank = |t: &FieldText| t.blank + if numbers(t) { t.blank_in_numbers + t.spaces } else { 0 }; + let missing = |t: &FieldText| usize::from(t.needs_value && !t.valued); + let selected = |count: &dyn Fn(&FieldText) -> usize| { + let counted: Vec<_> = fields.iter().zip(&self.fields).map(|(f, t)| (f, count(t))).filter(|(_, n)| *n > 0).collect(); + let names: Vec<_> = counted.iter().take(5).map(|(f, _)| format!("'{}'", dbf_notice_name(&f.name))).collect(); + let more = if counted.len() > 5 { format!(" and {} more", counted.len() - 5) } else { String::new() }; + (counted.iter().map(|(_, n)| n).sum::(), format!("{}{more}", names.join(", "))) + }; + let target: String = target.chars().map(dbf_notice_char).collect(); + let mut notes = Vec::new(); + let (n, names) = selected(&trimmed); + if n > 0 { + let what = match (n, self.ends_only) { + (1, true) => "1 text value ends with spaces".to_string(), + (1, false) => "1 text value starts or ends with spaces".to_string(), + (n, true) => format!("{n} text values end with spaces"), + (n, false) => format!("{n} text values start or end with spaces"), + }; + notes.push(format!("{target}: {what}, which reading the file back drops, in {names}")); + } + let (n, names) = selected(&blank); + if n > 0 { + let what = if n == 1 { "1 blank text value reads".to_string() } else { format!("{n} blank text values read") }; + notes.push(format!("{target}: {what} back as empty (null), in {names}")); + } + let (n, names) = selected(&missing); + if n > 0 { + let what = if n == 1 { + "1 field is empty in every feature, so reading the file back has no column for it".to_string() + } else { + format!("{n} fields are empty in every feature, so reading the file back has no columns for them") + }; + notes.push(format!("{target}: {what}: {names}")); + } + notes + } +} + +impl std::ops::AddAssign for TextLosses { + /// Adds a chunk's losses, of the same fields. + fn add_assign(&mut self, other: Self) { + if self.fields.is_empty() { + *self = other; + return; + } + for (a, b) in self.fields.iter_mut().zip(other.fields) { + a.padded += b.padded; + a.blank += b.blank; + a.blank_in_numbers += b.blank_in_numbers; + a.spaces += b.spaces; + if let (Some(a), Some(b)) = (&mut a.column, b.column) { + a.merge(b); + } + a.valued |= b.valued; + } + } +} + +/// What a CSV, Shapefile, KML or GPX file (extension `ext`) of the whole dataset `ds` can't +/// hold, written to `target`: [`CsvLosses`]' notices, [`gpx_notes`] with each feature named from +/// `name_field`, and [`TextLosses`]' (a Shapefile's other values are [`shapefile_values_notes`]); /// none for another format. A streamed export counts CSV's a chunk at a time instead. pub fn export_losses_notes(ds: &Dataset, ext: &str, name_field: Option, target: &str) -> Vec { - match ext { + let mut notes = match ext { "csv" => { let losses = CsvLosses::of(&ds.features, ds.geometry_type); let mut notes = losses.notes(target); @@ -3817,7 +4047,9 @@ pub fn export_losses_notes(ds: &Dataset, ext: &str, name_field: Option, t } "gpx" => gpx_notes(ds, name_field, target), _ => Vec::new(), - } + }; + notes.extend(TextLosses::of(&ds.features, &ds.fields, ds.geometry_type, ext, name_field).notes(&ds.fields, target)); + notes } /// Features a GPX file of `ds` leaves out: those without geometry, and multipoints without a @@ -5549,6 +5781,124 @@ mod tests { assert_eq!(write_bytes(&ds, "gpx").unwrap().1, 2); } + /// A text layer for [`TextLosses`]: point features with `rows` of text values, and one without + /// geometry holding blanks and padded text, which KML, GPX and Shapefile don't write. + fn text_layer(names: &[&str], rows: &[&[Option<&str>]]) -> Dataset { + let fields = names.iter().map(|n| Field::new(*n, FieldType::Text)).collect(); + let mut ds = Dataset::new("t", GeometryType::Point, fields); + for (i, row) in rows.iter().enumerate() { + let attrs = row.iter().map(|v| v.map_or(Value::Null, |t| Value::Text(t.to_string()))).collect(); + ds.push(Some(Geometry::Point(Coord::new(i as f64, 1.0))), attrs); + } + ds.push(None, names.iter().map(|_| Value::Text(" ".into())).collect()); + ds + } + + fn text_notes(ds: &Dataset, ext: &str) -> Vec { + TextLosses::of(&ds.features, &ds.fields, ds.geometry_type, ext, name_field(ds)).notes(&ds.fields, "t") + } + + #[test] + fn csv_says_blank_text_that_reads_as_null() { + // 'code' reads as numbers, so its blank of spaces reads as null; 'note' stays text, which + // keeps spaces. + let ds = text_layer(&["note", "code"], &[&[Some(""), Some("1")], &[Some(" "), Some(" ")], &[Some(" x "), Some("")]]); + // The feature without geometry is a CSV row: its blank in 'code' counts too. + assert_eq!(text_notes(&ds, "csv"), ["t: 4 blank text values read back as empty (null), in 'note', 'code'"]); + assert_eq!(text_notes(&ds, "wkt"), ["t: 4 blank text values read back as empty (null), in 'note', 'code'"]); + let mut clean = text_layer(&["note", "code"], &[&[Some(" x "), Some("1")], &[Some(" "), None]]); + // Without the row of spaces, which 'code' reads as null. + clean.features.truncate(2); + assert!(text_notes(&clean, "csv").is_empty()); + } + + #[test] + fn shapefile_says_trailing_spaces_and_blank_text() { + let ds = text_layer(&["a", "b"], &[&[Some("lead "), Some(" kept")], &[Some(" "), Some("")], &[None, Some("x ")]]); + assert_eq!( + text_notes(&ds, "shp"), + [ + "t: 2 text values end with spaces, which reading the file back drops, in 'a', 'b'", + "t: 2 blank text values read back as empty (null), in 'a', 'b'", + ] + ); + assert_eq!(text_notes(&ds, "zip"), text_notes(&ds, "shp")); + let clean = text_layer(&["a"], &[&[Some(" kept")], &[None]]); + assert!(text_notes(&clean, "shp").is_empty()); + } + + #[test] + fn kml_says_trimmed_and_blank_text_and_fields_without_values() { + let ds = text_layer( + &["name", "note", "code", "gone", "folder", "description"], + &[ + &[Some(" a"), Some(" padded "), Some("1"), None, None, Some(" kept ")], + &[Some(" "), Some(""), Some(""), None, None, Some("")], + &[Some("b"), Some(" "), Some("2"), None, None, None], + ], + ); + assert_eq!( + text_notes(&ds, "kml"), + [ + "t: 3 text values start or end with spaces, which reading the file back drops, in 'name', 'note'", + "t: 2 blank text values read back as empty (null), in 'name', 'code'", + "t: 1 field is empty in every feature, so reading the file back has no column for it: 'gone'", + ] + ); + assert_eq!(text_notes(&ds, "kmz"), text_notes(&ds, "kml")); + // What the notes say is what reading the file back does. + let (bytes, _) = write_bytes(&ds, "kml").unwrap(); + let back = &crate::kml::read("t.kml", &bytes).unwrap()[0].dataset; + let column = |n: &str| back.field_index(n).map(|i| back.features.iter().map(|f| f.attrs[i].clone()).collect::>()); + let text = |t: &str| Value::Text(t.into()); + assert_eq!(column("name"), Some(vec![text("a"), Value::Null, text("b")])); + assert_eq!(column("note"), Some(vec![text("padded"), text(""), text("")])); + assert_eq!(column("code"), Some(vec![Value::Int(1), Value::Null, Value::Int(2)])); + assert_eq!(column("gone"), None); + assert_eq!(column("description"), Some(vec![text(" kept "), text(""), Value::Null])); + let clean = text_layer(&["name", "note"], &[&[Some("a"), Some("")], &[None, Some("x")]]); + assert!(text_notes(&clean, "kml").is_empty()); + } + + #[test] + fn gpx_says_trimmed_and_blank_names_and_fields_without_values() { + let ds = text_layer(&["name", "note", "gone", "ele"], &[&[Some("a "), Some("x"), None, None], &[Some(""), None, None, None]]); + // 'note' isn't written, which `gpx_notes` says; 'ele' comes back as a waypoint's column. + assert_eq!( + text_notes(&ds, "gpx"), + [ + "t: 1 text value starts or ends with spaces, which reading the file back drops, in 'name'", + "t: 1 blank text value reads back as empty (null), in 'name'", + "t: 1 field is empty in every feature, so reading the file back has no column for it: 'gone'", + ] + ); + let clean = text_layer(&["name", "note"], &[&[Some("a"), Some("x")], &[None, None]]); + assert!(text_notes(&clean, "gpx").is_empty()); + assert!(text_notes(&ds, "geojson").is_empty()); + } + + /// A streamed CSV export adds up its chunks' text losses to the whole layer's, and types a + /// column over all of them: 'code' reads as numbers only from the second chunk on. + #[test] + fn text_losses_of_chunks_add_up_to_the_whole_layer() { + let ds = text_layer( + &["note", "code"], + &[&[Some(""), Some(" ")], &[Some(" "), Some("")], &[Some("x"), Some("12")], &[None, Some(" ")]], + ); + let whole = TextLosses::of(&ds.features, &ds.fields, ds.geometry_type, "csv", None); + for size in 1..=ds.features.len() { + let mut sum = TextLosses::default(); + for chunk in ds.features.chunks(size) { + sum += TextLosses::of(chunk, &ds.fields, ds.geometry_type, "csv", None); + } + assert_eq!(sum, whole, "chunks of {size}"); + } + assert_eq!(whole.notes(&ds.fields, "t"), ["t: 5 blank text values read back as empty (null), in 'note', 'code'"]); + // Alone, the first chunk's 'code' is text, which keeps its spaces. + let first = TextLosses::of(&ds.features[..1], &ds.fields, ds.geometry_type, "csv", None); + assert_eq!(first.notes(&ds.fields, "t"), ["t: 1 blank text value reads back as empty (null), in 'note'"]); + } + /// A point layer's fields named like coordinates keep their values when its CSV is read back: /// the coordinate columns come first, so reading takes them, not the fields. (Reading keeps the /// coordinate columns as fields too.) diff --git a/crates/engine/src/cmd/share.rs b/crates/engine/src/cmd/share.rs index 5746c6d732..bb6968adf2 100644 --- a/crates/engine/src/cmd/share.rs +++ b/crates/engine/src/cmd/share.rs @@ -705,7 +705,7 @@ fn write_layer(l: &rustgis_map::Layer, path: &str, asked: Option, gpkg: Gpk return Err(format!("{path}: {e}")); } let parquet = matches!(ext.as_str(), "parquet" | "geoparquet"); - let (written, left_out, skipped, table, unfit, null_numbers, moved, csv, dates) = match &chunks { + let (written, left_out, skipped, table, unfit, null_numbers, moved, csv, text, dates) = match &chunks { Some((src, layer)) => { let (e, table) = rustgis_data::export::write_source_to(src.as_ref(), layer, Path::new(&path), crs, &gpkg).map_err(|e| e.to_string())?; @@ -731,16 +731,17 @@ fn write_layer(l: &rustgis_map::Layer, path: &str, asked: Option, gpkg: Gpk } dates.extend(e.date_messages.iter().map(|n| format!("{path}: {n}"))); dates.extend(e.read_notes.iter().map(|n| format!("{path}: {}: {n} when read for the export", layer.name))); - (e.written, e.left_out, e.skipped, table, unfit, e.null_numbers, moved, e.csv, dates) + (e.written, e.left_out, e.skipped, table, unfit, e.null_numbers, moved, e.csv, e.text, dates) } None => { let (left_out, table) = rustgis_data::io::write_path_to(ds, Path::new(&path), crs, &gpkg).map_err(|e| e.to_string())?; let unfit = if parquet { rustgis_data::source::parquet::values_note(ds, path) } else { None }; let null_numbers = rustgis_data::export::numbers_written_as_null(&ds.features, &ds.fields, &ext); let csv = if ext == "csv" { rustgis_data::io::CsvLosses::of(&ds.features, ds.geometry_type) } else { Default::default() }; + let text = rustgis_data::io::TextLosses::of(&ds.features, &ds.fields, ds.geometry_type, &ext, rustgis_data::io::name_field(ds)); let mut dates = read_notes(path, &ds.name, &unreadable); dates.extend(gpkg_dates_note(ds, &ext, path)); - (ds.features.len().saturating_sub(left_out), left_out, unread, table, unfit, null_numbers, None, csv, dates) + (ds.features.len().saturating_sub(left_out), left_out, unread, table, unfit, null_numbers, None, csv, text, dates) } }; // The features written give their own extent. A streamed layer written a chunk at a time has @@ -778,6 +779,8 @@ fn write_layer(l: &rustgis_map::Layer, path: &str, asked: Option, gpkg: Gpk if ext == "gpx" { said.extend(rustgis_data::io::gpx_notes(ds, rustgis_data::io::name_field(ds), path)); } + // CSV, Shapefile, KML and GPX readers trim text or read blanks as null. + said.extend(text.notes(&ds.fields, path)); if skipped > 0 { said.push(format!("{path}: {skipped} rows couldn't be read and were left out")); } diff --git a/crates/engine/src/cmd/workflows.rs b/crates/engine/src/cmd/workflows.rs index 073f05df51..162bbaf386 100644 --- a/crates/engine/src/cmd/workflows.rs +++ b/crates/engine/src/cmd/workflows.rs @@ -1930,6 +1930,7 @@ pub(crate) fn convert_work(s: &Session, p: &Value) -> Result 0 { notes.push(format!("{path}: {} rows couldn't be read and were left out", result.skipped)); @@ -2014,7 +2015,7 @@ fn converted(ds: &Dataset, p: &Value) -> Result<(String, Vec), String> { // Every format here is longitude/latitude. let target = ps(p, "path").unwrap_or(&ds.name); let mut notes = rustgis_data::export_notes([(ds, ds.extent())], target, rustgis_data::raster::Crs::LonLat); - // CSV holds a point a row, GPX a name for each feature and no areas. + // CSV holds a point a row, GPX a name for each feature and no areas; reading text back trims it or reads blanks as null. notes.extend(rustgis_data::io::export_losses_notes(ds, format, name_field, target)); // KML and GPX hold features with geometry only. if let ext @ ("kml" | "gpx") = format { diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index fa74fd0b2e..f736582045 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -24610,8 +24610,15 @@ fn csv_and_gpx_exports_say_what_they_leave_out() { (Geometry::MultiPoint(vec![Coord::new(3.0, 4.0), Coord::new(5.0, 6.0)]), vec![V::Text("M".into()), V::Null]), ]; s.map_mut().add_dataset(layer("Sites", GeometryType::Point, pts)); + // A field null everywhere has no column when a GPX or KML file is read back, so a clean layer + // holds only names. + let named = |mut ds: Dataset| { + ds.fields.truncate(1); + ds.features.iter_mut().for_each(|f| f.attrs.truncate(1)); + ds + }; let clean = vec![(Geometry::Point(Coord::new(1.0, 2.0)), vec![V::Text("P".into()), V::Null])]; - s.map_mut().add_dataset(layer("Clean", GeometryType::Point, clean)); + s.map_mut().add_dataset(named(layer("Clean", GeometryType::Point, clean))); let said = |s: &mut Session, id: &str, p: Value| { let mark = s.notices.len(); s.run(id, &p).unwrap(); @@ -24631,7 +24638,8 @@ fn csv_and_gpx_exports_say_what_they_leave_out() { "{n:?}" ); let n = said(&mut s, "share.exportLayer", json!({"layer": "Sites", "path": out("sites.gpx")})); - assert!(n.len() == 1 && n[0].contains("1 multipoint was written as a waypoint for each"), "{n:?}"); + assert!(n.len() == 2 && n[0].contains("1 multipoint was written as a waypoint for each"), "{n:?}"); + assert!(n[1].contains("1 field is empty in every feature, so reading the file back has no column for it: 'height'"), "{n:?}"); let n = said(&mut s, "data.convert", json!({"layer": "Areas", "format": "gpx"})); assert!(n.iter().any(|t| t.contains("'height'")) && n.iter().any(|t| t.contains("tracks")), "{n:?}"); let n = said(&mut s, "data.convert", json!({"layer": "Areas", "format": "csv"})); @@ -24642,12 +24650,13 @@ fn csv_and_gpx_exports_say_what_they_leave_out() { s.map_mut().add_dataset(rows); for format in ["kml", "gpx"] { let n = said(&mut s, "data.convert", json!({"layer": "Rows", "format": format})); - assert!(n.len() == 1 && n[0].contains("1 features without drawable geometry were left out"), "{format}: {n:?}"); + assert!(n.len() == 2 && n.iter().any(|t| t.contains("1 features without drawable geometry were left out")), "{format}: {n:?}"); + assert!(n.iter().any(|t| t.contains("no column for it: 'height'")), "{format}: {n:?}"); } // A standalone table keeps geometry too: Export Table says the same, and nothing for a clean one. let areas = layer("Area table", GeometryType::Polygon, vec![(square(0.0, true), vec![V::Text("A".into()), V::Float(2.5)])]); let points = - layer("Point table", GeometryType::Point, vec![(Geometry::Point(Coord::new(1.0, 2.0)), vec![V::Text("P".into()), V::Null])]); + named(layer("Point table", GeometryType::Point, vec![(Geometry::Point(Coord::new(1.0, 2.0)), vec![V::Text("P".into()), V::Null])])); s.project.tables.push(crate::project::Table::new(9001, areas)); s.project.tables.push(crate::project::Table::new(9002, points)); let n = said(&mut s, "share.exportTable", json!({"table": 9001, "path": out("table.csv")})); @@ -24658,7 +24667,7 @@ fn csv_and_gpx_exports_say_what_they_leave_out() { let n = said(&mut s, "share.exportTable", json!({"table": 9002, "path": out(&format!("clean-table.{ext}"))})); assert_eq!(n, Vec::::new(), "{ext}"); } - // Points alone, their other field empty: CSV and GPX hold them whole. + // Points alone, with only a name: CSV and GPX hold them whole. for ext in ["csv", "gpx"] { assert_eq!( said(&mut s, "share.exportLayer", json!({"layer": "Clean", "path": out(&format!("clean.{ext}"))})), diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 81cafed03f..c700d0d9c6 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -4957,7 +4957,7 @@ impl RustGisApp { dbf_notes.push(format!("{name}: {} rows couldn't be read and were left out", lost.rows)); } dbf_notes.extend(rustgis_engine::cmd::share::read_notes(&name, &l.name, &lost)); - // CSV holds a point a row, GPX a name for each feature and no areas. + // CSV holds a point a row, GPX a name for each feature and no areas; reading text back trims it or reads blanks as null. dbf_notes.extend(io::export_losses_notes(ds, &ext, io::name_field(ds), &name)); if let Some(note) = io::left_out_note(&name, &ext, left_out) { self.session.notify(note, false); From 2415ef2919f11e4bb53ad361d29e6765269ff047 Mon Sep 17 00:00:00 2001 From: Cory Douglas Martin <4108748+flight1973@users.noreply.github.com> Date: Wed, 18 Nov 2026 08:40:51 -0600 Subject: [PATCH 02/12] test(engine): drop the round-trip limits exports now say (#1907) --- crates/engine/tests/never_silent_roundtrip.rs | 20 +++++-------------- 1 file changed, 5 insertions(+), 15 deletions(-) diff --git a/crates/engine/tests/never_silent_roundtrip.rs b/crates/engine/tests/never_silent_roundtrip.rs index b2658218e4..b431a85e78 100644 --- a/crates/engine/tests/never_silent_roundtrip.rs +++ b/crates/engine/tests/never_silent_roundtrip.rs @@ -23,13 +23,10 @@ const GEOMETRY_ONLY: [&str; 4] = ["fgb", "shp", "kml", "gpx"]; /// Changes a format makes without a notice, as (format, the start of a change from [`changes`], /// why). Each is what the format can hold or how its reader works, not a loss of a value's -/// number or text, except trimming (Shapefile, KML, GPX), blanks read as null and (KML, GPX) a -/// field of nulls left out, which are kept here until they are said (#1907). CSV keeps the spaces -/// around a value (#2059). +/// number or text. Text a reader trims, blanks read as null and (KML, GPX) a field of nulls left +/// out are said by the export (#1907). const LIMITS: &[(&str, &str, &str)] = &[ - // CSV holds text: reading types each column from its values (`text_type`) and reads an empty - // cell as null. - ("csv", "blank text became null", "an empty cell is read as null"), + // CSV holds text: reading types each column from its values (`text_type`). ("csv", "field type changed", "a column's type comes from its values"), ("csv", "field of nulls type changed", "a column's type comes from its values"), ("csv", "boolean became text", "yes/no values are written as True/False, read back as text"), @@ -46,23 +43,16 @@ const LIMITS: &[(&str, &str, &str)] = &[ ("geojson", "date became text", "a date is written as ISO 8601 text and stays text on read (#853)"), ("geojson", "datetime became text", "a date is written as ISO 8601 text and stays text on read (#853)"), ("geojson", "not read back: nothing", "a layer without geometry or values reads as nothing"), - // dBase pads text with spaces and has no null text; reading makes a whole-number column an - // integer one. - ("shp", "text trimmed", "dBase pads text with spaces after it, and reading drops them, so spaces at its end go"), - ("shp", "blank text became null", "dBase has no null text: blank text reads as null"), + // Reading makes a whole-number column an integer one. ("shp", "field of nulls type changed", "a number column's type comes from its values"), ("shp", "field type changed Double → Integer", "a column of whole numbers reads as integers"), ]; /// KML and GPX hold text, read with types from the values as for CSV (`type_text_columns`); the -/// name field is written as the feature's name and read back as `name`, and a field that is -/// null everywhere isn't in the file. +/// name field is written as the feature's name and read back as `name`. const TEXT_FORMAT_LIMITS: &[&str] = &[ - "text trimmed", - "blank text became null", "field type changed", "field of nulls type changed", - "field of nulls missing", "field renamed", "boolean became text", "date became text", From 291c20095663fc223573e41a76aa8fb86961c880 Mon Sep 17 00:00:00 2001 From: Cory Douglas Martin <4108748+flight1973@users.noreply.github.com> Date: Wed, 18 Nov 2026 08:44:11 -0600 Subject: [PATCH 03/12] fix(data): KML and GPX trim tabs and line breaks too, and say so --- crates/data/src/io.rs | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/crates/data/src/io.rs b/crates/data/src/io.rs index 056bdcc5c7..c09a268150 100644 --- a/crates/data/src/io.rs +++ b/crates/data/src/io.rs @@ -3989,9 +3989,9 @@ impl TextLosses { if n > 0 { let what = match (n, self.ends_only) { (1, true) => "1 text value ends with spaces".to_string(), - (1, false) => "1 text value starts or ends with spaces".to_string(), + (1, false) => "1 text value starts or ends with spaces, tabs or line breaks".to_string(), (n, true) => format!("{n} text values end with spaces"), - (n, false) => format!("{n} text values start or end with spaces"), + (n, false) => format!("{n} text values start or end with spaces, tabs or line breaks"), }; notes.push(format!("{target}: {what}, which reading the file back drops, in {names}")); } @@ -5840,7 +5840,7 @@ mod tests { assert_eq!( text_notes(&ds, "kml"), [ - "t: 3 text values start or end with spaces, which reading the file back drops, in 'name', 'note'", + "t: 3 text values start or end with spaces, tabs or line breaks, which reading the file back drops, in 'name', 'note'", "t: 2 blank text values read back as empty (null), in 'name', 'code'", "t: 1 field is empty in every feature, so reading the file back has no column for it: 'gone'", ] @@ -5867,7 +5867,7 @@ mod tests { assert_eq!( text_notes(&ds, "gpx"), [ - "t: 1 text value starts or ends with spaces, which reading the file back drops, in 'name'", + "t: 1 text value starts or ends with spaces, tabs or line breaks, which reading the file back drops, in 'name'", "t: 1 blank text value reads back as empty (null), in 'name'", "t: 1 field is empty in every feature, so reading the file back has no column for it: 'gone'", ] From 8633b2a59b47590834a3a6b897d76e394e8b4f57 Mon Sep 17 00:00:00 2001 From: Cory Douglas Martin <4108748+flight1973@users.noreply.github.com> Date: Wed, 18 Nov 2026 09:29:41 -0600 Subject: [PATCH 04/12] fix(data): count text losses as KML and GPX read the file back (#1907) Only features the reader keeps count (the KML and GPX readers' own predicates), and KML types each geometry kind's layer apart. A KML name field of another name counts as its own extended data column too. GPX fields without a value join the fields-not-written notice, unless every layer read has a column of that name. A column typed Text skips later values. --- crates/data/src/gpx.rs | 16 +- crates/data/src/io.rs | 366 ++++++++++++++++++++++++++++--------- crates/data/src/kml.rs | 15 +- crates/engine/src/tests.rs | 45 +++-- 4 files changed, 329 insertions(+), 113 deletions(-) diff --git a/crates/data/src/gpx.rs b/crates/data/src/gpx.rs index bd84066f63..c66709f0e3 100644 --- a/crates/data/src/gpx.rs +++ b/crates/data/src/gpx.rs @@ -29,7 +29,21 @@ fn child_text(n: &Node, name: &str) -> Option { fn coord(n: &Node) -> Option { let x = n.attribute("lon")?.trim().parse::().ok()?; let y = n.attribute("lat")?.trim().parse::().ok()?; - ((-180.0..=180.0).contains(&x) && (-90.0..=90.0).contains(&y)).then(|| Coord::new(x, y)) + crate::io::lon_lat_in_range(x, y).then(|| Coord::new(x, y)) +} + +/// Whether reading keeps a feature that [`crate::interop::to_gpx`] writes with geometry `g`: a +/// waypoint in range ([`coord`]), or a track with a segment of two such points. +pub(crate) fn keeps(g: &Geometry) -> bool { + let kept = |c: &&Coord| crate::io::lon_lat_in_range(c.x, c.y); + let segment = |p: &Vec| p.iter().filter(kept).count() >= 2; + match g { + Geometry::Point(c) => kept(&c), + Geometry::MultiPoint(v) => v.iter().any(|c| kept(&c)), + Geometry::Line(parts) => parts.iter().any(segment), + // Written as a track along each part's outer ring. + Geometry::Polygon(polys) => polys.iter().filter_map(|rings| rings.first()).any(segment), + } } fn text(v: Option) -> Value { diff --git a/crates/data/src/io.rs b/crates/data/src/io.rs index c09a268150..cdc3fdd6c4 100644 --- a/crates/data/src/io.rs +++ b/crates/data/src/io.rs @@ -2276,6 +2276,7 @@ impl TextColumn { FieldType::Text }; self.ty = Some(self.ty.map_or(t, |prev| widen(prev, Some(t)))); + self.settle(); } /// Adds another chunk of the column. @@ -2285,6 +2286,20 @@ impl TextColumn { None => other.ty, Some(prev) => Some(widen(prev, other.ty)), }; + self.settle(); + } + + /// Whether the column is Text whatever values follow. + fn is_text(self) -> bool { + self.ty == Some(FieldType::Text) + } + + /// One state for a Text column, however its values came: a column skips the values after it + /// is Text, and its chunks then compare equal to the whole. + fn settle(&mut self) { + if self.is_text() { + self.whole_past_double = false; + } } /// The column's type: Text without values. @@ -3831,26 +3846,28 @@ impl std::ops::AddAssign for CsvLosses { } /// What reading a CSV, Shapefile, KML or GPX export back does to its text, counted for each field -/// over the features the writer writes: spaces around text dropped, blank text read as null, and -/// (KML, GPX) a field without a value left without a column. Readers, as they are: +/// over the features the writer writes and reading keeps: spaces around text dropped, blank text +/// read as null, and (KML) a field without a value left without a column. Readers, as they are: /// - CSV (and Data Interop's WKT CSV) keeps a cell as it is; an empty one reads as null, and so /// does one of spaces in a column read as numbers ([`Value::parse_file`]). /// - dBase drops the spaces after text, and reads text of spaces only as null ([`read_dbf`]). /// - KML and GPX trim each value; a blank name reads as null, and a blank KML extended data -/// value too in a column read as numbers ([`type_text_columns`]). A KML description is kept as -/// it is. A value that is null isn't written, so a field without one has no column. +/// value too in a column read as numbers ([`type_text_columns`], for each kind of geometry's +/// layer). A KML description is kept as it is. KML writes no null value, so a field without one +/// has no column; GPX writes only names, which [`gpx_notes`] says. /// /// A streamed export adds up its chunks' (`+=`): whether reading takes a column as numbers, which /// decides what its blanks become, is settled over all of them. #[derive(Clone, Debug, Default, PartialEq, Eq)] pub struct TextLosses { - /// For each field, in the layer's order. - fields: Vec, + /// For each layer reading gives (KML: points, lines, polygons; the others: one), each field's, + /// in the layer's order. + layers: Vec>, /// Only the spaces after text are dropped (dBase). ends_only: bool, } -/// One field's [`TextLosses`]. +/// One field's [`TextLosses`] in one layer read back. #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] struct FieldText { /// Text with spaces around it that reading drops, unless its column reads as numbers (the @@ -3866,16 +3883,34 @@ struct FieldText { column: Option, /// A value of the field is written. valued: bool, - /// Reading the file back has no column for the field when it has no value (KML, GPX). + /// Reading the file back has no column for the field when it has no value (KML). needs_value: bool, } +/// How reading treats one copy of a field's text. +#[derive(Clone, Copy, PartialEq, Eq)] +enum TextRead { + /// A CSV cell, as it is. + Cell, + /// A dBase Character column: the spaces after it dropped. + Dbf, + /// A KML or GPX name: trimmed, a blank one null. + Name, + /// KML extended data: trimmed, its column typed from its values. + Data, +} + /// The columns the KML reader gives every layer. const KML_COLUMNS: [&str; 4] = ["name", "description", "folder", "style"]; /// The columns the GPX reader gives waypoints, and tracks. const GPX_POINT_COLUMNS: [&str; 7] = ["name", "ele", "time", "desc", "cmt", "sym", "type"]; const GPX_TRACK_COLUMNS: [&str; 6] = ["name", "desc", "cmt", "type", "number", "points"]; +/// Whether a longitude and latitude are in range, which the KML and GPX readers keep. +pub(crate) fn lon_lat_in_range(x: f64, y: f64) -> bool { + (-180.0..=180.0).contains(&x) && (-90.0..=90.0).contains(&y) +} + impl TextLosses { /// The losses of `features`, with `fields`, in a layer of type `gt` written to a file of /// extension `ext` (lowercase), each KML or GPX feature named from field `name_field`; none @@ -3885,31 +3920,65 @@ impl TextLosses { if !(csv || shp || kml || gpx) { return Self::default(); } - let gpx_columns: &[&str] = if gt == GeometryType::Point { &GPX_POINT_COLUMNS } else { &GPX_TRACK_COLUMNS }; - let mut out: Vec = (fields.iter().enumerate()) + // How reading treats each field's copies: a KML name field is the placemark's name and, + // unless called `name` (whose copy reading leaves out as the same), extended data too. + let reads: Vec> = (fields.iter().enumerate()) .map(|(k, f)| { - let named = Some(k) == name_field; - let fixed = |columns: &[&str]| columns.iter().any(|c| f.name.eq_ignore_ascii_case(c)); - // A KML description is text as it is, not typed. - let typed = csv || kml && !named && f.name != "description"; - let needs_value = !named && (kml && !fixed(&KML_COLUMNS) || gpx && !fixed(gpx_columns)); - FieldText { column: typed.then(TextColumn::default), needs_value, ..FieldText::default() } + let named = (kml || gpx) && Some(k) == name_field; + let mut reads = Vec::new(); + if named { + reads.push(TextRead::Name); + } + if csv { + reads.push(TextRead::Cell); + } else if shp && matches!(f.ty, FieldType::Text | FieldType::DateTime) { + reads.push(TextRead::Dbf); + } else if kml && f.name != "description" && !(named && f.name.eq_ignore_ascii_case("name")) { + // A KML description is text as it is. + reads.push(TextRead::Data); + } + reads }) .collect(); - let written = |f: &crate::Feature| match &f.geometry { - _ if csv => true, - g if shp => shapefile_keeps(g.as_ref(), gt), - Some(Geometry::MultiPoint(v)) if gpx => !v.is_empty(), - g => (kml || gpx) && g.is_some(), + let fresh: Vec = (fields.iter().zip(&reads)) + .map(|(f, r)| FieldText { + column: (csv || r.contains(&TextRead::Data)).then(TextColumn::default), + needs_value: kml && !KML_COLUMNS.iter().any(|c| f.name.eq_ignore_ascii_case(c)), + ..FieldText::default() + }) + .collect(); + // KML reads a layer for each kind of geometry, and types each one's columns apart. + let mut layers = vec![fresh; if kml { 3 } else { 1 }]; + let layer_of = |g: &Geometry| match g.kind() { + _ if !kml => 0, + GeometryType::Point => 0, + GeometryType::Polyline => 1, + _ => 2, }; - for feature in features.iter().filter(|f| written(f)) { - for (k, (field, v)) in fields.iter().zip(&feature.attrs).enumerate() { - let Some(loss) = out.get_mut(k) else { continue }; + for feature in features { + let layer = match &feature.geometry { + _ if csv => 0, + g if shp && shapefile_keeps(g.as_ref(), gt) => 0, + Some(g) if kml && crate::kml::keeps(g) || gpx && crate::gpx::keeps(g) => layer_of(g), + // A placemark reading skips still gives its extended data's names columns. + Some(_) if kml => { + if let Some(first) = layers.first_mut() { + first.iter_mut().zip(&feature.attrs).for_each(|(loss, v)| loss.valued |= !v.is_null()); + } + continue; + } + _ => continue, + }; + let Some(layer) = layers.get_mut(layer) else { continue }; + for ((v, loss), reads) in feature.attrs.iter().zip(layer.iter_mut()).zip(&reads) { if v.is_null() { continue; } loss.valued = true; - if let Some(column) = &mut loss.column { + // Text absorbs every later value, so a column typed Text needs no more. + if let Some(column) = &mut loss.column + && !column.is_text() + { let text = match ext { "csv" => csv_cell(v), "wkt" => crate::interop::wkt_csv_text(&v.to_file_text()), @@ -3922,70 +3991,47 @@ impl TextLosses { } let Value::Text(s) = v else { continue }; let trimmed = s.trim(); - let count = if csv { - if s.is_empty() { - &mut loss.blank - } else if trimmed.is_empty() { - &mut loss.blank_in_numbers - } else { - continue; - } - } else if shp { - // A Character column; text cut to 254 bytes is said as cut. - if !matches!(field.ty, FieldType::Text | FieldType::DateTime) || s.len() > 254 { - continue; - } - let kept = s.trim_end_matches(' '); - if kept.is_empty() { - &mut loss.blank - } else if kept.len() < s.len() { - &mut loss.padded - } else { - continue; - } - } else if (kml || gpx) && Some(k) == name_field { - if trimmed.is_empty() { - &mut loss.blank - } else if trimmed.len() < s.len() { - &mut loss.padded - } else { - continue; - } - } else if kml && field.name != "description" { - if s.is_empty() { - &mut loss.blank_in_numbers - } else if trimmed.is_empty() { - &mut loss.spaces - } else if trimmed.len() < s.len() { - &mut loss.padded - } else { - continue; - } - } else { - continue; - }; - *count += 1; + for read in reads { + let count = match read { + TextRead::Cell if s.is_empty() => &mut loss.blank, + TextRead::Cell if trimmed.is_empty() => &mut loss.blank_in_numbers, + // A Character column; text cut to 254 bytes is said as cut. + TextRead::Dbf if s.len() <= 254 && s.trim_end_matches(' ').is_empty() => &mut loss.blank, + TextRead::Dbf if s.len() <= 254 && s.ends_with(' ') => &mut loss.padded, + TextRead::Name if trimmed.is_empty() => &mut loss.blank, + TextRead::Name if trimmed.len() < s.len() => &mut loss.padded, + TextRead::Data if s.is_empty() => &mut loss.blank_in_numbers, + TextRead::Data if trimmed.is_empty() => &mut loss.spaces, + TextRead::Data if trimmed.len() < s.len() => &mut loss.padded, + _ => continue, + }; + *count += 1; + } } } - Self { fields: out, ends_only: shp } + Self { layers, ends_only: shp } } /// One notice for each loss of a layer with `fields` written to `target`, with a count and /// the fields; none without loss. pub fn notes(&self, fields: &[Field], target: &str) -> Vec { let numbers = |t: &FieldText| t.column.is_some_and(|c| c.ty() != FieldType::Text); - let trimmed = |t: &FieldText| if numbers(t) { 0 } else { t.padded + t.spaces }; - let blank = |t: &FieldText| t.blank + if numbers(t) { t.blank_in_numbers + t.spaces } else { 0 }; - let missing = |t: &FieldText| usize::from(t.needs_value && !t.valued); - let selected = |count: &dyn Fn(&FieldText) -> usize| { - let counted: Vec<_> = fields.iter().zip(&self.fields).map(|(f, t)| (f, count(t))).filter(|(_, n)| *n > 0).collect(); - let names: Vec<_> = counted.iter().take(5).map(|(f, _)| format!("'{}'", dbf_notice_name(&f.name))).collect(); - let more = if counted.len() > 5 { format!(" and {} more", counted.len() - 5) } else { String::new() }; - (counted.iter().map(|(_, n)| n).sum::(), format!("{}{more}", names.join(", "))) + // Each field's count over the layers read back. + let counts = |count: &dyn Fn(&FieldText) -> usize| -> Vec { + (0..fields.len()).map(|k| self.layers.iter().filter_map(|l| l.get(k)).map(count).sum()).collect() }; + let trimmed = counts(&|t| if numbers(t) { 0 } else { t.padded + t.spaces }); + let blank = counts(&|t| t.blank + if numbers(t) { t.blank_in_numbers + t.spaces } else { 0 }); + // A field is missing when no layer has a value of it. + let missing: Vec = (0..fields.len()) + .map(|k| { + let needs = self.layers.first().and_then(|l| l.get(k)).is_some_and(|t| t.needs_value); + usize::from(needs && !self.layers.iter().filter_map(|l| l.get(k)).any(|t| t.valued)) + }) + .collect(); let target: String = target.chars().map(dbf_notice_char).collect(); let mut notes = Vec::new(); - let (n, names) = selected(&trimmed); + let n: usize = trimmed.iter().sum(); if n > 0 { let what = match (n, self.ends_only) { (1, true) => "1 text value ends with spaces".to_string(), @@ -3993,21 +4039,21 @@ impl TextLosses { (n, true) => format!("{n} text values end with spaces"), (n, false) => format!("{n} text values start or end with spaces, tabs or line breaks"), }; - notes.push(format!("{target}: {what}, which reading the file back drops, in {names}")); + notes.push(format!("{target}: {what}, which reading the file back drops, in {}", named_fields(fields, &trimmed))); } - let (n, names) = selected(&blank); + let n: usize = blank.iter().sum(); if n > 0 { let what = if n == 1 { "1 blank text value reads".to_string() } else { format!("{n} blank text values read") }; - notes.push(format!("{target}: {what} back as empty (null), in {names}")); + notes.push(format!("{target}: {what} back as empty (null), in {}", named_fields(fields, &blank))); } - let (n, names) = selected(&missing); + let n: usize = missing.iter().sum(); if n > 0 { let what = if n == 1 { "1 field is empty in every feature, so reading the file back has no column for it".to_string() } else { format!("{n} fields are empty in every feature, so reading the file back has no columns for them") }; - notes.push(format!("{target}: {what}: {names}")); + notes.push(format!("{target}: {what}: {}", named_fields(fields, &missing))); } notes } @@ -4016,11 +4062,11 @@ impl TextLosses { impl std::ops::AddAssign for TextLosses { /// Adds a chunk's losses, of the same fields. fn add_assign(&mut self, other: Self) { - if self.fields.is_empty() { + if self.layers.is_empty() { *self = other; return; } - for (a, b) in self.fields.iter_mut().zip(other.fields) { + for (a, b) in self.layers.iter_mut().zip(other.layers).flat_map(|(a, b)| a.iter_mut().zip(b)) { a.padded += b.padded; a.blank += b.blank; a.blank_in_numbers += b.blank_in_numbers; @@ -4064,13 +4110,23 @@ pub fn gpx_left_out(ds: &Dataset) -> usize { } /// What a GPX file of `ds` can't hold, each feature named from field `name_field`: other -/// fields' values, polygons (written as tracks along their outer rings, holes left out) and -/// multipoints (a waypoint per point). One notice per kind; none for a layer GPX holds whole. +/// fields (their values, or, for one without a value, its column, unless every layer reading +/// gives has a column of its name), polygons (written as tracks along their outer rings, holes +/// left out) and multipoints (a waypoint per point). One notice per kind; none for a layer GPX +/// holds whole. pub fn gpx_notes(ds: &Dataset, name_field: Option, target: &str) -> Vec { let drawn = || ds.features.iter().filter(|f| f.geometry.is_some()); + // The layers reading gives, of the features it keeps: waypoints for points, tracks for lines + // and polygons. A field without a value comes back only as a column each of them has. + let kept = || drawn().filter_map(|f| f.geometry.as_ref()).filter(|g| crate::gpx::keeps(g)); + let waypoints = kept().any(|g| matches!(g, Geometry::Point(_) | Geometry::MultiPoint(_))); + let tracks = kept().any(|g| matches!(g, Geometry::Line(_) | Geometry::Polygon(_))); + let has = |columns: &[&str], name: &str| columns.iter().any(|c| name.eq_ignore_ascii_case(c)); + let read_column = + |name: &str| (waypoints || tracks) && (!waypoints || has(&GPX_POINT_COLUMNS, name)) && (!tracks || has(&GPX_TRACK_COLUMNS, name)); let fields: Vec<&str> = (ds.fields.iter().enumerate()) .filter(|(k, _)| Some(*k) != name_field) - .filter(|(k, _)| drawn().any(|f| f.attrs.get(*k).is_some_and(|v| !v.is_null()))) + .filter(|(k, f)| drawn().any(|r| r.attrs.get(*k).is_some_and(|v| !v.is_null())) || !read_column(&f.name)) .map(|(_, f)| f.name.as_str()) .collect(); let (mut polygons, mut holes, mut multipoints) = (0, 0, 0); @@ -5863,20 +5919,136 @@ mod tests { #[test] fn gpx_says_trimmed_and_blank_names_and_fields_without_values() { let ds = text_layer(&["name", "note", "gone", "ele"], &[&[Some("a "), Some("x"), None, None], &[Some(""), None, None, None]]); - // 'note' isn't written, which `gpx_notes` says; 'ele' comes back as a waypoint's column. assert_eq!( text_notes(&ds, "gpx"), [ "t: 1 text value starts or ends with spaces, tabs or line breaks, which reading the file back drops, in 'name'", "t: 1 blank text value reads back as empty (null), in 'name'", - "t: 1 field is empty in every feature, so reading the file back has no column for it: 'gone'", ] ); - let clean = text_layer(&["name", "note"], &[&[Some("a"), Some("x")], &[None, None]]); + // GPX writes only names: one notice says the other fields, with a value or without; 'ele' + // without one comes back as a waypoint's column. + assert_eq!( + gpx_notes(&ds, name_field(&ds), "t"), + ["t: GPX holds a name for each feature, so fields weren't written: 'note', 'gone'"] + ); + let clean = text_layer(&["name", "type"], &[&[Some("a"), None], &[None, None]]); assert!(text_notes(&clean, "gpx").is_empty()); + assert!(gpx_notes(&clean, name_field(&clean), "t").is_empty()); assert!(text_notes(&ds, "geojson").is_empty()); } + /// GPX reads points as waypoints and lines as tracks, whatever the layer's type: a field without + /// a value comes back only as a column of each layer read. + #[test] + fn gpx_fields_without_values_follow_how_each_feature_is_written() { + let line = Geometry::Line(vec![vec![Coord::new(0.0, 0.0), Coord::new(1.0, 1.0)]]); + let layer = |geometries: &[Geometry]| { + let mut ds = + Dataset::new("t", GeometryType::None, vec![Field::new("ele", FieldType::Text), Field::new("number", FieldType::Text)]); + for g in geometries { + ds.push(Some(g.clone()), vec![Value::Null, Value::Null]); + } + ds + }; + let point = Geometry::Point(Coord::new(1.0, 2.0)); + assert_eq!( + gpx_notes(&layer(&[point.clone()]), None, "t"), + ["t: GPX holds a name for each feature, so 1 field wasn't written: 'number'"] + ); + assert_eq!( + gpx_notes(&layer(&[line.clone()]), None, "t"), + ["t: GPX holds a name for each feature, so 1 field wasn't written: 'ele'"] + ); + assert_eq!( + gpx_notes(&layer(&[point, line]), None, "t"), + ["t: GPX holds a name for each feature, so fields weren't written: 'ele', 'number'"] + ); + } + + /// A placemark or waypoint reading skips (no coordinate in range, or a line of one point) + /// holds nothing that comes back. + #[test] + fn kml_and_gpx_count_only_features_reading_keeps() { + let mut ds = text_layer(&["name", "note"], &[&[Some("a"), None]]); + ds.push(Some(Geometry::Point(Coord::new(200.0, 0.0))), vec![Value::Text(" off ".into()), Value::Text(" x".into())]); + ds.push(Some(Geometry::MultiPoint(vec![])), vec![Value::Text("".into()), Value::Text("".into())]); + ds.push(Some(Geometry::Line(vec![vec![Coord::new(0.0, 0.0)]])), vec![Value::Text(" ".into()), Value::Text(" ".into())]); + // 'note' has values only where reading skips the placemark: its padded text doesn't come + // back, but its name still gives a column, of nulls. + assert!(text_notes(&ds, "kml").is_empty()); + let (bytes, _) = write_bytes(&ds, "kml").unwrap(); + let layers = crate::kml::read("t.kml", &bytes).unwrap(); + assert_eq!(layers.len(), 1); + let back = &layers[0].dataset; + assert_eq!(back.features.len(), 1); + assert_eq!(back.field_index("note").map(|i| back.value(0, i).clone()), Some(Value::Null)); + assert!(text_notes(&ds, "gpx").is_empty()); + let (bytes, _) = write_bytes(&ds, "gpx").unwrap(); + let read = crate::gpx::read("t.gpx", &bytes).unwrap(); + // One waypoint, and no track (its lone point, unnamed, is among the track points). + let count = |name: &str| read.iter().find(|(d, _)| d.name == name).map(|(d, _)| d.features.len()); + assert_eq!((count("t waypoints"), count("t tracks")), (Some(1), None)); + // The same values in a feature reading keeps are said. + let kept = text_layer(&["name", "note"], &[&[Some(" off "), Some(" x")]]); + assert_eq!(text_notes(&kept, "kml").len(), 1); + assert_eq!(text_notes(&kept, "gpx").len(), 1); + } + + /// A KML name field not called `name` is the placemark's name and its own extended data + /// column, read with a type from its values. + #[test] + fn a_kml_name_field_of_another_name_is_counted_as_both_columns() { + let mut ds = text_layer(&["title", "other"], &[&[Some(" a"), Some("x")], &[Some(""), Some("y")], &[Some("5"), Some("z")]]); + let losses = |ds: &Dataset| TextLosses::of(&ds.features, &ds.fields, ds.geometry_type, "kml", Some(0)).notes(&ds.fields, "t"); + // In the name, " a" is trimmed and "" null; in 'title', a text column, " a" is trimmed. + assert_eq!( + losses(&ds), + [ + "t: 2 text values start or end with spaces, tabs or line breaks, which reading the file back drops, in 'title'", + "t: 1 blank text value reads back as empty (null), in 'title'", + ] + ); + let back = crate::interop::to_kml(&ds, Some(0)).unwrap(); + let read = &crate::kml::read("t.kml", back.as_bytes()).unwrap()[0].dataset; + let column = |n: &str| read.field_index(n).map(|i| read.features.iter().map(|f| f.attrs[i].clone()).collect::>()); + let text = |t: &str| Value::Text(t.into()); + assert_eq!(column("name"), Some(vec![text("a"), Value::Null, text("5")])); + assert_eq!(column("title"), Some(vec![text("a"), text(""), text("5")])); + // A name field without a value has no extended data column. + for f in ds.features.iter_mut() { + f.attrs[0] = Value::Null; + } + assert_eq!(losses(&ds), ["t: 1 field is empty in every feature, so reading the file back has no column for it: 'title'"]); + let clean = text_layer(&["title"], &[&[Some("a")], &[Some("b")]]); + assert!(losses(&clean).is_empty()); + } + + /// KML reads a layer for each kind of geometry and types each one's columns apart: a blank in + /// the points' column of numbers reads as null, one in the lines' column of text doesn't. + #[test] + fn kml_types_each_kind_of_geometry_apart() { + let line = || Some(Geometry::Line(vec![vec![Coord::new(0.0, 0.0), Coord::new(1.0, 1.0)]])); + let point = |x: f64| Some(Geometry::Point(Coord::new(x, 1.0))); + let mut ds = Dataset::new("t", GeometryType::Point, vec![Field::new("code", FieldType::Text)]); + for (g, v) in [(point(0.0), "1"), (point(1.0), ""), (line(), "x"), (line(), "")] { + ds.push(g, vec![Value::Text(v.into())]); + } + assert_eq!(text_notes(&ds, "kml"), ["t: 1 blank text value reads back as empty (null), in 'code'"]); + let (bytes, _) = write_bytes(&ds, "kml").unwrap(); + let layers = crate::kml::read("t.kml", &bytes).unwrap(); + let code = |l: usize| { + let d = &layers[l].dataset; + let i = d.field_index("code").unwrap(); + d.features.iter().map(|f| f.attrs[i].clone()).collect::>() + }; + assert_eq!(code(0), [Value::Int(1), Value::Null]); + assert_eq!(code(1), [Value::Text("x".into()), Value::Text("".into())]); + // Lines alone: their blank is kept. + ds.features.retain(|f| matches!(f.geometry, Some(Geometry::Line(_)))); + assert!(text_notes(&ds, "kml").is_empty()); + } + /// A streamed CSV export adds up its chunks' text losses to the whole layer's, and types a /// column over all of them: 'code' reads as numbers only from the second chunk on. #[test] @@ -5897,6 +6069,18 @@ mod tests { // Alone, the first chunk's 'code' is text, which keeps its spaces. let first = TextLosses::of(&ds.features[..1], &ds.fields, ds.geometry_type, "csv", None); assert_eq!(first.notes(&ds.fields, "t"), ["t: 1 blank text value reads back as empty (null), in 'note'"]); + // A column that is Text skips the values after, and chunks still add up to the whole: a + // whole number past a Double's digits, alone a chunk's Integer, is Text after text. + let wide = text_layer(&["id"], &[&[Some("abc")], &[Some("9007199254740993")], &[Some(" ")]]); + let whole = TextLosses::of(&wide.features, &wide.fields, wide.geometry_type, "csv", None); + for size in 1..=wide.features.len() { + let mut sum = TextLosses::default(); + for chunk in wide.features.chunks(size) { + sum += TextLosses::of(chunk, &wide.fields, wide.geometry_type, "csv", None); + } + assert_eq!(sum, whole, "chunks of {size}"); + } + assert_eq!(whole.notes(&wide.fields, "t"), Vec::::new()); } /// A point layer's fields named like coordinates keep their values when its CSV is read back: diff --git a/crates/data/src/kml.rs b/crates/data/src/kml.rs index cf0af379e7..5172a0c2f3 100644 --- a/crates/data/src/kml.rs +++ b/crates/data/src/kml.rs @@ -254,7 +254,7 @@ fn coords(s: &str, zm: &Cell) -> Vec { let x = it.next()?.trim().parse::().ok()?; let y = it.next()?.trim().parse::().ok()?; // Longitude/latitude, as KML always is. - if !((-180.0..=180.0).contains(&x) && (-90.0..=90.0).contains(&y)) { + if !crate::io::lon_lat_in_range(x, y) { return None; } if it.next().and_then(|z| z.trim().parse::().ok()).is_some_and(|z| z != 0.0) { @@ -265,6 +265,19 @@ fn coords(s: &str, zm: &Cell) -> Vec { .collect() } +/// Whether reading keeps a placemark that [`crate::interop::to_kml`] writes with geometry `g`: +/// one with a point in range ([`coords`]), a line part of two such points, or a polygon whose +/// outer ring has three ([`geometry`]). It is read into the layer of `g`'s kind. +pub(crate) fn keeps(g: &Geometry) -> bool { + let kept = |c: &&Coord| crate::io::lon_lat_in_range(c.x, c.y); + match g { + Geometry::Point(c) => kept(&c), + Geometry::MultiPoint(v) => v.iter().any(|c| kept(&c)), + Geometry::Line(parts) => parts.iter().any(|p| p.iter().filter(kept).count() >= 2), + Geometry::Polygon(polys) => polys.iter().any(|rings| rings.first().is_some_and(|r| r.iter().filter(kept).count() >= 3)), + } +} + /// The parts of a geometry element: (points, lines, polygons), MultiGeometry flattened. #[derive(Default)] struct Parts { diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index f736582045..1d11928fb9 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -24610,15 +24610,15 @@ fn csv_and_gpx_exports_say_what_they_leave_out() { (Geometry::MultiPoint(vec![Coord::new(3.0, 4.0), Coord::new(5.0, 6.0)]), vec![V::Text("M".into()), V::Null]), ]; s.map_mut().add_dataset(layer("Sites", GeometryType::Point, pts)); - // A field null everywhere has no column when a GPX or KML file is read back, so a clean layer - // holds only names. + let clean = vec![(Geometry::Point(Coord::new(1.0, 2.0)), vec![V::Text("P".into()), V::Null])]; + s.map_mut().add_dataset(layer("Clean", GeometryType::Point, clean.clone())); + // Names alone, which GPX holds whole. let named = |mut ds: Dataset| { ds.fields.truncate(1); ds.features.iter_mut().for_each(|f| f.attrs.truncate(1)); ds }; - let clean = vec![(Geometry::Point(Coord::new(1.0, 2.0)), vec![V::Text("P".into()), V::Null])]; - s.map_mut().add_dataset(named(layer("Clean", GeometryType::Point, clean))); + s.map_mut().add_dataset(named(layer("Names", GeometryType::Point, clean))); let said = |s: &mut Session, id: &str, p: Value| { let mark = s.notices.len(); s.run(id, &p).unwrap(); @@ -24638,8 +24638,9 @@ fn csv_and_gpx_exports_say_what_they_leave_out() { "{n:?}" ); let n = said(&mut s, "share.exportLayer", json!({"layer": "Sites", "path": out("sites.gpx")})); - assert!(n.len() == 2 && n[0].contains("1 multipoint was written as a waypoint for each"), "{n:?}"); - assert!(n[1].contains("1 field is empty in every feature, so reading the file back has no column for it: 'height'"), "{n:?}"); + // GPX writes only names: 'height', without a value, has no column read back either. + assert!(n.len() == 2 && n[0].contains("1 field wasn't written: 'height'"), "{n:?}"); + assert!(n[1].contains("1 multipoint was written as a waypoint for each"), "{n:?}"); let n = said(&mut s, "data.convert", json!({"layer": "Areas", "format": "gpx"})); assert!(n.iter().any(|t| t.contains("'height'")) && n.iter().any(|t| t.contains("tracks")), "{n:?}"); let n = said(&mut s, "data.convert", json!({"layer": "Areas", "format": "csv"})); @@ -24651,30 +24652,34 @@ fn csv_and_gpx_exports_say_what_they_leave_out() { for format in ["kml", "gpx"] { let n = said(&mut s, "data.convert", json!({"layer": "Rows", "format": format})); assert!(n.len() == 2 && n.iter().any(|t| t.contains("1 features without drawable geometry were left out")), "{format}: {n:?}"); - assert!(n.iter().any(|t| t.contains("no column for it: 'height'")), "{format}: {n:?}"); + let height = if format == "kml" { "no column for it: 'height'" } else { "1 field wasn't written: 'height'" }; + assert!(n.iter().any(|t| t.contains(height)), "{format}: {n:?}"); } // A standalone table keeps geometry too: Export Table says the same, and nothing for a clean one. let areas = layer("Area table", GeometryType::Polygon, vec![(square(0.0, true), vec![V::Text("A".into()), V::Float(2.5)])]); let points = - named(layer("Point table", GeometryType::Point, vec![(Geometry::Point(Coord::new(1.0, 2.0)), vec![V::Text("P".into()), V::Null])])); + layer("Point table", GeometryType::Point, vec![(Geometry::Point(Coord::new(1.0, 2.0)), vec![V::Text("P".into()), V::Null])]); s.project.tables.push(crate::project::Table::new(9001, areas)); s.project.tables.push(crate::project::Table::new(9002, points)); let n = said(&mut s, "share.exportTable", json!({"table": 9001, "path": out("table.csv")})); assert!(n.len() == 1 && n[0].contains("the geometry of 1 feature wasn't written"), "{n:?}"); let n = said(&mut s, "share.exportTable", json!({"table": 9001, "path": out("table.gpx")})); assert!(n.iter().any(|t| t.contains("'height'")) && n.iter().any(|t| t.contains("1 hole left out")), "{n:?}"); - for ext in ["csv", "gpx"] { - let n = said(&mut s, "share.exportTable", json!({"table": 9002, "path": out(&format!("clean-table.{ext}"))})); - assert_eq!(n, Vec::::new(), "{ext}"); - } - // Points alone, with only a name: CSV and GPX hold them whole. - for ext in ["csv", "gpx"] { - assert_eq!( - said(&mut s, "share.exportLayer", json!({"layer": "Clean", "path": out(&format!("clean.{ext}"))})), - Vec::::new() - ); - assert_eq!(said(&mut s, "data.convert", json!({"layer": "Clean", "format": ext})), Vec::::new()); - } + // Points alone, their other field empty: CSV holds them whole, GPX all but that field. + let height = |n: &[String]| n.len() == 1 && n[0].contains("GPX holds a name for each feature, so 1 field wasn't written: 'height'"); + let n = said(&mut s, "share.exportTable", json!({"table": 9002, "path": out("clean-table.csv")})); + assert_eq!(n, Vec::::new()); + let n = said(&mut s, "share.exportTable", json!({"table": 9002, "path": out("clean-table.gpx")})); + assert!(height(&n), "{n:?}"); + assert_eq!(said(&mut s, "share.exportLayer", json!({"layer": "Clean", "path": out("clean.csv")})), Vec::::new()); + assert_eq!(said(&mut s, "data.convert", json!({"layer": "Clean", "format": "csv"})), Vec::::new()); + let n = said(&mut s, "share.exportLayer", json!({"layer": "Clean", "path": out("clean.gpx")})); + assert!(height(&n), "{n:?}"); + let n = said(&mut s, "data.convert", json!({"layer": "Clean", "format": "gpx"})); + assert!(height(&n), "{n:?}"); + // Names alone: GPX holds them whole. + assert_eq!(said(&mut s, "share.exportLayer", json!({"layer": "Names", "path": out("names.gpx")})), Vec::::new()); + assert_eq!(said(&mut s, "data.convert", json!({"layer": "Names", "format": "gpx"})), Vec::::new()); std::fs::remove_dir_all(dir).unwrap(); } From 4e02841041264ff2f3311abc3ac0fa386b1e56d7 Mon Sep 17 00:00:00 2001 From: Cory Douglas Martin <4108748+flight1973@users.noreply.github.com> Date: Wed, 18 Nov 2026 09:43:28 -0600 Subject: [PATCH 05/12] test(data): slices from a reference, not a clone --- crates/data/src/io.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/crates/data/src/io.rs b/crates/data/src/io.rs index cdc3fdd6c4..91d40943a9 100644 --- a/crates/data/src/io.rs +++ b/crates/data/src/io.rs @@ -5953,11 +5953,11 @@ mod tests { }; let point = Geometry::Point(Coord::new(1.0, 2.0)); assert_eq!( - gpx_notes(&layer(&[point.clone()]), None, "t"), + gpx_notes(&layer(std::slice::from_ref(&point)), None, "t"), ["t: GPX holds a name for each feature, so 1 field wasn't written: 'number'"] ); assert_eq!( - gpx_notes(&layer(&[line.clone()]), None, "t"), + gpx_notes(&layer(std::slice::from_ref(&line)), None, "t"), ["t: GPX holds a name for each feature, so 1 field wasn't written: 'ele'"] ); assert_eq!( From a63234e258e5401cad4debbc8dce20f2b2f20fff Mon Sep 17 00:00:00 2001 From: Cory Douglas Martin <4108748+flight1973@users.noreply.github.com> Date: Wed, 18 Nov 2026 10:41:59 -0600 Subject: [PATCH 06/12] fix(data): count name padding, text, filled GPX columns and multipoint names (#1907) - A KML name field's placemark name is trimmed even when its own column reads as numbers. - CSV and dBase read text as null; it is counted with blank text. - A GPX field without a value is said as not written when its name is a column reading always fills (name, points). - A multipoint's name is counted once for each waypoint reading keeps. --- crates/data/src/io.rs | 126 ++++++++++++++++++++++++++++++++++++++---- 1 file changed, 115 insertions(+), 11 deletions(-) diff --git a/crates/data/src/io.rs b/crates/data/src/io.rs index 91d40943a9..bee15d3a6b 100644 --- a/crates/data/src/io.rs +++ b/crates/data/src/io.rs @@ -3849,8 +3849,9 @@ impl std::ops::AddAssign for CsvLosses { /// over the features the writer writes and reading keeps: spaces around text dropped, blank text /// read as null, and (KML) a field without a value left without a column. Readers, as they are: /// - CSV (and Data Interop's WKT CSV) keeps a cell as it is; an empty one reads as null, and so -/// does one of spaces in a column read as numbers ([`Value::parse_file`]). -/// - dBase drops the spaces after text, and reads text of spaces only as null ([`read_dbf`]). +/// does one of spaces in a column read as numbers, and text `` ([`Value::parse_file`]). +/// - dBase drops the spaces after text, and reads text of spaces only, or ``, as null +/// ([`read_dbf`]). /// - KML and GPX trim each value; a blank name reads as null, and a blank KML extended data /// value too in a column read as numbers ([`type_text_columns`], for each kind of geometry's /// layer). A KML description is kept as it is. KML writes no null value, so a field without one @@ -3873,8 +3874,13 @@ struct FieldText { /// Text with spaces around it that reading drops, unless its column reads as numbers (the /// text is then a number, and read as one). padded: usize, + /// Text with spaces around it in a KML or GPX name, which reading trims whatever its + /// extended data column's type. + name_padded: usize, /// Blank text, read as null. blank: usize, + /// Text `` ([`Value::is_null_marker`]), which CSV and dBase read as null. + markers: usize, /// Blank text read as null in a column read as numbers, else read as it is. blank_in_numbers: usize, /// Text of spaces only: read as null in a column read as numbers, else as empty text. @@ -3902,9 +3908,11 @@ enum TextRead { /// The columns the KML reader gives every layer. const KML_COLUMNS: [&str; 4] = ["name", "description", "folder", "style"]; -/// The columns the GPX reader gives waypoints, and tracks. -const GPX_POINT_COLUMNS: [&str; 7] = ["name", "ele", "time", "desc", "cmt", "sym", "type"]; -const GPX_TRACK_COLUMNS: [&str; 6] = ["name", "desc", "cmt", "type", "number", "points"]; +/// The columns the GPX reader gives waypoints, and tracks, that read as null without their +/// element, which [`crate::interop::to_gpx`] doesn't write: not the name it writes, nor a +/// track's count of points. +const GPX_POINT_COLUMNS: [&str; 6] = ["ele", "time", "desc", "cmt", "sym", "type"]; +const GPX_TRACK_COLUMNS: [&str; 4] = ["desc", "cmt", "type", "number"]; /// Whether a longitude and latitude are in range, which the KML and GPX readers keep. pub(crate) fn lon_lat_in_range(x: f64, y: f64) -> bool { @@ -3956,6 +3964,12 @@ impl TextLosses { _ => 2, }; for feature in features { + // GPX writes a waypoint for each point of a multipoint, each with the name; reading + // keeps those in range. + let copies = match &feature.geometry { + Some(Geometry::MultiPoint(v)) if gpx => v.iter().filter(|c| lon_lat_in_range(c.x, c.y)).count(), + _ => 1, + }; let layer = match &feature.geometry { _ if csv => 0, g if shp && shapefile_keeps(g.as_ref(), gt) => 0, @@ -3994,18 +4008,19 @@ impl TextLosses { for read in reads { let count = match read { TextRead::Cell if s.is_empty() => &mut loss.blank, + TextRead::Cell | TextRead::Dbf if Value::is_null_marker(s) => &mut loss.markers, TextRead::Cell if trimmed.is_empty() => &mut loss.blank_in_numbers, // A Character column; text cut to 254 bytes is said as cut. TextRead::Dbf if s.len() <= 254 && s.trim_end_matches(' ').is_empty() => &mut loss.blank, TextRead::Dbf if s.len() <= 254 && s.ends_with(' ') => &mut loss.padded, TextRead::Name if trimmed.is_empty() => &mut loss.blank, - TextRead::Name if trimmed.len() < s.len() => &mut loss.padded, + TextRead::Name if trimmed.len() < s.len() => &mut loss.name_padded, TextRead::Data if s.is_empty() => &mut loss.blank_in_numbers, TextRead::Data if trimmed.is_empty() => &mut loss.spaces, TextRead::Data if trimmed.len() < s.len() => &mut loss.padded, _ => continue, }; - *count += 1; + *count += if *read == TextRead::Name { copies } else { 1 }; } } } @@ -4020,8 +4035,9 @@ impl TextLosses { let counts = |count: &dyn Fn(&FieldText) -> usize| -> Vec { (0..fields.len()).map(|k| self.layers.iter().filter_map(|l| l.get(k)).map(count).sum()).collect() }; - let trimmed = counts(&|t| if numbers(t) { 0 } else { t.padded + t.spaces }); - let blank = counts(&|t| t.blank + if numbers(t) { t.blank_in_numbers + t.spaces } else { 0 }); + let trimmed = counts(&|t| t.name_padded + if numbers(t) { 0 } else { t.padded + t.spaces }); + let blank = counts(&|t| t.blank + t.markers + if numbers(t) { t.blank_in_numbers + t.spaces } else { 0 }); + let markers = self.layers.iter().flatten().any(|t| t.markers > 0); // A field is missing when no layer has a value of it. let missing: Vec = (0..fields.len()) .map(|k| { @@ -4043,7 +4059,12 @@ impl TextLosses { } let n: usize = blank.iter().sum(); if n > 0 { - let what = if n == 1 { "1 blank text value reads".to_string() } else { format!("{n} blank text values read") }; + let what = match (n, markers) { + (1, false) => "1 blank text value reads".to_string(), + (n, false) => format!("{n} blank text values read"), + (1, true) => "1 text value, blank or , reads".to_string(), + (n, true) => format!("{n} text values, blank or , read"), + }; notes.push(format!("{target}: {what} back as empty (null), in {}", named_fields(fields, &blank))); } let n: usize = missing.iter().sum(); @@ -4068,7 +4089,9 @@ impl std::ops::AddAssign for TextLosses { } for (a, b) in self.layers.iter_mut().zip(other.layers).flat_map(|(a, b)| a.iter_mut().zip(b)) { a.padded += b.padded; + a.name_padded += b.name_padded; a.blank += b.blank; + a.markers += b.markers; a.blank_in_numbers += b.blank_in_numbers; a.spaces += b.spaces; if let (Some(a), Some(b)) = (&mut a.column, b.column) { @@ -4111,7 +4134,7 @@ pub fn gpx_left_out(ds: &Dataset) -> usize { /// What a GPX file of `ds` can't hold, each feature named from field `name_field`: other /// fields (their values, or, for one without a value, its column, unless every layer reading -/// gives has a column of its name), polygons (written as tracks along their outer rings, holes +/// gives has a column of its name that reads as null), polygons (written as tracks along their outer rings, holes /// left out) and multipoints (a waypoint per point). One notice per kind; none for a layer GPX /// holds whole. pub fn gpx_notes(ds: &Dataset, name_field: Option, target: &str) -> Vec { @@ -6024,6 +6047,87 @@ mod tests { assert!(losses(&clean).is_empty()); } + /// A KML name field's placemark name is trimmed even when its own extended data column reads + /// as numbers, which keeps the padded number as a number. + #[test] + fn a_kml_name_of_numbers_is_still_trimmed() { + let ds = text_layer(&["code"], &[&[Some(" 5")], &[Some("6")]]); + let losses = |ds: &Dataset| TextLosses::of(&ds.features, &ds.fields, ds.geometry_type, "kml", Some(0)).notes(&ds.fields, "t"); + assert_eq!( + losses(&ds), + ["t: 1 text value starts or ends with spaces, tabs or line breaks, which reading the file back drops, in 'code'"] + ); + let back = crate::interop::to_kml(&ds, Some(0)).unwrap(); + let read = &crate::kml::read("t.kml", back.as_bytes()).unwrap()[0].dataset; + let column = |n: &str| read.field_index(n).map(|i| read.features.iter().map(|f| f.attrs[i].clone()).collect::>()); + assert_eq!(column("name"), Some(vec![Value::Text("5".into()), Value::Text("6".into())])); + assert_eq!(column("code"), Some(vec![Value::Int(5), Value::Int(6)])); + let clean = text_layer(&["code"], &[&[Some("5")], &[Some("6")]]); + assert!(losses(&clean).is_empty()); + } + + /// CSV and dBase read text ``, in any case and with spaces around it, as null. + #[test] + fn csv_and_shapefile_say_text_null_markers() { + let mut ds = text_layer(&["note"], &[&[Some("")], &[Some(" ")], &[Some("x")], &[Some("")]]); + ds.features.retain(|f| f.geometry.is_some()); + for ext in ["csv", "zip"] { + assert_eq!(text_notes(&ds, ext), ["t: 3 text values, blank or , read back as empty (null), in 'note'"], "{ext}"); + let (bytes, _) = write_bytes(&ds, ext).unwrap(); + let (back, _) = read_bytes(&format!("t.{ext}"), &bytes).unwrap(); + let i = back.field_index("note").unwrap(); + let values: Vec<_> = back.features.iter().map(|f| f.attrs[i].clone()).collect(); + assert_eq!(values, [Value::Null, Value::Null, Value::Text("x".into()), Value::Null], "{ext}"); + } + // Text that only looks like the marker comes back as it is. + let mut clean = text_layer(&["note"], &[&[Some("Null")], &[Some("x")]]); + clean.features.retain(|f| f.geometry.is_some()); + assert!(text_notes(&clean, "csv").is_empty()); + assert!(text_notes(&clean, "zip").is_empty()); + } + + /// A field without a value named like a column GPX reading always fills (a name, a track's + /// count of points) comes back changed, so it is said as not written. + #[test] + fn gpx_fields_without_values_named_like_filled_columns_are_said() { + let line = Geometry::Line(vec![vec![Coord::new(0.0, 0.0), Coord::new(1.0, 1.0)]]); + let fields = ["title", "points", "number", "Name"].map(|n| Field::new(n, FieldType::Text)).to_vec(); + let mut ds = Dataset::new("t", GeometryType::Polyline, fields); + ds.push(Some(line), vec![Value::Text("a".into()), Value::Null, Value::Null, Value::Null]); + assert_eq!(gpx_notes(&ds, Some(0), "t"), ["t: GPX holds a name for each feature, so fields weren't written: 'points', 'Name'"]); + let back = crate::interop::to_gpx(&ds, Some(0)).unwrap(); + let read = crate::gpx::read("t.gpx", back.as_bytes()).unwrap(); + let (tracks, _) = read.iter().find(|(d, _)| d.name == "t tracks").unwrap(); + let value = |n: &str| tracks.field_index(n).map(|i| tracks.value(0, i).clone()); + assert_eq!(value("points"), Some(Value::Int(2))); + assert_eq!(value("name"), Some(Value::Text("a".into()))); + assert_eq!(value("number"), Some(Value::Null)); + // Only 'number', which reads as null without its element. + ds.fields = vec![Field::new("title", FieldType::Text), Field::new("number", FieldType::Text)]; + ds.features[0].attrs = vec![Value::Text("a".into()), Value::Null]; + assert!(gpx_notes(&ds, Some(0), "t").is_empty()); + } + + /// GPX writes a waypoint for each point of a multipoint, each with the name: each one reading + /// keeps trims it. + #[test] + fn gpx_counts_a_multipoints_name_once_for_each_waypoint() { + let mut ds = Dataset::new("t", GeometryType::Point, vec![Field::new("name", FieldType::Text)]); + let points = vec![Coord::new(0.0, 0.0), Coord::new(1.0, 1.0), Coord::new(200.0, 0.0)]; + ds.push(Some(Geometry::MultiPoint(points)), vec![Value::Text(" a".into())]); + assert_eq!( + text_notes(&ds, "gpx"), + ["t: 2 text values start or end with spaces, tabs or line breaks, which reading the file back drops, in 'name'"] + ); + let (bytes, _) = write_bytes(&ds, "gpx").unwrap(); + let read = crate::gpx::read("t.gpx", &bytes).unwrap(); + let (waypoints, _) = read.iter().find(|(d, _)| d.name == "t waypoints").unwrap(); + let names: Vec<_> = waypoints.features.iter().map(|f| f.attrs[0].clone()).collect(); + assert_eq!(names, [Value::Text("a".into()), Value::Text("a".into())]); + ds.features[0].attrs = vec![Value::Text("a".into())]; + assert!(text_notes(&ds, "gpx").is_empty()); + } + /// KML reads a layer for each kind of geometry and types each one's columns apart: a blank in /// the points' column of numbers reads as null, one in the lines' column of text doesn't. #[test] From 9c26e0c5782d9e16d28b68c8496938bf12ef689e Mon Sep 17 00:00:00 2001 From: Cory Douglas Martin <4108748+flight1973@users.noreply.github.com> Date: Wed, 18 Nov 2026 11:37:37 -0600 Subject: [PATCH 07/12] fix(engine): a streamed CSV conversion says coordinate columns reading wouldn't take (#1907) --- crates/engine/src/cmd/workflows.rs | 1 + crates/engine/src/tests.rs | 28 ++++++++++++++++++++++++++++ 2 files changed, 29 insertions(+) diff --git a/crates/engine/src/cmd/workflows.rs b/crates/engine/src/cmd/workflows.rs index 162bbaf386..c25c6084a0 100644 --- a/crates/engine/src/cmd/workflows.rs +++ b/crates/engine/src/cmd/workflows.rs @@ -1930,6 +1930,7 @@ pub(crate) fn convert_work(s: &Session, p: &Value) -> Result 0 { diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index 1d11928fb9..cfbf01e6f1 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -40401,6 +40401,34 @@ fn data_interop_reads_the_whole_source() { assert!(error.contains("path"), "{error}"); } +/// A streamed point layer converted to CSV in chunks says, as a whole conversion does, when its +/// fields take every name reading takes for a longitude or latitude; a plain one doesn't. +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn streamed_csv_conversion_says_coordinate_columns_reading_wouldnt_take() { + let fixture = GpkgRegressionFixture::new("interop-coordinates"); + let said = |name: &str| { + let mut s = Session::new(Project::default()); + let id = s.run("layer.addData", &json!({"path": fixture.path(), "stream": true})).unwrap()["layer"].clone(); + assert!(s.map().layer(id.as_u64().unwrap() as u32).unwrap().is_streamed()); + let mark = s.notice_mark(); + s.run("data.convert", &json!({"layer": id, "format": "csv", "path": fixture.dir.join(name)})).unwrap(); + s.notices_since(mark).iter().filter(|n| n.text.contains("every name read as a longitude or latitude")).count() + }; + assert_eq!(said("plain.csv"), 0); + let db = rusqlite::Connection::open(fixture.path()).unwrap(); + for column in ["longitude", "lon", "lng", "long", "lon_dd", "longitude_dd", "stop_lon"].iter().chain(&[ + "latitude", + "lat", + "lat_dd", + "latitude_dd", + "stop_lat", + ]) { + db.execute_batch(&format!("ALTER TABLE roads ADD COLUMN \"{column}\" TEXT DEFAULT 'a';")).unwrap(); + } + assert_eq!(said("named.csv"), 1); +} + /// A non-finite REAL survives source reading but becomes JSON null: both whole and chunked /// conversion report the count after success, and a clean conversion gives no such notice. #[cfg(not(target_arch = "wasm32"))] From f49f0aee13b0ccf202b4df21367c4e1517371f03 Mon Sep 17 00:00:00 2001 From: Cory Douglas Martin <4108748+flight1973@users.noreply.github.com> Date: Wed, 18 Nov 2026 11:37:37 -0600 Subject: [PATCH 08/12] fix(data): a KML field without values named like a reader column is said unless it reads back as null (#1907) --- crates/data/src/io.rs | 38 +++++++++++++++++++++++++++++++++++--- 1 file changed, 35 insertions(+), 3 deletions(-) diff --git a/crates/data/src/io.rs b/crates/data/src/io.rs index bee15d3a6b..0f13ef5719 100644 --- a/crates/data/src/io.rs +++ b/crates/data/src/io.rs @@ -3948,10 +3948,21 @@ impl TextLosses { reads }) .collect(); - let fresh: Vec = (fields.iter().zip(&reads)) - .map(|(f, r)| FieldText { + // A KML field without a value still comes back as the reader's own column of its name + // when that column reads as null: the folder and the style, which aren't written, the + // description unless another field is the description written, and the name only for the + // name field (another one reads back each placemark's name). + let description = fields.iter().position(|f| f.name == "description" && f.ty == FieldType::Text); + let own_column = |k: usize, f: &Field| { + let is = |c: &str| f.name.eq_ignore_ascii_case(c); + KML_COLUMNS.iter().any(|c| is(c)) + && (!is("name") || Some(k) == name_field) + && (!is("description") || description.is_none_or(|d| d == k)) + }; + let fresh: Vec = (fields.iter().enumerate().zip(&reads)) + .map(|((k, f), r)| FieldText { column: (csv || r.contains(&TextRead::Data)).then(TextColumn::default), - needs_value: kml && !KML_COLUMNS.iter().any(|c| f.name.eq_ignore_ascii_case(c)), + needs_value: kml && !own_column(k, f), ..FieldText::default() }) .collect(); @@ -6066,6 +6077,27 @@ mod tests { assert!(losses(&clean).is_empty()); } + /// A KML field without a value called `name` that isn't the name field comes back as the + /// placemarks' names, so it is said; one called like a column the reader leaves null isn't. + #[test] + fn a_kml_name_column_without_values_of_another_field_is_said() { + let mut ds = text_layer(&["title", "name"], &[&[Some("a"), None], &[Some("b"), None]]); + let losses = |ds: &Dataset| TextLosses::of(&ds.features, &ds.fields, ds.geometry_type, "kml", Some(0)).notes(&ds.fields, "t"); + assert_eq!(losses(&ds), ["t: 1 field is empty in every feature, so reading the file back has no column for it: 'name'"]); + let back = crate::interop::to_kml(&ds, Some(0)).unwrap(); + let read = &crate::kml::read("t.kml", back.as_bytes()).unwrap()[0].dataset; + let column = |n: &str| read.field_index(n).map(|i| read.features.iter().map(|f| f.attrs[i].clone()).collect::>()); + assert_eq!(column("name"), Some(vec![Value::Text("a".into()), Value::Text("b".into())])); + // The name field itself, and columns the reader leaves null without a value, come back. + assert!(TextLosses::of(&ds.features, &ds.fields, ds.geometry_type, "kml", Some(1)).notes(&ds.fields, "t").is_empty()); + ds.fields[1] = Field::new("description", FieldType::Integer); + assert!(losses(&ds).is_empty()); + let back = crate::interop::to_kml(&ds, Some(0)).unwrap(); + let read = &crate::kml::read("t.kml", back.as_bytes()).unwrap()[0].dataset; + let column = |n: &str| read.field_index(n).map(|i| read.features.iter().map(|f| f.attrs[i].clone()).collect::>()); + assert_eq!(column("description"), Some(vec![Value::Null, Value::Null])); + } + /// CSV and dBase read text ``, in any case and with spaces around it, as null. #[test] fn csv_and_shapefile_say_text_null_markers() { From 4b45de33befafe7634dabaae7f90eae6b7984458 Mon Sep 17 00:00:00 2001 From: Cory Douglas Martin <4108748+flight1973@users.noreply.github.com> Date: Wed, 18 Nov 2026 13:17:20 -0600 Subject: [PATCH 09/12] fix(data): a field without a value in KML is said as such, not as empty everywhere A field whose values are only on features KML doesn't write, or a field called name that reads back filled with the placemark names, isn't empty in every feature. The notice now says it has no value in any feature written, so reading the file back has no column of its own for it. --- crates/data/src/io.rs | 10 +++++----- crates/engine/src/tests.rs | 2 +- 2 files changed, 6 insertions(+), 6 deletions(-) diff --git a/crates/data/src/io.rs b/crates/data/src/io.rs index 0f13ef5719..67ea9ebb30 100644 --- a/crates/data/src/io.rs +++ b/crates/data/src/io.rs @@ -4081,9 +4081,9 @@ impl TextLosses { let n: usize = missing.iter().sum(); if n > 0 { let what = if n == 1 { - "1 field is empty in every feature, so reading the file back has no column for it".to_string() + "1 field has no value in any feature written, so reading the file back has no column of its own for it".to_string() } else { - format!("{n} fields are empty in every feature, so reading the file back has no columns for them") + format!("{n} fields have no value in any feature written, so reading the file back has no columns of their own for them") }; notes.push(format!("{target}: {what}: {}", named_fields(fields, &missing))); } @@ -5932,7 +5932,7 @@ mod tests { [ "t: 3 text values start or end with spaces, tabs or line breaks, which reading the file back drops, in 'name', 'note'", "t: 2 blank text values read back as empty (null), in 'name', 'code'", - "t: 1 field is empty in every feature, so reading the file back has no column for it: 'gone'", + "t: 1 field has no value in any feature written, so reading the file back has no column of its own for it: 'gone'", ] ); assert_eq!(text_notes(&ds, "kmz"), text_notes(&ds, "kml")); @@ -6053,7 +6053,7 @@ mod tests { for f in ds.features.iter_mut() { f.attrs[0] = Value::Null; } - assert_eq!(losses(&ds), ["t: 1 field is empty in every feature, so reading the file back has no column for it: 'title'"]); + assert_eq!(losses(&ds), ["t: 1 field has no value in any feature written, so reading the file back has no column of its own for it: 'title'"]); let clean = text_layer(&["title"], &[&[Some("a")], &[Some("b")]]); assert!(losses(&clean).is_empty()); } @@ -6083,7 +6083,7 @@ mod tests { fn a_kml_name_column_without_values_of_another_field_is_said() { let mut ds = text_layer(&["title", "name"], &[&[Some("a"), None], &[Some("b"), None]]); let losses = |ds: &Dataset| TextLosses::of(&ds.features, &ds.fields, ds.geometry_type, "kml", Some(0)).notes(&ds.fields, "t"); - assert_eq!(losses(&ds), ["t: 1 field is empty in every feature, so reading the file back has no column for it: 'name'"]); + assert_eq!(losses(&ds), ["t: 1 field has no value in any feature written, so reading the file back has no column of its own for it: 'name'"]); let back = crate::interop::to_kml(&ds, Some(0)).unwrap(); let read = &crate::kml::read("t.kml", back.as_bytes()).unwrap()[0].dataset; let column = |n: &str| read.field_index(n).map(|i| read.features.iter().map(|f| f.attrs[i].clone()).collect::>()); diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index cfbf01e6f1..8323e9f36b 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -24652,7 +24652,7 @@ fn csv_and_gpx_exports_say_what_they_leave_out() { for format in ["kml", "gpx"] { let n = said(&mut s, "data.convert", json!({"layer": "Rows", "format": format})); assert!(n.len() == 2 && n.iter().any(|t| t.contains("1 features without drawable geometry were left out")), "{format}: {n:?}"); - let height = if format == "kml" { "no column for it: 'height'" } else { "1 field wasn't written: 'height'" }; + let height = if format == "kml" { "no column of its own for it: 'height'" } else { "1 field wasn't written: 'height'" }; assert!(n.iter().any(|t| t.contains(height)), "{format}: {n:?}"); } // A standalone table keeps geometry too: Export Table says the same, and nothing for a clean one. From 406da510cf85c768b3422c3f41a633ea2735e750 Mon Sep 17 00:00:00 2001 From: Cory Douglas Martin <4108748+flight1973@users.noreply.github.com> Date: Wed, 18 Nov 2026 13:53:18 -0600 Subject: [PATCH 10/12] fix(data): KML and GPX exports say features that won't read back A feature with no coordinate inside longitude/latitude, or too few for its shape (a one-point line), is written to KML or GPX, and reading the file back skips it without a word. The export now counts those features in one notice, using what the readers keep. --- crates/data/src/io.rs | 39 +++++++++++++++++++++++++++++++++------ 1 file changed, 33 insertions(+), 6 deletions(-) diff --git a/crates/data/src/io.rs b/crates/data/src/io.rs index 67ea9ebb30..42c6bf9d79 100644 --- a/crates/data/src/io.rs +++ b/crates/data/src/io.rs @@ -3866,6 +3866,9 @@ pub struct TextLosses { layers: Vec>, /// Only the spaces after text are dropped (dBase). ends_only: bool, + /// Features written that reading skips (KML, GPX): no coordinate in longitude/latitude, or + /// too few for their shape. + unread: usize, } /// One field's [`TextLosses`] in one layer read back. @@ -3968,6 +3971,7 @@ impl TextLosses { .collect(); // KML reads a layer for each kind of geometry, and types each one's columns apart. let mut layers = vec![fresh; if kml { 3 } else { 1 }]; + let mut unread = 0usize; let layer_of = |g: &Geometry| match g.kind() { _ if !kml => 0, GeometryType::Point => 0, @@ -3990,6 +3994,13 @@ impl TextLosses { if let Some(first) = layers.first_mut() { first.iter_mut().zip(&feature.attrs).for_each(|(loss, v)| loss.valued |= !v.is_null()); } + unread = unread.saturating_add(1); + continue; + } + // Written, and skipped on reading (an empty multipoint isn't written at all, and + // is said as left out). + Some(g) if gpx && !matches!(g, Geometry::MultiPoint(v) if v.is_empty()) => { + unread = unread.saturating_add(1); continue; } _ => continue, @@ -4035,7 +4046,7 @@ impl TextLosses { } } } - Self { layers, ends_only: shp } + Self { layers, ends_only: shp, unread } } /// One notice for each loss of a layer with `fields` written to `target`, with a count and @@ -4087,6 +4098,12 @@ impl TextLosses { }; notes.push(format!("{target}: {what}: {}", named_fields(fields, &missing))); } + if self.unread > 0 { + let what = if self.unread == 1 { "1 feature is".to_string() } else { format!("{} features are", self.unread) }; + notes.push(format!( + "{target}: {what} written but won't read back: no coordinate is inside longitude/latitude, or too few for the shape" + )); + } notes } } @@ -4098,6 +4115,7 @@ impl std::ops::AddAssign for TextLosses { *self = other; return; } + self.unread = self.unread.saturating_add(other.unread); for (a, b) in self.layers.iter_mut().zip(other.layers).flat_map(|(a, b)| a.iter_mut().zip(b)) { a.padded += b.padded; a.name_padded += b.name_padded; @@ -6009,15 +6027,18 @@ mod tests { ds.push(Some(Geometry::MultiPoint(vec![])), vec![Value::Text("".into()), Value::Text("".into())]); ds.push(Some(Geometry::Line(vec![vec![Coord::new(0.0, 0.0)]])), vec![Value::Text(" ".into()), Value::Text(" ".into())]); // 'note' has values only where reading skips the placemark: its padded text doesn't come - // back, but its name still gives a column, of nulls. - assert!(text_notes(&ds, "kml").is_empty()); + // back, but its name still gives a column, of nulls. The skipped placemarks are said. + let unread = + |n: &str| format!("t: {n} written but won't read back: no coordinate is inside longitude/latitude, or too few for the shape"); + assert_eq!(text_notes(&ds, "kml"), [unread("3 features are")]); let (bytes, _) = write_bytes(&ds, "kml").unwrap(); let layers = crate::kml::read("t.kml", &bytes).unwrap(); assert_eq!(layers.len(), 1); let back = &layers[0].dataset; assert_eq!(back.features.len(), 1); assert_eq!(back.field_index("note").map(|i| back.value(0, i).clone()), Some(Value::Null)); - assert!(text_notes(&ds, "gpx").is_empty()); + // GPX doesn't write the empty multipoint (said as left out); the other two it skips. + assert_eq!(text_notes(&ds, "gpx"), [unread("2 features are")]); let (bytes, _) = write_bytes(&ds, "gpx").unwrap(); let read = crate::gpx::read("t.gpx", &bytes).unwrap(); // One waypoint, and no track (its lone point, unnamed, is among the track points). @@ -6053,7 +6074,10 @@ mod tests { for f in ds.features.iter_mut() { f.attrs[0] = Value::Null; } - assert_eq!(losses(&ds), ["t: 1 field has no value in any feature written, so reading the file back has no column of its own for it: 'title'"]); + assert_eq!( + losses(&ds), + ["t: 1 field has no value in any feature written, so reading the file back has no column of its own for it: 'title'"] + ); let clean = text_layer(&["title"], &[&[Some("a")], &[Some("b")]]); assert!(losses(&clean).is_empty()); } @@ -6083,7 +6107,10 @@ mod tests { fn a_kml_name_column_without_values_of_another_field_is_said() { let mut ds = text_layer(&["title", "name"], &[&[Some("a"), None], &[Some("b"), None]]); let losses = |ds: &Dataset| TextLosses::of(&ds.features, &ds.fields, ds.geometry_type, "kml", Some(0)).notes(&ds.fields, "t"); - assert_eq!(losses(&ds), ["t: 1 field has no value in any feature written, so reading the file back has no column of its own for it: 'name'"]); + assert_eq!( + losses(&ds), + ["t: 1 field has no value in any feature written, so reading the file back has no column of its own for it: 'name'"] + ); let back = crate::interop::to_kml(&ds, Some(0)).unwrap(); let read = &crate::kml::read("t.kml", back.as_bytes()).unwrap()[0].dataset; let column = |n: &str| read.field_index(n).map(|i| read.features.iter().map(|f| f.attrs[i].clone()).collect::>()); From 7a99cd191d7db30a10e4d342b970805b341bd604 Mon Sep 17 00:00:00 2001 From: Cory Douglas Martin <4108748+flight1973@users.noreply.github.com> Date: Wed, 18 Nov 2026 22:57:27 -0600 Subject: [PATCH 11/12] fix(data): KML and GPX exports count the vertices that won't read back, and each value once --- crates/data/src/gpx.rs | 18 +++++++ crates/data/src/io.rs | 111 ++++++++++++++++++++++++++++++++++------- crates/data/src/kml.rs | 24 +++++++++ 3 files changed, 135 insertions(+), 18 deletions(-) diff --git a/crates/data/src/gpx.rs b/crates/data/src/gpx.rs index c66709f0e3..832260d674 100644 --- a/crates/data/src/gpx.rs +++ b/crates/data/src/gpx.rs @@ -46,6 +46,24 @@ pub(crate) fn keeps(g: &Geometry) -> bool { } } +/// The vertices of a feature reading keeps ([`keeps`]) that don't read back with it: points of a +/// multipoint outside longitude/latitude ([`coord`]), and those of a track's segments (a polygon's +/// outer rings) out of range, or all of a segment left with fewer than two, which reading leaves +/// out of the track. +pub(crate) fn lost_vertices(g: &Geometry) -> usize { + let in_range = |p: &[Coord]| p.iter().filter(|c| crate::io::lon_lat_in_range(c.x, c.y)).count(); + let segment = |p: &Vec| { + let n = in_range(p); + if n >= 2 { p.len().saturating_sub(n) } else { p.len() } + }; + match g { + Geometry::Point(_) => 0, + Geometry::MultiPoint(v) => v.len().saturating_sub(in_range(v)), + Geometry::Line(parts) => parts.iter().map(segment).sum(), + Geometry::Polygon(polys) => polys.iter().filter_map(|rings| rings.first()).map(segment).sum(), + } +} + fn text(v: Option) -> Value { v.map(Value::Text).unwrap_or_default() } diff --git a/crates/data/src/io.rs b/crates/data/src/io.rs index 42c6bf9d79..ea21017458 100644 --- a/crates/data/src/io.rs +++ b/crates/data/src/io.rs @@ -3869,6 +3869,9 @@ pub struct TextLosses { /// Features written that reading skips (KML, GPX): no coordinate in longitude/latitude, or /// too few for their shape. unread: usize, + /// Vertices of the features reading keeps (KML, GPX) that don't read back with them + /// ([`crate::kml::lost_vertices`], [`crate::gpx::lost_vertices`]). + vertices: usize, } /// One field's [`TextLosses`] in one layer read back. @@ -3972,6 +3975,7 @@ impl TextLosses { // KML reads a layer for each kind of geometry, and types each one's columns apart. let mut layers = vec![fresh; if kml { 3 } else { 1 }]; let mut unread = 0usize; + let mut vertices = 0usize; let layer_of = |g: &Geometry| match g.kind() { _ if !kml => 0, GeometryType::Point => 0, @@ -3979,16 +3983,17 @@ impl TextLosses { _ => 2, }; for feature in features { - // GPX writes a waypoint for each point of a multipoint, each with the name; reading - // keeps those in range. - let copies = match &feature.geometry { - Some(Geometry::MultiPoint(v)) if gpx => v.iter().filter(|c| lon_lat_in_range(c.x, c.y)).count(), - _ => 1, - }; let layer = match &feature.geometry { _ if csv => 0, g if shp && shapefile_keeps(g.as_ref(), gt) => 0, - Some(g) if kml && crate::kml::keeps(g) || gpx && crate::gpx::keeps(g) => layer_of(g), + Some(g) if kml && crate::kml::keeps(g) => { + vertices = vertices.saturating_add(crate::kml::lost_vertices(g)); + layer_of(g) + } + Some(g) if gpx && crate::gpx::keeps(g) => { + vertices = vertices.saturating_add(crate::gpx::lost_vertices(g)); + layer_of(g) + } // A placemark reading skips still gives its extended data's names columns. Some(_) if kml => { if let Some(first) = layers.first_mut() { @@ -4027,7 +4032,10 @@ impl TextLosses { } let Value::Text(s) = v else { continue }; let trimmed = s.trim(); - for read in reads { + // A value is counted once, however many copies of it are written (a KML name + // field's extended data, a GPX multipoint's waypoints): by its first copy, the + // name, whose loss is never less than the extended data's. + if let Some(read) = reads.first() { let count = match read { TextRead::Cell if s.is_empty() => &mut loss.blank, TextRead::Cell | TextRead::Dbf if Value::is_null_marker(s) => &mut loss.markers, @@ -4042,11 +4050,11 @@ impl TextLosses { TextRead::Data if trimmed.len() < s.len() => &mut loss.padded, _ => continue, }; - *count += if *read == TextRead::Name { copies } else { 1 }; + *count += 1; } } } - Self { layers, ends_only: shp, unread } + Self { layers, ends_only: shp, unread, vertices } } /// One notice for each loss of a layer with `fields` written to `target`, with a count and @@ -4104,6 +4112,12 @@ impl TextLosses { "{target}: {what} written but won't read back: no coordinate is inside longitude/latitude, or too few for the shape" )); } + if self.vertices > 0 { + let what = if self.vertices == 1 { "1 vertex won't".to_string() } else { format!("{} vertices won't", self.vertices) }; + notes.push(format!( + "{target}: {what} read back with the features kept: outside longitude/latitude, or in a part left with too few to keep" + )); + } notes } } @@ -4116,6 +4130,7 @@ impl std::ops::AddAssign for TextLosses { return; } self.unread = self.unread.saturating_add(other.unread); + self.vertices = self.vertices.saturating_add(other.vertices); for (a, b) in self.layers.iter_mut().zip(other.layers).flat_map(|(a, b)| a.iter_mut().zip(b)) { a.padded += b.padded; a.name_padded += b.name_padded; @@ -6051,16 +6066,17 @@ mod tests { } /// A KML name field not called `name` is the placemark's name and its own extended data - /// column, read with a type from its values. + /// column, read with a type from its values: each value is counted once. #[test] - fn a_kml_name_field_of_another_name_is_counted_as_both_columns() { + fn a_kml_name_field_of_another_name_counts_each_value_once() { let mut ds = text_layer(&["title", "other"], &[&[Some(" a"), Some("x")], &[Some(""), Some("y")], &[Some("5"), Some("z")]]); let losses = |ds: &Dataset| TextLosses::of(&ds.features, &ds.fields, ds.geometry_type, "kml", Some(0)).notes(&ds.fields, "t"); - // In the name, " a" is trimmed and "" null; in 'title', a text column, " a" is trimmed. + // In the name, " a" is trimmed and "" null; in 'title', a text column, " a" is trimmed too, + // the same value. assert_eq!( losses(&ds), [ - "t: 2 text values start or end with spaces, tabs or line breaks, which reading the file back drops, in 'title'", + "t: 1 text value starts or ends with spaces, tabs or line breaks, which reading the file back drops, in 'title'", "t: 1 blank text value reads back as empty (null), in 'title'", ] ); @@ -6167,16 +6183,20 @@ mod tests { assert!(gpx_notes(&ds, Some(0), "t").is_empty()); } - /// GPX writes a waypoint for each point of a multipoint, each with the name: each one reading - /// keeps trims it. + /// GPX writes a waypoint for each point of a multipoint, each with the name: reading trims each + /// copy, and the value is counted once. The point out of range is a vertex that doesn't read + /// back. #[test] - fn gpx_counts_a_multipoints_name_once_for_each_waypoint() { + fn gpx_counts_a_multipoints_name_once() { let mut ds = Dataset::new("t", GeometryType::Point, vec![Field::new("name", FieldType::Text)]); let points = vec![Coord::new(0.0, 0.0), Coord::new(1.0, 1.0), Coord::new(200.0, 0.0)]; ds.push(Some(Geometry::MultiPoint(points)), vec![Value::Text(" a".into())]); assert_eq!( text_notes(&ds, "gpx"), - ["t: 2 text values start or end with spaces, tabs or line breaks, which reading the file back drops, in 'name'"] + [ + "t: 1 text value starts or ends with spaces, tabs or line breaks, which reading the file back drops, in 'name'", + "t: 1 vertex won't read back with the features kept: outside longitude/latitude, or in a part left with too few to keep", + ] ); let (bytes, _) = write_bytes(&ds, "gpx").unwrap(); let read = crate::gpx::read("t.gpx", &bytes).unwrap(); @@ -6184,9 +6204,64 @@ mod tests { let names: Vec<_> = waypoints.features.iter().map(|f| f.attrs[0].clone()).collect(); assert_eq!(names, [Value::Text("a".into()), Value::Text("a".into())]); ds.features[0].attrs = vec![Value::Text("a".into())]; + ds.features[0].geometry = Some(Geometry::MultiPoint(vec![Coord::new(0.0, 0.0), Coord::new(1.0, 1.0)])); assert!(text_notes(&ds, "gpx").is_empty()); } + /// KML and GPX readers drop a vertex outside longitude/latitude one at a time, and a part left + /// with too few: the features kept lose those vertices, which are counted. + #[test] + fn kml_and_gpx_count_vertices_that_dont_read_back() { + let c = Coord::new; + let geometries = [ + // One vertex out of range; the line keeps two. + Geometry::Line(vec![vec![c(0.0, 0.0), c(200.0, 0.0), c(1.0, 1.0)]]), + // A second part left with one vertex is dropped whole: 2 vertices. + Geometry::Line(vec![vec![c(0.0, 0.0), c(1.0, 1.0)], vec![c(2.0, 2.0), c(0.0, 95.0)]]), + // Two points of three out of range. + Geometry::MultiPoint(vec![c(0.0, 0.0), c(181.0, 0.0), c(0.0, -91.0)]), + ]; + let mut ds = Dataset::new("t", GeometryType::Polyline, vec![Field::new("name", FieldType::Text)]); + for g in geometries { + ds.push(Some(g), vec![Value::Text("a".into())]); + } + let vertices = |n: usize| { + format!( + "t: {n} vertices won't read back with the features kept: outside longitude/latitude, or in a part left with too few to keep" + ) + }; + assert_eq!(text_notes(&ds, "kml"), [vertices(5)]); + assert_eq!(text_notes(&ds, "gpx"), [vertices(5)]); + // Reading the file back keeps the other 5 of the 10 vertices written. + let (bytes, _) = write_bytes(&ds, "kml").unwrap(); + let read = crate::kml::read("t.kml", &bytes).unwrap(); + let kept: usize = + read.iter().flat_map(|l| &l.dataset.features).filter_map(|f| f.geometry.as_ref()).map(Geometry::coord_count).sum(); + assert_eq!(kept, 10 - 5); + // A polygon: an outer ring of four in range keeps them; a hole left with two is dropped + // (4 vertices), and a part whose outer ring is left with two is dropped with its hole. + let square = |x: f64| vec![c(x, 0.0), c(x + 1.0, 0.0), c(x + 1.0, 1.0), c(x, 0.0)]; + let polygon = Geometry::Polygon(vec![ + vec![square(0.0), vec![c(0.1, 0.1), c(200.0, 0.0), c(200.0, 1.0), c(0.1, 0.1)]], + vec![vec![c(2.0, 0.0), c(300.0, 0.0), c(300.0, 1.0), c(2.0, 1.0)], square(2.0)], + ]); + let mut ds = Dataset::new("t", GeometryType::Polygon, vec![Field::new("name", FieldType::Text)]); + ds.push(Some(polygon), vec![Value::Text("a".into())]); + assert_eq!(text_notes(&ds, "kml"), [vertices(12)]); + let (bytes, _) = write_bytes(&ds, "kml").unwrap(); + let read = crate::kml::read("t.kml", &bytes).unwrap(); + assert_eq!(read[0].dataset.features[0].geometry, Some(Geometry::Polygon(vec![vec![square(0.0)]]))); + // GPX writes the outer rings as a track: the second is left with two, so isn't dropped. + assert_eq!(text_notes(&ds, "gpx"), [vertices(2)]); + // In range, nothing is said. + let mut clean = Dataset::new("t", GeometryType::Polyline, vec![Field::new("name", FieldType::Text)]); + clean.push(Some(Geometry::Line(vec![vec![c(0.0, 0.0), c(180.0, 90.0)]])), vec![Value::Text("a".into())]); + clean.push(Some(Geometry::MultiPoint(vec![c(-180.0, -90.0), c(1.0, 1.0)])), vec![Value::Text("b".into())]); + clean.push(Some(Geometry::Polygon(vec![vec![square(0.0), square(0.0)]])), vec![Value::Text("c".into())]); + assert!(text_notes(&clean, "kml").is_empty()); + assert!(text_notes(&clean, "gpx").is_empty()); + } + /// KML reads a layer for each kind of geometry and types each one's columns apart: a blank in /// the points' column of numbers reads as null, one in the lines' column of text doesn't. #[test] diff --git a/crates/data/src/kml.rs b/crates/data/src/kml.rs index 5172a0c2f3..f9c7a62a54 100644 --- a/crates/data/src/kml.rs +++ b/crates/data/src/kml.rs @@ -278,6 +278,30 @@ pub(crate) fn keeps(g: &Geometry) -> bool { } } +/// The vertices of a placemark reading keeps ([`keeps`]) that don't read back with it: those +/// outside longitude/latitude ([`coords`]), and every vertex of a line part left with fewer than +/// two, a ring with fewer than three, or a polygon whose outer ring is dropped ([`geometry`]). +pub(crate) fn lost_vertices(g: &Geometry) -> usize { + let in_range = |p: &[Coord]| p.iter().filter(|c| crate::io::lon_lat_in_range(c.x, c.y)).count(); + // A part reading keeps loses its vertices out of range; one it drops, all of them. + let part = |p: &[Coord], min: usize| { + let n = in_range(p); + if n >= min { p.len().saturating_sub(n) } else { p.len() } + }; + match g { + Geometry::Point(_) => 0, + Geometry::MultiPoint(v) => v.len().saturating_sub(in_range(v)), + Geometry::Line(parts) => parts.iter().map(|p| part(p, 2)).sum(), + Geometry::Polygon(polys) => polys + .iter() + .map(|rings| match rings.split_first() { + Some((outer, inner)) if in_range(outer) >= 3 => part(outer, 3) + inner.iter().map(|r| part(r, 3)).sum::(), + _ => rings.iter().map(Vec::len).sum(), + }) + .sum(), + } +} + /// The parts of a geometry element: (points, lines, polygons), MultiGeometry flattened. #[derive(Default)] struct Parts { From dfd66d672de2fb1ccde4794a5a6a3d3b0ea631c8 Mon Sep 17 00:00:00 2001 From: Cory Douglas Martin <4108748+flight1973@users.noreply.github.com> Date: Thu, 19 Nov 2026 00:14:01 -0600 Subject: [PATCH 12/12] docs(data): the export's loss count is one in-memory pass without a Cancel check, and why --- crates/data/src/io.rs | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/crates/data/src/io.rs b/crates/data/src/io.rs index ea21017458..20fec33550 100644 --- a/crates/data/src/io.rs +++ b/crates/data/src/io.rs @@ -3929,6 +3929,11 @@ impl TextLosses { /// The losses of `features`, with `fields`, in a layer of type `gt` written to a file of /// extension `ext` (lowercase), each KML or GPX feature named from field `name_field`; none /// for another format. + /// + /// One pass over the features without a check for Cancel: the counts of a pass stopped half + /// way would understate the losses, so it can't return early. It formats each value once, + /// in memory, which is less than the write it follows (the same formatting, plus the write), + /// and a streamed export counts a chunk at a time, looking at Cancel between chunks. pub fn of(features: &[crate::Feature], fields: &[Field], gt: GeometryType, ext: &str, name_field: Option) -> Self { let (csv, shp, kml, gpx) = (matches!(ext, "csv" | "wkt"), matches!(ext, "shp" | "zip"), matches!(ext, "kml" | "kmz"), ext == "gpx"); if !(csv || shp || kml || gpx) {