Skip to content
Merged
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
100 changes: 93 additions & 7 deletions crates/data/src/kml.rs
Original file line number Diff line number Diff line change
Expand Up @@ -88,7 +88,7 @@ pub fn read(file_name: &str, bytes: &[u8]) -> Result<Vec<Layer>> {
geometry_losses: GeometryLosses::default(),
};
r.collect_styles(doc.root());
r.walk(doc.root(), &mut Vec::new(), 0);
r.walk(doc.root(), &schema_strings(doc.root()), &mut Vec::new(), 0);
r.collect_fields(doc.root());
Ok(r.layers(&name))
}
Expand Down Expand Up @@ -233,6 +233,21 @@ fn explicit_string(n: &Node) -> bool {
name == "string" && n.lookup_namespace_uri(prefix) == Some("http://www.w3.org/2001/XMLSchema")
}

/// The (schema id, field name) pairs the file's own schemas declare `string`. A value is looked up by the
/// schema its SchemaData names; one found makes its column text for the whole layer it is in.
fn schema_strings<'a>(root: Node<'a, '_>) -> HashSet<(&'a str, &'a str)> {
let mut strings = HashSet::new();
for schema in root.descendants().filter(|n| local(n) == "Schema") {
let Some(id) = schema.attribute("id") else { continue };
for field in schema.children().filter(|n| local(n) == "SimpleField" && n.attribute("type") == Some("string")) {
if let Some(name) = field.attribute("name") {
strings.insert((id, name));
}
}
}
strings
}

fn local<'a>(n: &Node<'a, '_>) -> &'a str {
n.tag_name().name()
}
Expand All @@ -251,6 +266,19 @@ fn text_of(n: &Node) -> String {
raw_text_of(n).trim().to_string()
}

/// The text of a field declared `string`, padding and all, without the line breaks and indentation an
/// indented file puts around it.
fn string_text(n: &Node) -> String {
let raw = raw_text_of(n);
let (start, end) = (raw.trim_start(), raw.trim_end());
let lead = raw.len() - start.len();
let trail = raw.len() - end.len();
let broken = |edge: Option<&str>| edge.is_some_and(|s| s.contains('\n'));
let from = if broken(raw.get(..lead)) { lead } else { 0 };
let to = if broken(raw.get(end.len()..)) { raw.len() - trail } else { raw.len() };
raw.get(from..to).unwrap_or_default().to_string()
}

fn data_text(n: &Node, key: &str) -> String {
if key == "description" { raw_text_of(n) } else { text_of(n) }
}
Expand Down Expand Up @@ -592,7 +620,8 @@ impl Reader {
self.styles.contains_key(&id).then_some(id)
}

fn walk(&mut self, n: Node, folders: &mut Vec<String>, depth: usize) {
/// Visits nested folders in source order, keeping the path used by each placemark.
fn walk(&mut self, n: Node, strings: &HashSet<(&str, &str)>, folders: &mut Vec<String>, depth: usize) {
if depth > MAX_DEPTH {
return;
}
Expand All @@ -603,21 +632,22 @@ impl Reader {
if named {
folders.push(child_text(&c, "name").unwrap_or_default());
}
self.walk(c, folders, depth + 1);
self.walk(c, strings, folders, depth + 1);
if named {
folders.pop();
}
}
"Placemark" => self.placemark(&c, folders),
"Placemark" => self.placemark(&c, strings, folders),
// Pictures, read by `ground_overlays`.
"GroundOverlay" => {}
"kml" => self.walk(c, folders, depth + 1),
"kml" => self.walk(c, strings, folders, depth + 1),
_ => {}
}
}
}

