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 .github/workflows/nightly.yml
Original file line number Diff line number Diff line change
Expand Up @@ -60,7 +60,7 @@ jobs:
release-build: true

# Everyday jobs on real data: the Census Bureau's tracts for Shelby County, Tennessee, checked
# against the areas it publishes (crates/engine/tests/workflows.rs). The files are public domain
# against the areas it publishes (crates/engine/tests/integration/workflows.rs). The files are public domain
# and pinned by checksum; a changed file fails the run, a download that fails skips the tests
# (`tested` tells the report, which then neither opens nor closes an issue).
workflows:
Expand Down
2 changes: 1 addition & 1 deletion ROADMAP.md
Original file line number Diff line number Diff line change
Expand Up @@ -71,7 +71,7 @@ A result is right, or RustGIS says what it lost or assumed
([AGENTS.md](AGENTS.md#never-silent)).
- Known silent losses: DuckDB queries (`ST_Force2D`) drop Z without a notice; the OSM reader leaves out rings that don't close, rings and member ways with
nodes or ways the file doesn't hold, and inner rings outside every outer one; and the text
readers' losses listed as `Silent` in `crates/engine/tests/never_silent_reading.rs`, among them
readers' losses listed as `Silent` in `crates/engine/tests/integration/never_silent_reading.rs`, among them
each vertex's Z in DXF and unreadable coordinates, holes and parts in KML, GeoRSS, MapInfo and
DXF, plus geometry-collection members in XLSX/ODS/XLS/XLSB, error-valued attribute cells in XLSX,
and attribute fields/values in XLSB short-cell workbooks (the original SheetJS 0.18.5 clean
Expand Down
29 changes: 27 additions & 2 deletions crates/data/src/citygml.rs
Original file line number Diff line number Diff line change
Expand Up @@ -569,6 +569,13 @@ fn written_dim(e: &BytesStart) -> Option<Box<str>> {
Some(written_attribute("srsDimension", value).into())
}

/// Whether the `<!` markup error at `at` is the text ending at `<!` (a cut), not markup that `<!`
/// starts and nothing knows, earlier in the text.
fn bang_at_end(text: &str, at: u64) -> bool {
// The error is placed at the `<` of the markup.
usize::try_from(at).ok().and_then(|at| text.get(at..)).is_some_and(|rest| rest.trim_end() == "<!")
}

fn position(reader: &Reader<&[u8]>) -> usize {
usize::try_from(reader.buffer_position()).unwrap_or(usize::MAX)
}
Expand Down Expand Up @@ -740,7 +747,10 @@ impl Index {
// A syntax error is the text ending inside markup (a tag, a comment): a file cut
// short, as one cut between tags is. But for `<!` followed by what no markup
// starts with, which is a file broken there.
Err(quick_xml::Error::Syntax(e)) if !matches!(e, SyntaxError::InvalidBangMarkup) || text.ends_with("<!") => {
// The `<!` must be the one the text ends at, not one earlier in it.
Err(quick_xml::Error::Syntax(e))
if !matches!(e, SyntaxError::InvalidBangMarkup) || bang_at_end(text, reader.error_position()) =>
{
let at = usize::try_from(reader.error_position()).unwrap_or(usize::MAX);
in_root_end = depth == 1 && text.get(at..).is_some_and(|rest| rest.starts_with("</"));
break;
Expand Down Expand Up @@ -901,6 +911,21 @@ impl Index {
self.other.get_or_insert_with(|| cut(srs));
Ok(())
}
// One RustGIS doesn't know may be the same system as the other: said as unknown.
(a, b) if a.is_none() || b.is_none() => {
let (unknown, other) = if a.is_none() { (first.as_str(), srs) } else { (srs, first.as_str()) };
let both = if a.is_none() && b.is_none() { "two coordinate systems" } else { "a coordinate system" };
let then = if self.archive {
"which aren't read together in a model in an archive"
} else {
"which aren't read together; give the coordinate system (crs) to read it in one"
};
Err(DataError::Unsupported(format!(
"{file_name}: it names {both} RustGIS doesn't know ({} beside {}), {then}",
cut(unknown),
cut(other)
)))
}
_ if self.archive => Err(DataError::Unsupported(format!(
"{file_name}: it names different coordinate systems ({} and {}), which aren't read together; in an archive a model keeps the systems it names, so a coordinate system given doesn't apply to it",
cut(first),
Expand Down Expand Up @@ -2599,7 +2624,7 @@ impl<'a, 'i> Walk<'_, 'a, 'i> {
fn implicit(&mut self, g: &Node<'a, 'i>) -> Option<()> {
if self.local {
// A prototype's geometries are GML's: one that is an implicit geometry places nothing.
self.counts.unknown.insert("ImplicitGeometry in a prototype".to_string());
self.counts.nested_instances += 1;
return Some(());
}
let at = elements(*g).find(|c| local(c) == "referencePoint")?;
Expand Down
27 changes: 27 additions & 0 deletions crates/data/src/citygml/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -210,6 +210,13 @@ fn a_compound_system_is_read_by_its_horizontal_part() {
let other = inner.replace("EPSG:25832", "EPSG:25833");
let err = read("model.gml", &model("EPSG:25832", &building("b1", &other)), None).unwrap_err().to_string();
assert!(err.contains("different coordinate systems (EPSG:25832 and EPSG:25833)"), "{err}");
// One RustGIS doesn't know beside a known one: said as unknown, not as another system.
let unknown = inner.replace("EPSG:25832", "EPSG:999999");
let err = read("model.gml", &model("EPSG:25832", &building("b1", &unknown)), None).unwrap_err().to_string();
assert!(err.contains("a coordinate system RustGIS doesn't know (EPSG:999999 beside EPSG:25832)"), "{err}");
assert!(err.contains("give the coordinate system (crs)") && !err.contains("different coordinate systems"), "{err}");
// Given one, it is read in it.
assert!(read("model.gml", &model("EPSG:25832", &building("b1", &unknown)), Some(Crs::Epsg(25832))).is_ok());
}

/// A compound system's vertical part is said when its heights aren't metres upward: another unit, a
Expand Down Expand Up @@ -1109,6 +1116,11 @@ fn a_file_broken_in_the_middle_is_refused() {
// Markup that `<!` starts and nothing knows, in the middle: refused too. Ending at `<!`: cut.
let bang = lonlat(&[building("b1", &box_surfaces("b1")), "<!x>".to_string(), building("b2", &box_surfaces("b2"))].concat());
assert!(read("model.gml", &bang, None).is_err());
// Broken in the middle and ending at `<!` too: still refused, not read as cut short there.
let mut bang_cut = bang.clone();
bang_cut.extend_from_slice(b"<!");
let err = read("model.gml", &bang_cut, None).unwrap_err().to_string();
assert!(!err.contains("cut short"), "{err}");
let whole = lonlat(&[building("b1", &box_surfaces("b1")), "<!-- n -->".to_string(), building("b2", &box_surfaces("b2"))].concat());
let cut = whole.windows(4).position(|w| w == b"<!--").unwrap() + 2;
let out = read("model.gml", &whole[..cut], None).unwrap();
Expand Down Expand Up @@ -1935,6 +1947,21 @@ fn a_prototype_that_cant_be_read_is_said_once() {
assert!(says(&out, "2 geometry instances are drawn as a point"), "{:?}", messages_of(&out));
}

/// An implicit geometry inside a prototype places nothing: said as such, not as a geometry of an
/// unknown type.
#[test]
fn an_implicit_geometry_inside_a_prototype_is_said() {
let nested = format!(
"<core:relativeGMLGeometry><gml:MultiGeometry><gml:geometryMember><core:ImplicitGeometry>{}</core:ImplicitGeometry></gml:geometryMember></gml:MultiGeometry></core:relativeGMLGeometry>{}",
reference(1.0, 1.0, 0.0),
reference(5.0, 5.0, 0.0)
);
let out = read("model.gml", &lonlat(&furniture("t1", &nested)), None).unwrap();
assert!(says(&out, "1 implicit geometries inside a prototype aren't placed"), "{:?}", messages_of(&out));
assert!(!says(&out, "unknown types"), "{:?}", messages_of(&out));
assert!(says(&out, "its template or prototype is missing, in another file, can't be read or draws nothing"), "{:?}", messages_of(&out));
}

/// A prototype's geometry linked from outside an implicit geometry isn't read as the file's.
#[test]
fn a_prototype_linked_from_outside_is_said() {
Expand Down
5 changes: 4 additions & 1 deletion crates/data/src/citymodel.rs
Original file line number Diff line number Diff line change
Expand Up @@ -146,6 +146,8 @@ pub(crate) struct Counts {
pub(crate) dropped_rings: usize,
pub(crate) instances: usize,
pub(crate) tin_reliefs: usize,
/// Implicit geometries inside a prototype (CityGML), which place nothing.
pub(crate) nested_instances: usize,
pub(crate) unconverted: usize,
pub(crate) bad_heights: usize,
/// Objects whose lowest and highest Z, or lowest Z and ground, are too far apart for their
Expand Down Expand Up @@ -1147,10 +1149,11 @@ pub(crate) fn messages(c: &Counts) -> Vec<String> {
say(
c.instances,
format!(
"{} geometry instances are drawn as a point at their reference point, with no height: their shape isn't placed (it is in another file, it or its matrix can't be read, or placing every instance would cost many times the file)",
"{} geometry instances are drawn as a point at their reference point, with no height: their shape isn't placed (its template or prototype is missing, in another file, can't be read or draws nothing; its matrix is missing or can't be read; its placed point isn't a finite number; or placing every instance would cost many times the file)",
c.instances
),
);
say(c.nested_instances, format!("{} implicit geometries inside a prototype aren't placed", c.nested_instances));
say(c.tin_reliefs, format!("{} TINRelief objects aren't drawn and are left out", c.tin_reliefs));
say(
c.unconverted,
Expand Down
50 changes: 30 additions & 20 deletions crates/data/src/interop.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,19 +6,11 @@ use rustgis_geom::Coord;

use crate::{Dataset, Geometry};

/// Text for XML: special characters escaped, control characters (invalid in XML 1.0) dropped.
fn xml(s: &str) -> String {
let clean: String = s.chars().filter(|c| !c.is_control() || matches!(c, '\t' | '\n' | '\r')).collect();
escaped_xml(&clean)
}

fn escaped_xml(s: &str) -> String {
s.replace('&', "&amp;").replace('<', "&lt;").replace('>', "&gt;").replace('"', "&quot;").replace('\r', "&#13;")
}

/// Text for XML, special characters escaped: kept exactly or refused, never cleaned without
/// reporting its loss. `place` says where in the file of `format` the text goes, for the refusal.
///
/// XML 1.0 Char production: https://www.w3.org/TR/xml/#charsets.
/// A description is kept exactly or refused, never cleaned without reporting its loss.
fn description_xml(text: &str, layer: &str, feature: u64) -> crate::Result<String> {
fn xml(text: &str, format: &str, place: impl FnOnce() -> String) -> crate::Result<String> {
let mut invalid = text.chars().filter(|c| {
!matches!(*c,
'\t' | '\n' | '\r' | '\u{20}'..='\u{d7ff}' | '\u{e000}'..='\u{fffd}' | '\u{10000}'..='\u{10ffff}'
Expand All @@ -27,13 +19,23 @@ fn description_xml(text: &str, layer: &str, feature: u64) -> crate::Result<Strin
if let Some(first) = invalid.next() {
let count = invalid.count().saturating_add(1);
return Err(crate::DataError::Format(format!(
"KML: {layer}, feature id {feature}, description: {count} character(s) cannot be represented in XML 1.0 (first U+{:04X})",
"{format}: {}: {count} character(s) cannot be represented in XML 1.0 (first U+{:04X})",
place(),
first as u32
)));
}
Ok(escaped_xml(text))
}

fn escaped_xml(s: &str) -> String {
s.replace('&', "&amp;").replace('<', "&lt;").replace('>', "&gt;").replace('"', "&quot;").replace('\r', "&#13;")
}

/// Where in a layer's file a feature's text goes, for [`xml`]'s refusal.
fn feature_place(layer: &str, feature: u64, what: &str) -> String {
format!("{layer}, feature id {feature}, {what}")
}

fn coords(pts: &[Coord]) -> String {
pts.iter().map(|c| format!("{},{}", c.x, c.y)).collect::<Vec<_>>().join(" ")
}
Expand Down Expand Up @@ -77,7 +79,7 @@ fn kml_geometry(g: &Geometry) -> String {
pub fn to_kml(ds: &Dataset, name_field: Option<usize>) -> crate::Result<String> {
let mut out = format!(
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<kml xmlns=\"http://www.opengis.net/kml/2.2\"><Document><name>{}</name>\n",
xml(&ds.name)
xml(&ds.name, "KML", || "layer name".to_string())?
);
// KML's description is text. Other types and differently-cased columns stay in
// ExtendedData, where the reader preserves their values and reports name collisions.
Expand All @@ -87,7 +89,9 @@ pub fn to_kml(ds: &Dataset, name_field: Option<usize>) -> crate::Result<String>
let Some(g) = &f.geometry else { continue };
let name = name_field.map(|fi| ds.value(r, fi).to_file_text()).unwrap_or_else(|| f.id.to_string());
let description = match description.map(|fi| ds.value(r, fi)) {
Some(crate::Value::Text(text)) => format!("<description>{}</description>", description_xml(text, &ds.name, f.id)?),
Some(crate::Value::Text(text)) => {
format!("<description>{}</description>", xml(text, "KML", || feature_place(&ds.name, f.id, "description"))?)
}
_ => String::new(),
};
let data: String = ds
Expand All @@ -98,16 +102,21 @@ pub fn to_kml(ds: &Dataset, name_field: Option<usize>) -> crate::Result<String>
.map(|(fd, v)| {
let value = match v {
crate::Value::Text(text) if fd.name == "description" && fd.ty == crate::FieldType::Text => {
description_xml(text, &ds.name, f.id)?
xml(text, "KML", || feature_place(&ds.name, f.id, "description"))?
}
_ => xml(&v.to_file_text()),
_ => xml(&v.to_file_text(), "KML", || feature_place(&ds.name, f.id, &format!("field '{}'", fd.name.escape_debug())))?,
};
Ok(format!("<Data name=\"{}\"><value>{value}</value></Data>", xml(&fd.name)))
// In an attribute, where a reader turns tabs and line breaks into spaces unless
// they are written as references.
let name = xml(&fd.name, "KML", || format!("{}, field name '{}'", ds.name, fd.name.escape_debug()))?
.replace('\t', "&#9;")
.replace('\n', "&#10;");
Ok(format!("<Data name=\"{name}\"><value>{value}</value></Data>"))
})
.collect::<crate::Result<String>>()?;
out.push_str(&format!(
"<Placemark><name>{}</name>{description}<ExtendedData>{data}</ExtendedData>{}</Placemark>\n",
xml(&name),
xml(&name, "KML", || feature_place(&ds.name, f.id, "name"))?,
kml_geometry(g)
));
}
Expand All @@ -126,7 +135,8 @@ pub fn to_gpx(ds: &Dataset, name_field: Option<usize>) -> crate::Result<String>
for (r, f) in ds.features.iter().enumerate() {
crate::progress::step(1)?;
let Some(g) = &f.geometry else { continue };
let name = xml(&name_field.map(|fi| ds.value(r, fi).to_file_text()).unwrap_or_else(|| f.id.to_string()));
let name = name_field.map(|fi| ds.value(r, fi).to_file_text()).unwrap_or_else(|| f.id.to_string());
let name = xml(&name, "GPX", || feature_place(&ds.name, f.id, "name"))?;
match g {
Geometry::Point(c) => out.push_str(&format!("<wpt {}><name>{name}</name></wpt>\n", pt(c))),
Geometry::MultiPoint(v) => v.iter().for_each(|c| out.push_str(&format!("<wpt {}><name>{name}</name></wpt>\n", pt(c)))),
Expand Down
Loading
Loading