From c757ee9665467841c2bde4232c5528278731281b Mon Sep 17 00:00:00 2001 From: mavrick Date: Sat, 28 Nov 2026 08:46:16 -0600 Subject: [PATCH 1/4] fix(data): read GML schema members and keep their geometry properties --- crates/data/src/gml.rs | 786 +++++++++++++++++++++----------- crates/data/src/io.rs | 32 +- crates/engine/src/cmd/layer.rs | 79 +++- docs/user-guide/data-formats.md | 2 +- 4 files changed, 613 insertions(+), 286 deletions(-) diff --git a/crates/data/src/gml.rs b/crates/data/src/gml.rs index 428bf66793..f0329c1f17 100644 --- a/crates/data/src/gml.rs +++ b/crates/data/src/gml.rs @@ -1,7 +1,7 @@ //! GML: simple features in Geography Markup Language 2 and 3 — WFS feature collections, OGR's //! GML, and other application schemas whose features are members of a collection. Each feature -//! type becomes a layer; a feature's simple child elements are its attributes and its first -//! geometry is its shape (points, lines, polygons and their multi forms, envelopes). +//! type becomes a layer, or one layer per geometry property when several can be read. A feature's +//! simple child elements are its attributes. //! //! Coordinates are converted to longitude/latitude from the `srsName` (EPSG codes, URNs and URLs); //! the URN and URL forms of geographic systems are latitude first, as GML 3 says. A file without @@ -16,13 +16,14 @@ use std::collections::{BTreeMap, HashSet}; use roxmltree::{Node, ParsingOptions}; use rustgis_geom::Coord; -use crate::raster::Crs; +use crate::io::LayerRead; +use crate::raster::{Crs, Transformer}; use crate::{DataError, Dataset, Field, Geometry, GeometryType, ReadReport, Result, Value}; /// GML file types. pub const EXTENSIONS: &[&str] = &["gml"]; -/// Most feature types (layers) read from one file. +/// Most layers read from one file. const MAX_LAYERS: usize = 64; pub(crate) fn local<'a>(n: &Node<'a, '_>) -> &'a str { @@ -446,62 +447,114 @@ impl Names { /// Most attribute columns of a feature type. const MAX_COLUMNS: usize = 500; -/// A feature type being read: its attribute columns in order of appearance, and its rows. +/// One shape before it has been matched against the file's declared coordinate system. +struct Shape<'a, 'input> { + property: Node<'a, 'input>, + node: Node<'a, 'input>, + geometry: Geometry, + declared_srs: Option<&'a str>, + parsed_srs: Option<(Crs, bool)>, + zm: bool, + lost: usize, +} + +struct Row<'a, 'input> { + attrs: BTreeMap, + shapes: Vec>, +} + +/// A feature type's rows and losses shared by all its geometry properties. #[derive(Default)] -struct Kind { +struct Kind<'a, 'input> { columns: Vec, - rows: Vec<(Option, BTreeMap)>, - /// Features whose Z or M values were dropped. - zm: usize, - /// Properties not read (a nested record, a time, a shape past the one kept): how many, and the - /// first few names. + rows: Vec>, unread: usize, unread_names: Names, - /// Features whose shape couldn't be read. skipped: usize, - /// Values of a property the feature already had (the last is kept), and values of properties - /// past the column cap: how many, and the first few names. repeated: usize, repeated_names: Names, capped: usize, capped_names: Names, - /// Members of multi-geometries that gave nothing to keep. +} + +/// Rows and reported geometry losses for one property. Rows refer to the feature type's +/// attributes so the reader holds just one copy until it builds the output layers. +#[derive(Default)] +struct ShapeLayer { + rows: Vec<(usize, Option)>, + zm: usize, parts_lost: usize, - /// Rings and surface patches of its geometries left out. lost: usize, - /// Features with curve segments read as their control points: how many, and the first few kinds. approximated: usize, approximated_names: Names, - /// Features with curve segments given by a centre point, which is read as a vertex. centred: usize, } -/// Reads a GML file into a layer per feature type (those with features). Cancel is looked at -/// between features; parsing the whole document first is one step without a look. +impl ShapeLayer { + /// Account for losses only in a geometry accepted for this layer. + fn push(&mut self, row: usize, shape: Shape<'_, '_>) { + self.zm += usize::from(shape.zm); + self.lost += shape.lost; + self.parts_lost += parts_lost(&shape.node); + let mut approximated_curve = false; + let mut centred_curve = false; + for name in approximated(&shape.node) { + if name.ends_with("ByCenterPoint") { + centred_curve = true; + } else { + approximated_curve = true; + self.approximated_names.add(name); + } + } + self.approximated += usize::from(approximated_curve); + self.centred += usize::from(centred_curve); + self.rows.push((row, Some(shape.geometry))); + } +} + +/// Standard members take precedence. A standard-looking property inside an application +/// member is part of that feature, just as a nested member inside a standard member is. +fn collection_features<'a, 'input>(root: Node<'a, 'input>) -> Vec> { + let standard = |n: &Node| n.is_element() && matches!(local(n), "featureMember" | "featureMembers" | "member" | "members"); + let custom = |n: &Node| { + n.is_element() && n.parent() == Some(root) && { + let name = local(n); + name.ends_with("Member") || name.ends_with("Members") + } + }; + let mut members: Vec<_> = + root.descendants().filter(|n| standard(n) && n.ancestors().skip(1).all(|a| !standard(&a) && !custom(&a))).collect(); + if members.is_empty() && !(is_gml(&root) && is_shape(local(&root))) { + members.extend(root.children().filter(custom)); + } + members + .into_iter() + .flat_map(|m| m.children().filter(|c| c.is_element())) + .filter(|f| !(is_gml(f) && GEOMETRIES.contains(&local(f)))) + .collect() +} + +/// Reads the layers of a GML file and their reports. pub fn read(file_name: &str, bytes: &[u8]) -> Result> { + Ok(read_layers(file_name, bytes)?.into_iter().map(|r| (r.dataset, r.report)).collect()) +} + +/// Reads a GML file into layers by feature type and geometry property. Cancel is checked between +/// features. Parsing the whole document first is one step without a check. +pub(crate) fn read_layers(file_name: &str, bytes: &[u8]) -> Result> { let stem = std::path::Path::new(file_name).file_stem().and_then(|s| s.to_str()).unwrap_or("gml").to_string(); let text = std::str::from_utf8(bytes).map_err(|_| DataError::Format(format!("{file_name} is not UTF-8 text")))?; let opts = ParsingOptions { allow_dtd: false, nodes_limit: crate::io::XML_NODES, ..ParsingOptions::default() }; let doc = crate::xml::parse(text.trim_start_matches('\u{feff}'), opts).map_err(|e| DataError::Format(format!("{file_name}: {e}")))?; - let root = doc.root_element(); - // The features: children of member elements (not of one inside a feature, such as a - // property or a geometry collection's member named alike). - let is_member = |n: &Node| n.is_element() && matches!(local(n), "featureMember" | "featureMembers" | "member" | "members"); - let members: Vec = root - .descendants() - .filter(|n| is_member(n) && n.ancestors().skip(1).all(|a| !is_member(&a))) - .flat_map(|m| m.children().filter(|c| c.is_element())) - .filter(|f| !(is_gml(f) && GEOMETRIES.contains(&local(f)))) - .collect(); + let members = collection_features(doc.root_element()); if members.is_empty() { - return Err(DataError::Format(format!("{file_name}: no features (featureMember elements) in the GML"))); + return Err(DataError::Format(format!("{file_name}: no features in GML collection member elements"))); } - let mut kinds: BTreeMap = BTreeMap::new(); + let mut kinds: BTreeMap> = BTreeMap::new(); let mut order: Vec = Vec::new(); let mut file_srs: Option<(Crs, bool)> = None; let mut unknown_srs: Option = None; let mut over = 0usize; - // Rings and parts left out of the geometries kept. for f in members { // Read ahead, off the UI thread: a large file can be cancelled between features. crate::progress::check()?; @@ -515,17 +568,10 @@ pub fn read(file_name: &str, bytes: &[u8]) -> Result> } let kind = kinds.entry(name).or_default(); let mut attrs = BTreeMap::new(); - let mut geom = None; - let mut bad = false; - // Whether the geometry kept had Z or M values. - let mut zm = false; - // Rings and surface patches left out of the geometry kept. - let mut rings_lost = 0; - // Properties not read, and those holding GML of a kind not read (another kind of - // geometry): the feature's unreadable shape when it has none, else not read. - // Each with the property's place, so the notice names them in document order. - let (mut unread, mut shapes_not_read): (Vec<(usize, String)>, Vec<(usize, String)>) = (Vec::new(), Vec::new()); - // Geometry properties that couldn't be read: said as not read when another gave the shape. + let mut shapes = Vec::new(); + // Properties listed as unread are counted in document order. If no shape could be + // decoded, the first failed property is accounted for by the feature's skipped count. + let mut unread = Vec::new(); let mut failed = Vec::new(); for (at, p) in f.children().filter(|c| c.is_element()).enumerate() { // A property holding a geometry, or a simple value. @@ -534,48 +580,32 @@ pub fn read(file_name: &str, bytes: &[u8]) -> Result> continue; } if let Some(g) = p.children().find(|c| c.is_element() && is_gml(c) && GEOMETRIES.contains(&local(c))) { - if geom.is_some() { - unread.push((at, local(&p).to_string())); - continue; - } - let s = g.attribute("srsName").or_else(|| g.descendants().find_map(|d| d.attribute("srsName"))); - // A system RustGIS doesn't know is said only for a geometry read in it. - let mut unknown = None; - if let Some(s) = s { - match srs(s) { - Some(found) => { - file_srs.get_or_insert(found); - } - None => unknown = Some(s.to_string()), - } + let declared_srs = g.attribute("srsName").or_else(|| g.descendants().find_map(|d| d.attribute("srsName"))); + let parsed_srs = declared_srs.and_then(srs); + // The file still takes its system from the same properties as before: those + // considered up to and including each feature's first readable geometry. + if shapes.is_empty() + && let Some(found) = parsed_srs + { + file_srs.get_or_insert(found); } let (dims, lost) = (Cell::new(false), Cell::new(0)); match geometry(&g, &dims, &lost) { - Some(gm) => { - if unknown.is_some() { - unknown_srs = unknown; - } - zm = dims.get(); - rings_lost += lost.get(); - geom = Some(gm); - kind.parts_lost += parts_lost(&g); - let (centred, approx): (Vec, Vec) = - approximated(&g).into_iter().partition(|n| n.ends_with("ByCenterPoint")); - kind.centred += usize::from(!centred.is_empty()); - kind.approximated += usize::from(!approx.is_empty()); - for n in approx { - kind.approximated_names.add(n); + Some(geometry) => { + if shapes.is_empty() + && parsed_srs.is_none() + && let Some(s) = declared_srs + { + unknown_srs = Some(s.to_string()); } + shapes.push(Shape { property: p, node: g, geometry, declared_srs, parsed_srs, zm: dims.get(), lost: lost.get() }); } - None => { - bad = true; - failed.push((at, local(&p).to_string())); - } + None => failed.push((at, local(&p).to_string())), } } else if let Some(c) = p.children().find(|c| c.is_element() && is_gml(c)) { - // A geometry of a kind not read (a CompositeCurve, a Solid…) may be the feature's - // only shape; another GML value (a time, a definition) is no shape. - if is_shape(local(&c)) { &mut shapes_not_read } else { &mut unread }.push((at, local(&p).to_string())); + // A geometry of a kind not read can be the only shape; other GML values are + // counted as unread properties regardless of whether the feature has a shape. + if is_shape(local(&c)) { &mut failed } else { &mut unread }.push((at, local(&p).to_string())); } else if p.children().any(|c| c.is_element()) { // A nested record isn't an attribute. unread.push((at, local(&p).to_string())); @@ -595,13 +625,9 @@ pub fn read(file_name: &str, bytes: &[u8]) -> Result> } } } - // With no shape read, the first one that failed or isn't read is the feature's unreadable - // shape; any others are said as not read. - failed.append(&mut shapes_not_read); - failed.sort_by_key(|(at, _)| *at); - if geom.is_none() && !failed.is_empty() { - bad = true; - unread.extend(failed.drain(..).skip(1)); + if shapes.is_empty() && !failed.is_empty() { + kind.skipped += 1; + unread.extend(failed.into_iter().skip(1)); } else { unread.append(&mut failed); } @@ -617,21 +643,19 @@ pub fn read(file_name: &str, bytes: &[u8]) -> Result> } attrs.insert("gml_id".into(), id); } - // A geometry that couldn't be read, unless another property gave the feature its shape. - kind.skipped += usize::from(bad && geom.is_none()); - kind.zm += usize::from(zm && geom.is_some()); - kind.lost += rings_lost; - kind.rows.push((geom, attrs)); + kind.rows.push(Row { shapes, attrs }); } - let mut report = ReadReport::default(); + let mut file_notices = crate::loss::Notes::new(); if over > 0 { - report.messages.push(crate::loss::Note::loss( + file_notices.push(crate::loss::Note::loss( crate::loss::LossCode::DroppedOverLimit, format!("{over} features of more than {MAX_LAYERS} feature types were left out"), )); } - if let Some(s) = &unknown_srs { - report.messages.push(crate::loss::Note::loss( + if file_srs.is_none() + && let Some(s) = &unknown_srs + { + file_notices.push(crate::loss::Note::loss( crate::loss::LossCode::AssumedCrs, format!("unknown coordinate system '{s}': coordinates are read as they are"), )); @@ -641,9 +665,11 @@ pub fn read(file_name: &str, bytes: &[u8]) -> Result> None => None, }; let single = order.len() == 1; + let mut extra_layers = MAX_LAYERS.saturating_sub(order.len()); + let mut extra_rows_budget = None; let mut out = Vec::new(); for name in order { - let Some(kind) = kinds.remove(&name) else { continue }; + let Some(mut kind) = kinds.remove(&name) else { continue }; let fields: Vec = kind .columns .iter() @@ -651,195 +677,357 @@ pub fn read(file_name: &str, bytes: &[u8]) -> Result> Field::new( c.clone(), crate::io::text_type( - kind.rows.iter().filter_map(|(_, a)| a.get(c)).map(String::as_str).filter(|v| !Value::is_null_marker(v)), + kind.rows.iter().filter_map(|r| r.attrs.get(c)).map(String::as_str).filter(|v| !Value::is_null_marker(v)), ), ) }) .collect(); let title = if single { stem.clone() } else { format!("{stem} {name}") }; - let mut ds = Dataset::new(title, GeometryType::None, fields); - let (zm, unread, parts) = (kind.zm, kind.unread, kind.parts_lost); - let unread_names = kind.unread_names.said(); - let (mut outside, mut null_text) = (false, Vec::new()); - // Features with a place the file's system can't give in longitude/latitude, kept missing. - let (mut unplaced, mut beyond) = (0usize, 0usize); - // Held as the file holds its coordinates, in its own system (in the axis order RustGIS - // gives every system's), when RustGIS converts it. - if let Some((Some(_), _)) = &transform - && let Some((c, _)) = file_srs - { - ds.held_in = c; + let mut notes = ReadReport::default(); + let mut limits = SplitLimits { layers: &mut extra_layers, rows_budget: &mut extra_rows_budget, columns: fields.len() }; + let layers = group_shapes(&mut kind.rows, &title, file_srs, unknown_srs.as_deref(), &mut limits, &mut notes)?; + let split = layers.len() > 1; + let first = out.len(); + let mut used_names = BTreeMap::new(); + let names: Vec<_> = layers + .iter() + .map(|(property, _)| match property.filter(|_| split) { + Some(property) => { + let name = local(&property); + let count = used_names.entry(name).or_insert(0); + *count += 1; + if *count == 1 { format!("{title} {name}") } else { format!("{title} {name} ({count})") } + } + None => title.clone(), + }) + .collect(); + for (layer_name, (_, shapes)) in names.into_iter().zip(layers) { + let mut ds = Dataset::new(layer_name, GeometryType::None, fields.clone()); + let rep = finish_layer(&mut ds, shapes, &kind.rows, file_srs, transform.as_ref())?; + out.push(LayerRead::plain(ds, rep)); } - for (g, attrs) in kind.rows { - let g = g.map(|g| match &transform { - Some((_, true)) => g.map_coords(&|c| Coord::new(c.y, c.x)), - _ => g, + report_attributes(&mut notes, &title, &fields, kind); + if let Some([primary, siblings @ ..]) = out.get_mut(first..) { + let mut shared = file_notices.clone(); + shared.extend(notes.messages.iter().cloned()); + let shared = std::sync::Arc::new(shared); + primary.sibling_messages = Some(shared.clone()); + for layer in siblings { + layer.sibling_messages = Some(shared.clone()); + } + if first == 0 { + primary.report.messages.extend(file_notices.iter().cloned()); + } + primary.report.skipped = notes.skipped; + primary.report.messages.extend(notes.messages); + } + } + Ok(out) +} + +/// Bounds the new layers and the extra storage of attributes shared by their output rows. +struct SplitLimits<'a> { + layers: &'a mut usize, + rows_budget: &'a mut Option, + columns: usize, +} + +impl SplitLimits<'_> { + /// Charge the extra output row before materializing it, including its dense attribute slots + /// and room for row capacity. A source feature's first row is covered by the ordinary reader. + fn charge_row(&mut self, attrs: &BTreeMap, title: &str) -> Result<()> { + let remaining = self.rows_budget.get_or_insert_with(|| crate::memory::planned(256 << 20, 1 << 30, 1)); + let bytes = + attrs.values().fold(2 * std::mem::size_of::() + self.columns * std::mem::size_of::(), |bytes, text| { + bytes.saturating_add(text.len()) }); - // A place that can't be given in longitude/latitude is kept as the file holds it, and - // counted: its feature doesn't draw, and each step that needs longitude/latitude - // leaves it out and says so (#2032 C2f-4b). Its box in longitude/latitude from the - // rest. - let mut e = rustgis_geom::Extent::EMPTY; - let g = match (&transform, g) { - (Some((Some(t), _)), Some(g)) => { - let lonlat = std::cell::Cell::new(rustgis_geom::Extent::EMPTY); - let missing = std::cell::Cell::new(false); - let kept = g.map_coords(&|c| match t.to_lonlat(c) { - Some(l) if l.is_finite() => { - let mut b = lonlat.get(); - b.expand(l); - lonlat.set(b); - c - } - _ if !c.is_finite() => c, - _ => { - missing.set(true); - c - } - }); - unplaced += usize::from(missing.get()); - e = lonlat.get(); - // Converted, but beyond longitude/latitude: it draws out of place. - beyond += usize::from(!missing.get() && e.beyond_lonlat()); - Some(kept) + *remaining = remaining.checked_sub(bytes).ok_or_else(|| { + DataError::Format(format!("{title}: the geometry layers' additional rows exceed the memory budget. Import a smaller GML file.")) + })?; + Ok(()) + } +} + +/// Group compatible shapes by XML property, keeping a row with no readable shape once in +/// the first layer. The first layer of each feature type is reserved by the feature-type cap. +fn group_shapes<'a, 'input>( + rows: &mut [Row<'a, 'input>], + title: &str, + file_srs: Option<(Crs, bool)>, + unknown_srs: Option<&str>, + limits: &mut SplitLimits<'_>, + report: &mut ReadReport, +) -> Result>, ShapeLayer)>> { + let mut layers: Vec<(Option, ShapeLayer)> = Vec::new(); + let mut missing = Vec::new(); + let (mut mismatch, mut over) = (0, 0); + let (mut mismatched_names, mut capped_names) = (Names::default(), Names::default()); + for (i, row) in rows.iter_mut().enumerate() { + crate::progress::check()?; + let mut kept = false; + for shape in std::mem::take(&mut row.shapes) { + let property = shape.property; + if let Some(declared) = shape.declared_srs { + let matches = if file_srs.is_some() { shape.parsed_srs == file_srs } else { unknown_srs == Some(declared) }; + if !matches { + mismatch += 1; + mismatched_names.add(local(&property).to_string()); + continue; } - (_, g) => { - if let Some(g) = &g { - e = g.extent(); + } + let layer = match layers.iter().position(|(p, _)| p.is_some_and(|p| p.tag_name() == property.tag_name())) { + Some(i) => layers.get_mut(i), + None if layers.is_empty() || *limits.layers > 0 => { + if !layers.is_empty() { + *limits.layers -= 1; } - g + layers.push((Some(property), ShapeLayer::default())); + layers.last_mut() + } + None => { + over += 1; + capped_names.add(local(&property).to_string()); + continue; } }; - if !e.is_empty() { - outside |= e.min_x < -180.0 || e.max_x > 180.0 || e.min_y < -90.0 || e.max_y > 90.0; + if kept { + limits.charge_row(&row.attrs, title)?; } - let row = ds - .fields - .iter() - .enumerate() - .map(|(k, f)| match attrs.get(&f.name) { - Some(v) if Value::is_null_marker(v) => { - crate::source::null_text_at(&mut null_text, k); - Value::Null - } - Some(v) => Value::parse_file(v, f.ty), - None => Value::Null, - }) - .collect(); - ds.push_next(g, row); + if let Some((_, layer)) = layer { + layer.push(i, shape); + } + kept = true; } - ds.geometry_type = crate::io::dominant_type(&ds); - // The file's notices go with its first layer only. - let mut rep = if out.is_empty() { report.clone() } else { ReadReport::default() }; - // Features whose shape couldn't be read are said with their own feature type. - rep.skipped = kind.skipped; - if kind.skipped > 0 { - let what = if kind.skipped == 1 { "feature" } else { "features" }; - // Kept, without the geometry. - rep.messages.push(crate::loss::Note::loss( - crate::loss::LossCode::DroppedGeometry, - format!("{}: {} {what} had geometry that couldn't be read", ds.name, kind.skipped), - )); + if !kept { + missing.push((i, None)); } - if unplaced > 0 { - let what = if unplaced == 1 { "feature has" } else { "features have" }; - let system = file_srs.map_or_else(String::new, |(c, _)| format!(" in {}", c.label())); - rep.messages.push(format!( - "{}: {unplaced} {what} places{system} that can't be given in longitude/latitude; they are kept as the file holds them, but don't draw", - ds.name - )); + } + if mismatch > 0 { + let what = if mismatch == 1 { "property" } else { "properties" }; + report.messages.push(crate::loss::Note::loss( + crate::loss::LossCode::DroppedValue, + format!( + "{title}: {mismatch} geometry {what} not read: coordinate system or axis order differs from the layer's ({})", + mismatched_names.said() + ), + )); + } + if over > 0 { + let what = if over == 1 { "property" } else { "properties" }; + report.messages.push(crate::loss::Note::loss( + crate::loss::LossCode::DroppedOverLimit, + format!("{title}: {over} geometry {what} not read past the {MAX_LAYERS}-layer limit ({})", capped_names.said()), + )); + } + if let Some((_, first)) = layers.first_mut() { + if !missing.is_empty() { + first.rows.extend(missing); + first.rows.sort_by_key(|(i, _)| *i); } - if let Some((c, _)) = file_srs { - rep.messages.extend(crate::io::beyond_lonlat_note("features", beyond, c).map(|n| format!("{}: {n}", ds.name))); + } else { + // A type with no readable geometry is one table. + layers.push((None, ShapeLayer { rows: missing, ..Default::default() })); + } + Ok(layers) +} + +/// Builds one layer with the file's established placement and the losses for this geometry. +fn finish_layer( + ds: &mut Dataset, + shapes: ShapeLayer, + rows: &[Row<'_, '_>], + file_srs: Option<(Crs, bool)>, + transform: Option<&(Option, bool)>, +) -> Result { + let mut outside = false; + // Features with a place the file's system can't give in longitude/latitude, kept missing. + let (mut unplaced, mut beyond) = (0usize, 0usize); + // Held as the file holds its coordinates, in its own system (in the axis order RustGIS + // gives every system's), when RustGIS converts it. + if let Some((Some(_), _)) = transform + && let Some((c, _)) = file_srs + { + ds.held_in = c; + } + for (i, g) in shapes.rows { + crate::progress::check()?; + let Some(row) = rows.get(i) else { continue }; + let attrs = &row.attrs; + let g = g.map(|g| match transform { + Some((_, true)) => g.map_coords(&|c| Coord::new(c.y, c.x)), + _ => g, + }); + // A place that can't be given in longitude/latitude is kept as the file holds it, and + // counted: its feature doesn't draw, and each step that needs longitude/latitude + // leaves it out and says so (#2032 C2f-4b). Its box in longitude/latitude from the + // rest. + let mut e = rustgis_geom::Extent::EMPTY; + let g = match (transform, g) { + (Some((Some(t), _)), Some(g)) => { + let lonlat = std::cell::Cell::new(rustgis_geom::Extent::EMPTY); + let missing = std::cell::Cell::new(false); + let kept = g.map_coords(&|c| match t.to_lonlat(c) { + Some(l) if l.is_finite() => { + let mut b = lonlat.get(); + b.expand(l); + lonlat.set(b); + c + } + _ if !c.is_finite() => c, + _ => { + missing.set(true); + c + } + }); + unplaced += usize::from(missing.get()); + e = lonlat.get(); + // Converted, but beyond longitude/latitude: it draws out of place. + beyond += usize::from(!missing.get() && e.beyond_lonlat()); + Some(kept) + } + (_, g) => { + if let Some(g) = &g { + e = g.extent(); + } + g + } + }; + if !e.is_empty() { + outside |= e.min_x < -180.0 || e.max_x > 180.0 || e.min_y < -90.0 || e.max_y > 90.0; } - if file_srs.is_none() && outside { - rep.messages.push(crate::loss::Note::loss( - crate::loss::LossCode::AssumedCrs, - "the GML doesn't say its coordinate system (srsName) and its coordinates aren't longitude/latitude", + let row = ds + .fields + .iter() + .map(|f| match attrs.get(&f.name) { + Some(v) if Value::is_null_marker(v) => Value::Null, + Some(v) => Value::parse_file(v, f.ty), + None => Value::Null, + }) + .collect(); + ds.push_next(g, row); + } + ds.geometry_type = crate::io::dominant_type(ds); + let mut rep = ReadReport::default(); + if unplaced > 0 { + let what = if unplaced == 1 { "feature has" } else { "features have" }; + let system = file_srs.map_or_else(String::new, |(c, _)| format!(" in {}", c.label())); + rep.messages.push(format!( + "{}: {unplaced} {what} places{system} that can't be given in longitude/latitude; they are kept as the file holds them, but don't draw", + ds.name )); - } - // Said with the layer it happened in, which may be the only one added. - if kind.lost > 0 { - let what = - if kind.lost == 1 { "ring or surface patch of a geometry was" } else { "rings or surface patches of geometries were" }; - rep.messages.push(crate::loss::Note::loss(crate::loss::LossCode::DroppedRing, format!( + } + if let Some((c, _)) = file_srs { + rep.messages.extend(crate::io::beyond_lonlat_note("features", beyond, c).map(|n| format!("{}: {n}", ds.name))); + } + if file_srs.is_none() && outside { + rep.messages.push(crate::loss::Note::loss( + crate::loss::LossCode::AssumedCrs, + "the GML doesn't say its coordinate system (srsName) and its coordinates aren't longitude/latitude", + )); + } + // Said with the layer it happened in, which may be the only one added. + if shapes.lost > 0 { + let what = if shapes.lost == 1 { "ring or surface patch of a geometry was" } else { "rings or surface patches of geometries were" }; + rep.messages.push(crate::loss::Note::loss(crate::loss::LossCode::DroppedRing, format!( "{}: {} {what} left out: too few points, unreadable coordinates, a patch with no exterior ring or of a kind not read, or an exterior ring past the first", - ds.name, kind.lost + ds.name, shapes.lost ))); - } - if zm > 0 { - ds.zm_dropped = true; - rep.messages.push(crate::loss::Note::loss( - crate::loss::LossCode::DroppedZm, - format!("{}: {}", ds.name, crate::zm_note(Some(zm as u64))), - )); - } - if let Some(n) = crate::source::null_text_note(&ds.fields, &null_text) { - rep.messages.push(n.prefixed(&ds.name)); - } - if parts > 0 { - let what = if parts == 1 { "part" } else { "parts" }; - rep.messages.push(crate::loss::Note::loss( - crate::loss::LossCode::DroppedGeometry, - format!( - "{}: {parts} {what} of multi-geometries not read (a reference, too short, invalid coordinates, or of a kind not read)", - ds.name - ), - )); - } - if kind.approximated > 0 { - let what = if kind.approximated == 1 { "feature" } else { "features" }; - rep.messages.push(crate::loss::Note::loss( - crate::loss::LossCode::ApproximatedCurve, - format!( - "{}: {} {what} had curve segments approximated by their control points ({})", - ds.name, - kind.approximated, - kind.approximated_names.said() - ), - )); - } - if kind.centred > 0 { - let what = if kind.centred == 1 { "feature" } else { "features" }; - rep.messages.push(crate::loss::Note::loss(crate::loss::LossCode::ApproximatedCurve, format!( + } + if shapes.zm > 0 { + ds.zm_dropped = true; + rep.messages.push(crate::loss::Note::loss( + crate::loss::LossCode::DroppedZm, + format!("{}: {}", ds.name, crate::zm_note(Some(shapes.zm as u64))), + )); + } + let parts = shapes.parts_lost; + if parts > 0 { + let what = if parts == 1 { "part" } else { "parts" }; + rep.messages.push(crate::loss::Note::loss( + crate::loss::LossCode::DroppedGeometry, + format!( + "{}: {parts} {what} of multi-geometries not read (a reference, too short, invalid coordinates, or of a kind not read)", + ds.name + ), + )); + } + if shapes.approximated > 0 { + let what = if shapes.approximated == 1 { "feature" } else { "features" }; + rep.messages.push(crate::loss::Note::loss( + crate::loss::LossCode::ApproximatedCurve, + format!( + "{}: {} {what} had curve segments approximated by their control points ({})", + ds.name, + shapes.approximated, + shapes.approximated_names.said() + ), + )); + } + if shapes.centred > 0 { + let what = if shapes.centred == 1 { "feature" } else { "features" }; + rep.messages.push(crate::loss::Note::loss(crate::loss::LossCode::ApproximatedCurve, format!( "{}: {} {what} had curve segments given by a centre point (ArcByCenterPoint or CircleByCenterPoint): the centre was read as a vertex, so the line doesn't follow the curve there", - ds.name, kind.centred + ds.name, shapes.centred ))); + } + Ok(rep) +} + +/// Attribute loss belongs to the source feature and is reported once, even if it has several shapes. +fn report_attributes(rep: &mut ReadReport, name: &str, fields: &[Field], kind: Kind<'_, '_>) { + let (unread, unread_names) = (kind.unread, kind.unread_names.said()); + let mut null_text = Vec::new(); + for row in kind.rows { + for (field, _) in row.attrs.iter().filter(|(_, value)| Value::is_null_marker(value)) { + if let Some(i) = fields.iter().position(|f| f.name == *field) { + crate::source::null_text_at(&mut null_text, i); + } } - if unread > 0 { - let what = if unread == 1 { "property" } else { "properties" }; - rep.messages.push(crate::loss::Note::loss( - crate::loss::LossCode::DroppedValue, - format!("{}: {unread} {what} not read: nested records, other GML values or further shapes ({unread_names})", ds.name), - )); - } - if kind.repeated > 0 { - let what = if kind.repeated == 1 { "value" } else { "values" }; - rep.messages.push(crate::loss::Note::loss( - crate::loss::LossCode::DroppedValue, - format!( - "{}: {} {what} of repeated properties not read, only the last is kept ({})", - ds.name, - kind.repeated, - kind.repeated_names.said() - ), - )); - } - if kind.capped > 0 { - let what = if kind.capped == 1 { "value" } else { "values" }; - rep.messages.push(crate::loss::Note::loss( - crate::loss::LossCode::DroppedOverLimit, - format!( - "{}: {} {what} of properties past the first {MAX_COLUMNS} names not read ({})", - ds.name, - kind.capped, - kind.capped_names.said() - ), - )); - } - out.push((ds, rep)); } - Ok(out) + if let Some(n) = crate::source::null_text_note(fields, &null_text) { + rep.messages.push(n.prefixed(name)); + } + // Features whose shape couldn't be read are said with their own feature type. + rep.skipped = kind.skipped; + if kind.skipped > 0 { + let what = if kind.skipped == 1 { "feature" } else { "features" }; + // Kept, without the geometry. + rep.messages.push(crate::loss::Note::loss( + crate::loss::LossCode::DroppedGeometry, + format!("{}: {} {what} had geometry that couldn't be read", name, kind.skipped), + )); + } + if unread > 0 { + let what = if unread == 1 { "property" } else { "properties" }; + rep.messages.push(crate::loss::Note::loss( + crate::loss::LossCode::DroppedValue, + format!("{}: {unread} {what} not read: nested records, other GML values or further shapes ({unread_names})", name), + )); + } + if kind.repeated > 0 { + let what = if kind.repeated == 1 { "value" } else { "values" }; + rep.messages.push(crate::loss::Note::loss( + crate::loss::LossCode::DroppedValue, + format!( + "{}: {} {what} of repeated properties not read, only the last is kept ({})", + name, + kind.repeated, + kind.repeated_names.said() + ), + )); + } + if kind.capped > 0 { + let what = if kind.capped == 1 { "value" } else { "values" }; + rep.messages.push(crate::loss::Note::loss( + crate::loss::LossCode::DroppedOverLimit, + format!( + "{}: {} {what} of properties past the first {MAX_COLUMNS} names not read ({})", + name, + kind.capped, + kind.capped_names.said() + ), + )); + } } #[cfg(test)] @@ -1117,8 +1305,8 @@ mod tests { ); } - /// Properties that aren't attributes (a nested record, a time, a second shape) are said on - /// their own feature type's layer, counted. + /// Properties that aren't attributes (a nested record and a time) are said once for their + /// own feature type. A second readable geometry gets a layer. #[test] fn unread_properties_are_said_on_their_layer() { let gml = r#" @@ -1132,11 +1320,16 @@ mod tests { assert!(!layers[0].1.messages.iter().any(|m| m.contains("not read")), "{:?}", layers[0].1.messages); let (ds, rep) = &layers[1]; assert_eq!(ds.features.len(), 1); - // The first shape is the one kept; the second is said as not read. assert_eq!(ds.features[0].geometry, Some(Geometry::Point(Coord::new(10.0, 48.0)))); + let (entrance, report) = &layers[2]; + assert_eq!(entrance.name, "t parks entrance"); + assert_eq!(entrance.features.len(), 1); + assert_eq!(entrance.features[0].geometry, Some(Geometry::Point(Coord::new(10.0, 49.0)))); + assert!(report.messages.is_empty(), "{:?}", report.messages); assert!( - rep.messages.iter().any(|m| m.as_str() - == "t parks: 3 properties not read: nested records, other GML values or further shapes (owner, built, entrance)"), + rep.messages + .iter() + .any(|m| m.as_str() == "t parks: 2 properties not read: nested records, other GML values or further shapes (owner, built)"), "{:?}", rep.messages ); @@ -1206,6 +1399,65 @@ mod tests { ) } + /// An application collection with a label before the parcel boundary. Nested members are + /// properties of a feature, and a zip reads the same GML layers and notices as the loose file. + #[test] + fn schema_members_keep_the_label_and_boundary_in_separate_layers() { + let parcel = r#"P-1 +5.1 52.1 + +5 52 5.2 52 5.2 52.2 5 52 + +{history}"#; + let history = ""; + for history in [history, ""] { + let parcel = parcel.replace("{history}", history); + let gml = doc(&format!("{parcel}")); + let zip = crate::zip::write(&[("parcels.gml".into(), gml.as_bytes().to_vec())]).unwrap(); + for (file, bytes) in [("parcels.gml", gml.as_bytes()), ("parcels.zip", zip.as_slice())] { + let layers = crate::io::read_layers(file, bytes).unwrap(); + assert_eq!(layers.len(), 2); + for (property, expected) in [("plaatscoordinaten", GeometryType::Point), ("begrenzingPerceel", GeometryType::Polygon)] { + let layer = layers.iter().find(|l| l.dataset.name == format!("parcels {property}")).unwrap(); + assert_eq!(layer.dataset.geometry_type, expected); + assert_eq!(layer.dataset.features.len(), 1); + let id = layer.dataset.field_index("identificatie").unwrap(); + assert_eq!(layer.dataset.value(0, id), &Value::Text("P-1".into())); + } + let notes: Vec<_> = layers.iter().flat_map(|l| l.report.messages.iter()).collect(); + if history.is_empty() { + assert!(notes.is_empty(), "{notes:?}"); + } else { + assert_eq!(notes.len(), 1, "{notes:?}"); + assert_eq!(notes[0].loss, Some(crate::loss::LossCode::DroppedValue)); + assert!(notes[0].ends_with(": 1 property not read: nested records, other GML values or further shapes (historie)")); + } + } + } + } + + /// A differently placed geometry is counted as unread before any layer is built for it. + #[test] + fn a_geometry_property_in_a_different_coordinate_system_is_said() { + let gml = doc(r#" +5.1 52.1 + +124000 455000 125000 455000 125000 456000 124000 455000 + +"#); + let layers = read("parcels.gml", gml.as_bytes()).unwrap(); + assert_eq!(layers.len(), 1); + let (layer, report) = &layers[0]; + assert_eq!(layer.features.len(), 1); + assert_eq!(layer.features[0].geometry, Some(Geometry::Point(Coord::new(5.1, 52.1)))); + assert_eq!(report.messages.len(), 1); + assert_eq!(report.messages[0].loss, Some(crate::loss::LossCode::DroppedValue)); + assert_eq!( + report.messages[0].as_str(), + "parcels: 1 geometry property not read: coordinate system or axis order differs from the layer's (begrenzingPerceel)" + ); + } + fn said(layer: &(Dataset, ReadReport), what: &str) -> bool { layer.1.messages.iter().any(|m| m.contains(what)) } diff --git a/crates/data/src/io.rs b/crates/data/src/io.rs index 66e8e72122..09e5e9fb88 100644 --- a/crates/data/src/io.rs +++ b/crates/data/src/io.rs @@ -230,6 +230,16 @@ pub struct LayerRead { pub dataset: Dataset, pub report: ReadReport, pub styles: Vec<(String, crate::kml::Style)>, + /// Notices shared with other layers from this file. When present, Add Data can pick a layer + /// using these notices and its own report, without borrowing another layer's report. + pub sibling_messages: Option>, +} + +impl LayerRead { + /// A layer read without styles or notices shared with other layers. + pub fn plain(dataset: Dataset, report: ReadReport) -> Self { + Self { dataset, report, styles: Vec::new(), sibling_messages: None } + } } /// Whether a file holds several layers ([`read_layers`] reads them all): a zip, KML, KMZ, GPX or @@ -278,8 +288,9 @@ fn read_city_member(file_name: &str, bytes: &[u8], crs: Option) -> Result Result> { @@ -293,13 +304,12 @@ pub fn read_layers(file_name: &str, bytes: &[u8]) -> Result> { if bytes.len() as u64 > max { return Err(DataError::Format(file_size_error(file_name, max))); } - let plain = - |v: Vec<(Dataset, ReadReport)>| v.into_iter().map(|(dataset, report)| LayerRead { dataset, report, styles: Vec::new() }).collect(); + let plain = |v: Vec<(Dataset, ReadReport)>| v.into_iter().map(|(d, r)| LayerRead::plain(d, r)).collect(); let mut out: Vec = match ext.as_str() { "zip" => read_zip_layers(file_name, bytes, &CsvOptions::default())?, "kml" | "kmz" => crate::kml::read(file_name, bytes)? .into_iter() - .map(|l| LayerRead { dataset: l.dataset, report: l.report, styles: l.styles }) + .map(|l| LayerRead { dataset: l.dataset, report: l.report, styles: l.styles, sibling_messages: None }) .collect(), "gpx" => plain(crate::gpx::read(file_name, bytes)?), "rss" | "atom" | "georss" => plain(crate::georss::read(file_name, bytes)?), @@ -318,7 +328,7 @@ pub fn read_layers(file_name: &str, bytes: &[u8]) -> Result> { } else if text.contains(" Result> { } // A CityGML city model, or the features of a collection. "gml" if crate::citygml::looks_like_citygml(bytes) => plain(crate::citygml::read(file_name, bytes, None)?), - "gml" => plain(crate::gml::read(file_name, bytes)?), + "gml" => crate::gml::read_layers(file_name, bytes)?, "dxf" => plain(crate::dxf::read(file_name, bytes, &crate::dxf::Options::default())?), // OpenStreetMap PBF, not a vector tile (`.pbf` too). "pbf" if crate::osm::looks_like_osm_pbf(bytes) => plain(crate::osm::read(file_name, bytes)?), @@ -4147,7 +4157,7 @@ fn read_zip_layers_budget(file_name: &str, bytes: &[u8], opts: &CsvOptions, budg match read_shapefile_parts(ShapefileParts { shp, shx, dbf, prj, cpg }, &name, crs) { Ok((mut dataset, report)) => { dataset.source = Some(format!("{file_name}/{n}")); - out.push(LayerRead { dataset, report, styles: Vec::new() }); + out.push(LayerRead::plain(dataset, report)); } Err(DataError::Cancelled) => return Err(DataError::Cancelled), Err(e) => skipped.push(format!("{n} ({e})")), @@ -4169,7 +4179,7 @@ fn read_zip_layers_budget(file_name: &str, bytes: &[u8], opts: &CsvOptions, budg match crate::mapinfo::read_bytes(&mif, mid.as_deref(), &name) { Ok((mut dataset, report)) => { dataset.source = Some(format!("{file_name}/{n}")); - out.push(LayerRead { dataset, report, styles: Vec::new() }); + out.push(LayerRead::plain(dataset, report)); } Err(DataError::Cancelled) => return Err(DataError::Cancelled), Err(e) => skipped.push(format!("{n} ({e})")), @@ -4204,9 +4214,7 @@ fn read_zip_layers_budget(file_name: &str, bytes: &[u8], opts: &CsvOptions, budg continue; } let leaf = n.rsplit('/').next().unwrap_or(&n); - let plain = |reads: Vec<(Dataset, ReadReport)>| { - reads.into_iter().map(|(dataset, report)| LayerRead { dataset, report, styles: Vec::new() }).collect::>() - }; + let plain = |reads: Vec<(Dataset, ReadReport)>| reads.into_iter().map(|(d, r)| LayerRead::plain(d, r)).collect::>(); let mut table = false; // A city model has many layers. let read = if ext_of(&n) == "dbf" { diff --git a/crates/engine/src/cmd/layer.rs b/crates/engine/src/cmd/layer.rs index c5d55e0d74..59a6764f05 100644 --- a/crates/engine/src/cmd/layer.rs +++ b/crates/engine/src/cmd/layer.rs @@ -1957,8 +1957,7 @@ fn add_geodatabase(s: &mut Session, p: &Value, path: &str) -> CmdResult { } Err(e) => return Err(format!("{path}: {e}")), }; - let reads = - read.layers.into_iter().map(|(dataset, report)| rustgis_data::io::LayerRead { dataset, report, styles: Vec::new() }).collect(); + let reads = read.layers.into_iter().map(|(dataset, report)| rustgis_data::io::LayerRead::plain(dataset, report)).collect(); // The tables read, then those it couldn't read (compressed, raster fields), through GDAL when it // is installed; else, or if GDAL can't either, said. The second go on whether the first added. let mut results: Vec = Vec::new(); @@ -2275,7 +2274,7 @@ fn city_reads(file_name: &str, bytes: &[u8], crs: Option match rustgis_data::io::read_layers(file_name, bytes) { @@ -2885,13 +2884,15 @@ fn add_picked( let pick = |n: &str| n.eq_ignore_ascii_case(want) || n.rsplit(' ').next().is_some_and(|w| w.eq_ignore_ascii_case(want)); // A city model's first layer holds what the file as a whole says, after its own one // notice: that its heights were dropped (it has no other). OSM has no such height notice. - // In a zip, a model is the one member that gives several layers, and it says so for its own layers only. + // A zip member can give several layers. When the reader provides shared notices, + // those are restored below instead of borrowing its first layer's report. let same = |a: &rustgis_data::io::LayerRead, b: &rustgis_data::io::LayerRead| a.dataset.source == b.dataset.source; let file_wide: Vec<(Option, rustgis_data::ReadReport)> = reads .iter() .enumerate() .filter(|(i, r)| { !pick(&r.dataset.name) + && r.sibling_messages.is_none() && !reads.iter().take(*i).any(|o| same(o, r)) && (whole || (lower.ends_with(".zip") && reads.iter().skip(i + 1).any(|o| same(o, r)))) }) @@ -2933,10 +2934,30 @@ fn add_picked( kept.report.skipped += said.skipped; } } + restore_sibling_notices(&mut reads); } add_reads(s, p, file_name, reads, overlays, zoom) } +/// Restore shared reports on a selected sibling and avoid repeating notices already carried by +/// the zip or another selected layer of the same source. +fn restore_sibling_notices(reads: &mut [rustgis_data::io::LayerRead]) { + if reads.iter().all(|r| r.sibling_messages.is_none()) { + return; + } + let mut seen: std::collections::HashSet<_> = + reads.iter().flat_map(|r| r.report.messages.iter().map(move |n| (r.dataset.source.clone(), n.clone()))).collect(); + for read in reads { + if let Some(notes) = read.sibling_messages.take() { + for note in notes.iter() { + if seen.insert((read.dataset.source.clone(), note.clone())) { + read.report.messages.push(note.clone()); + } + } + } + } +} + /// Adds the layers a file gave and its ground overlays: a layer that can't be added is skipped /// and said, the others are still added. A name given goes to the first layer added. The /// overlays go in first and the layers bottom first ([`stack_rank`]), so no image or polygon @@ -8423,6 +8444,52 @@ mod tests { use crate::Session; use serde_json::json; + /// A geometry selected from a loose file or a zip still reports its source feature's unread + /// properties. Adding both geometry layers says that once as well. + #[test] + fn gml_selected_geometry_has_its_shared_notices() { + use base64::Engine; + use rustgis_data::loss::LossCode; + + let gml = r#" + +10 48 + +10.1 48 +Ann + +"#; + let zip = rustgis_data::zip::write(&[("parks.gml".into(), gml.as_bytes().to_vec())]).unwrap(); + let zip = base64::engine::general_purpose::STANDARD.encode(zip); + for (cmd, params) in [ + ("layer.addDataText", json!({"fileName": "parks.gml", "text": gml})), + ("layer.addDataBytes", json!({"fileName": "parks.zip", "data": zip})), + ] { + for pick in [false, true] { + let mut s = Session::new(crate::Project::default()); + let mut params = params.clone(); + if pick { + params["layer"] = json!("parks entrance"); + } + let mark = s.notice_mark(); + s.run(cmd, ¶ms).unwrap(); + assert_eq!(s.map().layers.len(), if pick { 1 } else { 2 }); + assert!(s.map().layer_by_name("parks entrance").is_some()); + let notices: Vec<_> = s.notices_since(mark).iter().filter(|n| n.loss() == Some(LossCode::DroppedValue)).collect(); + assert_eq!(notices.len(), 1, "{notices:?}"); + assert_eq!(notices[0].text, "parks: 1 property not read: nested records, other GML values or further shapes (owner)"); + let geometry_notices: Vec<_> = + s.notices_since(mark).iter().filter(|n| n.loss() == Some(LossCode::DroppedGeometry)).collect(); + if pick { + assert!(geometry_notices.is_empty(), "{geometry_notices:?}"); + } else { + assert_eq!(geometry_notices.len(), 1, "{geometry_notices:?}"); + assert!(geometry_notices[0].text.starts_with("parks label: 1 part of multi-geometries not read")); + } + } + } + } + /// A GDAL conversion's parts say their Z or M values once for each kind: a part alone in a /// fresh conversion's words, several counted together; parts without any say nothing. #[cfg(not(target_arch = "wasm32"))] diff --git a/docs/user-guide/data-formats.md b/docs/user-guide/data-formats.md index 04344f7b15..13bc4c342d 100644 --- a/docs/user-guide/data-formats.md +++ b/docs/user-guide/data-formats.md @@ -28,7 +28,7 @@ export names its feature. | GeoRSS | `.rss`, `.atom`, `.georss`, or `.xml` | Add Data, drop the file, upload, or From URL… | RSS 2.0, RSS 1.0 and Atom feeds with GeoRSS Simple, GeoRSS GML or W3C Basic Geo places: points, lines and polygons layers with each item's title, link, description, date, id and category. | | LandXML | `.landxml`, or `.xml` | Add Data, drop the file, or upload | Coordinate geometry points, parcels (polygons), alignments (lines; curves as chords) and TIN surfaces (a triangle per face, with its mean elevation), converted from the file's `epsgCode` or `"crs"`. | | Encoded polylines | text | `layer.addEncodedPolyline` with `"polyline"` (one or a list) | Google's encoding, precision 5, or 6 (`"precision"`) as OSRM and Valhalla can give: a line layer. | -| GML | `.gml` | Add Data, drop the file, or upload | Simple features in GML 2 and 3 (WFS answers, OGR's GML): a layer per feature type, its simple elements as fields (a property holding nested values, another GML value or a second shape isn't read, and is said). Converted from the `srsName` (EPSG codes, URNs and URLs; the URN and URL forms of geographic systems are latitude first). Arcs and other curve segments are approximated through their control points, and said; a segment given by a centre point (`ArcByCenterPoint`, `CircleByCenterPoint`) has its centre read as a vertex instead, so the line doesn't follow the curve there, also said (a curve with only such a segment has too few positions for a line, and is kept without geometry, said as not read). | +| GML | `.gml` | Add Data, drop the file, or upload | Simple features in GML 2 and 3, including collections with application-specific `Member` or `Members` elements. Each feature type gives a layer, with simple properties as fields. When several geometry properties can be read, each gives a layer named for that property. A notice names unread properties, including nested values and geometries that declare a different coordinate system or axis order from the one used by the file. Converted from the `srsName` (EPSG codes, URNs and URLs; the URN and URL forms of geographic systems are latitude first). Arcs and other curve segments are approximated through their control points, and said; a segment given by a centre point (`ArcByCenterPoint`, `CircleByCenterPoint`) has its centre read as a vertex instead, so the line doesn't follow the curve there, also said (a curve with only such a segment has too few positions for a line, and is kept without geometry, said as not read). | | MapInfo Interchange | `.mif` with its `.mid` (or both zipped) | Add Data, drop the file, or upload the zip | Points, lines, polylines, regions (holes found by nesting), rectangles and ellipses; text and arcs are rows without geometry. Converted from the `CoordSys`: longitude/latitude, Transverse Mercator, Lambert Conformal Conic, Albers or Mercator. A loose `.mif` upload has no `.mid` attributes; zip both files to keep them in the web app. | | OpenStreetMap PBF | `.osm.pbf`, or `.pbf` containing OSM data | Add Data, drop the file, or upload | Points (tagged nodes), lines and multipolygons (closed ways that are areas, also with a lifecycle prefix such as `destroyed:building` or `demolished:building`; a closed road or barrier, prefixed or not, is a line unless it has `area=yes`, as from Overpass; and multipolygon and boundary relations), with common tags as fields and the rest in `other_tags`, as GDAL gives them. In the native reader, sub-relation members are not expanded; omissions are counted when the parent relation still yields a polygon. Within the relation limit, the native reader refuses a file holding a multipolygon or boundary relation whose member-ID, role and type arrays differ in length. Up to 40 million nodes (4 million in the web app); on the desktop, extracts over 256 MiB open through GDAL when it is installed, which follows its own configuration instead: a closed way whose only area key has a lifecycle prefix is a line there (one with `area=yes` is still a polygon), and a closed road or barrier with an area key such as `landuse` is a polygon. Vector-tile `.pbf` files use Add Tile Layer instead. | | ArcGIS feature-service answers (protocol buffer) | `.pbf` holding an answer to an ArcGIS query with `f=pbf`, or the query's address | Add Data, drop the file, upload, or From URL… with the query's address (`…/FeatureServer/0/query?…&f=pbf`) | One page of the layer: the fields and values the same query gives as GeoJSON, with the fields' aliases as their display names (dates as milliseconds since 1970, date-only and time values as text), points, lines or polygons held in the answer's coordinate system when RustGIS reads it. Z and M values, geometry, blob and raster fields are left out, with a notice. A page that stopped at the service's record limit keeps its features, with a notice that the rest aren't in it. A query the service refuses (an empty answer), a count, ids or an extent, curves, multipatches and envelopes give an error. Told from OpenStreetMap data by its content. | From 8db18f41213164d4ff7600dcdea93290e24c563e Mon Sep 17 00:00:00 2001 From: mavrick Date: Sat, 28 Nov 2026 12:37:48 -0600 Subject: [PATCH 2/4] fix(data): preserve GML primary geometries and bound split rows --- crates/data/src/gml.rs | 347 +++++++++++++++++++++++--------- crates/data/src/io.rs | 46 ++++- crates/engine/src/cmd/layer.rs | 32 ++- docs/user-guide/data-formats.md | 2 +- 4 files changed, 321 insertions(+), 106 deletions(-) diff --git a/crates/data/src/gml.rs b/crates/data/src/gml.rs index f0329c1f17..b9bfe40295 100644 --- a/crates/data/src/gml.rs +++ b/crates/data/src/gml.rs @@ -11,7 +11,7 @@ //! can't be read are counted. use std::cell::{Cell, OnceCell}; -use std::collections::{BTreeMap, HashSet}; +use std::collections::{BTreeMap, HashMap, HashSet}; use roxmltree::{Node, ParsingOptions}; use rustgis_geom::Coord; @@ -516,15 +516,16 @@ impl ShapeLayer { /// member is part of that feature, just as a nested member inside a standard member is. fn collection_features<'a, 'input>(root: Node<'a, 'input>) -> Vec> { let standard = |n: &Node| n.is_element() && matches!(local(n), "featureMember" | "featureMembers" | "member" | "members"); + let allow_custom = !is_gml(&root) || local(&root) == "FeatureCollection"; let custom = |n: &Node| { - n.is_element() && n.parent() == Some(root) && { + allow_custom && n.is_element() && n.parent() == Some(root) && { let name = local(n); - name.ends_with("Member") || name.ends_with("Members") + name != "cityObjectMember" && (name.ends_with("Member") || name.ends_with("Members")) } }; let mut members: Vec<_> = root.descendants().filter(|n| standard(n) && n.ancestors().skip(1).all(|a| !standard(&a) && !custom(&a))).collect(); - if members.is_empty() && !(is_gml(&root) && is_shape(local(&root))) { + if members.is_empty() { members.extend(root.children().filter(custom)); } members @@ -542,6 +543,11 @@ pub fn read(file_name: &str, bytes: &[u8]) -> Result> /// Reads a GML file into layers by feature type and geometry property. Cancel is checked between /// features. Parsing the whole document first is one step without a check. pub(crate) fn read_layers(file_name: &str, bytes: &[u8]) -> Result> { + read_layers_with_budget(file_name, bytes, None) +} + +/// Reads all primary rows with a shared allowance for rows copied into geometry siblings. +fn read_layers_with_budget(file_name: &str, bytes: &[u8], mut extra_rows_budget: Option) -> Result> { let stem = std::path::Path::new(file_name).file_stem().and_then(|s| s.to_str()).unwrap_or("gml").to_string(); let text = std::str::from_utf8(bytes).map_err(|_| DataError::Format(format!("{file_name} is not UTF-8 text")))?; let opts = ParsingOptions { allow_dtd: false, nodes_limit: crate::io::XML_NODES, ..ParsingOptions::default() }; @@ -568,7 +574,8 @@ pub(crate) fn read_layers(file_name: &str, bytes: &[u8]) -> Result> = Vec::new(); + let mut further_properties = HashSet::new(); // Properties listed as unread are counted in document order. If no shape could be // decoded, the first failed property is accounted for by the feature's skipped count. let mut unread = Vec::new(); @@ -580,23 +587,27 @@ pub(crate) fn read_layers(file_name: &str, bytes: &[u8]) -> Result { - if shapes.is_empty() - && parsed_srs.is_none() - && let Some(s) = declared_srs - { - unknown_srs = Some(s.to_string()); + // Only a feature's first decoded geometry can establish the file's system. + if shapes.is_empty() { + shapes.reserve_exact(1); + if let Some(found) = parsed_srs { + file_srs.get_or_insert(found); + } else if let Some(s) = declared_srs { + unknown_srs = Some(s.to_string()); + } + } else { + further_properties.insert(key); } shapes.push(Shape { property: p, node: g, geometry, declared_srs, parsed_srs, zm: dims.get(), lost: lost.get() }); } @@ -666,7 +677,7 @@ pub(crate) fn read_layers(file_name: &str, bytes: &[u8]) -> Result Result 1; let first = out.len(); - let mut used_names = BTreeMap::new(); - let names: Vec<_> = layers - .iter() - .map(|(property, _)| match property.filter(|_| split) { - Some(property) => { - let name = local(&property); - let count = used_names.entry(name).or_insert(0); - *count += 1; - if *count == 1 { format!("{title} {name}") } else { format!("{title} {name} ({count})") } - } + report_attributes(&mut notes, &title, &fields, &kind)?; + let last = layers.len().saturating_sub(1); + for (i, (property, shapes)) in layers.into_iter().enumerate() { + let base = match property.filter(|_| split) { + Some(property) => format!("{title} {}", local(&property)), None => title.clone(), - }) - .collect(); - for (layer_name, (_, shapes)) in names.into_iter().zip(layers) { + }; + let mut layer_name = base.clone(); + let mut suffix = 2; + while !used_names.insert(layer_name.to_ascii_lowercase()) { + layer_name = format!("{base} ({suffix})"); + suffix += 1; + } let mut ds = Dataset::new(layer_name, GeometryType::None, fields.clone()); - let rep = finish_layer(&mut ds, shapes, &kind.rows, file_srs, transform.as_ref())?; + let rep = finish_layer(&mut ds, shapes, &mut kind.rows, i == last, file_srs, transform.as_ref())?; out.push(LayerRead::plain(ds, rep)); } - report_attributes(&mut notes, &title, &fields, kind); if let Some([primary, siblings @ ..]) = out.get_mut(first..) { - let mut shared = file_notices.clone(); - shared.extend(notes.messages.iter().cloned()); + let mut shared = ReadReport { skipped: notes.skipped, messages: file_notices.clone(), ..Default::default() }; + shared.messages.extend(notes.messages.iter().cloned()); let shared = std::sync::Arc::new(shared); - primary.sibling_messages = Some(shared.clone()); + primary.sibling_report = Some(shared.clone()); for layer in siblings { - layer.sibling_messages = Some(shared.clone()); + layer.sibling_report = Some(shared.clone()); } if first == 0 { primary.report.messages.extend(file_notices.iter().cloned()); @@ -735,16 +744,22 @@ struct SplitLimits<'a> { impl SplitLimits<'_> { /// Charge the extra output row before materializing it, including its dense attribute slots /// and room for row capacity. A source feature's first row is covered by the ordinary reader. - fn charge_row(&mut self, attrs: &BTreeMap, title: &str) -> Result<()> { + fn charge_row(&mut self, attrs: &BTreeMap) -> bool { let remaining = self.rows_budget.get_or_insert_with(|| crate::memory::planned(256 << 20, 1 << 30, 1)); + if *remaining == 0 { + return false; + } let bytes = attrs.values().fold(2 * std::mem::size_of::() + self.columns * std::mem::size_of::(), |bytes, text| { bytes.saturating_add(text.len()) }); - *remaining = remaining.checked_sub(bytes).ok_or_else(|| { - DataError::Format(format!("{title}: the geometry layers' additional rows exceed the memory budget. Import a smaller GML file.")) - })?; - Ok(()) + if let Some(left) = remaining.checked_sub(bytes) { + *remaining = left; + true + } else { + *remaining = 0; + false + } } } @@ -760,39 +775,50 @@ fn group_shapes<'a, 'input>( ) -> Result>, ShapeLayer)>> { let mut layers: Vec<(Option, ShapeLayer)> = Vec::new(); let mut missing = Vec::new(); - let (mut mismatch, mut over) = (0, 0); - let (mut mismatched_names, mut capped_names) = (Names::default(), Names::default()); + let (mut mismatch, mut unset, mut over, mut over_budget) = (0, 0, 0, 0); + let (mut mismatched_names, mut unset_names, mut capped_names, mut budget_names) = + (Names::default(), Names::default(), Names::default(), Names::default()); for (i, row) in rows.iter_mut().enumerate() { crate::progress::check()?; let mut kept = false; - for shape in std::mem::take(&mut row.shapes) { + for (shape_index, shape) in std::mem::take(&mut row.shapes).into_iter().enumerate() { let property = shape.property; - if let Some(declared) = shape.declared_srs { + if shape_index > 0 + && let Some(declared) = shape.declared_srs + { let matches = if file_srs.is_some() { shape.parsed_srs == file_srs } else { unknown_srs == Some(declared) }; if !matches { - mismatch += 1; - mismatched_names.add(local(&property).to_string()); + if file_srs.is_none() && unknown_srs.is_none() { + unset += 1; + unset_names.add(local(&property).to_string()); + } else { + mismatch += 1; + mismatched_names.add(local(&property).to_string()); + } continue; } } - let layer = match layers.iter().position(|(p, _)| p.is_some_and(|p| p.tag_name() == property.tag_name())) { + let index = layers.iter().position(|(p, _)| p.is_some_and(|p| p.tag_name() == property.tag_name())); + if index.is_none() && !layers.is_empty() && *limits.layers == 0 { + over += 1; + capped_names.add(local(&property).to_string()); + continue; + } + if kept && !limits.charge_row(&row.attrs) { + over_budget += 1; + budget_names.add(local(&property).to_string()); + continue; + } + let layer = match index { Some(i) => layers.get_mut(i), - None if layers.is_empty() || *limits.layers > 0 => { + None => { if !layers.is_empty() { *limits.layers -= 1; } layers.push((Some(property), ShapeLayer::default())); layers.last_mut() } - None => { - over += 1; - capped_names.add(local(&property).to_string()); - continue; - } }; - if kept { - limits.charge_row(&row.attrs, title)?; - } if let Some((_, layer)) = layer { layer.push(i, shape); } @@ -812,6 +838,20 @@ fn group_shapes<'a, 'input>( ), )); } + if unset > 0 { + let what = if unset == 1 { "property" } else { "properties" }; + report.messages.push(crate::loss::Note::loss( + crate::loss::LossCode::DroppedValue, + format!("{title}: {unset} geometry {what} not read: the layer has no declared coordinate system ({})", unset_names.said()), + )); + } + if over_budget > 0 { + let what = if over_budget == 1 { "property" } else { "properties" }; + report.messages.push(crate::loss::Note::loss( + crate::loss::LossCode::DroppedOverLimit, + format!("{title}: {over_budget} geometry {what} not read past the additional-row memory budget ({})", budget_names.said()), + )); + } if over > 0 { let what = if over == 1 { "property" } else { "properties" }; report.messages.push(crate::loss::Note::loss( @@ -835,7 +875,8 @@ fn group_shapes<'a, 'input>( fn finish_layer( ds: &mut Dataset, shapes: ShapeLayer, - rows: &[Row<'_, '_>], + rows: &mut [Row<'_, '_>], + last: bool, file_srs: Option<(Crs, bool)>, transform: Option<&(Option, bool)>, ) -> Result { @@ -851,8 +892,16 @@ fn finish_layer( } for (i, g) in shapes.rows { crate::progress::check()?; - let Some(row) = rows.get(i) else { continue }; - let attrs = &row.attrs; + let Some(row) = rows.get_mut(i) else { continue }; + // Each row appears at most once in a property layer. The final layer can take + // ownership of its attributes and free them as it builds. + let owned; + let attrs = if last { + owned = std::mem::take(&mut row.attrs); + &owned + } else { + &row.attrs + }; let g = g.map(|g| match transform { Some((_, true)) => g.map_coords(&|c| Coord::new(c.y, c.x)), _ => g, @@ -864,26 +913,16 @@ fn finish_layer( let mut e = rustgis_geom::Extent::EMPTY; let g = match (transform, g) { (Some((Some(t), _)), Some(g)) => { - let lonlat = std::cell::Cell::new(rustgis_geom::Extent::EMPTY); - let missing = std::cell::Cell::new(false); - let kept = g.map_coords(&|c| match t.to_lonlat(c) { - Some(l) if l.is_finite() => { - let mut b = lonlat.get(); - b.expand(l); - lonlat.set(b); - c - } - _ if !c.is_finite() => c, - _ => { - missing.set(true); - c - } + let mut missing = false; + g.for_each_coord(|c| match t.to_lonlat(c) { + Some(l) if l.is_finite() => e.expand(l), + _ if c.is_finite() => missing = true, + _ => {} }); - unplaced += usize::from(missing.get()); - e = lonlat.get(); + unplaced += usize::from(missing); // Converted, but beyond longitude/latitude: it draws out of place. - beyond += usize::from(!missing.get() && e.beyond_lonlat()); - Some(kept) + beyond += usize::from(!missing && e.beyond_lonlat()); + Some(g) } (_, g) => { if let Some(g) = &g { @@ -895,15 +934,7 @@ fn finish_layer( if !e.is_empty() { outside |= e.min_x < -180.0 || e.max_x > 180.0 || e.min_y < -90.0 || e.max_y > 90.0; } - let row = ds - .fields - .iter() - .map(|f| match attrs.get(&f.name) { - Some(v) if Value::is_null_marker(v) => Value::Null, - Some(v) => Value::parse_file(v, f.ty), - None => Value::Null, - }) - .collect(); + let row = ds.fields.iter().map(|f| attrs.get(&f.name).map_or(Value::Null, |v| Value::parse_file(v, f.ty))).collect(); ds.push_next(g, row); } ds.geometry_type = crate::io::dominant_type(ds); @@ -974,12 +1005,14 @@ fn finish_layer( } /// Attribute loss belongs to the source feature and is reported once, even if it has several shapes. -fn report_attributes(rep: &mut ReadReport, name: &str, fields: &[Field], kind: Kind<'_, '_>) { +fn report_attributes(rep: &mut ReadReport, name: &str, fields: &[Field], kind: &Kind<'_, '_>) -> Result<()> { let (unread, unread_names) = (kind.unread, kind.unread_names.said()); + let index: HashMap<_, _> = fields.iter().enumerate().map(|(i, f)| (f.name.as_str(), i)).collect(); let mut null_text = Vec::new(); - for row in kind.rows { + for row in &kind.rows { + crate::progress::check()?; for (field, _) in row.attrs.iter().filter(|(_, value)| Value::is_null_marker(value)) { - if let Some(i) = fields.iter().position(|f| f.name == *field) { + if let Some(&i) = index.get(field.as_str()) { crate::source::null_text_at(&mut null_text, i); } } @@ -1028,6 +1061,7 @@ fn report_attributes(rep: &mut ReadReport, name: &str, fields: &[Field], kind: K ), )); } + Ok(()) } #[cfg(test)] @@ -1458,6 +1492,137 @@ mod tests { ); } + fn point_property(name: &str, position: &str, system: &str) -> String { + let srs = if system.is_empty() { String::new() } else { format!(r#" srsName="{system}""#) }; + format!("{position}") + } + + fn parcel(properties: &str) -> String { + format!("{properties}") + } + + #[test] + fn repeating_a_geometry_property_keeps_the_first_shape_once() { + let first = point_property("label", "5 52", ""); + let repeated = point_property("label", "6 53", ""); + for (properties, expected) in [(first.clone(), None), (first + &repeated, Some("1 property"))] { + let layers = read("parcels.gml", doc(&parcel(&properties)).as_bytes()).unwrap(); + let [(ds, report)] = layers.as_slice() else { panic!("expected one layer") }; + assert_eq!(ds.features.len(), 1); + assert_eq!(ds.features[0].geometry, Some(Geometry::Point(Coord::new(5.0, 52.0)))); + if let Some(expected) = expected { + assert_eq!(report.messages.len(), 1); + assert_eq!(report.messages[0].loss, Some(crate::loss::LossCode::DroppedValue)); + assert!(report.messages[0].contains(expected) && report.messages[0].ends_with("(label)")); + } else { + assert!(report.messages.is_empty()); + } + } + } + + #[test] + fn feature_members_with_one_shape_each_keep_the_file_wide_axis_order() { + for (first, second, expected_note) in [ + ("EPSG:4326", "urn:ogc:def:crs:EPSG::4326", None), + ("unknown-a", "unknown-b", Some("unknown coordinate system 'unknown-b': coordinates are read as they are")), + ] { + let members = parcel(&point_property("label", "5 52", first)) + &parcel(&point_property("label", "6 53", second)); + let layers = read("parcels.gml", doc(&members).as_bytes()).unwrap(); + let [(ds, report)] = layers.as_slice() else { panic!("expected one layer") }; + assert_eq!(ds.features.len(), 2); + assert_eq!(ds.features[0].geometry, Some(Geometry::Point(Coord::new(5.0, 52.0)))); + assert_eq!(ds.features[1].geometry, Some(Geometry::Point(Coord::new(6.0, 53.0)))); + assert_eq!(report.messages.texts().collect::>(), expected_note.into_iter().collect::>()); + } + } + + #[test] + fn a_later_geometry_declaring_a_system_is_said_when_the_file_declares_none() { + let first = point_property("label", "5 52", ""); + let later = point_property("boundary", "6 53", "EPSG:4326"); + let layers = read("parcels.gml", doc(&parcel(&(first + &later))).as_bytes()).unwrap(); + let [(ds, report)] = layers.as_slice() else { panic!("expected one layer") }; + assert_eq!(ds.features[0].geometry, Some(Geometry::Point(Coord::new(5.0, 52.0)))); + assert_eq!(report.messages.len(), 1); + assert_eq!(report.messages[0].loss, Some(crate::loss::LossCode::DroppedValue)); + assert_eq!( + report.messages[0].as_str(), + "parcels: 1 geometry property not read: the layer has no declared coordinate system (boundary)" + ); + } + + #[test] + fn an_unreadable_shape_does_not_establish_the_file_system() { + let bad = point_property("bad", "invalid", "EPSG:3857"); + let good = point_property("good", "5 52", "EPSG:4326"); + let layers = read("parcels.gml", doc(&parcel(&(bad + &good))).as_bytes()).unwrap(); + let [(ds, report)] = layers.as_slice() else { panic!("expected one layer") }; + assert_eq!(ds.held_in, Crs::LonLat); + assert_eq!(ds.features[0].geometry, Some(Geometry::Point(Coord::new(5.0, 52.0)))); + assert_eq!(report.messages.len(), 1); + assert!(report.messages[0].contains("1 property not read") && report.messages[0].ends_with("(bad)")); + } + + #[test] + fn case_distinct_geometry_properties_have_selectable_layer_names() { + let properties = point_property("label", "5 52", "") + &point_property("Label", "6 53", ""); + let layers = read("parcels.gml", doc(&parcel(&properties)).as_bytes()).unwrap(); + let [(first, _), (second, _)] = layers.as_slice() else { panic!("expected two layers") }; + assert_eq!(first.name, "parcels label"); + assert_eq!(second.name, "parcels Label (2)"); + assert_eq!(first.features[0].geometry, Some(Geometry::Point(Coord::new(5.0, 52.0)))); + assert_eq!(second.features[0].geometry, Some(Geometry::Point(Coord::new(6.0, 53.0)))); + } + + #[test] + fn exhausted_split_budget_keeps_primary_rows_and_names_omitted_properties() { + let first = point_property("primary", "5 52", ""); + let second = point_property("secondary", "6 53", ""); + let third = point_property("tertiary", "7 54", ""); + let xml = doc(&(parcel(&(first.clone() + &second)) + &parcel(&(first + &second + &third)))); + let layers = read_layers_with_budget("parcels.gml", xml.as_bytes(), Some(2 * std::mem::size_of::())).unwrap(); + let [primary, secondary] = layers.as_slice() else { panic!("expected two layers") }; + assert_eq!(primary.dataset.features.len(), 2); + assert_eq!(secondary.dataset.features.len(), 1); + assert_eq!(primary.report.messages.len(), 1); + assert_eq!(primary.report.messages[0].loss, Some(crate::loss::LossCode::DroppedOverLimit)); + assert_eq!( + primary.report.messages[0].as_str(), + "parcels: 2 geometry properties not read past the additional-row memory budget (secondary, tertiary)" + ); + let clean = read("parcels.gml", xml.as_bytes()).unwrap(); + assert_eq!(clean.len(), 3); + assert!(clean.iter().all(|(_, report)| report.messages.is_empty())); + } + + #[test] + fn the_geometry_layer_cap_counts_and_names_the_remaining_properties() { + let mut properties = String::new(); + for i in 0..MAX_LAYERS { + properties.push_str(&point_property(&format!("shape{i}"), "5 52", "")); + } + let clean = read("parcels.gml", doc(&parcel(&properties)).as_bytes()).unwrap(); + assert_eq!(clean.len(), MAX_LAYERS); + assert!(clean.iter().all(|(_, report)| report.messages.is_empty())); + properties.push_str(&(point_property("overA", "5 52", "") + &point_property("overB", "5 52", ""))); + let capped = read("parcels.gml", doc(&parcel(&properties)).as_bytes()).unwrap(); + assert_eq!(capped.len(), MAX_LAYERS); + assert_eq!(capped[0].1.messages.len(), 1); + assert_eq!(capped[0].1.messages[0].loss, Some(crate::loss::LossCode::DroppedOverLimit)); + assert_eq!(capped[0].1.messages[0].as_str(), "parcels: 2 geometry properties not read past the 64-layer limit (overA, overB)"); + } + + #[test] + fn custom_members_leave_non_feature_collection_gml_and_city_objects_to_their_readers() { + for xml in [ + r#""#, + r#""#, + ] { + let error = read("test.gml", xml.as_bytes()).unwrap_err().to_string(); + assert!(error.contains("no features in GML collection member elements"), "{error}"); + } + } + fn said(layer: &(Dataset, ReadReport), what: &str) -> bool { layer.1.messages.iter().any(|m| m.contains(what)) } diff --git a/crates/data/src/io.rs b/crates/data/src/io.rs index 09e5e9fb88..db6a06a045 100644 --- a/crates/data/src/io.rs +++ b/crates/data/src/io.rs @@ -230,15 +230,15 @@ pub struct LayerRead { pub dataset: Dataset, pub report: ReadReport, pub styles: Vec<(String, crate::kml::Style)>, - /// Notices shared with other layers from this file. When present, Add Data can pick a layer - /// using these notices and its own report, without borrowing another layer's report. - pub sibling_messages: Option>, + /// Notices and skipped feature counts shared with other layers from this file. Add Data + /// can restore them when it picks a layer without its sibling that carries them. + pub sibling_report: Option>, } impl LayerRead { /// A layer read without styles or notices shared with other layers. pub fn plain(dataset: Dataset, report: ReadReport) -> Self { - Self { dataset, report, styles: Vec::new(), sibling_messages: None } + Self { dataset, report, styles: Vec::new(), sibling_report: None } } } @@ -290,9 +290,8 @@ fn read_city_member(file_name: &str, bytes: &[u8], crs: Option) -> Result Result> { let ext = Path::new(file_name).extension().and_then(|e| e.to_str()).unwrap_or("").to_ascii_lowercase(); // KML and KMZ, LandXML, RSS, Atom, GeoRSS and other XML that isn't a city model are read as @@ -309,7 +308,7 @@ pub fn read_layers(file_name: &str, bytes: &[u8]) -> Result> { "zip" => read_zip_layers(file_name, bytes, &CsvOptions::default())?, "kml" | "kmz" => crate::kml::read(file_name, bytes)? .into_iter() - .map(|l| LayerRead { dataset: l.dataset, report: l.report, styles: l.styles, sibling_messages: None }) + .map(|l| LayerRead { dataset: l.dataset, report: l.report, styles: l.styles, sibling_report: None }) .collect(), "gpx" => plain(crate::gpx::read(file_name, bytes)?), "rss" | "atom" | "georss" => plain(crate::georss::read(file_name, bytes)?), @@ -328,7 +327,7 @@ pub fn read_layers(file_name: &str, bytes: &[u8]) -> Result> { } else if text.contains(" skipped.push(format!("{n}'s ground overlays, which couldn't be counted ({e})")), } } - read_layers(leaf, &b).and_then(|layers| { + read_layers(leaf, &b).and_then(|mut layers| { + // Only layers that fit the archive's cap can contribute to its retained memory. + let remaining = MAX_ZIP_LAYERS - out.len(); + if layers.len() > remaining { + for layer in layers.drain(remaining..) { + skipped.push(format!("{n}: {} (past the {MAX_ZIP_LAYERS}-layer limit)", layer.dataset.name)); + } + } // A KML's styles stay with its layers. let styles = layers.iter().flat_map(|l| &l.styles).fold(0usize, |sum, (id, _)| { sum.saturating_add(std::mem::size_of::<(String, crate::kml::Style)>()).saturating_add(id.capacity()) @@ -9754,6 +9760,26 @@ mod tests { assert!(e.contains("a.xlsx") && e.contains("memory budget"), "{e}"); } + #[test] + fn zipped_gml_only_charges_layers_that_fit_the_zip_layer_cap() { + use std::fmt::Write as _; + let mut gml = r#""#.to_owned(); + for i in 0..=MAX_ZIP_LAYERS { + write!(gml, "5 52").unwrap(); + } + gml.push_str(""); + let loose = read_layers("parcels.gml", gml.as_bytes()).unwrap(); + assert_eq!(loose.len(), MAX_ZIP_LAYERS + 1); + let mut budget = loose.iter().take(MAX_ZIP_LAYERS).map(|layer| retained_cost(&layer.dataset)).sum(); + let zip = crate::zip::write(&[("parcels.gml".into(), gml.into_bytes())]).unwrap(); + let layers = read_zip_budget("parcels.zip", &zip, None, &mut budget).unwrap(); + assert_eq!(layers.len(), MAX_ZIP_LAYERS); + assert_eq!(budget, 0); + assert_eq!(layers[0].0.name, "parcels shape0"); + let notice = format!("parcels.zip: skipped parcels.gml: parcels shape{MAX_ZIP_LAYERS} (past the {MAX_ZIP_LAYERS}-layer limit)"); + assert_eq!(layers[0].1.messages.texts().collect::>(), [notice.as_str()]); + } + /// A zipped KML says the ground overlays it doesn't draw, and its layers share the zip's /// allowance: two that each fit don't both fit in it. #[test] diff --git a/crates/engine/src/cmd/layer.rs b/crates/engine/src/cmd/layer.rs index 59a6764f05..fcb9805200 100644 --- a/crates/engine/src/cmd/layer.rs +++ b/crates/engine/src/cmd/layer.rs @@ -2892,7 +2892,7 @@ fn add_picked( .enumerate() .filter(|(i, r)| { !pick(&r.dataset.name) - && r.sibling_messages.is_none() + && r.sibling_report.is_none() && !reads.iter().take(*i).any(|o| same(o, r)) && (whole || (lower.ends_with(".zip") && reads.iter().skip(i + 1).any(|o| same(o, r)))) }) @@ -2942,14 +2942,19 @@ fn add_picked( /// Restore shared reports on a selected sibling and avoid repeating notices already carried by /// the zip or another selected layer of the same source. fn restore_sibling_notices(reads: &mut [rustgis_data::io::LayerRead]) { - if reads.iter().all(|r| r.sibling_messages.is_none()) { + if reads.iter().all(|r| r.sibling_report.is_none()) { return; } let mut seen: std::collections::HashSet<_> = reads.iter().flat_map(|r| r.report.messages.iter().map(move |n| (r.dataset.source.clone(), n.clone()))).collect(); + let mut counted: std::collections::HashSet<_> = + reads.iter().filter(|r| r.report.skipped > 0).filter_map(|r| r.sibling_report.as_ref().map(std::sync::Arc::as_ptr)).collect(); for read in reads { - if let Some(notes) = read.sibling_messages.take() { - for note in notes.iter() { + if let Some(shared) = read.sibling_report.take() { + if shared.skipped > 0 && counted.insert(std::sync::Arc::as_ptr(&shared)) { + read.report.skipped += shared.skipped; + } + for note in shared.messages.iter() { if seen.insert((read.dataset.source.clone(), note.clone())) { read.report.messages.push(note.clone()); } @@ -8490,6 +8495,25 @@ mod tests { } } + #[test] + fn a_selected_gml_sibling_carries_the_skipped_geometry_count_once() { + let gml = br#" + +11 48 + +"#; + for pick_sibling in [false, true] { + let mut reads = rustgis_data::io::read_layers("parks.gml", gml).unwrap(); + assert_eq!(reads.len(), 2); + if pick_sibling { + reads.retain(|read| read.dataset.name == "parks entrance"); + } + super::restore_sibling_notices(&mut reads); + assert_eq!(reads.len(), if pick_sibling { 1 } else { 2 }); + assert_eq!(reads.iter().map(|read| read.report.skipped).sum::(), 1); + } + } + /// A GDAL conversion's parts say their Z or M values once for each kind: a part alone in a /// fresh conversion's words, several counted together; parts without any say nothing. #[cfg(not(target_arch = "wasm32"))] diff --git a/docs/user-guide/data-formats.md b/docs/user-guide/data-formats.md index 13bc4c342d..fd1b798d05 100644 --- a/docs/user-guide/data-formats.md +++ b/docs/user-guide/data-formats.md @@ -28,7 +28,7 @@ export names its feature. | GeoRSS | `.rss`, `.atom`, `.georss`, or `.xml` | Add Data, drop the file, upload, or From URL… | RSS 2.0, RSS 1.0 and Atom feeds with GeoRSS Simple, GeoRSS GML or W3C Basic Geo places: points, lines and polygons layers with each item's title, link, description, date, id and category. | | LandXML | `.landxml`, or `.xml` | Add Data, drop the file, or upload | Coordinate geometry points, parcels (polygons), alignments (lines; curves as chords) and TIN surfaces (a triangle per face, with its mean elevation), converted from the file's `epsgCode` or `"crs"`. | | Encoded polylines | text | `layer.addEncodedPolyline` with `"polyline"` (one or a list) | Google's encoding, precision 5, or 6 (`"precision"`) as OSRM and Valhalla can give: a line layer. | -| GML | `.gml` | Add Data, drop the file, or upload | Simple features in GML 2 and 3, including collections with application-specific `Member` or `Members` elements. Each feature type gives a layer, with simple properties as fields. When several geometry properties can be read, each gives a layer named for that property. A notice names unread properties, including nested values and geometries that declare a different coordinate system or axis order from the one used by the file. Converted from the `srsName` (EPSG codes, URNs and URLs; the URN and URL forms of geographic systems are latitude first). Arcs and other curve segments are approximated through their control points, and said; a segment given by a centre point (`ArcByCenterPoint`, `CircleByCenterPoint`) has its centre read as a vertex instead, so the line doesn't follow the curve there, also said (a curve with only such a segment has too few positions for a line, and is kept without geometry, said as not read). | +| GML | `.gml` | Add Data, drop the file, or upload | Simple features in GML 2 and 3. When no standard member elements are found, the reader looks for application-specific `…Member` or `…Members` elements directly under the collection root. Each feature type gives a layer, with simple properties as fields. When several geometry properties can be read, each gives a layer named for that property. If a feature repeats a geometry property, the first readable occurrence is kept. The first readable geometry of each feature uses the file's coordinate system and axis order. A later geometry that declares a different system or axis order, or declares a system when the file declares none, is left out with a notice naming its property. Notices also name nested values and extra geometry properties left out by the 64-layer limit or the memory budget for additional rows. Converted from the `srsName` (EPSG codes, URNs and URLs; the URN and URL forms of geographic systems are latitude first). Arcs and other curve segments are approximated through their control points, and said; a segment given by a centre point (`ArcByCenterPoint`, `CircleByCenterPoint`) has its centre read as a vertex instead, so the line doesn't follow the curve there, also said (a curve with only such a segment has too few positions for a line, and is kept without geometry, said as not read). | | MapInfo Interchange | `.mif` with its `.mid` (or both zipped) | Add Data, drop the file, or upload the zip | Points, lines, polylines, regions (holes found by nesting), rectangles and ellipses; text and arcs are rows without geometry. Converted from the `CoordSys`: longitude/latitude, Transverse Mercator, Lambert Conformal Conic, Albers or Mercator. A loose `.mif` upload has no `.mid` attributes; zip both files to keep them in the web app. | | OpenStreetMap PBF | `.osm.pbf`, or `.pbf` containing OSM data | Add Data, drop the file, or upload | Points (tagged nodes), lines and multipolygons (closed ways that are areas, also with a lifecycle prefix such as `destroyed:building` or `demolished:building`; a closed road or barrier, prefixed or not, is a line unless it has `area=yes`, as from Overpass; and multipolygon and boundary relations), with common tags as fields and the rest in `other_tags`, as GDAL gives them. In the native reader, sub-relation members are not expanded; omissions are counted when the parent relation still yields a polygon. Within the relation limit, the native reader refuses a file holding a multipolygon or boundary relation whose member-ID, role and type arrays differ in length. Up to 40 million nodes (4 million in the web app); on the desktop, extracts over 256 MiB open through GDAL when it is installed, which follows its own configuration instead: a closed way whose only area key has a lifecycle prefix is a line there (one with `area=yes` is still a polygon), and a closed road or barrier with an area key such as `landuse` is a polygon. Vector-tile `.pbf` files use Add Tile Layer instead. | | ArcGIS feature-service answers (protocol buffer) | `.pbf` holding an answer to an ArcGIS query with `f=pbf`, or the query's address | Add Data, drop the file, upload, or From URL… with the query's address (`…/FeatureServer/0/query?…&f=pbf`) | One page of the layer: the fields and values the same query gives as GeoJSON, with the fields' aliases as their display names (dates as milliseconds since 1970, date-only and time values as text), points, lines or polygons held in the answer's coordinate system when RustGIS reads it. Z and M values, geometry, blob and raster fields are left out, with a notice. A page that stopped at the service's record limit keeps its features, with a notice that the rest aren't in it. A query the service refuses (an empty answer), a count, ids or an extent, curves, multipatches and envelopes give an error. Told from OpenStreetMap data by its content. | From a706b792f754675a34d5e44762d8cc449bf28b66 Mon Sep 17 00:00:00 2001 From: mavrick Date: Sat, 28 Nov 2026 14:22:46 -0600 Subject: [PATCH 3/4] fix(data): preserve GML single-geometry reads and report CRS assumptions --- crates/data/src/gml.rs | 314 ++++++++++++++++++++++++-------- docs/user-guide/data-formats.md | 2 +- 2 files changed, 239 insertions(+), 77 deletions(-) diff --git a/crates/data/src/gml.rs b/crates/data/src/gml.rs index b9bfe40295..edf313b023 100644 --- a/crates/data/src/gml.rs +++ b/crates/data/src/gml.rs @@ -458,6 +458,27 @@ struct Shape<'a, 'input> { lost: usize, } +/// The last primary declaration still controls secondary compatibility when no known system +/// exists. The report counts only the primary geometries that made it into a layer. +#[derive(Default)] +struct UnknownSystems<'a> { + last_declared: Option<&'a str>, + retained: usize, + names: Names, +} + +impl UnknownSystems<'_> { + /// Counts an unknown declaration on a geometry retained as the feature's first shape. + fn record(&mut self, shape: &Shape<'_, '_>) { + if shape.parsed_srs.is_none() + && let Some(name) = shape.declared_srs + { + self.retained += 1; + self.names.add(name.to_string()); + } + } +} + struct Row<'a, 'input> { attrs: BTreeMap, shapes: Vec>, @@ -468,6 +489,7 @@ struct Row<'a, 'input> { struct Kind<'a, 'input> { columns: Vec, rows: Vec>, + has_multiple_shapes: bool, unread: usize, unread_names: Names, skipped: usize, @@ -488,11 +510,13 @@ struct ShapeLayer { approximated: usize, approximated_names: Names, centred: usize, + different_system: usize, } impl ShapeLayer { /// Account for losses only in a geometry accepted for this layer. - fn push(&mut self, row: usize, shape: Shape<'_, '_>) { + fn push(&mut self, row: usize, shape: Shape<'_, '_>, file_srs: Option<(Crs, bool)>) { + self.different_system += usize::from(file_srs.is_some() && shape.parsed_srs.is_some() && file_srs != shape.parsed_srs); self.zm += usize::from(shape.zm); self.lost += shape.lost; self.parts_lost += parts_lost(&shape.node); @@ -559,7 +583,7 @@ fn read_layers_with_budget(file_name: &str, bytes: &[u8], mut extra_rows_budget: let mut kinds: BTreeMap> = BTreeMap::new(); let mut order: Vec = Vec::new(); let mut file_srs: Option<(Crs, bool)> = None; - let mut unknown_srs: Option = None; + let mut unknown = UnknownSystems::default(); let mut over = 0usize; for f in members { // Read ahead, off the UI thread: a large file can be cancelled between features. @@ -595,16 +619,22 @@ fn read_layers_with_budget(file_name: &str, bytes: &[u8], mut extra_rows_budget: } let declared_srs = g.attribute("srsName").or_else(|| g.descendants().find_map(|d| d.attribute("srsName"))); let parsed_srs = declared_srs.and_then(srs); + // Preserve the file-wide system chosen while looking for each feature's first + // readable geometry, even if this candidate turns out to be unreadable. + if shapes.is_empty() + && let Some(found) = parsed_srs + { + file_srs.get_or_insert(found); + } let (dims, lost) = (Cell::new(false), Cell::new(0)); match geometry(&g, &dims, &lost) { Some(geometry) => { - // Only a feature's first decoded geometry can establish the file's system. if shapes.is_empty() { shapes.reserve_exact(1); - if let Some(found) = parsed_srs { - file_srs.get_or_insert(found); - } else if let Some(s) = declared_srs { - unknown_srs = Some(s.to_string()); + if parsed_srs.is_none() + && let Some(s) = declared_srs + { + unknown.last_declared = Some(s); } } else { further_properties.insert(key); @@ -654,31 +684,19 @@ fn read_layers_with_budget(file_name: &str, bytes: &[u8], mut extra_rows_budget: } attrs.insert("gml_id".into(), id); } + kind.has_multiple_shapes |= shapes.len() > 1; kind.rows.push(Row { shapes, attrs }); } - let mut file_notices = crate::loss::Notes::new(); - if over > 0 { - file_notices.push(crate::loss::Note::loss( - crate::loss::LossCode::DroppedOverLimit, - format!("{over} features of more than {MAX_LAYERS} feature types were left out"), - )); - } - if file_srs.is_none() - && let Some(s) = &unknown_srs - { - file_notices.push(crate::loss::Note::loss( - crate::loss::LossCode::AssumedCrs, - format!("unknown coordinate system '{s}': coordinates are read as they are"), - )); - } let transform = match file_srs { Some((c, swap)) => Some((if c == Crs::LonLat { None } else { Some(c.transformer().map_err(DataError::Format)?) }, swap)), None => None, }; let single = order.len() == 1; + let has_multi_geometry_features = kinds.values().any(|kind| kind.has_multiple_shapes); let mut extra_layers = MAX_LAYERS.saturating_sub(order.len()); let mut used_names = HashSet::new(); let mut out = Vec::new(); + let mut sibling_reports = Vec::new(); for name in order { let Some(mut kind) = kinds.remove(&name) else { continue }; let fields: Vec = kind @@ -696,10 +714,17 @@ fn read_layers_with_budget(file_name: &str, bytes: &[u8], mut extra_rows_budget: let title = if single { stem.clone() } else { format!("{stem} {name}") }; let mut notes = ReadReport::default(); let mut limits = SplitLimits { layers: &mut extra_layers, rows_budget: &mut extra_rows_budget, columns: fields.len() }; - let layers = group_shapes(&mut kind.rows, &title, file_srs, unknown_srs.as_deref(), &mut limits, &mut notes)?; + let layers = group_shapes(&mut kind, file_srs, &mut unknown, &title, &mut limits, &mut notes)?; let split = layers.len() > 1; let first = out.len(); - report_attributes(&mut notes, &title, &fields, &kind)?; + let null_text = report_attributes(&mut notes, &title, &fields, &kind)?; + let skipped = (kind.skipped > 0).then(|| { + let what = if kind.skipped == 1 { "feature" } else { "features" }; + crate::loss::Note::loss( + crate::loss::LossCode::DroppedGeometry, + format!("{title}: {} {what} had geometry that couldn't be read", kind.skipped), + ) + }); let last = layers.len().saturating_sub(1); for (i, (property, shapes)) in layers.into_iter().enumerate() { let base = match property.filter(|_| split) { @@ -708,29 +733,65 @@ fn read_layers_with_budget(file_name: &str, bytes: &[u8], mut extra_rows_budget: }; let mut layer_name = base.clone(); let mut suffix = 2; - while !used_names.insert(layer_name.to_ascii_lowercase()) { + while has_multi_geometry_features && !used_names.insert(layer_name.to_ascii_lowercase()) { layer_name = format!("{base} ({suffix})"); suffix += 1; } let mut ds = Dataset::new(layer_name, GeometryType::None, fields.clone()); - let rep = finish_layer(&mut ds, shapes, &mut kind.rows, i == last, file_srs, transform.as_ref())?; + let null_text = if i == 0 { null_text.as_ref() } else { None }; + let rep = finish_layer(&mut ds, shapes, &mut kind.rows, i == last, file_srs, transform.as_ref(), null_text)?; out.push(LayerRead::plain(ds, rep)); } - if let Some([primary, siblings @ ..]) = out.get_mut(first..) { - let mut shared = ReadReport { skipped: notes.skipped, messages: file_notices.clone(), ..Default::default() }; - shared.messages.extend(notes.messages.iter().cloned()); - let shared = std::sync::Arc::new(shared); - primary.sibling_report = Some(shared.clone()); - for layer in siblings { + if has_multi_geometry_features { + let mut shared = crate::loss::Notes::new(); + shared.extend(skipped.iter().cloned()); + shared.extend(null_text); + shared.extend(notes.messages.iter().cloned()); + sibling_reports.push((first..out.len(), kind.skipped, shared)); + } + if let Some(primary) = out.get_mut(first) { + // Lead with the skipped count, then the losses specific to the layer and its attributes. + let mut messages = crate::loss::Notes::new(); + messages.extend(skipped); + messages.extend(std::mem::take(&mut primary.report.messages)); + messages.extend(notes.messages); + primary.report.messages = messages; + primary.report.skipped = kind.skipped; + } + } + let mut file_notices = crate::loss::Notes::new(); + if over > 0 { + file_notices.push(crate::loss::Note::loss( + crate::loss::LossCode::DroppedOverLimit, + format!("{over} features of more than {MAX_LAYERS} feature types were left out"), + )); + } + let count = unknown.retained; + if count > 0 { + let what = if count == 1 { "feature declares" } else { "features declare" }; + let placement = match file_srs { + Some((crs, _)) => format!("placed in the file's system ({})", crs.label()), + None => "coordinates are read as they are".to_string(), + }; + file_notices.push(crate::loss::Note::loss( + crate::loss::LossCode::AssumedCrs, + format!("{count} {what} an unknown coordinate system ({}): {placement}", unknown.names.said()), + )); + } + for (range, skipped, notes) in sibling_reports { + let mut messages = file_notices.clone(); + messages.extend(notes); + let shared = std::sync::Arc::new(ReadReport { skipped, messages, ..Default::default() }); + if let Some(layers) = out.get_mut(range) { + for layer in layers { layer.sibling_report = Some(shared.clone()); } - if first == 0 { - primary.report.messages.extend(file_notices.iter().cloned()); - } - primary.report.skipped = notes.skipped; - primary.report.messages.extend(notes.messages); } } + if let Some(first) = out.first_mut() { + file_notices.extend(std::mem::take(&mut first.report.messages)); + first.report.messages = file_notices; + } Ok(out) } @@ -763,16 +824,30 @@ impl SplitLimits<'_> { } } -/// Group compatible shapes by XML property, keeping a row with no readable shape once in -/// the first layer. The first layer of each feature type is reserved by the feature-type cap. +/// Group compatible shapes by XML property when a feature has several readable shapes. +/// With at most one shape per feature, keep the feature type's rows together in source order. fn group_shapes<'a, 'input>( - rows: &mut [Row<'a, 'input>], - title: &str, + kind: &mut Kind<'a, 'input>, file_srs: Option<(Crs, bool)>, - unknown_srs: Option<&str>, + unknown: &mut UnknownSystems<'_>, + title: &str, limits: &mut SplitLimits<'_>, report: &mut ReadReport, ) -> Result>, ShapeLayer)>> { + let rows = &mut kind.rows; + if !kind.has_multiple_shapes { + let mut layer = ShapeLayer { rows: Vec::with_capacity(rows.len()), ..Default::default() }; + for (i, row) in rows.iter_mut().enumerate() { + crate::progress::check()?; + if let Some(shape) = std::mem::take(&mut row.shapes).into_iter().next() { + unknown.record(&shape); + layer.push(i, shape, file_srs); + } else { + layer.rows.push((i, None)); + } + } + return Ok(vec![(None, layer)]); + } let mut layers: Vec<(Option, ShapeLayer)> = Vec::new(); let mut missing = Vec::new(); let (mut mismatch, mut unset, mut over, mut over_budget) = (0, 0, 0, 0); @@ -786,9 +861,9 @@ fn group_shapes<'a, 'input>( if shape_index > 0 && let Some(declared) = shape.declared_srs { - let matches = if file_srs.is_some() { shape.parsed_srs == file_srs } else { unknown_srs == Some(declared) }; + let matches = if file_srs.is_some() { shape.parsed_srs == file_srs } else { unknown.last_declared == Some(declared) }; if !matches { - if file_srs.is_none() && unknown_srs.is_none() { + if file_srs.is_none() && unknown.last_declared.is_none() { unset += 1; unset_names.add(local(&property).to_string()); } else { @@ -820,7 +895,10 @@ fn group_shapes<'a, 'input>( } }; if let Some((_, layer)) = layer { - layer.push(i, shape); + if shape_index == 0 { + unknown.record(&shape); + } + layer.push(i, shape, file_srs); } kept = true; } @@ -879,6 +957,7 @@ fn finish_layer( last: bool, file_srs: Option<(Crs, bool)>, transform: Option<&(Option, bool)>, + null_text: Option<&crate::loss::Note>, ) -> Result { let mut outside = false; // Features with a place the file's system can't give in longitude/latitude, kept missing. @@ -956,6 +1035,20 @@ fn finish_layer( "the GML doesn't say its coordinate system (srsName) and its coordinates aren't longitude/latitude", )); } + if shapes.different_system > 0 + && let Some((crs, _)) = file_srs + { + let what = if shapes.different_system == 1 { "feature declares" } else { "features declare" }; + rep.messages.push(crate::loss::Note::loss( + crate::loss::LossCode::AssumedCrs, + format!( + "{}: {} {what} a different coordinate system or axis order: placed in the file's system and axis order ({})", + ds.name, + shapes.different_system, + crs.label() + ), + )); + } // Said with the layer it happened in, which may be the only one added. if shapes.lost > 0 { let what = if shapes.lost == 1 { "ring or surface patch of a geometry was" } else { "rings or surface patches of geometries were" }; @@ -971,6 +1064,7 @@ fn finish_layer( format!("{}: {}", ds.name, crate::zm_note(Some(shapes.zm as u64))), )); } + rep.messages.extend(null_text.cloned()); let parts = shapes.parts_lost; if parts > 0 { let what = if parts == 1 { "part" } else { "parts" }; @@ -1005,7 +1099,8 @@ fn finish_layer( } /// Attribute loss belongs to the source feature and is reported once, even if it has several shapes. -fn report_attributes(rep: &mut ReadReport, name: &str, fields: &[Field], kind: &Kind<'_, '_>) -> Result<()> { +/// The null-marker notice precedes part and curve notices on the primary layer. +fn report_attributes(rep: &mut ReadReport, name: &str, fields: &[Field], kind: &Kind<'_, '_>) -> Result> { let (unread, unread_names) = (kind.unread, kind.unread_names.said()); let index: HashMap<_, _> = fields.iter().enumerate().map(|(i, f)| (f.name.as_str(), i)).collect(); let mut null_text = Vec::new(); @@ -1017,19 +1112,6 @@ fn report_attributes(rep: &mut ReadReport, name: &str, fields: &[Field], kind: & } } } - if let Some(n) = crate::source::null_text_note(fields, &null_text) { - rep.messages.push(n.prefixed(name)); - } - // Features whose shape couldn't be read are said with their own feature type. - rep.skipped = kind.skipped; - if kind.skipped > 0 { - let what = if kind.skipped == 1 { "feature" } else { "features" }; - // Kept, without the geometry. - rep.messages.push(crate::loss::Note::loss( - crate::loss::LossCode::DroppedGeometry, - format!("{}: {} {what} had geometry that couldn't be read", name, kind.skipped), - )); - } if unread > 0 { let what = if unread == 1 { "property" } else { "properties" }; rep.messages.push(crate::loss::Note::loss( @@ -1061,7 +1143,7 @@ fn report_attributes(rep: &mut ReadReport, name: &str, fields: &[Field], kind: & ), )); } - Ok(()) + Ok(crate::source::null_text_note(fields, &null_text).map(|note| note.prefixed(name))) } #[cfg(test)] @@ -1521,18 +1603,30 @@ mod tests { } #[test] - fn feature_members_with_one_shape_each_keep_the_file_wide_axis_order() { - for (first, second, expected_note) in [ - ("EPSG:4326", "urn:ogc:def:crs:EPSG::4326", None), - ("unknown-a", "unknown-b", Some("unknown coordinate system 'unknown-b': coordinates are read as they are")), + fn single_shapes_report_crs_and_axis_mismatches_without_changing_placement() { + let first = parcel(&point_property("label", "5 52", "EPSG:4326")); + for (second, third, count) in [ + ("EPSG:28992", "urn:ogc:def:crs:EPSG::4326", 2), + ("EPSG:4326", "EPSG:4326", 0), + ("http://www.opengis.net/gml/srs/epsg.xml#4326", "OGC:CRS84", 0), ] { - let members = parcel(&point_property("label", "5 52", first)) + &parcel(&point_property("label", "6 53", second)); + let members = first.clone() + + &parcel(&point_property("label", "124000 455000", second)) + + &parcel(&point_property("label", "6 53", third)); let layers = read("parcels.gml", doc(&members).as_bytes()).unwrap(); let [(ds, report)] = layers.as_slice() else { panic!("expected one layer") }; - assert_eq!(ds.features.len(), 2); - assert_eq!(ds.features[0].geometry, Some(Geometry::Point(Coord::new(5.0, 52.0)))); - assert_eq!(ds.features[1].geometry, Some(Geometry::Point(Coord::new(6.0, 53.0)))); - assert_eq!(report.messages.texts().collect::>(), expected_note.into_iter().collect::>()); + assert_eq!(ds.held_in, Crs::LonLat); + assert_eq!(ds.features.len(), 3); + assert_eq!(ds.features[1].geometry, Some(Geometry::Point(Coord::new(124000.0, 455000.0)))); + assert_eq!(ds.features[2].geometry, Some(Geometry::Point(Coord::new(6.0, 53.0)))); + if count > 0 { + assert_eq!(report.messages.len(), 1); + assert_eq!(report.messages[0].loss, Some(crate::loss::LossCode::AssumedCrs)); + assert!(report.messages[0].contains("2 features declare a different coordinate system or axis order")); + assert!(report.messages[0].contains("placed in the file's system and axis order")); + } else { + assert!(report.messages.is_empty()); + } } } @@ -1552,15 +1646,83 @@ mod tests { } #[test] - fn an_unreadable_shape_does_not_establish_the_file_system() { - let bad = point_property("bad", "invalid", "EPSG:3857"); - let good = point_property("good", "5 52", "EPSG:4326"); - let layers = read("parcels.gml", doc(&parcel(&(bad + &good))).as_bytes()).unwrap(); + fn an_unreadable_first_shape_can_establish_the_file_system() { + let bad = parcel(&point_property("label", "invalid", "EPSG:3857")); + for system in ["EPSG:4326", ""] { + let members = bad.clone() + &parcel(&point_property("label", "5 52", system)); + let layers = read("parcels.gml", doc(&members).as_bytes()).unwrap(); + let [(ds, report)] = layers.as_slice() else { panic!("expected one layer") }; + assert_eq!(ds.held_in, Crs::WebMercator); + assert_eq!(ds.features.len(), 2); + assert_eq!(ds.features[0].geometry, None); + assert_eq!(ds.features[1].geometry, Some(Geometry::Point(Coord::new(5.0, 52.0)))); + assert_eq!(report.skipped, 1); + assert_eq!(report.messages[0].loss, Some(crate::loss::LossCode::DroppedGeometry)); + } + } + + #[test] + fn kept_unknown_systems_are_counted_and_named() { + for (first, second, third, expected) in [ + ("unknown:42", "EPSG:4326", "unknown:43", Some("placed in the file's system")), + ("unknown:42", "", "unknown:43", Some("coordinates are read as they are")), + ("EPSG:4326", "EPSG:4326", "EPSG:4326", None), + ] { + let members = parcel(&point_property("label", "5 52", first)) + + &parcel(&point_property("label", "6 53", second)) + + &parcel(&point_property("label", "7 54", third)); + let layers = read("parcels.gml", doc(&members).as_bytes()).unwrap(); + let [(ds, report)] = layers.as_slice() else { panic!("expected one layer") }; + assert_eq!(ds.features.len(), 3); + assert_eq!(ds.features[0].geometry, Some(Geometry::Point(Coord::new(5.0, 52.0)))); + assert_eq!(ds.features[2].geometry, Some(Geometry::Point(Coord::new(7.0, 54.0)))); + if let Some(placement) = expected { + assert_eq!(report.messages.len(), 1); + let notice = &report.messages[0]; + assert_eq!(notice.loss, Some(crate::loss::LossCode::AssumedCrs)); + assert!(notice.contains("2 features declare an unknown coordinate system (unknown:42, unknown:43)")); + assert!(notice.contains(placement)); + } else { + assert!(report.messages.is_empty()); + } + } + } + + #[test] + fn single_shapes_with_different_properties_keep_the_feature_type_layer() { + let members = parcel(&point_property("label", "5 52", "")) + + &parcel(&point_property("label", "invalid", "")) + + &parcel(&point_property("position", "6 53", "")); + let layers = read("parcels.gml", doc(&members).as_bytes()).unwrap(); let [(ds, report)] = layers.as_slice() else { panic!("expected one layer") }; - assert_eq!(ds.held_in, Crs::LonLat); + assert_eq!(ds.name, "parcels"); + assert_eq!(ds.features.len(), 3); assert_eq!(ds.features[0].geometry, Some(Geometry::Point(Coord::new(5.0, 52.0)))); - assert_eq!(report.messages.len(), 1); - assert!(report.messages[0].contains("1 property not read") && report.messages[0].ends_with("(bad)")); + assert_eq!(ds.features[1].geometry, None); + assert_eq!(ds.features[2].geometry, Some(Geometry::Point(Coord::new(6.0, 53.0)))); + assert_eq!(report.skipped, 1); + } + + #[test] + fn single_shape_losses_are_reported_in_reader_order() { + use crate::loss::LossCode; + + let attrs = "old<Null>"; + let members = + parcel(&(point_property("label", "200 10 9", "unknown:42") + attrs)) + &parcel(&point_property("label", "invalid", "")); + let layers = read("parcels.gml", doc(&members).as_bytes()).unwrap(); + let [(_, report)] = layers.as_slice() else { panic!("expected one layer") }; + assert_eq!( + report.messages.iter().filter_map(|note| note.loss).collect::>(), + [ + LossCode::AssumedCrs, + LossCode::DroppedGeometry, + LossCode::AssumedCrs, + LossCode::DroppedZm, + LossCode::AssumedNullMarker, + LossCode::DroppedValue, + ] + ); } #[test] diff --git a/docs/user-guide/data-formats.md b/docs/user-guide/data-formats.md index fd1b798d05..226d3d7d72 100644 --- a/docs/user-guide/data-formats.md +++ b/docs/user-guide/data-formats.md @@ -28,7 +28,7 @@ export names its feature. | GeoRSS | `.rss`, `.atom`, `.georss`, or `.xml` | Add Data, drop the file, upload, or From URL… | RSS 2.0, RSS 1.0 and Atom feeds with GeoRSS Simple, GeoRSS GML or W3C Basic Geo places: points, lines and polygons layers with each item's title, link, description, date, id and category. | | LandXML | `.landxml`, or `.xml` | Add Data, drop the file, or upload | Coordinate geometry points, parcels (polygons), alignments (lines; curves as chords) and TIN surfaces (a triangle per face, with its mean elevation), converted from the file's `epsgCode` or `"crs"`. | | Encoded polylines | text | `layer.addEncodedPolyline` with `"polyline"` (one or a list) | Google's encoding, precision 5, or 6 (`"precision"`) as OSRM and Valhalla can give: a line layer. | -| GML | `.gml` | Add Data, drop the file, or upload | Simple features in GML 2 and 3. When no standard member elements are found, the reader looks for application-specific `…Member` or `…Members` elements directly under the collection root. Each feature type gives a layer, with simple properties as fields. When several geometry properties can be read, each gives a layer named for that property. If a feature repeats a geometry property, the first readable occurrence is kept. The first readable geometry of each feature uses the file's coordinate system and axis order. A later geometry that declares a different system or axis order, or declares a system when the file declares none, is left out with a notice naming its property. Notices also name nested values and extra geometry properties left out by the 64-layer limit or the memory budget for additional rows. Converted from the `srsName` (EPSG codes, URNs and URLs; the URN and URL forms of geographic systems are latitude first). Arcs and other curve segments are approximated through their control points, and said; a segment given by a centre point (`ArcByCenterPoint`, `CircleByCenterPoint`) has its centre read as a vertex instead, so the line doesn't follow the curve there, also said (a curve with only such a segment has too few positions for a line, and is kept without geometry, said as not read). | +| GML | `.gml` | Add Data, drop the file, or upload | Simple features in GML 2 and 3. When no standard member elements are found, the reader looks for application-specific `…Member` or `…Members` elements directly under the collection root. Each feature type gives a layer, with simple properties as fields. When a feature has several readable geometry properties, its feature type can give a layer named for each property. If a feature repeats a geometry property, the first readable occurrence is kept. The first readable geometry of each feature is placed using the file's coordinate system and axis order. Notices count first geometries that declare a different system or axis order, or name an unknown system. A later geometry that declares a different system or axis order, or declares a system when the file declares none, is left out with a notice naming its property. Notices also name nested values and extra geometry properties left out by the 64-layer limit or the memory budget for additional rows. Converted from the `srsName` (EPSG codes, URNs and URLs; the URN and URL forms of geographic systems are latitude first). Arcs and other curve segments are approximated through their control points, and said; a segment given by a centre point (`ArcByCenterPoint`, `CircleByCenterPoint`) has its centre read as a vertex instead, so the line doesn't follow the curve there, also said (a curve with only such a segment has too few positions for a line, and is kept without geometry, said as not read). | | MapInfo Interchange | `.mif` with its `.mid` (or both zipped) | Add Data, drop the file, or upload the zip | Points, lines, polylines, regions (holes found by nesting), rectangles and ellipses; text and arcs are rows without geometry. Converted from the `CoordSys`: longitude/latitude, Transverse Mercator, Lambert Conformal Conic, Albers or Mercator. A loose `.mif` upload has no `.mid` attributes; zip both files to keep them in the web app. | | OpenStreetMap PBF | `.osm.pbf`, or `.pbf` containing OSM data | Add Data, drop the file, or upload | Points (tagged nodes), lines and multipolygons (closed ways that are areas, also with a lifecycle prefix such as `destroyed:building` or `demolished:building`; a closed road or barrier, prefixed or not, is a line unless it has `area=yes`, as from Overpass; and multipolygon and boundary relations), with common tags as fields and the rest in `other_tags`, as GDAL gives them. In the native reader, sub-relation members are not expanded; omissions are counted when the parent relation still yields a polygon. Within the relation limit, the native reader refuses a file holding a multipolygon or boundary relation whose member-ID, role and type arrays differ in length. Up to 40 million nodes (4 million in the web app); on the desktop, extracts over 256 MiB open through GDAL when it is installed, which follows its own configuration instead: a closed way whose only area key has a lifecycle prefix is a line there (one with `area=yes` is still a polygon), and a closed road or barrier with an area key such as `landuse` is a polygon. Vector-tile `.pbf` files use Add Tile Layer instead. | | ArcGIS feature-service answers (protocol buffer) | `.pbf` holding an answer to an ArcGIS query with `f=pbf`, or the query's address | Add Data, drop the file, upload, or From URL… with the query's address (`…/FeatureServer/0/query?…&f=pbf`) | One page of the layer: the fields and values the same query gives as GeoJSON, with the fields' aliases as their display names (dates as milliseconds since 1970, date-only and time values as text), points, lines or polygons held in the answer's coordinate system when RustGIS reads it. Z and M values, geometry, blob and raster fields are left out, with a notice. A page that stopped at the service's record limit keeps its features, with a notice that the rest aren't in it. A query the service refuses (an empty answer), a count, ids or an extent, curves, multipatches and envelopes give an error. Told from OpenStreetMap data by its content. | From 110bc1f75ec7bf69bb6f9f586e4f49712827e431 Mon Sep 17 00:00:00 2001 From: mavrick Date: Sat, 28 Nov 2026 17:25:33 -0600 Subject: [PATCH 4/4] fix(data): preserve GML member discovery and layer selection --- crates/data/src/citygml.rs | 2 +- crates/data/src/gml.rs | 394 ++++++++++++++++++++++++-------- crates/data/src/io.rs | 16 +- crates/engine/src/cmd/layer.rs | 84 ++++++- docs/user-guide/data-formats.md | 2 +- 5 files changed, 390 insertions(+), 108 deletions(-) diff --git a/crates/data/src/citygml.rs b/crates/data/src/citygml.rs index aea5948686..ececddd4b7 100644 --- a/crates/data/src/citygml.rs +++ b/crates/data/src/citygml.rs @@ -99,7 +99,7 @@ const WRAP_BUDGET: usize = 1 << 30; const LINK_READS: usize = 4; /// The namespace every CityGML version's core namespace starts with. -const CITYGML: &str = "http://www.opengis.net/citygml/"; +pub(crate) const CITYGML: &str = "http://www.opengis.net/citygml/"; /// CityGML 3.0's core namespace. const CITYGML_3: &str = "http://www.opengis.net/citygml/3.0"; diff --git a/crates/data/src/gml.rs b/crates/data/src/gml.rs index edf313b023..fac33a8181 100644 --- a/crates/data/src/gml.rs +++ b/crates/data/src/gml.rs @@ -458,16 +458,14 @@ struct Shape<'a, 'input> { lost: usize, } -/// The last primary declaration still controls secondary compatibility when no known system -/// exists. The report counts only the primary geometries that made it into a layer. +/// Unknown declarations on the first readable geometries that made it into a layer. #[derive(Default)] -struct UnknownSystems<'a> { - last_declared: Option<&'a str>, +struct UnknownSystems { retained: usize, names: Names, } -impl UnknownSystems<'_> { +impl UnknownSystems { /// Counts an unknown declaration on a geometry retained as the feature's first shape. fn record(&mut self, shape: &Shape<'_, '_>) { if shape.parsed_srs.is_none() @@ -489,7 +487,6 @@ struct Row<'a, 'input> { struct Kind<'a, 'input> { columns: Vec, rows: Vec>, - has_multiple_shapes: bool, unread: usize, unread_names: Names, skipped: usize, @@ -536,26 +533,25 @@ impl ShapeLayer { } } -/// Standard members take precedence. A standard-looking property inside an application -/// member is part of that feature, just as a nested member inside a standard member is. +/// Use the ordinary member search unchanged. Only try application-schema members +/// at the root when that search yields no features. fn collection_features<'a, 'input>(root: Node<'a, 'input>) -> Vec> { let standard = |n: &Node| n.is_element() && matches!(local(n), "featureMember" | "featureMembers" | "member" | "members"); - let allow_custom = !is_gml(&root) || local(&root) == "FeatureCollection"; - let custom = |n: &Node| { - allow_custom && n.is_element() && n.parent() == Some(root) && { - let name = local(n); - name != "cityObjectMember" && (name.ends_with("Member") || name.ends_with("Members")) - } - }; - let mut members: Vec<_> = - root.descendants().filter(|n| standard(n) && n.ancestors().skip(1).all(|a| !standard(&a) && !custom(&a))).collect(); - if members.is_empty() { - members.extend(root.children().filter(custom)); + let features = |m: Node<'a, 'input>| m.children().filter(|f| f.is_element() && !(is_gml(f) && GEOMETRIES.contains(&local(f)))); + let members: Vec<_> = + root.descendants().filter(|n| standard(n) && n.ancestors().skip(1).all(|a| !standard(&a))).flat_map(features).collect(); + if !members.is_empty() + || (is_gml(&root) && local(&root) != "FeatureCollection") + || root.tag_name().namespace().is_some_and(|ns| ns.starts_with(crate::citygml::CITYGML)) + { + return members; } - members - .into_iter() - .flat_map(|m| m.children().filter(|c| c.is_element())) - .filter(|f| !(is_gml(f) && GEOMETRIES.contains(&local(f)))) + root.children() + .filter(|n| { + let name = local(n); + n.is_element() && name != "cityObjectMember" && (name.ends_with("Member") || name.ends_with("Members")) + }) + .flat_map(features) .collect() } @@ -629,17 +625,13 @@ fn read_layers_with_budget(file_name: &str, bytes: &[u8], mut extra_rows_budget: let (dims, lost) = (Cell::new(false), Cell::new(0)); match geometry(&g, &dims, &lost) { Some(geometry) => { + let shape = Shape { property: p, node: g, geometry, declared_srs, parsed_srs, zm: dims.get(), lost: lost.get() }; if shapes.is_empty() { - shapes.reserve_exact(1); - if parsed_srs.is_none() - && let Some(s) = declared_srs - { - unknown.last_declared = Some(s); - } + shapes = vec![shape]; } else { further_properties.insert(key); + shapes.push(shape); } - shapes.push(Shape { property: p, node: g, geometry, declared_srs, parsed_srs, zm: dims.get(), lost: lost.get() }); } None => failed.push((at, local(&p).to_string())), } @@ -684,7 +676,6 @@ fn read_layers_with_budget(file_name: &str, bytes: &[u8], mut extra_rows_budget: } attrs.insert("gml_id".into(), id); } - kind.has_multiple_shapes |= shapes.len() > 1; kind.rows.push(Row { shapes, attrs }); } let transform = match file_srs { @@ -692,7 +683,6 @@ fn read_layers_with_budget(file_name: &str, bytes: &[u8], mut extra_rows_budget: None => None, }; let single = order.len() == 1; - let has_multi_geometry_features = kinds.values().any(|kind| kind.has_multiple_shapes); let mut extra_layers = MAX_LAYERS.saturating_sub(order.len()); let mut used_names = HashSet::new(); let mut out = Vec::new(); @@ -717,7 +707,7 @@ fn read_layers_with_budget(file_name: &str, bytes: &[u8], mut extra_rows_budget: let layers = group_shapes(&mut kind, file_srs, &mut unknown, &title, &mut limits, &mut notes)?; let split = layers.len() > 1; let first = out.len(); - let null_text = report_attributes(&mut notes, &title, &fields, &kind)?; + let mut null_text = None; let skipped = (kind.skipped > 0).then(|| { let what = if kind.skipped == 1 { "feature" } else { "features" }; crate::loss::Note::loss( @@ -733,16 +723,26 @@ fn read_layers_with_budget(file_name: &str, bytes: &[u8], mut extra_rows_budget: }; let mut layer_name = base.clone(); let mut suffix = 2; - while has_multi_geometry_features && !used_names.insert(layer_name.to_ascii_lowercase()) { + while split && !used_names.insert(layer_name.to_ascii_lowercase()) { layer_name = format!("{base} ({suffix})"); suffix += 1; } + if i == 0 { + null_text = report_attributes(&mut notes, &title, &layer_name, &fields, &kind)?; + } let mut ds = Dataset::new(layer_name, GeometryType::None, fields.clone()); - let null_text = if i == 0 { null_text.as_ref() } else { None }; - let rep = finish_layer(&mut ds, shapes, &mut kind.rows, i == last, file_srs, transform.as_ref(), null_text)?; - out.push(LayerRead::plain(ds, rep)); + let layer_null_text = if i == 0 { null_text.as_ref() } else { None }; + let rep = finish_layer(&mut ds, shapes, &mut kind.rows, i == last, file_srs, transform.as_ref(), layer_null_text)?; + let mut layer = LayerRead::plain(ds, rep); + if i == 0 { + layer.pick_aliases.push(title.clone()); + if split { + layer.pick_aliases.push(name.clone()); + } + } + out.push(layer); } - if has_multi_geometry_features { + if split { let mut shared = crate::loss::Notes::new(); shared.extend(skipped.iter().cloned()); shared.extend(null_text); @@ -778,13 +778,20 @@ fn read_layers_with_budget(file_name: &str, bytes: &[u8], mut extra_rows_budget: format!("{count} {what} an unknown coordinate system ({}): {placement}", unknown.names.said()), )); } - for (range, skipped, notes) in sibling_reports { - let mut messages = file_notices.clone(); - messages.extend(notes); - let shared = std::sync::Arc::new(ReadReport { skipped, messages, ..Default::default() }); - if let Some(layers) = out.get_mut(range) { - for layer in layers { - layer.sibling_report = Some(shared.clone()); + if out.len() > 1 { + // Unsplit types share only file notices. Keep their own losses on their own layer. + let file_report = std::sync::Arc::new(ReadReport { messages: file_notices.clone(), ..Default::default() }); + for layer in &mut out { + layer.sibling_report = Some(file_report.clone()); + } + for (range, skipped, notes) in sibling_reports { + let mut messages = file_notices.clone(); + messages.extend(notes); + let shared = std::sync::Arc::new(ReadReport { skipped, messages, ..Default::default() }); + if let Some(layers) = out.get_mut(range) { + for layer in layers { + layer.sibling_report = Some(shared.clone()); + } } } } @@ -824,18 +831,81 @@ impl SplitLimits<'_> { } } +/// Drop incompatible secondary shapes before deciding whether a type needs separate layers. +fn reject_incompatible_shapes( + rows: &mut [Row<'_, '_>], + file_srs: Option<(Crs, bool)>, + title: &str, + report: &mut ReadReport, +) -> Result { + let (mut mismatch, mut unset) = (0, 0); + let (mut mismatched_names, mut unset_names) = (Names::default(), Names::default()); + let mut split = false; + for row in rows { + crate::progress::check()?; + if row.shapes.len() < 2 { + continue; + } + let primary_srs = row.shapes.first().and_then(|shape| shape.declared_srs); + let mut first = true; + row.shapes.retain(|shape| { + if std::mem::take(&mut first) { + return true; + } + let Some(declared) = shape.declared_srs else { return true }; + let compatible = match file_srs { + Some(system) => shape.parsed_srs == Some(system), + None => primary_srs == Some(declared), + }; + if compatible { + return true; + } + let name = local(&shape.property).to_string(); + if file_srs.is_none() && primary_srs.is_none() { + unset += 1; + unset_names.add(name); + } else { + mismatch += 1; + mismatched_names.add(name); + } + false + }); + split |= row.shapes.len() > 1; + } + if mismatch > 0 { + let what = if mismatch == 1 { "property" } else { "properties" }; + let why = if file_srs.is_some() { + "coordinate system or axis order differs from the layer's" + } else { + "coordinate system differs from the feature's first geometry" + }; + report.messages.push(crate::loss::Note::loss( + crate::loss::LossCode::DroppedValue, + format!("{title}: {mismatch} geometry {what} not read: {why} ({})", mismatched_names.said()), + )); + } + if unset > 0 { + let what = if unset == 1 { "property" } else { "properties" }; + report.messages.push(crate::loss::Note::loss( + crate::loss::LossCode::DroppedValue, + format!("{title}: {unset} geometry {what} not read: no known file coordinate system and the corresponding first geometries declare none ({})", unset_names.said()), + )); + } + Ok(split) +} + /// Group compatible shapes by XML property when a feature has several readable shapes. /// With at most one shape per feature, keep the feature type's rows together in source order. fn group_shapes<'a, 'input>( kind: &mut Kind<'a, 'input>, file_srs: Option<(Crs, bool)>, - unknown: &mut UnknownSystems<'_>, + unknown: &mut UnknownSystems, title: &str, limits: &mut SplitLimits<'_>, report: &mut ReadReport, ) -> Result>, ShapeLayer)>> { let rows = &mut kind.rows; - if !kind.has_multiple_shapes { + if !reject_incompatible_shapes(rows, file_srs, title, report)? { let mut layer = ShapeLayer { rows: Vec::with_capacity(rows.len()), ..Default::default() }; for (i, row) in rows.iter_mut().enumerate() { crate::progress::check()?; @@ -850,40 +920,33 @@ fn group_shapes<'a, 'input>( } let mut layers: Vec<(Option, ShapeLayer)> = Vec::new(); let mut missing = Vec::new(); - let (mut mismatch, mut unset, mut over, mut over_budget) = (0, 0, 0, 0); - let (mut mismatched_names, mut unset_names, mut capped_names, mut budget_names) = - (Names::default(), Names::default(), Names::default(), Names::default()); + let (mut over, mut over_budget) = (0, 0); + let (mut capped_names, mut budget_names) = (Names::default(), Names::default()); for (i, row) in rows.iter_mut().enumerate() { crate::progress::check()?; - let mut kept = false; + let mut primary_layer = None; for (shape_index, shape) in std::mem::take(&mut row.shapes).into_iter().enumerate() { let property = shape.property; - if shape_index > 0 - && let Some(declared) = shape.declared_srs - { - let matches = if file_srs.is_some() { shape.parsed_srs == file_srs } else { unknown.last_declared == Some(declared) }; - if !matches { - if file_srs.is_none() && unknown.last_declared.is_none() { - unset += 1; - unset_names.add(local(&property).to_string()); - } else { - mismatch += 1; - mismatched_names.add(local(&property).to_string()); - } - continue; - } - } - let index = layers.iter().position(|(p, _)| p.is_some_and(|p| p.tag_name() == property.tag_name())); - if index.is_none() && !layers.is_empty() && *limits.layers == 0 { + let mut index = layers.iter().position(|(p, _)| p.is_some_and(|p| p.tag_name() == property.tag_name())); + let at_cap = index.is_none() && !layers.is_empty() && *limits.layers == 0; + if shape_index == 0 && at_cap { + // An additional layer cannot take this property, but its first geometry + // still belongs in the type's primary layer. + index = Some(0); + } else if at_cap || (shape_index > 0 && index.is_some() && index == primary_layer) { over += 1; capped_names.add(local(&property).to_string()); continue; } - if kept && !limits.charge_row(&row.attrs) { + if shape_index > 0 && !limits.charge_row(&row.attrs) { over_budget += 1; budget_names.add(local(&property).to_string()); continue; } + if shape_index == 0 { + primary_layer = Some(index.unwrap_or(layers.len())); + unknown.record(&shape); + } let layer = match index { Some(i) => layers.get_mut(i), None => { @@ -895,34 +958,13 @@ fn group_shapes<'a, 'input>( } }; if let Some((_, layer)) = layer { - if shape_index == 0 { - unknown.record(&shape); - } layer.push(i, shape, file_srs); } - kept = true; } - if !kept { + if primary_layer.is_none() { missing.push((i, None)); } } - if mismatch > 0 { - let what = if mismatch == 1 { "property" } else { "properties" }; - report.messages.push(crate::loss::Note::loss( - crate::loss::LossCode::DroppedValue, - format!( - "{title}: {mismatch} geometry {what} not read: coordinate system or axis order differs from the layer's ({})", - mismatched_names.said() - ), - )); - } - if unset > 0 { - let what = if unset == 1 { "property" } else { "properties" }; - report.messages.push(crate::loss::Note::loss( - crate::loss::LossCode::DroppedValue, - format!("{title}: {unset} geometry {what} not read: the layer has no declared coordinate system ({})", unset_names.said()), - )); - } if over_budget > 0 { let what = if over_budget == 1 { "property" } else { "properties" }; report.messages.push(crate::loss::Note::loss( @@ -1100,7 +1142,13 @@ fn finish_layer( /// Attribute loss belongs to the source feature and is reported once, even if it has several shapes. /// The null-marker notice precedes part and curve notices on the primary layer. -fn report_attributes(rep: &mut ReadReport, name: &str, fields: &[Field], kind: &Kind<'_, '_>) -> Result> { +fn report_attributes( + rep: &mut ReadReport, + name: &str, + primary_layer: &str, + fields: &[Field], + kind: &Kind<'_, '_>, +) -> Result> { let (unread, unread_names) = (kind.unread, kind.unread_names.said()); let index: HashMap<_, _> = fields.iter().enumerate().map(|(i, f)| (f.name.as_str(), i)).collect(); let mut null_text = Vec::new(); @@ -1125,7 +1173,7 @@ fn report_attributes(rep: &mut ReadReport, name: &str, fields: &[Field], kind: & crate::loss::LossCode::DroppedValue, format!( "{}: {} {what} of repeated properties not read, only the last is kept ({})", - name, + primary_layer, kind.repeated, kind.repeated_names.said() ), @@ -1515,8 +1563,8 @@ mod tests { ) } - /// An application collection with a label before the parcel boundary. Nested members are - /// properties of a feature, and a zip reads the same GML layers and notices as the loose file. + /// The parcel label and boundary both survive, with the same notices in a ZIP. + /// History is a nested record as in the BRK parcel file. #[test] fn schema_members_keep_the_label_and_boundary_in_separate_layers() { let parcel = r#"P-1 @@ -1525,7 +1573,7 @@ mod tests { 5 52 5.2 52 5.2 52.2 5 52 {history}"#; - let history = ""; + let history = "2004-03-22"; for history in [history, ""] { let parcel = parcel.replace("{history}", history); let gml = doc(&format!("{parcel}")); @@ -1641,7 +1689,7 @@ mod tests { assert_eq!(report.messages[0].loss, Some(crate::loss::LossCode::DroppedValue)); assert_eq!( report.messages[0].as_str(), - "parcels: 1 geometry property not read: the layer has no declared coordinate system (boundary)" + "parcels: 1 geometry property not read: no known file coordinate system and the corresponding first geometries declare none (boundary)" ); } @@ -1779,12 +1827,164 @@ mod tests { for xml in [ r#""#, r#""#, + r#""#, ] { let error = read("test.gml", xml.as_bytes()).unwrap_err().to_string(); assert!(error.contains("no features in GML collection member elements"), "{error}"); } } + /// The standard member search reaches through application containers and collections, + /// preserving the feature types, their layer names, and their row order. + #[test] + fn standard_members_inside_application_members_take_precedence() { + let r = format!("{}", point_property("label", "5 52", "")); + let q = format!("{}", point_property("label", "6 53", "")); + let s = format!("{}", point_property("label", "7 54", "")); + let member = format!("{r}"); + for (contents, expected) in [ + ( + format!("{member}{member}"), + vec![("nested", vec![5.0, 5.0])], + ), + ( + format!( + "{r}{q}" + ), + vec![("nested R", vec![5.0]), ("nested Q", vec![6.0])], + ), + ( + format!("{member}"), + vec![("nested", vec![5.0])], + ), + (format!("{r}"), vec![("nested", vec![5.0])]), + (format!("{r}"), vec![("nested", vec![5.0])]), + ( + format!( + "{member}{s}" + ), + vec![("nested R", vec![5.0]), ("nested S", vec![7.0])], + ), + ] { + for root in ["app:Set", "wfs:FeatureCollection"] { + let xml = doc("{members}").replace("wfs:FeatureCollection", root).replace("{members}", &contents); + let layers = read("nested.gml", xml.as_bytes()).unwrap(); + assert_eq!(layers.len(), expected.len(), "{contents}"); + for ((layer, report), (name, xs)) in layers.iter().zip(&expected) { + assert_eq!(layer.name.as_str(), *name); + assert!(report.messages.is_empty(), "{:?}", report.messages); + assert_eq!(layer.features.len(), xs.len()); + for (row, x) in layer.features.iter().zip(xs) { + assert!(matches!(row.geometry, Some(Geometry::Point(coord)) if coord.x == *x)); + } + } + } + } + } + + #[test] + fn a_rejected_secondary_leaves_one_layer_for_the_feature_type() { + let first = point_property("label", "5 52", "EPSG:4326"); + let secondary = point_property("boundary", "6 53", "EPSG:3857"); + let next = point_property("position", "7 54", "EPSG:4326"); + let members = parcel(&(first + &secondary)) + &parcel(&next); + let layers = read("parcels.gml", doc(&members).as_bytes()).unwrap(); + let [(layer, report)] = layers.as_slice() else { panic!("expected one layer") }; + assert_eq!(layer.name, "parcels"); + assert_eq!(layer.features.len(), 2); + assert_eq!(layer.features[1].geometry, Some(Geometry::Point(Coord::new(7.0, 54.0)))); + assert_eq!(report.messages.len(), 1); + assert_eq!(report.messages[0].loss, Some(crate::loss::LossCode::DroppedValue)); + assert!(report.messages[0].contains("1 geometry property") && report.messages[0].ends_with("(boundary)")); + } + + #[test] + fn an_unknown_secondary_system_matches_its_own_primary_in_either_order() { + let feature = + |system, label, boundary| parcel(&(point_property("label", label, system) + &point_property("boundary", boundary, system))); + let x = feature("X", "5 52", "6 53"); + let y = feature("Y", "7 54", "8 55"); + for (members, expected) in [(x.clone() + &y, [6.0, 8.0]), (y + &x, [8.0, 6.0])] { + let layers = read("parcels.gml", doc(&members).as_bytes()).unwrap(); + let [(primary, report), (secondary, extra)] = layers.as_slice() else { panic!("expected two layers") }; + assert_eq!(primary.features.len(), 2); + assert_eq!(secondary.features.len(), 2); + for (row, x) in secondary.features.iter().zip(expected) { + assert!(matches!(row.geometry, Some(Geometry::Point(coord)) if coord.x == x)); + } + assert_eq!(report.messages.len(), 1); + assert!(report.messages[0].contains("2 features declare an unknown coordinate system")); + assert!(extra.messages.is_empty()); + } + } + + /// A later feature's unknown declaration leaves the first feature's line intact. + #[test] + fn a_line_with_its_own_points_unknown_system_is_read_in_either_order() { + let line = + r#"6 53 7 54"#; + let a = parcel(&(point_property("label", "5 52", "urn:x:a") + line)); + let b = parcel(&point_property("label", "8 55", "urn:x:b")); + for members in [a.clone() + &b, b + &a] { + let layers = read("parcels.gml", doc(&members).as_bytes()).unwrap(); + let [(primary, report), (secondary, line_report)] = layers.as_slice() else { panic!("expected two layers") }; + assert_eq!(primary.features.len(), 2); + assert_eq!(secondary.features.len(), 1); + assert_eq!(secondary.features[0].geometry, Some(Geometry::Line(vec![vec![Coord::new(6.0, 53.0), Coord::new(7.0, 54.0)]]))); + assert_eq!(report.messages.len(), 1); + assert!(report.messages[0].contains("2 features declare an unknown coordinate system")); + assert!(line_report.messages.is_empty()); + } + } + + /// A type can use its primary layer for an overflow first property, even when a + /// later property on the same feature would also have used that layer. + #[test] + fn a_full_layer_cap_keeps_each_features_first_geometry() { + let mut members = String::new(); + for i in 0..MAX_LAYERS - 1 { + members.push_str(&format!("{}", point_property("label", "5 52", ""))); + } + let label = point_property("label", "5 52", ""); + let boundary = point_property("boundary", "6 53", ""); + let other = point_property("other", "7 54", "unknown:42"); + members += &parcel(&(label.clone() + &boundary)); + members += &parcel(&(other + &label)); + members += &parcel(&boundary); + let layers = read("parcels.gml", doc(&members).as_bytes()).unwrap(); + assert_eq!(layers.len(), MAX_LAYERS); + let (layer, report) = layers.last().unwrap(); + assert_eq!(layer.name, "parcels Parcel"); + assert_eq!(layer.features.len(), 3); + for (row, x) in layer.features.iter().zip([5.0, 7.0, 6.0]) { + assert!(matches!(row.geometry, Some(Geometry::Point(coord)) if coord.x == x)); + } + assert_eq!(report.messages.len(), 1); + assert_eq!(report.messages[0].loss, Some(crate::loss::LossCode::DroppedOverLimit)); + assert_eq!(report.messages[0].as_str(), "parcels Parcel: 2 geometry properties not read past the 64-layer limit (boundary, label)"); + assert!(layers[0].1.messages[0].contains("1 feature declares an unknown coordinate system (unknown:42)")); + } + + #[test] + fn split_names_leave_case_distinct_unsplit_types_alone_and_name_repeated_losses() { + let shape = point_property("label", "5 52", ""); + let another = point_property("boundary", "6 53", ""); + let members = format!( + "{shape}{shape}{}", + parcel(&(shape.clone() + &another + "12")) + ); + let layers = read("map.gml", doc(&members).as_bytes()).unwrap(); + assert_eq!( + layers.iter().map(|(ds, _)| ds.name.as_str()).collect::>(), + ["map road", "map Road", "map Parcel label", "map Parcel boundary"] + ); + assert_eq!(layers[2].1.messages.len(), 1); + assert_eq!( + layers[2].1.messages[0].as_str(), + "map Parcel label: 1 value of repeated properties not read, only the last is kept (code)" + ); + } + fn said(layer: &(Dataset, ReadReport), what: &str) -> bool { layer.1.messages.iter().any(|m| m.contains(what)) } diff --git a/crates/data/src/io.rs b/crates/data/src/io.rs index db6a06a045..df6884fc85 100644 --- a/crates/data/src/io.rs +++ b/crates/data/src/io.rs @@ -233,12 +233,14 @@ pub struct LayerRead { /// Notices and skipped feature counts shared with other layers from this file. Add Data /// can restore them when it picks a layer without its sibling that carries them. pub sibling_report: Option>, + /// A primary geometry layer's feature type selectors, for imports that can split a type. + pub pick_aliases: Vec, } impl LayerRead { /// A layer read without styles or notices shared with other layers. pub fn plain(dataset: Dataset, report: ReadReport) -> Self { - Self { dataset, report, styles: Vec::new(), sibling_report: None } + Self { dataset, report, styles: Vec::new(), sibling_report: None, pick_aliases: Vec::new() } } } @@ -308,7 +310,7 @@ pub fn read_layers(file_name: &str, bytes: &[u8]) -> Result> { "zip" => read_zip_layers(file_name, bytes, &CsvOptions::default())?, "kml" | "kmz" => crate::kml::read(file_name, bytes)? .into_iter() - .map(|l| LayerRead { dataset: l.dataset, report: l.report, styles: l.styles, sibling_report: None }) + .map(|l| LayerRead { dataset: l.dataset, report: l.report, styles: l.styles, sibling_report: None, pick_aliases: Vec::new() }) .collect(), "gpx" => plain(crate::gpx::read(file_name, bytes)?), "rss" | "atom" | "georss" => plain(crate::georss::read(file_name, bytes)?), @@ -327,7 +329,13 @@ pub fn read_layers(file_name: &str, bytes: &[u8]) -> Result> { } else if text.contains(" remaining { for layer in layers.drain(remaining..) { skipped.push(format!("{n}: {} (past the {MAX_ZIP_LAYERS}-layer limit)", layer.dataset.name)); diff --git a/crates/engine/src/cmd/layer.rs b/crates/engine/src/cmd/layer.rs index fcb9805200..12b8952db2 100644 --- a/crates/engine/src/cmd/layer.rs +++ b/crates/engine/src/cmd/layer.rs @@ -2880,8 +2880,22 @@ fn add_picked( let lower = file_name.to_ascii_lowercase(); if let Some(want) = ps(p, "layer").map(str::trim).filter(|t| !t.is_empty()) { let names: Vec = reads.iter().map(|r| r.dataset.name.clone()).collect(); - // By its full name or its last word ("tracks" for "walk tracks"). - let pick = |n: &str| n.eq_ignore_ascii_case(want) || n.rsplit(' ').next().is_some_and(|w| w.eq_ignore_ascii_case(want)); + // A GML type's old name picks its primary layer when no layer has that full name. + let short_name = |name: &str| name.rsplit(' ').next().is_some_and(|word| word.eq_ignore_ascii_case(want)); + let alias = |r: &rustgis_data::io::LayerRead| r.pick_aliases.iter().any(|name| name.eq_ignore_ascii_case(want) || short_name(name)); + let mut alias_sources = std::collections::HashSet::new(); + if !names.iter().any(|name| name.eq_ignore_ascii_case(want)) { + alias_sources.extend(reads.iter().filter(|r| alias(r)).map(|r| r.dataset.source.clone())); + } + let pick = |r: &rustgis_data::io::LayerRead| { + let name = &r.dataset.name; + if alias_sources.contains(&r.dataset.source) { + alias(r) + } else { + // By its full name or its last word ("tracks" for "walk tracks"). + name.eq_ignore_ascii_case(want) || short_name(name) + } + }; // A city model's first layer holds what the file as a whole says, after its own one // notice: that its heights were dropped (it has no other). OSM has no such height notice. // A zip member can give several layers. When the reader provides shared notices, @@ -2891,7 +2905,7 @@ fn add_picked( .iter() .enumerate() .filter(|(i, r)| { - !pick(&r.dataset.name) + !pick(r) && r.sibling_report.is_none() && !reads.iter().take(*i).any(|o| same(o, r)) && (whole || (lower.ends_with(".zip") && reads.iter().skip(i + 1).any(|o| same(o, r)))) @@ -2915,13 +2929,13 @@ fn add_picked( // What a zip says of itself (members skipped, overlays not drawn) sits on its first layer, // named by the zip: it goes with whichever layer is picked. let zip_wide: Vec = match reads.first() { - Some(first) if lower.ends_with(".zip") && !pick(&first.dataset.name) => { + Some(first) if lower.ends_with(".zip") && !pick(first) => { let prefix = format!("{file_name}: "); first.report.messages.iter().filter(|n| n.text.starts_with(&prefix)).cloned().collect() } _ => Vec::new(), }; - reads.retain(|r| pick(&r.dataset.name)); + reads.retain(pick); if reads.is_empty() { return Err(format!("{file_name}: no layer '{want}' (layers: {})", names.join(", "))); } @@ -8514,6 +8528,66 @@ mod tests { } } + /// Only file notices follow an unsplit type selected from another type's file. + #[test] + fn a_picked_gml_type_carries_only_its_own_and_file_notices() { + use base64::Engine; + use rustgis_data::loss::LossCode; + + let gml = r#" + + +"#; + let encode = |bytes: &[u8]| base64::engine::general_purpose::STANDARD.encode(bytes); + let zip = rustgis_data::zip::write(&[("types.gml".into(), gml.as_bytes().to_vec())]).unwrap(); + for (cmd, params) in [ + ("layer.addDataText", json!({"fileName": "types.gml", "text": gml})), + ("layer.addDataBytes", json!({"fileName": "types.gml", "data": encode(gml.as_bytes())})), + ("layer.addDataBytes", json!({"fileName": "types.zip", "data": encode(&zip)})), + ] { + let mut params = params; + params["layer"] = json!("S"); + let mut s = Session::new(crate::Project::default()); + let mark = s.notice_mark(); + s.run(cmd, ¶ms).unwrap(); + assert_eq!(s.map().layers.len(), 1); + assert!(s.map().layer_by_name("types S").is_some()); + let notices = s.notices_since(mark); + assert!(notices.iter().all(|n| n.loss() != Some(LossCode::DroppedValue)), "{notices:?}"); + let assumed: Vec<_> = notices.iter().filter(|n| n.loss() == Some(LossCode::AssumedCrs)).collect(); + assert_eq!(assumed.len(), 1, "{notices:?}"); + assert!(assumed[0].text.contains("2 features declare an unknown coordinate system (U)")); + } + } + + /// A previous layer selector keeps opening the primary geometry after a type is split. + #[test] + fn gml_add_data_accepts_the_original_feature_type_and_stem() { + let wrap = |members| { + format!( + r#"{members}"# + ) + }; + let r = "0 01 1"; + for (stem, xml, picks, name) in [ + ("one", wrap(r.to_string()), ["one", "R"], "one extent"), + ( + "two", + wrap(format!("{r}")), + ["two R", "R"], + "two R extent", + ), + ] { + let file_name = format!("{stem}.gml"); + for pick in picks { + let mut s = Session::new(crate::Project::default()); + s.run("layer.addDataText", &json!({"fileName": file_name, "text": xml, "layer": pick})).unwrap(); + assert_eq!(s.map().layers.len(), 1); + assert!(s.map().layer_by_name(name).is_some()); + } + } + } + /// A GDAL conversion's parts say their Z or M values once for each kind: a part alone in a /// fresh conversion's words, several counted together; parts without any say nothing. #[cfg(not(target_arch = "wasm32"))] diff --git a/docs/user-guide/data-formats.md b/docs/user-guide/data-formats.md index 226d3d7d72..c3d2c08efa 100644 --- a/docs/user-guide/data-formats.md +++ b/docs/user-guide/data-formats.md @@ -28,7 +28,7 @@ export names its feature. | GeoRSS | `.rss`, `.atom`, `.georss`, or `.xml` | Add Data, drop the file, upload, or From URL… | RSS 2.0, RSS 1.0 and Atom feeds with GeoRSS Simple, GeoRSS GML or W3C Basic Geo places: points, lines and polygons layers with each item's title, link, description, date, id and category. | | LandXML | `.landxml`, or `.xml` | Add Data, drop the file, or upload | Coordinate geometry points, parcels (polygons), alignments (lines; curves as chords) and TIN surfaces (a triangle per face, with its mean elevation), converted from the file's `epsgCode` or `"crs"`. | | Encoded polylines | text | `layer.addEncodedPolyline` with `"polyline"` (one or a list) | Google's encoding, precision 5, or 6 (`"precision"`) as OSRM and Valhalla can give: a line layer. | -| GML | `.gml` | Add Data, drop the file, or upload | Simple features in GML 2 and 3. When no standard member elements are found, the reader looks for application-specific `…Member` or `…Members` elements directly under the collection root. Each feature type gives a layer, with simple properties as fields. When a feature has several readable geometry properties, its feature type can give a layer named for each property. If a feature repeats a geometry property, the first readable occurrence is kept. The first readable geometry of each feature is placed using the file's coordinate system and axis order. Notices count first geometries that declare a different system or axis order, or name an unknown system. A later geometry that declares a different system or axis order, or declares a system when the file declares none, is left out with a notice naming its property. Notices also name nested values and extra geometry properties left out by the 64-layer limit or the memory budget for additional rows. Converted from the `srsName` (EPSG codes, URNs and URLs; the URN and URL forms of geographic systems are latitude first). Arcs and other curve segments are approximated through their control points, and said; a segment given by a centre point (`ArcByCenterPoint`, `CircleByCenterPoint`) has its centre read as a vertex instead, so the line doesn't follow the curve there, also said (a curve with only such a segment has too few positions for a line, and is kept without geometry, said as not read). | +| GML | `.gml` | Add Data, drop the file, or upload | Simple features in GML 2 and 3. When the standard member search yields no features, the reader looks for application-specific `…Member` or `…Members` elements directly under the collection root. Each retained feature type gives a layer, with simple properties as fields. When a feature has several compatible readable geometry properties, its feature type can give a layer named for each property. For a split type, its original layer title or feature-type name selects its first layer when no layer has that exact name. In a single-type file the original layer title is the file stem. If a feature repeats a geometry property, the first readable occurrence is kept. The first readable geometry of each feature is placed using the file's coordinate system and axis order. Notices count first geometries that declare a different system or axis order, or name an unknown system. A later geometry with a declaration must match the file's system and axis order. If the file has no known system, its declaration must match the same feature's first geometry. A notice names properties left out. Notices name nested values and later geometries left out by the 64-layer limit or the memory budget for additional rows. If a first geometry has no room for a layer of its own, it goes in the retained type's first layer. Converted from the `srsName` (EPSG codes, URNs and URLs; the URN and URL forms of geographic systems are latitude first). Arcs and other curve segments are approximated through their control points, and said; a segment given by a centre point (`ArcByCenterPoint`, `CircleByCenterPoint`) has its centre read as a vertex instead, so the line doesn't follow the curve there, also said (a curve with only such a segment has too few positions for a line, and is kept without geometry, said as not read). | | MapInfo Interchange | `.mif` with its `.mid` (or both zipped) | Add Data, drop the file, or upload the zip | Points, lines, polylines, regions (holes found by nesting), rectangles and ellipses; text and arcs are rows without geometry. Converted from the `CoordSys`: longitude/latitude, Transverse Mercator, Lambert Conformal Conic, Albers or Mercator. A loose `.mif` upload has no `.mid` attributes; zip both files to keep them in the web app. | | OpenStreetMap PBF | `.osm.pbf`, or `.pbf` containing OSM data | Add Data, drop the file, or upload | Points (tagged nodes), lines and multipolygons (closed ways that are areas, also with a lifecycle prefix such as `destroyed:building` or `demolished:building`; a closed road or barrier, prefixed or not, is a line unless it has `area=yes`, as from Overpass; and multipolygon and boundary relations), with common tags as fields and the rest in `other_tags`, as GDAL gives them. In the native reader, sub-relation members are not expanded; omissions are counted when the parent relation still yields a polygon. Within the relation limit, the native reader refuses a file holding a multipolygon or boundary relation whose member-ID, role and type arrays differ in length. Up to 40 million nodes (4 million in the web app); on the desktop, extracts over 256 MiB open through GDAL when it is installed, which follows its own configuration instead: a closed way whose only area key has a lifecycle prefix is a line there (one with `area=yes` is still a polygon), and a closed road or barrier with an area key such as `landuse` is a polygon. Vector-tile `.pbf` files use Add Tile Layer instead. | | ArcGIS feature-service answers (protocol buffer) | `.pbf` holding an answer to an ArcGIS query with `f=pbf`, or the query's address | Add Data, drop the file, upload, or From URL… with the query's address (`…/FeatureServer/0/query?…&f=pbf`) | One page of the layer: the fields and values the same query gives as GeoJSON, with the fields' aliases as their display names (dates as milliseconds since 1970, date-only and time values as text), points, lines or polygons held in the answer's coordinate system when RustGIS reads it. Z and M values, geometry, blob and raster fields are left out, with a notice. A page that stopped at the service's record limit keeps its features, with a notice that the rest aren't in it. A query the service refuses (an empty answer), a count, ids or an extent, curves, multipatches and envelopes give an error. Told from OpenStreetMap data by its content. |