fn placemark(&mut self, pm: &Node, folders: &[String]) {
/// Keeps the first value for each extended data field and retains each drawable geometry kind.
fn placemark(&mut self, pm: &Node, strings: &HashSet<(&str, &str)>, folders: &[String]) {
let mut parts = Parts::default();
for g in pm.children().filter(|c| c.is_element()) {
geometry(&g, &mut parts, 0);
Expand All @@ -638,7 +668,16 @@ impl Reader {
let text = value.map(|v| if string { raw_text_of(&v) } else { data_text(&v, k) }).unwrap_or_default();

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.

This is the twin of the SimpleData path the PR changes, and it still has the bug the PR fixes there. For a <Data> whose <value> has an explicit xsi:type string, raw_text_of(&v) keeps every character between the tags. In a pretty-printed file such as

<Data name="House">
  <value xsi:type="xs:string">
    012
  </value>
</Data>

the value reads as "\n 012\n " rather than "012", so the indentation becomes data. The SimpleData branch now uses string_text to drop line breaks and indentation, and this branch should do the same. data_text already returns the raw text for description, so the suggestion keeps that case unchanged. This path predates the PR, but it is the same family, and the new SimpleData test does not cover it. A regression test with an indented <Data>/<value> should go with the fix.

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.

Kept as it is, on purpose. An explicit xsi:type string is what RustGIS's own writer puts on a text field's values (interop.rs), with no layout around them, so every character between the tags is the value: one that begins or ends with a line break would be changed by a round trip if it were trimmed here. A SimpleData value has no such mark, and RustGIS doesn't write them, so only there can a line break at an end be taken for a file's layout.

(k.to_string(), text, string)
}),
"SimpleData" => d.attribute("name").map(|k| (k.to_string(), data_text(&d, k), false)),
"SimpleData" => d.attribute("name").map(|k| {
let string = d
.parent_element()
.filter(|parent| local(parent) == "SchemaData")
.and_then(|parent| parent.attribute("schemaUrl"))
.and_then(|url| url.strip_prefix('#'))
.is_some_and(|id| strings.contains(&(id, k)));
let text = if string && k != "description" { string_text(&d) } else { data_text(&d, k) };
(k.to_string(), text, string)
}),
_ => None,
};
if let Some((k, v, string)) = pair.filter(|(k, _, _)| !k.trim().is_empty()) {
Expand Down Expand Up @@ -1130,6 +1169,53 @@ mod tests {
assert_eq!(ds.value(0, id), &Value::Text("12345678901234567891".into()));
}

/// A local schema keeps numeric-looking house numbers as text, including padding.
#[test]
fn local_kml_schema_strings_keep_their_spelling() {
let xml = br##"<kml><Document>
<Placemark><ExtendedData><SchemaData schemaUrl="#permits">
<SimpleData name="House"> 12 </SimpleData><SimpleData name="sequence">7</SimpleData>
</SchemaData></ExtendedData><Point><coordinates>1,2</coordinates></Point></Placemark>
<Placemark><ExtendedData><SchemaData schemaUrl="#roads">
<SimpleData name="House">42</SimpleData>
</SchemaData></ExtendedData><LineString><coordinates>1,2 3,4</coordinates></LineString></Placemark>
<Schema id="permits"><SimpleField name="House" type="string"/><SimpleField name="sequence" type="int"/></Schema>
<Schema id="roads"><SimpleField name="House" type="int"/></Schema>
</Document></kml>"##;
let layers = read("permits.kml", xml).unwrap();
let points = &layers[0].dataset;
let house = points.field_index("House").unwrap();
assert_eq!(points.fields[house].ty, FieldType::Text);
assert_eq!(points.value(0, house), &Value::Text(" 12 ".into()));
assert_eq!(points.value(0, points.field_index("sequence").unwrap()), &Value::Int(7));
let lines = &layers[1].dataset;
assert_eq!(lines.value(0, lines.field_index("House").unwrap()), &Value::Int(42));
assert!(layers.iter().all(|layer| layer.report.messages.is_empty()));
}

/// An indented file's line breaks around a value aren't in it, and a value of one layer declared
/// `string` makes the layer's column text.
#[test]
fn local_kml_schema_strings_leave_out_the_files_indentation() {
let place = |schema: &str, house: &str| {
format!(
"<Placemark><ExtendedData><SchemaData schemaUrl=\"#{schema}\"><SimpleData name=\"House\">{house}</SimpleData></SchemaData></ExtendedData><Point><coordinates>1,2</coordinates></Point></Placemark>"
)
};
let values = ["\n 012\n ", " 12 ", "\n ", "a\nb", "\n 12 "];
let places: String = values.iter().map(|v| place("permits", v)).collect();
let xml = format!(
"<kml><Document><Schema id=\"permits\"><SimpleField name=\"House\" type=\"string\"/></Schema><Schema id=\"other\"><SimpleField name=\"House\" type=\"int\"/></Schema>{places}{}</Document></kml>",
place("other", "7")
);
let layers = read("permits.kml", xml.as_bytes()).unwrap();
let ds = &layers[0].dataset;
let house = ds.field_index("House").unwrap();
assert_eq!(ds.fields[house].ty, FieldType::Text);
let read: Vec<String> = (0..6).map(|r| ds.value(r, house).to_string()).collect();
assert_eq!(read, ["012", " 12 ", "", "a\nb", "12 ", "7"]);
}

#[test]
fn source_ids_and_declared_empty_columns_survive_kml_round_trips() {
let xml = r##"<kml><Document><Schema id="fields"><SimpleField name="empty" type="string"/></Schema>
Expand Down
Loading