Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion crates/data/src/citygml.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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";
Expand Down
291 changes: 285 additions & 6 deletions crates/data/src/gml.rs
Original file line number Diff line number Diff line change
Expand Up @@ -429,10 +429,10 @@ fn approximated(g: &Node) -> Vec<String> {
struct Names(Vec<String>, bool);

impl Names {
fn add(&mut self, p: String) {
if !self.0.contains(&p) {
fn add(&mut self, p: impl AsRef<str> + Into<String>) {
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;
}
Expand Down Expand Up @@ -476,25 +476,142 @@ 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<Vec<Node<'a, 'input>>> {
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);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

A …Members child that itself wraps another element (layerMembers > segMember > Seg, the nested collection case) is pushed here as a feature, so the wrapper becomes its own layer named segMember. The real Seg features and their shapes are then read as a nested property and not read, which leaves a geometry-less layer named after the wrapper. The note says only (Seg) was not read, so the user gets a notice but the layer is the wrong feature type. The test currently pins two layers for this case. Either descend one level when a child holds only wrapper elements, or refuse that case with the error. Found by reading the code path; I did not run it.

Category: bug

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Reproduced and fixed in 0a91c28. A member's child that is itself named like a member property is now left out and counted, so the nested file gives one layer and a notice naming segMember.

}
}
if !empty {
continue;
}
}
omit(name);
}
if !has_shape {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Silent loss when the file also has standard members. application_features returns an empty list before the count at line 591 runs, in three cases: no application feature with a shape of its own (this line), a root property that directly holds a shape (line 519), and a CityGML-namespace root. So in a file with featureMember elements, application features without a shape are dropped with no notice. For example, <a:Set><gml:featureMember>…</gml:featureMember><a:xMembers><a:X><a:name>q</a:name></a:X></a:xMembers></a:Set> never reads X and reports nothing. The around(...) test cases only pin counts where a shape exists, so nothing covers this. The new docs sentence ("Application features beside standard ones aren't read, and are counted in a notice") is wrong for these cases too.

This is new: the earlier thread asked for every dropped application feature to be counted, and the fix gates the count on has_shape. I traced the code path; I did not run the tests.

Suggested fix: have application_features return its candidate features and the shape flag separately. The standard-members branch then counts candidates with the left_out filter whether or not a shape exists, and only the fallback requires a shape. Add a test for the shapeless case that expects the notice, and align the docs sentence with it.

Category: bug

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Not extended. Main drops these silently too, and a child without a shape anywhere in its collection can't be told from metadata, so the notice counts only what this search could itself have read. The guide sentence was too broad and is corrected in ab392ab.

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<Vec<(Dataset, ReadReport)>> {
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<Vec<(Dataset, ReadReport)>> {
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<Node> = 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 {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

In the branch where standard members exist, found is never merged into report, so the omitted-item notes that application_features builds (root-level text, root …Member elements that aren't features, stray text inside a member) are discarded. Only the feature count reaches the notice. The fallback branch reports the same items, so a file with featureMember elements plus a shape-holding application member gets a notice for one kind of omission and silence for the other. AGENTS.md says a reader that drops items says how many and where, and says existing silent losses are bugs. Merging found.messages into report before the count note in this branch would give the same reporting in both cases. Confidence is medium (about 60%). I did not run the tests, and the mixed-file test expects exactly one notice, so it would need checking after the change.

Category: bug

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Not changed. In this branch the scan counts every standard featureMember as an omitted item, though the standard search reads them, so merging its notes would report features that were read as lost. Root text and other non-member elements beside standard members are left out as on main.

// 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));

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nits, grouped. application stays alive as a Vec of node handles for the whole standard-member read in this branch, though it is only needed for the count, so drop(application) after the count would release it. The counted closure would read better as a named helper whose doc comment states the rule: a feature with its own shape counts, and a wrapper of members without one does not. The doc comment on read (above line 569) still describes only the standard search and should mention the application fallback.

Category: quality

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Left for the release quality pass.

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<String, Kind> = BTreeMap::new();
let mut order: Vec<String> = Vec::new();
Expand Down Expand Up @@ -623,7 +740,6 @@ pub fn read(file_name: &str, bytes: &[u8]) -> Result<Vec<(Dataset, ReadReport)>>
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,
Expand Down Expand Up @@ -874,6 +990,169 @@ mod tests {
<gml:interior><gml:LinearRing><gml:posList>48.2 10.4 48.3 10.5 48.4 10.4 48.2 10.4</gml:posList></gml:LinearRing></gml:interior></gml:Polygon></app:geom></app:parks></wfs:member>
</wfs:FeatureCollection>"#;

// 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#"<app:DKK xmlns:app="urn:example:cadastre" xmlns:gml="http://www.opengis.net/gml/3.2">
<app:perceelMember><app:Perceel gml:id="parcel-1">
<app:identificatie>101</app:identificatie>
<app:historie><app:status><app:code>A</app:code></app:status></app:historie>
<app:begrenzingPerceel><gml:Polygon><gml:exterior><gml:LinearRing>
<gml:posList>1 1 3 1 3 3 1 3 1 1</gml:posList>
</gml:LinearRing></gml:exterior></gml:Polygon></app:begrenzingPerceel>
<app:plaatscoordinaten><gml:Point><gml:pos>2 2</gml:pos></gml:Point></app:plaatscoordinaten>
</app:Perceel></app:perceelMember>
</app:DKK>"#;

#[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("</app:DKK>", "<gml:featureMember><app:Other><app:name>A</app:name></app:Other></gml:featureMember></app:DKK>");
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 = "<gml:featureMember><a:F><a:n>1</a:n></a:F></gml:featureMember>";
let other = "<a:T><a:s><gml:Point/></a:s></a:T>";
let set = format!("<a:setMember><a:Set>{shape}{inner}</a:Set>{other}</a:setMember>");
format!(r#"<a:{root} xmlns:a="urn:a" xmlns:gml="http://www.opengis.net/gml/3.2">{set}</a:{root}>"#)
};
let shape = "<a:s><gml:Point/></a:s>";
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("</app:DKK>", "<app:shape><gml:Point><gml:pos>2 2</gml:pos></gml:Point></app:shape></app:DKK>");
assert!(read("feature.gml", feature.as_bytes()).is_err());
}

#[test]
fn application_members_report_omitted_root_children_once() {
let clean = r#"<app:Set xmlns:app="urn:example:cadastre" xmlns:gml="http://www.opengis.net/gml/3.2">
<gml:boundedBy><gml:Envelope/></gml:boundedBy>
<app:parcelMembers><app:Parcel><app:name>A</app:name><app:shape><gml:Point><gml:pos>1 2</gml:pos></gml:Point></app:shape></app:Parcel></app:parcelMembers>
</app:Set>"#;
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(
"</app:Set>",
"<app:metadata/><app:metadata/><gml:definitionMember><gml:Definition/></gml:definitionMember></app:Set>",
);
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",
"<a:definitionMember><gml:Definition><gml:name>D</gml:name></gml:Definition></a:definitionMember>",
"Definition",
),
("crs", "<a:crsMember><gml:ProjectedCRS><gml:name>C</gml:name></gml:ProjectedCRS></a:crsMember>", "ProjectedCRS"),
(
"coverage",
"<a:coverageMember><gml:RectifiedGridCoverage><gml:rangeSet/></gml:RectifiedGridCoverage></a:coverageMember>",
"RectifiedGridCoverage",
),
(
"time",
"<a:timeMember><gml:TimeInstant><gml:timePosition>2020</gml:timePosition></gml:TimeInstant></a:timeMember>",
"TimeInstant",
),
("topology", "<a:topologyMember><gml:Node/></a:topologyMember>", "Node"),
("empty WFS", "<a:responseMember><wfs:FeatureCollection numberReturned=\"0\"/></a:responseMember>", "FeatureCollection"),
("linked member", "<a:linkMember xlink:href=\"#ref\"/>", "linkMember"),
("text feature", "<a:teamMembers><a:Player>Ann</a:Player></a:teamMembers>", "Player"),
(
"nested collection",
"<a:layerMembers><a:segMember><a:Seg><a:geom><gml:Point/></a:geom></a:Seg></a:segMember></a:layerMembers>",
"segMember",
),
(
"CityGML lookalike",
"<a:cityObjectMember><a:Building><a:name>B</a:name></a:Building></a:cityObjectMember>",
"cityObjectMember",
),
("bounding box only", "<a:siteMember><a:Site><gml:boundedBy><gml:Envelope/></gml:boundedBy></a:Site></a:siteMember>", ""),
("unqualified shape", "<a:pointsMember><Point><pos>1 1</pos></Point></a:pointsMember>", ""),
];
let point = "<a:siteMember><a:Site><a:shape><gml:Point><gml:pos>1 2</gml:pos></gml:Point></a:shape></a:Site></a:siteMember>";
let wrap = |content: &str| {
format!(
r#"<a:Set xmlns:a="urn:test" xmlns:gml="http://www.opengis.net/gml/3.2" xmlns:wfs="http://www.opengis.net/wfs/2.0"
xmlns:xlink="http://www.w3.org/1999/xlink">{content}</a:Set>"#
)
};
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}<a:teamMembers>loose member text<a:Player>Ann</a:Player></a:teamMembers>"));
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:siteMembers><a:siteMember><a:name>A</a:name></a:siteMember>
<a:siteMember><a:shape><gml:Point><gml:pos>1 2</gml:pos></gml:Point></a:shape></a:siteMember></a:siteMembers>"#;
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("</a:Site>", "stray</a:Site>"));
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();
Expand Down
9 changes: 7 additions & 2 deletions crates/data/src/io.rs
Original file line number Diff line number Diff line change
Expand Up @@ -286,6 +286,11 @@ fn read_city_member(file_name: &str, bytes: &[u8], crs: Option<Crs>) -> Result<V
/// LandXML, RSS, Atom, GeoRSS, XML that isn't a city model) stays within [`BYTES_FLOOR`], as
/// before #2408; the others take [`max_bytes`].
pub fn read_layers(file_name: &str, bytes: &[u8]) -> Result<Vec<LayerRead>> {
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<Vec<LayerRead>> {
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
Expand Down Expand Up @@ -331,7 +336,7 @@ pub fn read_layers(file_name: &str, bytes: &[u8]) -> Result<Vec<LayerRead>> {
}
// 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)?),
Expand Down Expand Up @@ -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())
Expand Down
Loading
Loading