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 428bf66793..fac33a8181 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 @@ -11,18 +11,19 @@ //! 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; -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,140 @@ 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, +} + +/// Unknown declarations on the first readable geometries that made it into a layer. #[derive(Default)] -struct Kind { +struct UnknownSystems { + 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>, +} + +/// A feature type's rows and losses shared by all its geometry properties. +#[derive(Default)] +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, + different_system: 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<'_, '_>, 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); + 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))); + } +} + +/// 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 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; + } + 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() +} + +/// 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> { + 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() }; 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 unknown = UnknownSystems::default(); 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 +594,11 @@ 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> = 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(); 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 +607,38 @@ 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() { + let tag = p.tag_name(); + let key = (tag.namespace(), tag.name()); + if shapes.first().is_some_and(|shape| shape.property.tag_name() == tag) || further_properties.contains(&key) { 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); + // 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(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) => { + let shape = Shape { property: p, node: g, geometry, declared_srs, parsed_srs, zm: dims.get(), lost: lost.get() }; + if shapes.is_empty() { + shapes = vec![shape]; + } else { + further_properties.insert(key); + shapes.push(shape); } } - 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 +658,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,33 +676,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)); - } - let mut report = ReadReport::default(); - if over > 0 { - report.messages.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( - crate::loss::LossCode::AssumedCrs, - format!("unknown coordinate system '{s}': coordinates are read as they are"), - )); + kind.rows.push(Row { shapes, attrs }); } 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 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(kind) = kinds.remove(&name) else { continue }; + let Some(mut kind) = kinds.remove(&name) else { continue }; let fields: Vec = kind .columns .iter() @@ -651,195 +696,502 @@ 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; - } - 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, - }); - // 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 - } + 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, file_srs, &mut unknown, &title, &mut limits, &mut notes)?; + let split = layers.len() > 1; + let first = out.len(); + let mut null_text = None; + 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) { + Some(property) => format!("{title} {}", local(&property)), + None => title.clone(), }; - 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 mut layer_name = base.clone(); + let mut suffix = 2; + while split && !used_names.insert(layer_name.to_ascii_lowercase()) { + layer_name = format!("{base} ({suffix})"); + suffix += 1; } - 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 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 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); } - 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 split { + 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 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 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; } - if let Some((c, _)) = file_srs { - rep.messages.extend(crate::io::beyond_lonlat_note("features", beyond, c).map(|n| format!("{}: {n}", ds.name))); + } + 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()), + )); + } + 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()); } - 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", - )); + 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()); + } + } } - // 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!( - "{}: {} {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 - ))); + } + if let Some(first) = out.first_mut() { + file_notices.extend(std::mem::take(&mut first.report.messages)); + first.report.messages = file_notices; + } + 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) -> bool { + let remaining = self.rows_budget.get_or_insert_with(|| crate::memory::planned(256 << 20, 1 << 30, 1)); + if *remaining == 0 { + return false; } - 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))), - )); + let bytes = + attrs.values().fold(2 * std::mem::size_of::() + self.columns * std::mem::size_of::(), |bytes, text| { + bytes.saturating_add(text.len()) + }); + if let Some(left) = remaining.checked_sub(bytes) { + *remaining = left; + true + } else { + *remaining = 0; + false } - if let Some(n) = crate::source::null_text_note(&ds.fields, &null_text) { - rep.messages.push(n.prefixed(&ds.name)); + } +} + +/// 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; } - 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 - ), - )); + 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, + title: &str, + limits: &mut SplitLimits<'_>, + report: &mut ReadReport, +) -> Result>, ShapeLayer)>> { + let rows = &mut kind.rows; + 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()?; + 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)); + } } - 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() - ), - )); + return Ok(vec![(None, layer)]); + } + let mut layers: Vec<(Option, ShapeLayer)> = Vec::new(); + let mut missing = Vec::new(); + 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 primary_layer = None; + for (shape_index, shape) in std::mem::take(&mut row.shapes).into_iter().enumerate() { + let property = shape.property; + 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 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 => { + if !layers.is_empty() { + *limits.layers -= 1; + } + layers.push((Some(property), ShapeLayer::default())); + layers.last_mut() + } + }; + if let Some((_, layer)) = layer { + layer.push(i, shape, file_srs); + } } - 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!( - "{}: {} {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 - ))); + if primary_layer.is_none() { + missing.push((i, None)); } - 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 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( + 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 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() - ), - )); + } 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: &mut [Row<'_, '_>], + 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. + 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_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, + }); + // 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 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); + // Converted, but beyond longitude/latitude: it draws out of place. + beyond += usize::from(!missing && e.beyond_lonlat()); + Some(g) + } + (_, 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 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() - ), + 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); + 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 )); + } + 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", + )); + } + 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" }; + 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, shapes.lost + ))); + } + 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))), + )); + } + rep.messages.extend(null_text.cloned()); + 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, shapes.centred + ))); + } + Ok(rep) +} + +/// 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, + 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(); + 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) = index.get(field.as_str()) { + crate::source::null_text_at(&mut null_text, i); + } } - out.push((ds, rep)); } - Ok(out) + 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 ({})", + primary_layer, + 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() + ), + )); + } + Ok(crate::source::null_text_note(fields, &null_text).map(|note| note.prefixed(name))) } #[cfg(test)] @@ -1117,8 +1469,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 +1484,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 +1563,428 @@ mod tests { ) } + /// 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 +5.1 52.1 + +5 52 5.2 52 5.2 52.2 5 52 + +{history}"#; + let history = "2004-03-22"; + 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 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 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 = 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.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()); + } + } + } + + #[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: no known file coordinate system and the corresponding first geometries declare none (boundary)" + ); + } + + #[test] + 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.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!(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] + 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#""#, + 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 66e8e72122..df6884fc85 100644 --- a/crates/data/src/io.rs +++ b/crates/data/src/io.rs @@ -230,6 +230,18 @@ pub struct LayerRead { pub dataset: Dataset, pub report: ReadReport, pub styles: Vec<(String, crate::kml::Style)>, + /// 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, pick_aliases: Vec::new() } + } } /// Whether a file holds several layers ([`read_layers`] reads them all): a zip, KML, KMZ, GPX or @@ -278,10 +290,10 @@ 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 @@ -293,13 +305,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_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)?), @@ -318,7 +329,13 @@ 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 +4164,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 +4186,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 +4221,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" { @@ -4249,7 +4264,14 @@ fn read_zip_layers_budget(file_name: &str, bytes: &[u8], opts: &CsvOptions, budg Err(e) => 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.saturating_sub(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()) @@ -9746,6 +9768,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 c5d55e0d74..12b8952db2 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) { @@ -2881,17 +2880,33 @@ 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. - // 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) + !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)))) }) @@ -2914,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(", "))); } @@ -2933,10 +2948,35 @@ 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_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(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()); + } + } + } + } +} + /// 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 +8463,131 @@ 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")); + } + } + } + } + + #[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); + } + } + + /// 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 04344f7b15..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 (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. 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. |