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..811096f99e 100644 --- a/crates/data/src/gml.rs +++ b/crates/data/src/gml.rs @@ -429,10 +429,10 @@ fn approximated(g: &Node) -> Vec { struct Names(Vec, bool); impl Names { - fn add(&mut self, p: String) { - if !self.0.contains(&p) { + fn add(&mut self, p: impl AsRef + Into) { + if !self.0.iter().any(|n| n == p.as_ref()) { if self.0.len() < 3 { - self.0.push(p); + self.0.push(p.into()); } else { self.1 = true; } @@ -476,9 +476,102 @@ struct Kind { centred: usize, } +/// A standard member element, under any namespace. +fn is_member(n: &Node) -> bool { + n.is_element() && matches!(local(n), "featureMember" | "featureMembers" | "member" | "members") +} + +fn is_gml_shape(n: Node) -> bool { + n.is_element() && is_gml(&n) && is_shape(local(&n)) +} + +/// Whether a property of `feature` directly holds a GML shape, its bounds aside. +fn has_shape_property(feature: &Node) -> bool { + feature.children().any(|p| p.is_element() && !(is_gml(&p) && local(&p) == "boundedBy") && p.children().any(is_gml_shape)) +} + +/// Finds inline features in direct application-schema members. A root with a property that +/// directly holds a GML geometry isn't read as a collection. +fn application_features<'a, 'input>(root: Node<'a, 'input>, file_name: &str, report: &mut ReadReport) -> Result>> { + let holds_shape = |n: Node| n.is_element() && n.children().any(is_gml_shape); + let bounds = |n: &Node| is_gml(n) && local(n) == "boundedBy"; + let has_text = |n: Node| n.is_text() && n.text().is_some_and(|text| !text.trim().is_empty()); + let property = |n: &str| n.ends_with("Member") || n.ends_with("Members"); + // GML names properties in lower camel case: a member's child named like one, with no shape of + // its own but one further in, is a nested collection. + let nested = |n: &Node| { + property(local(n)) + && local(n).starts_with(char::is_lowercase) + && !has_shape_property(n) + && n.descendants().any(|d| has_shape_property(&d)) + }; + if is_gml_shape(root) || root.tag_name().namespace().is_some_and(|ns| ns.starts_with(crate::citygml::CITYGML)) { + return Ok(Vec::new()); + } + + let mut features = Vec::new(); + let mut has_shape = false; + let mut omitted = 0; + let mut omitted_names = Names::default(); + let mut omit = |name: &str| { + omitted += 1; + omitted_names.add(name); + }; + for member in root.children().filter(|n| (n.is_element() && !bounds(n)) || has_text(*n)) { + crate::progress::check()?; + if has_text(member) { + omit("root text"); + continue; + } + if holds_shape(member) { + return Ok(Vec::new()); + } + let name = local(&member); + if !is_gml(&member) && !is_member(&member) && name != "cityObjectMember" && property(name) { + let mut empty = true; + for child in member.children().filter(|n| n.is_element() || has_text(*n)) { + crate::progress::check()?; + empty = false; + if has_text(child) { + omit(&format!("{name} text")); + } else if is_gml(&child) || nested(&child) || child.first_element_child().is_none() { + omit(local(&child)); + } else { + has_shape = has_shape || has_shape_property(&child); + if child.children().any(has_text) { + omit(&format!("{} text", local(&child))); + } + features.push(child); + } + } + if !empty { + continue; + } + } + omit(name); + } + if !has_shape { + return Ok(Vec::new()); + } + if omitted > 0 { + let what = if omitted == 1 { "item" } else { "items" }; + report.messages.push(crate::loss::Note::loss( + crate::loss::LossCode::DroppedValue, + format!("{file_name}: {omitted} {what} not read when reading application members ({})", omitted_names.said()), + )); + } + Ok(features) +} + /// 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. pub fn read(file_name: &str, bytes: &[u8]) -> Result> { + read_with_members(file_name, bytes, true) +} + +/// Uses only standard members inside archives so their layer and memory budgets stay available +/// to the same files. +pub(crate) fn read_with_members(file_name: &str, bytes: &[u8], application_members: bool) -> 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() }; @@ -486,15 +579,39 @@ pub fn read(file_name: &str, bytes: &[u8]) -> Result> 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 mut report = ReadReport::default(); + let mut found = ReadReport::default(); + let application = application_features(root, file_name, &mut found)?; + let members = if members.is_empty() && application_members { + report = found; + application + } else { + // A root that is a member has these read as its features, and one holding members but no + // shape of its own only wraps features that are read. + let counted = |f: &&Node| has_shape_property(f) || !f.descendants().any(|n| is_member(&n)); + let count = if is_member(&root) { 0 } else { application.iter().filter(counted).count() }; + if !members.is_empty() && count > 0 { + let them = if count == 1 { "feature" } else { "features" }; + report.messages.push(crate::loss::Note::loss( + crate::loss::LossCode::DroppedValue, + format!("{file_name}: {count} {them} in application members not read beside standard members"), + )); + } + members + }; if members.is_empty() { - return Err(DataError::Format(format!("{file_name}: no features (featureMember elements) in the GML"))); + let reason = if application_members { + "no features found in featureMember, member or …Member elements" + } else { + "no features (featureMember elements) in the GML" + }; + return Err(DataError::Format(format!("{file_name}: {reason}"))); } let mut kinds: BTreeMap = BTreeMap::new(); let mut order: Vec = Vec::new(); @@ -623,7 +740,6 @@ pub fn read(file_name: &str, bytes: &[u8]) -> Result> 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, @@ -874,6 +990,169 @@ mod tests { 48.2 10.4 48.3 10.5 48.4 10.4 48.2 10.4 "#; + // As in BRK, the application member wraps the parcel, whose boundary precedes its label + // point and whose history is a nested record. All coordinates and values are synthetic. + const PARCELS: &str = r#" + + 101 + A + + 1 1 3 1 3 3 1 3 1 1 + + 2 2 + +"#; + + #[test] + fn application_members_keep_the_parcel_boundary() { + let layers = read("parcels.gml", PARCELS.as_bytes()).unwrap(); + assert_eq!(layers.len(), 1); + let (parcels, report) = &layers[0]; + assert_eq!(parcels.name, "parcels"); + assert_eq!(parcels.features.len(), 1); + assert_eq!(parcels.features[0].attrs, [Value::Text("parcel-1".into()), Value::Int(101)]); + assert!(matches!(&parcels.features[0].geometry, Some(Geometry::Polygon(_)))); + assert_eq!(report.messages.len(), 1); + let note = &report.messages[0]; + assert_eq!(note.loss, Some(crate::loss::LossCode::DroppedValue)); + assert!(note.contains("2 properties not read") && note.contains("(historie, plaatscoordinaten)")); + } + + #[test] + fn standard_members_take_precedence_over_application_members() { + let mixed = + PARCELS.replace("", "A"); + let layers = read("mixed.gml", mixed.as_bytes()).unwrap(); + assert_eq!(layers.len(), 1); + assert_eq!(layers[0].0.features.len(), 1); + assert_eq!(layers[0].0.fields[0].name, "name"); + let notes = &layers[0].1.messages; + assert_eq!(notes.len(), 1); + assert_eq!(notes[0].loss, Some(crate::loss::LossCode::DroppedValue)); + assert_eq!(notes[0].as_str(), "mixed.gml: 1 feature in application members not read beside standard members"); + + let around = |root: &str, shape: &str| { + let inner = "1"; + let other = ""; + let set = format!("{shape}{inner}{other}"); + format!(r#"{set}"#) + }; + let shape = ""; + for (xml, count) in [ + (mixed.replace("app:perceelMember", "app:featureMember"), 0), + (around("members", shape), 0), + (around("Set", ""), 1), + (around("Set", shape), 2), + ] { + let layers = read("read.gml", xml.as_bytes()).unwrap(); + let said: Vec<_> = layers.iter().flat_map(|(_, r)| &r.messages).filter(|m| m.contains("beside")).collect(); + assert_eq!(said.len(), usize::from(count > 0), "{xml}"); + assert!(said.iter().all(|m| m.contains(&format!(": {count} feature"))), "{said:?}"); + } + } + + #[test] + fn application_members_do_not_turn_a_feature_with_a_shape_into_a_collection() { + let feature = PARCELS.replace("", "2 2"); + assert!(read("feature.gml", feature.as_bytes()).is_err()); + } + + #[test] + fn application_members_report_omitted_root_children_once() { + let clean = r#" + +A1 2 +"#; + let layers = read("clean.gml", clean.as_bytes()).unwrap(); + assert_eq!(layers[0].0.features.len(), 1); + assert!(layers[0].1.messages.is_empty()); + + let mixed = clean.replace( + "", + "", + ); + let layers = read("mixed.gml", mixed.as_bytes()).unwrap(); + assert_eq!(layers.len(), 1); + assert_eq!(layers[0].0.features.len(), 1); + let notes = &layers[0].1.messages; + assert_eq!(notes.len(), 1); + assert_eq!(notes[0].loss, Some(crate::loss::LossCode::DroppedValue)); + assert!(notes[0].contains("3 items not read") && notes[0].contains("(metadata, definitionMember)")); + } + + #[test] + fn application_members_require_a_feature_with_a_gml_shape() { + let cases = [ + ( + "definition", + "D", + "Definition", + ), + ("crs", "C", "ProjectedCRS"), + ( + "coverage", + "", + "RectifiedGridCoverage", + ), + ( + "time", + "2020", + "TimeInstant", + ), + ("topology", "", "Node"), + ("empty WFS", "", "FeatureCollection"), + ("linked member", "", "linkMember"), + ("text feature", "Ann", "Player"), + ( + "nested collection", + "", + "segMember", + ), + ( + "CityGML lookalike", + "B", + "cityObjectMember", + ), + ("bounding box only", "", ""), + ("unqualified shape", "1 1", ""), + ]; + let point = "1 2"; + let wrap = |content: &str| { + format!( + r#"{content}"# + ) + }; + for (case, xml, omitted) in cases { + assert!(read("case.gml", wrap(xml).as_bytes()).is_err(), "{case}"); + if !omitted.is_empty() { + let layers = read("case.gml", wrap(&format!("{xml}{point}")).as_bytes()).unwrap(); + assert_eq!(layers.len(), 1, "{case}"); + let note = &layers[0].1.messages[0]; + assert_eq!(note.loss, Some(crate::loss::LossCode::DroppedValue), "{case}"); + assert!(note.contains(&format!("({omitted})")), "{case}: {note:?}"); + } + } + + let mixed = wrap(&format!("loose root text{point}loose member textAnn")); + let layers = read("case.gml", mixed.as_bytes()).unwrap(); + assert_eq!(layers.len(), 1); + let notes = &layers[0].1.messages; + assert_eq!(notes.len(), 1); + assert_eq!(notes[0].loss, Some(crate::loss::LossCode::DroppedValue)); + assert!(notes[0].contains("3 items") && notes[0].contains("(root text, teamMembers text, Player)")); + + let named = r#"A + 1 2"#; + let layers = read("case.gml", wrap(named).as_bytes()).unwrap(); + assert_eq!(layers[0].0.features.len(), 2, "a feature type named like a member, with and without a shape"); + assert!(layers[0].1.messages.is_empty(), "{:?}", layers[0].1.messages); + + let stray = wrap(&point.replace("", "stray")); + let layers = read("case.gml", stray.as_bytes()).unwrap(); + assert_eq!(layers[0].1.messages[0].as_str(), "case.gml: 1 item not read when reading application members (Site text)"); + } + #[test] fn reads_wfs_gml3() { let layers = read("w.gml", WFS.as_bytes()).unwrap(); diff --git a/crates/data/src/io.rs b/crates/data/src/io.rs index 61d8605674..0b03e11883 100644 --- a/crates/data/src/io.rs +++ b/crates/data/src/io.rs @@ -286,6 +286,11 @@ fn read_city_member(file_name: &str, bytes: &[u8], crs: Option) -> Result Result> { + read_layers_inner(file_name, bytes, true) +} + +/// Keeps the loose-file GML fallback off when reading archive members. +fn read_layers_inner(file_name: &str, bytes: &[u8], gml_application_members: bool) -> 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 // they are added, on the desktop's UI thread, never ahead: within [`BYTES_FLOOR`] whatever the @@ -331,7 +336,7 @@ pub fn read_layers(file_name: &str, bytes: &[u8]) -> 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" => plain(crate::gml::read_with_members(file_name, bytes, gml_application_members)?), "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)?), @@ -4569,7 +4574,7 @@ 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_inner(leaf, &b, false).and_then(|layers| { // 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()) diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index ebca733592..5182289ed1 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -32959,6 +32959,30 @@ fn a_system_without_an_epsg_code_is_exported_in_its_own_system() { let _ = std::fs::remove_dir_all(&dir); } +#[test] +fn application_gml_members_leave_other_zip_layers_available() { + use base64::Engine; + use std::fmt::Write; + let mut gml = r#""#.to_string(); + for i in 0..40 { + write!(gml, "1 2").unwrap(); + } + gml.push_str(""); + let geojson = br#"{"type":"Feature","properties":{},"geometry":{"type":"Point","coordinates":[5,52]}}"#; + let zip = rustgis_data::zip::write(&[("a.gml".into(), gml.into_bytes()), ("z.geojson".into(), geojson.to_vec())]).unwrap(); + let data = base64::engine::general_purpose::STANDARD.encode(zip); + for pick in [false, true] { + let mut s = Session::new(Project::default()); + let mut params = json!({"fileName": "mixed.zip", "data": data}); + if pick { + params["layer"] = json!("z"); + } + s.run("layer.addDataBytes", ¶ms).unwrap(); + assert_eq!(s.map().layers.len(), 1); + assert_eq!(s.map().layers[0].name, "z"); + } +} + #[test] fn zipped_shapefiles_add_as_layers() { use base64::Engine; diff --git a/docs/user-guide/data-formats.md b/docs/user-guide/data-formats.md index 06ddf17f1e..9968395593 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 (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). When the standard search finds no features, a loose GML file can be read through its root-level application elements ending in `Member` or `Members` if at least one feature property directly holds a GML shape, with whole-file import reporting omitted elements and stray text. A root property directly holding a GML shape causes the fallback to refuse the file, and GML inside a ZIP uses the standard search only. In a file with standard members, the application features aren't read, and a notice counts those this search could have 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. |