Skip to main content

hpr_flightdata/
kml.rs

1//! KML files holding a GPS track, as AltOS, Missile Works' RTx, Big Red Bee's BeeLine, fw2kml, GPS
2//! Visualizer and others write a flight's path for Google Earth.
3//!
4//! KML (Keyhole Markup Language) is XML, standardized as OGC 07-147r2 (*OGC KML*, version 2.2.0,
5//! 2008). A flight's path is a `Placemark` holding a geometry: a `LineString`, whose
6//! `coordinates` list one tuple per point, or Google's extension `gx:Track`, which pairs each
7//! point's `when` with its `gx:coord`:
8//!
9//! ```text
10//! <Placemark><name>Flight Track</name>
11//!   <LineString><altitudeMode>absolute</altitudeMode>
12//!     <coordinates>-97.10000,35.20000,402 -97.10001,35.20002,415</coordinates>
13//!   </LineString>
14//! </Placemark>
15//! <Placemark><name>fw2kml - Flight 0</name>
16//!   <gx:Track><altitudeMode>absolute</altitudeMode>
17//!     <when>2026-05-23T10:15:00.000Z</when><gx:coord>-97.10000 35.20000 402.0</gx:coord>
18//!   </gx:Track>
19//! </Placemark>
20//! ```
21//!
22//! **What the standard sets.** A tuple is longitude, latitude and an optional altitude, comma
23//! separated, tuples separated by whitespace (§16.9.1); degrees are WGS84's, and "altitude is
24//! measured from the vertical datum, which is the WGS84 EGM96 Geoid" (§6.2), in meters
25//! (§16.1.1). How a viewer places the altitude is the geometry's `altitudeMode` (§9.17, §16.1.1):
26//! `absolute`, "a value in meters relative to the vertical datum"; `relativeToGround`, "in meters
27//! relative to the terrain elevation"; `clampToGround`, the default, "ignore the altitude
28//! specification". Google adds `gx:altitudeMode`'s `relativeToSeaFloor` and `clampToSeaFloor`,
29//! and `gx:Track`, whose "number of `<when>` elements … must be equal to the number of
30//! `<gx:coord>` elements", each coordinate "three values for longitude, latitude, and altitude,
31//! with no comma separators" (Google, *KML Reference*, developers.google.com/kml/documentation/
32//! kmlreference, `<gx:Track>`). A `when` is an XML Schema date-time (§15.3.3.1, §16.10.1), with `Z`
33//! for UTC or a `±hh:mm` offset; one that states no zone is "the time in the timezone of some
34//! unspecified locality" (W3C, *XML Schema Part 2*, §3.2.7).
35//!
36//! **Tracks and channels.** A KML file holds tracks of positions, not an altimeter's record over
37//! time: even an altitude AltOS took from its barometer (below) is one value of a track's points.
38//! So the record's primary track is empty and every value is a channel, with a note, as the GPS
39//! logs' decision, [ADR-254][adr-254] §2, has it. Each geometry, in the file's order, inside a
40//! `MultiGeometry` too, is a track: each `LineString`, `gx:Track` and `Point`. A track's channels
41//! are named after its `Placemark`'s `name`, or `track` if it has none; a placemark holding several
42//! geometries numbers them, `<name> part 2`, and a name already used gains ` (2)`, ` (3)` …, so no
43//! two tracks share a name:
44//!
45//! | Channel | Quantity | From |
46//! |---|---|---|
47//! | `<name> latitude`, `<name> longitude` | [`Quantity::Latitude`], [`Quantity::Longitude`] | the tuple's second and first numbers |
48//! | `<name> altitude` | [`Quantity::GnssAltitude`], m | the third number, in mode `absolute` |
49//! | `<name> altitude` | [`Quantity::AltitudeMsl`], m | the same, in an AltOS track whose altitude is the barometer's (below) |
50//! | `<name> height above ground`, `<name> height above sea floor` | [`Quantity::Distance`], m | the third number, in mode `relativeToGround` or `relativeToSeaFloor`: a height above the terrain, not above sea level |
51//! | `<name> altitude` | [`Quantity::Unrecognized`], as written | the third number, in a mode that tells a viewer to ignore it (`clampToGround`, `clampToSeaFloor`, or none stated), in a mode the standard doesn't name, or from GPS Visualizer (below) |
52//! | `<name> GPS altitude` | [`Quantity::GnssAltitude`], m | AltOS's comment `alt`, where it differs from the tuple's, in a file where it equals the tuple's at some point |
53//! | `<name> GPS altitude` | [`Quantity::Unrecognized`], as written | the same, in a file where it equals the tuple's at no point, so nothing in the file shows its unit |
54//! | `<name> Alt` | [`Quantity::Unrecognized`], as written | the `Seconds` layout's `Alt`, where it differs from the tuple's |
55//! | `<name> time` | [`Quantity::Unrecognized`], as written | AltOS's comment `time`, where its steps don't show it is in seconds (below; none of the samples) |
56//! | `<name> satellites` | [`Quantity::Number`] | a comment's `sats` |
57//! | `<name> offset` | [`Quantity::Number`] | the BeeLine comment's first number |
58//!
59//! A track whose tuples carry no altitude (a two-number tuple's altitude is absent, not 0: the
60//! standard calls it optional) has no altitude channel. A `Point` is a track of one sample. A
61//! tuple that isn't two or three numbers, or a latitude or longitude out of range, is a gap,
62//! `NaN`, counted in a note.
63//!
64//! **Times.** A point's time is the one the file gives it ([ADR-254][adr-254] §3): a `gx:Track`'s
65//! `when`; a `Point` placemark's `TimeStamp`; or, where a writer puts a comment right after a
66//! tuple, the time in the comment. The log's zero is the first point the file times, and a note
67//! names it. A point the file gives no time keeps its place with its time a gap, `NaN` (§4), as
68//! every point of a path without times does, with a note. Times stay in the file's order; a note
69//! says how often and how far they go back. A `Point` with a time is also an [`Event`] named after
70//! its placemark. Times on two kinds of clock in one file (none of the samples) can't share a zero:
71//! those not on the first timed point's clock are gaps, with a note. A time of day that steps back
72//! by more than 12 h has passed midnight, and a day is added from there on, at most
73//! [`MAX_MIDNIGHTS`] times; the times of day after that are gaps, with a note.
74//!
75//! **Comments beside points.** Three layouts are read, case aside:
76//!
77//! - AltOS: `<!-- alt 1000.0000000 time 2.5000000 sats 6 -->`: the GPS receiver's altitude, a
78//!   time and its satellite count.
79//! - `<!-- Alt 250.0 Seconds 9.5 -->`, in files styled after AltOS's but not named by it.
80//! - Big Red Bee's BeeLine: `<!-- 1003 sats:8 UTC 12:34:56 -->`: a number that steps by 15 a
81//!   point, the record's place in the logger's memory as far as the files show, the satellite
82//!   count, and the UTC time of day.
83//!
84//! A comment is a point's only if it follows the point's tuple with nothing but whitespace
85//! between, and before the next tuple; other comments are counted in a note and not read, nor is
86//! their text quoted.
87//!
88//! **The writers, among the project's sample logs.** As of 2026-10-12, 43 distinct KML files:
89//!
90//! - *fw2kml* (14), the community converter of Featherweight GPS logs (a Rocketry Forum post,
91//!   2023-01-06; github.com/pirate21213/fw2kml): one `Placemark` named `fw2kml - Flight N`. 12 hold
92//!   a `LineString` with no times; 2 a `gx:Track` with a `when` per point, in UTC to the tenth of
93//!   a second, and a `gx:Tour` of camera views, which isn't a track. One of the two is the same
94//!   KML document four times over: a later document identical to the first is skipped with a
95//!   note. A later document that differs (none of the samples) is read as more tracks, with a
96//!   note, up to [`MAX_DOCUMENTS`].
97//! - *Missile Works' RTx* (12): document `RTx/GPS Flight`, KML 2.1's namespace, a byte-order mark
98//!   and CR LF; a `Folder` holding `Flight Track`, a path of whole meters with no times, and in 3
99//!   files a second path, `Ground Track`, the same positions with no altitude, `clampToGround`.
100//!   The RTx's manual says its GPS altitude "is always expressed as Mean Sea Level" (*RTx User
101//!   Manual*, 2016-11-26, p13). In 10 of the 12, all from pads near sea level, the altitude reads
102//!   exactly 0 for the first hundreds of points, and in none does it go below 0, as a receiver's
103//!   altitude clamped at sea level would; it is kept as written.
104//! - *AltOS* (11), AltosUI's KML export (Altus Metrum, *AltOS* manual, §12.5.2): a document named
105//!   `AO Flight#N S/N: M`, from which the flight number and serial number are read, and a comment
106//!   beside every point. 7 files hold one `GPS Altitude` path, whose tuple altitude equals the
107//!   comment's `alt`; their `Snippet` names the product and firmware, read into the record. 3
108//!   older files hold one path per flight state (`pad`, `boost`, …) and an unset date
109//!   (`2147483647-…`, or `0000-00-00`). 1 holds a `Barometric Altitude` path and a `GPS Altitude`
110//!   path, each with `Point` placemarks at the flight's events (`Boost (Baro)` …), and a byte that
111//!   isn't UTF-8 in its text; AltOS's release notes say that since 1.8.3 the "KML export now
112//!   reports both barometric and GPS altitude data". In the flight-state paths the tuple's
113//!   altitude climbs while the comment's `alt` holds still with few satellites, and in the
114//!   barometric path the two differ at every point: the tuple's is the barometer's. So in an AltOS
115//!   track whose tuple altitude differs from its comments' `alt` at more than half of the points
116//!   that carry both, the tuple altitude is read as a barometric altitude above sea level,
117//!   [`Quantity::AltitudeMsl`], and the comments' `alt` as the GPS altitude, a channel of its own;
118//!   otherwise the tuple's is the GPS altitude, and the comments' `alt` a channel only if it
119//!   differs somewhere. In every sample track the two differ at all the points or at none, so no
120//!   single point decides a track. The comments' `alt` is read in meters where it equals the
121//!   tuple's, meters by the standard, at some point of the file, as in the GPS path beside the
122//!   barometric one; in the flight-state files it equals it nowhere, so nothing in them shows its
123//!   unit and it is kept as written. The `time` is 0 in every comment of the 7 GPS-only files and
124//!   the barometric one, which this reader takes as unset: those points have no time. In the
125//!   flight-state files it runs on, stepping by about a second between GPS fixes, from an
126//!   unstated zero (a negative time on the pad in one, hundreds of seconds in the others). It is
127//!   read in seconds where the median step between a track's points of distinct times is 0.5 to
128//!   2 s, as a receiver reporting once a second gives and a time in tenths, milliseconds or
129//!   minutes wouldn't; otherwise those points have no time, and the `time` is a channel kept as
130//!   written. The `Snippet`'s `Max baro height` is read as the stated apogee.
131//! - *Big Red Bee's BeeLine* (2): KML 2.0's namespace, CR LF, one `Placemark` named `gps` with a
132//!   `MultiGeometry` path of zero-padded whole meters (`00850`), the BeeLine comment beside each
133//!   point, in one file comments of the flight's particulars before the first point, and after
134//!   the document a comment opening `BRBDATA` holding the logger's memory in hexadecimal, 128
135//!   KiB of it: none of these is read, each counted in a note. Big Red Bee's manuals say the
136//!   logger records "latitude, longitude, altitude, GPS time, and number of satellites in view"
137//!   once a second (*BeeLine GPS*, 2024-11, p3) and writes a KML file for Google Earth (p8); no
138//!   manual describes the comments.
139//! - *Unnamed, AltOS-styled* (2): styles named as AltOS names them (`ao-flightstate-…`), a
140//!   document named by a hexadecimal id, one `Path` in mode `relativeToGround`, and the
141//!   `Alt`/`Seconds` comment beside each point; `Alt` equals the tuple's altitude. `Seconds`
142//!   runs from a small negative number, a time from liftoff. The logger is `KML`.
143//! - *GPS Visualizer* (1), named in the document's `Snippet`: one placemark of 48 paths in a
144//!   `MultiGeometry`, 47 of a single point.
145//! - *A map drawn in Google Earth* (1): predicted tracks and pins in nested documents, not a
146//!   flight log; it is read as any KML file is (the survey of sample logs files it apart, by
147//!   id). The logger is `KML`: the file names no writer of its own.
148//!
149//! **The altitude's unit.** Meters, from the standard, but for GPS Visualizer's. Against a
150//! barometric logger flown on the same flight, among the project's sample logs, the track's rise
151//! above its first point is 0.99 to 1.06 times the logger's peak in meters in 9 of 11 fw2kml
152//! files, 0.73 to 1.15 in 11 of 12 RTx files, 0.76 to 1.06 in 8 of 10 AltOS files and 1.05 in a
153//! BeeLine file, where feet would make it 3.28 times. The others are a track whose receiver lost
154//! the rocket, two pairings with what may be another flight, and two AltOS files whose first path
155//! is the pad's alone. The GPS Visualizer file's rise is 3.24 times its flight's
156//! barometric peak in meters: its altitudes are feet written as meters. GPS Visualizer reads a
157//! source's altitude "as meters unless "(ft.)" or "(feet)" is included in the field name"
158//! (gpsvisualizer.com/tutorials/waypoints.php), so its KML holds meters only when its source
159//! said which unit it used, and the file can't say whether it did: its altitude is kept as
160//! written, [`Quantity::Unrecognized`]. The two unnamed files' rise is 0.42 times their flight's
161//! barometric peak, which neither unit explains; their altitude is read in meters, from the
162//! standard, as a height above the ground.
163//!
164//! Each decision is a note in one grammar, the same before the colon for every file decided
165//! alike, such as `` `coordinates` read in meters, from the KML standard: … ``, with this file's
166//! evidence after it.
167//!
168//! **Hostile input.** `roxmltree` parses the XML, with its default refusal of a document type
169//! declaration, so no entity can expand, and a limit of [`MAX_NODES`] nodes over all the file's
170//! documents together. The parser descends the tree on the stack, so the text's nesting is
171//! counted first and a file nesting elements deeper than [`MAX_DEPTH`] is refused. At most
172//! [`MAX_TRACKS`] tracks and [`MAX_POINTS`] points are read, the rest counted in a note; notes
173//! about single places are capped as every reader's are. Every track's channels hold one value
174//! per point read, so the record never holds more than the file wrote.
175//!
176//! **Where this comes from.** The standard and Google's reference as cited, and the files
177//! themselves; no KML reader was ported. Debrief, the project owner's own earlier tool, writes
178//! KML but doesn't read it.
179//!
180//! [adr-254]: https://github.com/nrdptel/fusionspace-eridanus/blob/main/docs/decisions/0254-gps-tracks-first-among-the-other-importers.md
181
182use std::borrow::Cow;
183use std::collections::HashMap;
184
185use roxmltree::{Document, Node, NodeId, ParsingOptions};
186
187use crate::error::LogError;
188use crate::log::{Channel, Event, FlightLog, LogFormat, Quantity, Stated};
189use crate::perfectflite::FOOT_M;
190use crate::table::{Notes, number, short};
191
192/// The format's name in errors.
193const FORMAT: &str = "KML";
194
195/// The most tracks (geometries) one file gives; past it, the rest are counted in a note. The
196/// sample files hold at most 48.
197pub const MAX_TRACKS: usize = 256;
198
199/// The most points read from one file, over all its tracks; past it, the rest are counted in a
200/// note. The sample files hold at most 8,736.
201pub const MAX_POINTS: usize = 1_000_000;
202
203/// The most KML documents read from one file, one after another; past it, the rest are counted in
204/// a note. A later document identical to the first doesn't count.
205pub const MAX_DOCUMENTS: usize = 8;
206
207/// The most XML nodes the parser builds for one file, over all the documents it holds together, so
208/// a file of many tiny elements, in one document or several, can't fill memory. The sample files
209/// hold well under 100,000.
210pub const MAX_NODES: u32 = 4_000_000;
211
212/// The deepest the XML may nest its elements. The parser underneath, `roxmltree`, descends the tree
213/// on the stack, so a file nesting far enough would exhaust it, a crash where an error is due: the
214/// nesting is counted before the text is parsed, as the `.ork` reader's is (`hpr_io::ork`). The
215/// sample files nest at most 9 deep; 64 is as deep as the `.ork` reader allows.
216pub const MAX_DEPTH: usize = 64;
217
218/// The most times a time of day is carried past midnight in one file; the times of day after are
219/// gaps. A BeeLine's memory holds a few hours of points at one a second, so a flight's file passes
220/// midnight once at most, and the bound keeps the days added from overflowing on a hostile file.
221pub const MAX_MIDNIGHTS: i64 = 7;
222
223/// The steps between a track's AltOS `time` values, in seconds, whose median shows the `time` is
224/// in seconds: a GPS receiver reporting once a second steps by 1 s, where a time in tenths would
225/// step by 10, in milliseconds by 1,000 and in minutes by 1/60. The samples' median is about 1 s.
226const ALTOS_STEP_S: std::ops::RangeInclusive<f64> = 0.5..=2.0;
227
228/// The most declarations and comments looked past before the root element when recognizing a
229/// file.
230const PROLOG_ITEMS: usize = 64;
231
232/// Nanoseconds in a second.
233const NS_PER_S: i64 = 1_000_000_000;
234
235/// Nanoseconds in a day.
236const DAY_NS: i64 = 86_400 * NS_PER_S;
237
238/// Whether the text is a KML document, judged from its content, never the file's name: its root
239/// element is `kml`, after an optional byte-order mark, XML declaration, comments and document
240/// type declaration. A file with a document type declaration is recognized so that [`read`]
241/// refuses it by name, rather than the importer calling it a layout it doesn't know.
242pub(crate) fn recognizes(text: &str) -> bool {
243    root_is(text, "kml")
244}
245
246/// Whether the text's root element is `name`, unprefixed, after an optional byte-order mark, XML
247/// declaration, comments and document type declaration: KML's test, and GPX's
248/// ([`crate::gpx`]).
249pub(crate) fn root_is(text: &str, name: &str) -> bool {
250    prolog(text).is_some_and(|(root, _)| {
251        text[root..]
252            .strip_prefix('<')
253            .and_then(|after| after.strip_prefix(name))
254            .is_some_and(|after| {
255                after.starts_with(|c: char| c.is_ascii_whitespace() || c == '>' || c == '/')
256            })
257    })
258}
259
260/// The byte offset of the document type declaration in the text's prolog, before its root
261/// element, so a refusal of it can name its line ([`crate::gpx`]); `None` if there is none.
262pub(crate) fn doctype_offset(text: &str) -> Option<usize> {
263    prolog(text).and_then(|(_, doctype)| doctype)
264}
265
266/// The text's prolog walked past an optional byte-order mark, XML declaration, comments and
267/// document type declaration, at most [`PROLOG_ITEMS`] of them: the byte offset where what
268/// follows them starts, and that of the document type declaration, if any. `None` if one of
269/// them doesn't close.
270fn prolog(text: &str) -> Option<(usize, Option<usize>)> {
271    let mut rest = text.strip_prefix('\u{feff}').unwrap_or(text);
272    let mut doctype = None;
273    for _ in 0..PROLOG_ITEMS {
274        rest = rest.trim_start();
275        let (open, close) = if rest.starts_with("<?") {
276            ("<?", "?>")
277        } else if rest.starts_with("<!--") {
278            ("<!--", "-->")
279        } else if rest.starts_with("<!DOCTYPE") {
280            let length = doctype_length(rest)?;
281            doctype = Some(text.len() - rest.len());
282            rest = &rest[length..];
283            continue;
284        } else {
285            break;
286        };
287        let end = rest[open.len()..].find(close)?;
288        rest = &rest[open.len() + end + close.len()..];
289    }
290    Some((text.len() - rest.len(), doctype))
291}
292
293/// The length of a document type declaration at the start of the text, `<!DOCTYPE` to its closing
294/// `>`, past an internal subset in brackets and quoted text; `None` if it doesn't close.
295fn doctype_length(text: &str) -> Option<usize> {
296    let mut quote: Option<u8> = None;
297    let mut brackets = 0usize;
298    for (index, byte) in text.bytes().enumerate() {
299        match (quote, byte) {
300            (Some(open), _) if byte == open => quote = None,
301            (Some(_), _) => {}
302            (None, b'"' | b'\'') => quote = Some(byte),
303            (None, b'[') => brackets += 1,
304            (None, b']') => brackets = brackets.saturating_sub(1),
305            (None, b'>') if brackets == 0 => return Some(index + 1),
306            (None, _) => {}
307        }
308    }
309    None
310}
311
312/// Reads a KML file's tracks into a flight record.
313///
314/// # Errors
315///
316/// [`LogError::Syntax`] if the XML isn't well formed, declares a document type, nests elements
317/// deeper than [`MAX_DEPTH`], or holds more than [`MAX_NODES`] nodes over its documents;
318/// [`LogError::NotThisFormat`] if its root element isn't `kml`; [`LogError::NoData`] if it holds
319/// no point.
320pub fn read(text: &str) -> Result<FlightLog, LogError> {
321    read_within(text, MAX_NODES)
322}
323
324/// [`read`], with `max_nodes` XML nodes for the whole file, so tests can reach the limit cheaply.
325fn read_within(text: &str, max_nodes: u32) -> Result<FlightLog, LogError> {
326    let text = text.strip_prefix('\u{feff}').unwrap_or(text);
327    let (pieces, more) = split_documents(text, max_nodes)?;
328    let mut copies = 0;
329    let mut left_out = usize::from(more);
330    let mut first: Option<(&str, Document<'_>)> = None;
331    let mut later: Vec<Document<'_>> = Vec::new();
332    // The nodes the documents held at once may still take: one budget for the file, not one a
333    // document, so that several documents can't hold more than one may.
334    let mut nodes_left = max_nodes;
335    let mut parse_within = |piece| {
336        let document = parse(piece, nodes_left)?;
337        let used = u32::try_from(document.descendants().count()).unwrap_or(u32::MAX);
338        nodes_left = nodes_left.saturating_sub(used);
339        Ok::<_, LogError>(document)
340    };
341    for piece in pieces {
342        if let Some((first_text, _)) = &first {
343            if piece.trim() == first_text.trim() {
344                copies += 1;
345            } else if later.len() + 1 >= MAX_DOCUMENTS {
346                left_out += 1;
347            } else {
348                later.push(parse_within(piece)?);
349            }
350        } else {
351            first = Some((piece, parse_within(piece)?));
352        }
353    }
354    let Some((_, first)) = first else {
355        // `split_documents` gives at least one piece, or an error.
356        return Err(LogError::NoData { format: FORMAT });
357    };
358    let mut reader = Reader {
359        copies,
360        documents_left_out: left_out,
361        later_documents: later.len(),
362        ..Reader::default()
363    };
364    for (index, document) in std::iter::once(&first).chain(&later).enumerate() {
365        let root = document.root_element();
366        if root.tag_name().name() != "kml" {
367            return Err(LogError::NotThisFormat {
368                format: FORMAT,
369                message: format!(
370                    "the root element is {:?}, not `kml`",
371                    short(root.tag_name().name())
372                ),
373            });
374        }
375        reader.read_document(document, index);
376    }
377    let about = About::of(&first, &reader);
378    reader.finish(about)
379}
380
381/// The file's text cut into its KML documents, as a writer may write several one after another,
382/// each with its own XML declaration; and whether more follow past [`MAX_DOCUMENTS`] × 2 pieces.
383/// Each trial parse is dropped before the next, so no more than one is held at a time.
384fn split_documents(text: &str, max_nodes: u32) -> Result<(Vec<&str>, bool), LogError> {
385    let mut pieces = Vec::new();
386    let mut rest = text;
387    loop {
388        match parse_xml(rest, max_nodes) {
389            Ok(_) => {
390                pieces.push(rest);
391                return Ok((pieces, false));
392            }
393            Err(XmlFailure::Xml(roxmltree::Error::UnexpectedDeclaration(position))) => {
394                let at = offset_of(rest, position)
395                    .filter(|&at| at > 0 && rest[at..].starts_with("<?xml"))
396                    .ok_or_else(|| {
397                        xml_error(&XmlFailure::Xml(roxmltree::Error::UnexpectedDeclaration(
398                            position,
399                        )))
400                    })?;
401                pieces.push(&rest[..at]);
402                rest = &rest[at..];
403                if pieces.len() >= 2 * MAX_DOCUMENTS {
404                    return Ok((pieces, true));
405                }
406            }
407            Err(failure) => return Err(xml_error(&failure)),
408        }
409    }
410}
411
412/// Why a text didn't parse.
413#[derive(Debug)]
414enum XmlFailure {
415    /// It nests elements deeper than [`MAX_DEPTH`]: how deep, and the line where it first does.
416    Deep { deepest: usize, line: usize },
417    /// The parser's own error.
418    Xml(roxmltree::Error),
419}
420
421/// The text parsed as XML, once its nesting is found no deeper than [`MAX_DEPTH`], with at most
422/// `nodes` nodes and no document type declaration.
423fn parse_xml(text: &str, nodes: u32) -> Result<Document<'_>, XmlFailure> {
424    let (deepest, line) = nesting(text);
425    if deepest > MAX_DEPTH {
426        return Err(XmlFailure::Deep { deepest, line });
427    }
428    let options = ParsingOptions {
429        nodes_limit: nodes,
430        ..ParsingOptions::default()
431    };
432    Document::parse_with_options(text, options).map_err(XmlFailure::Xml)
433}
434
435/// [`parse_xml`], its error the reader's.
436fn parse(text: &str, nodes: u32) -> Result<Document<'_>, LogError> {
437    parse_xml(text, nodes).map_err(|failure| xml_error(&failure))
438}
439
440/// A failure to parse as the reader's error.
441fn xml_error(failure: &XmlFailure) -> LogError {
442    let (line, message) = match failure {
443        XmlFailure::Deep { deepest, line } => (
444            *line,
445            format!(
446                "the XML nests elements {deepest} deep, past the {MAX_DEPTH} this reader reads, \
447                 so that the parser can't exhaust its stack"
448            ),
449        ),
450        XmlFailure::Xml(error) => (
451            usize::try_from(error.pos().row).unwrap_or(usize::MAX),
452            match error {
453                roxmltree::Error::DtdDetected => "the file declares a document type, which this \
454                     reader refuses so that no entity can expand"
455                    .to_owned(),
456                roxmltree::Error::NodesLimitReached => {
457                    format!("the file holds more than {MAX_NODES} XML nodes over its documents")
458                }
459                error => format!("the XML isn't well formed: {error}"),
460            },
461        ),
462    };
463    LogError::Syntax {
464        format: FORMAT,
465        line,
466        message,
467    }
468}
469
470/// How deep the text nests its elements, counted without parsing it, and the 1-based line where
471/// the nesting first passes [`MAX_DEPTH`] (0 if it doesn't). Comments, CDATA sections, processing
472/// instructions and declarations change no depth; a `>` inside a quoted attribute value doesn't
473/// end its tag. Adapted from the `.ork` reader's count (`hpr_io::ork`), the same project's code;
474/// GPX's reader counts with it too ([`crate::gpx`]).
475pub(crate) fn nesting(text: &str) -> (usize, usize) {
476    let bytes = text.as_bytes();
477    let mut index = 0;
478    let mut depth = 0usize;
479    let mut deepest = 0usize;
480    let mut past_at = None;
481    while index < bytes.len() {
482        if bytes[index] != b'<' {
483            index += 1;
484            continue;
485        }
486        let rest = &bytes[index..];
487        if let Some(skip) = skipped(rest, b"<!--", b"-->")
488            .or_else(|| skipped(rest, b"<![CDATA[", b"]]>"))
489            .or_else(|| skipped(rest, b"<?", b"?>"))
490        {
491            index += skip;
492            continue;
493        }
494        let closing = rest.starts_with(b"</");
495        let declaration = rest.starts_with(b"<!");
496        let mut cursor = index + 1;
497        let mut quote: Option<u8> = None;
498        let mut last = 0u8;
499        while cursor < bytes.len() {
500            let byte = bytes[cursor];
501            match quote {
502                Some(open) if byte == open => quote = None,
503                Some(_) => {}
504                None if byte == b'"' || byte == b'\'' => quote = Some(byte),
505                None if byte == b'>' => break,
506                None => {}
507            }
508            if !byte.is_ascii_whitespace() {
509                last = byte;
510            }
511            cursor += 1;
512        }
513        if !declaration {
514            if closing {
515                depth = depth.saturating_sub(1);
516            } else {
517                depth += 1;
518                deepest = deepest.max(depth);
519                if depth > MAX_DEPTH && past_at.is_none() {
520                    past_at = Some(index);
521                }
522                if last == b'/' {
523                    depth -= 1;
524                }
525            }
526        }
527        index = cursor + 1;
528    }
529    let line = past_at.map_or(0, |at| {
530        bytes[..at].iter().filter(|&&byte| byte == b'\n').count() + 1
531    });
532    (deepest, line)
533}
534
535/// When `rest` starts with `opening`, the length up to and including the next `closing`, or to the
536/// end of the text when there is none.
537fn skipped(rest: &[u8], opening: &[u8], closing: &[u8]) -> Option<usize> {
538    if !rest.starts_with(opening) {
539        return None;
540    }
541    let from = opening.len();
542    let found = rest[from..]
543        .windows(closing.len())
544        .position(|window| window == closing)
545        .map(|at| from + at + closing.len());
546    Some(found.unwrap_or(rest.len()))
547}
548
549/// The byte offset of a parser's position (1-based row, by `\n`, and column, in characters).
550fn offset_of(text: &str, position: roxmltree::TextPos) -> Option<usize> {
551    let mut line_start = 0;
552    for _ in 1..position.row {
553        line_start += text.get(line_start..)?.find('\n')? + 1;
554    }
555    let line = text.get(line_start..)?;
556    let column = usize::try_from(position.col).ok()?.checked_sub(1)?;
557    line.char_indices()
558        .map(|(index, _)| index)
559        .chain(std::iter::once(line.len()))
560        .nth(column)
561        .map(|index| line_start + index)
562}
563
564/// How a viewer places a track's altitude: its geometry's `altitudeMode` or `gx:altitudeMode`.
565#[derive(Debug, Clone, Copy, PartialEq, Eq)]
566enum Mode {
567    /// `absolute`: above the vertical datum, sea level.
568    Absolute,
569    /// `relativeToGround`: above the terrain.
570    RelativeToGround,
571    /// `relativeToSeaFloor`: above the sea floor, or the terrain on land.
572    RelativeToSeaFloor,
573    /// A mode in which a viewer ignores the altitude: as written, or `None` where none is stated
574    /// and the default, `clampToGround`, holds.
575    Ignored(Option<&'static str>),
576    /// A mode the standard doesn't name.
577    Unnamed,
578}
579
580impl Mode {
581    /// The geometry's mode, from its child `altitudeMode` in either namespace.
582    fn of(geometry: Node<'_, '_>) -> Self {
583        let Some(text) = child(geometry, "altitudeMode").map(|node| all_text(node)) else {
584            return Self::Ignored(None);
585        };
586        match text.trim() {
587            "absolute" => Self::Absolute,
588            "relativeToGround" => Self::RelativeToGround,
589            "relativeToSeaFloor" => Self::RelativeToSeaFloor,
590            "clampToGround" => Self::Ignored(Some("clampToGround")),
591            "clampToSeaFloor" => Self::Ignored(Some("clampToSeaFloor")),
592            _ => Self::Unnamed,
593        }
594    }
595}
596
597/// Which clock a point's time is on.
598#[derive(Debug, Clone, Copy, PartialEq, Eq)]
599pub(crate) enum Clock {
600    /// A `when` with its zone: UTC.
601    Utc,
602    /// A `when` with no zone: a local time in a zone the file doesn't state.
603    Local,
604    /// AltOS's comment `time`, seconds from an unstated zero.
605    AltOs,
606    /// The `Seconds` of a comment, from an unstated zero.
607    Seconds,
608    /// The BeeLine comment's UTC time of day.
609    TimeOfDay,
610}
611
612impl Clock {
613    /// The word the file names the time by, for notes.
614    fn word(self) -> &'static str {
615        match self {
616            Self::Utc | Self::Local => "`when`",
617            Self::AltOs => "`time`",
618            Self::Seconds => "`Seconds`",
619            Self::TimeOfDay => "`UTC`",
620        }
621    }
622}
623
624/// What AltOS's comment `time` is in a file.
625#[derive(Debug, Clone, Copy, PartialEq)]
626enum AltosTime {
627    /// The file holds no AltOS comment.
628    Absent,
629    /// 0 beside every point: unset.
630    Unset,
631    /// In seconds, from the median step between a track's points of distinct times, s.
632    Seconds(f64),
633    /// In a unit its steps don't show: the median step read as seconds, `NaN` if there is none.
634    Unsettled(f64),
635}
636
637/// How often a time of day was carried past midnight.
638#[derive(Debug, Clone, Copy, Default)]
639struct Midnights {
640    /// The days added.
641    days: usize,
642    /// The times of day made gaps past [`MAX_MIDNIGHTS`].
643    dropped: usize,
644}
645
646/// A point's time as the file writes it: nanoseconds on a clock, and the text it came from.
647#[derive(Debug, Clone, Copy, PartialEq, Eq)]
648struct Stamp<'a> {
649    clock: Clock,
650    ns: i64,
651    raw: &'a str,
652}
653
654/// The layout of a comment beside a point.
655#[derive(Debug, Clone, Copy, PartialEq, Eq)]
656enum Layout {
657    /// `alt X time Y sats N`.
658    AltOs,
659    /// `Alt X Seconds Y`.
660    Seconds,
661    /// `OFFSET sats:N UTC HH:MM:SS`.
662    BeeLine,
663}
664
665/// What a comment beside a point says.
666#[derive(Debug, Clone, Copy, PartialEq)]
667struct Remark<'a> {
668    layout: Layout,
669    /// The comment's altitude, `NaN` if it has none.
670    alt: f64,
671    /// The comment's time, nanoseconds, and its text.
672    time: Option<(i64, &'a str)>,
673    /// The satellite count, `NaN` if none.
674    sats: f64,
675    /// The BeeLine's first number, `NaN` if none.
676    offset: f64,
677}
678
679/// A comment beside a point, read; `None` if it is in none of the three layouts.
680fn remark(text: &str) -> Option<Remark<'_>> {
681    let mut tokens = [""; 6];
682    let mut count = 0;
683    for token in text.split_ascii_whitespace() {
684        *tokens.get_mut(count)? = token;
685        count += 1;
686    }
687    let tokens = &tokens[..count];
688    if let [offset, sats, utc, time] = tokens
689        && utc.eq_ignore_ascii_case("UTC")
690        && let Some(sats) = sats.strip_prefix("sats:")
691    {
692        return Some(Remark {
693            layout: Layout::BeeLine,
694            alt: f64::NAN,
695            time: Some((time_of_day_ns(time)?, *time)),
696            sats: number(sats, false)?,
697            offset: number(offset, false)?,
698        });
699    }
700    match tokens {
701        [alt_key, alt, time_key, time, sats_key, sats]
702            if alt_key.eq_ignore_ascii_case("alt")
703                && time_key.eq_ignore_ascii_case("time")
704                && sats_key.eq_ignore_ascii_case("sats") =>
705        {
706            Some(Remark {
707                layout: Layout::AltOs,
708                alt: number(alt, false)?,
709                time: Some((decimal_ns(time)?, *time)),
710                sats: number(sats, false)?,
711                offset: f64::NAN,
712            })
713        }
714        [alt_key, alt, seconds_key, seconds]
715            if alt_key.eq_ignore_ascii_case("alt")
716                && seconds_key.eq_ignore_ascii_case("seconds") =>
717        {
718            Some(Remark {
719                layout: Layout::Seconds,
720                alt: number(alt, false)?,
721                time: Some((decimal_ns(seconds)?, *seconds)),
722                sats: f64::NAN,
723                offset: f64::NAN,
724            })
725        }
726        _ => None,
727    }
728}
729
730/// A decimal number of seconds as nanoseconds, exactly to the ninth decimal (further digits are
731/// dropped): an optional sign, digits, an optional point and digits, no exponent. `None` if it
732/// isn't one, or is beyond ±9 × 10⁹ s.
733fn decimal_ns(text: &str) -> Option<i64> {
734    let (negative, digits) = match text.as_bytes().first()? {
735        b'-' => (true, &text[1..]),
736        b'+' => (false, &text[1..]),
737        _ => (false, text),
738    };
739    let (whole, fraction) = digits.split_once('.').unwrap_or((digits, ""));
740    if whole.is_empty() && fraction.is_empty()
741        || digits.ends_with('.')
742        || !whole
743            .bytes()
744            .chain(fraction.bytes())
745            .all(|b| b.is_ascii_digit())
746        || whole.len() > 10
747    {
748        return None;
749    }
750    let seconds: i64 = if whole.is_empty() {
751        0
752    } else {
753        whole.parse().ok()?
754    };
755    let mut nanos: i64 = 0;
756    for digit in fraction.bytes().chain(std::iter::repeat(b'0')).take(9) {
757        nanos = nanos * 10 + i64::from(digit - b'0');
758    }
759    let total = seconds.checked_mul(NS_PER_S)?.checked_add(nanos)?;
760    Some(if negative { -total } else { total })
761}
762
763/// A time of day, `HH:MM:SS` with optional decimals, as nanoseconds after midnight; each field
764/// two digits, with no sign. A second written 60, a leap second's, is read as the next minute's
765/// first, whatever the minute.
766fn time_of_day_ns(text: &str) -> Option<i64> {
767    let mut parts = text.split(':');
768    let (hours, minutes, seconds) = (parts.next()?, parts.next()?, parts.next()?);
769    if parts.next().is_some()
770        || hours.len() != 2
771        || minutes.len() != 2
772        || !hours
773            .bytes()
774            .chain(minutes.bytes())
775            .all(|b| b.is_ascii_digit())
776        || seconds.split('.').next().map(str::len) != Some(2)
777        || !seconds.bytes().take(2).all(|b| b.is_ascii_digit())
778    {
779        return None;
780    }
781    let hours: i64 = hours.parse().ok()?;
782    let minutes: i64 = minutes.parse().ok()?;
783    let seconds = decimal_ns(seconds).filter(|ns| (0..61 * NS_PER_S).contains(ns))?;
784    (hours < 24 && minutes < 60).then_some((hours * 3_600 + minutes * 60) * NS_PER_S + seconds)
785}
786
787/// A `when` as nanoseconds since 1970-01-01T00:00:00 on its clock: `YYYY-MM-DDThh:mm:ss`, optional
788/// decimals, then `Z`, `±hh:mm` or nothing ([`Clock::Local`]). `None` for a date without a time
789/// of day (XML Schema's `date`, `gYearMonth`, `gYear`), which places no point in a flight, or for
790/// anything else. GPX's reader reads its times with it too ([`crate::gpx`]).
791pub(crate) fn when_ns(text: &str) -> Option<(Clock, i64)> {
792    let text = text.trim();
793    let (date, rest) = text.split_once('T')?;
794    let mut fields = date.split('-');
795    let (year, month, day) = (fields.next()?, fields.next()?, fields.next()?);
796    if fields.next().is_some()
797        || year.len() != 4
798        || month.len() != 2
799        || day.len() != 2
800        || !year
801            .bytes()
802            .chain(month.bytes())
803            .chain(day.bytes())
804            .all(|b| b.is_ascii_digit())
805    {
806        return None;
807    }
808    let (year, month, day): (i64, i64, i64) =
809        (year.parse().ok()?, month.parse().ok()?, day.parse().ok()?);
810    if !(1..=12).contains(&month) || day < 1 || day > days_in_month(year, month) {
811        return None;
812    }
813    let (time, clock, offset_s) = if let Some(time) = rest.strip_suffix('Z') {
814        (time, Clock::Utc, 0)
815    } else if let Some(at) = rest.rfind(['+', '-']).filter(|&at| at >= 8) {
816        let (time, zone) = rest.split_at(at);
817        let sign = if zone.starts_with('-') { -1 } else { 1 };
818        let (hours, minutes) = zone[1..].split_once(':')?;
819        if hours.len() != 2 || minutes.len() != 2 {
820            return None;
821        }
822        let hours: i64 = hours.parse().ok()?;
823        let minutes: i64 = minutes.parse().ok()?;
824        // XML Schema's zones run from −14:00 to +14:00.
825        if minutes > 59 || hours * 60 + minutes > 14 * 60 {
826            return None;
827        }
828        (time, Clock::Utc, sign * (hours * 3_600 + minutes * 60))
829    } else {
830        (rest, Clock::Local, 0)
831    };
832    let of_day = time_of_day_ns(time)?;
833    let days = days_from_civil(year, month, day);
834    let ns = days
835        .checked_mul(DAY_NS)?
836        .checked_add(of_day)?
837        .checked_sub(offset_s.checked_mul(NS_PER_S)?)?;
838    Some((clock, ns))
839}
840
841/// Days in a month of the Gregorian calendar.
842fn days_in_month(year: i64, month: i64) -> i64 {
843    match month {
844        2 if year % 4 == 0 && (year % 100 != 0 || year % 400 == 0) => 29,
845        2 => 28,
846        4 | 6 | 9 | 11 => 30,
847        _ => 31,
848    }
849}
850
851/// Days from 1970-01-01 to a date of the proleptic Gregorian calendar (H. Hinnant,
852/// *chrono-Compatible Low-Level Date Algorithms*, `days_from_civil`, public domain).
853fn days_from_civil(year: i64, month: i64, day: i64) -> i64 {
854    let year = if month <= 2 { year - 1 } else { year };
855    let era = year.div_euclid(400);
856    let year_of_era = year - era * 400;
857    let shifted_month = (month + 9) % 12;
858    let day_of_year = (153 * shifted_month + 2) / 5 + day - 1;
859    let day_of_era = year_of_era * 365 + year_of_era / 4 - year_of_era / 100 + day_of_year;
860    era * 146_097 + day_of_era - 719_468
861}
862
863/// A coordinate tuple: longitude, latitude and an optional altitude, from `lon,lat[,alt]` (a
864/// `coordinates` tuple) or, if `gx`, `lon lat [alt]` separated by whitespace (a `gx:coord`). `None`
865/// if it isn't two or three finite numbers.
866fn tuple(text: &str, gx: bool) -> Option<(f64, f64, Option<f64>)> {
867    let mut parts: [&str; 3] = [""; 3];
868    let count = if gx {
869        fill(&mut parts, text.split_ascii_whitespace())?
870    } else {
871        fill(&mut parts, text.split(','))?
872    };
873    let value = |part: &str| number(part, false);
874    match count {
875        2 => Some((value(parts[0])?, value(parts[1])?, None)),
876        3 => Some((value(parts[0])?, value(parts[1])?, Some(value(parts[2])?))),
877        _ => None,
878    }
879}
880
881/// Puts the parts in the slots, in order; how many there were, or `None` if more than slots.
882fn fill<'t>(slots: &mut [&'t str], parts: impl Iterator<Item = &'t str>) -> Option<usize> {
883    let mut count = 0;
884    for part in parts {
885        *slots.get_mut(count)? = part;
886        count += 1;
887    }
888    Some(count)
889}
890
891/// The tuples of a `coordinates` text: split at whitespace, with whitespace beside a comma taken
892/// as part of the tuple, as some writers write `lon, lat, alt`.
893fn tuples(text: &str) -> Vec<Cow<'_, str>> {
894    let mut out: Vec<Cow<'_, str>> = Vec::new();
895    let mut current: Option<Cow<'_, str>> = None;
896    for token in text.split_ascii_whitespace() {
897        current = Some(match current.take() {
898            Some(previous) if previous.ends_with(',') || token.starts_with(',') => {
899                let mut joined = previous.into_owned();
900                joined.push_str(token);
901                Cow::Owned(joined)
902            }
903            Some(previous) => {
904                out.push(previous);
905                Cow::Borrowed(token)
906            }
907            None => Cow::Borrowed(token),
908        });
909    }
910    out.extend(current);
911    out
912}
913
914/// An element's first child element of a local name, in any namespace.
915fn child<'a, 'input>(node: Node<'a, 'input>, name: &str) -> Option<Node<'a, 'input>> {
916    node.children()
917        .find(|child| child.is_element() && child.tag_name().name() == name)
918}
919
920/// An element's text, its text and CDATA children joined.
921fn all_text(node: Node<'_, '_>) -> String {
922    node.children()
923        .filter(|child| child.is_text())
924        .filter_map(|child| child.text())
925        .collect()
926}
927
928/// A name as a channel's: its runs of whitespace one space, cut to the length a note quotes.
929fn clean(name: &str) -> String {
930    short(&name.split_whitespace().collect::<Vec<_>>().join(" "))
931}
932
933/// One geometry read: a path, a point or a timed track.
934struct Track<'a> {
935    /// Its placemark's name, or `track`.
936    label: String,
937    /// Its placemark, by document and node, to number several geometries in one.
938    placemark: Option<(usize, NodeId)>,
939    /// Whether it is a `Point`.
940    point: bool,
941    mode: Mode,
942    lat: Vec<f64>,
943    lon: Vec<f64>,
944    /// Each point's altitude, `NaN` where the tuple has none.
945    alt: Vec<f64>,
946    stamps: Vec<Option<Stamp<'a>>>,
947    remarks: Vec<Option<Remark<'a>>>,
948}
949
950/// What the reader gathers over the file's documents.
951#[derive(Default)]
952struct Reader<'a> {
953    tracks: Vec<Track<'a>>,
954    tracks_left_out: usize,
955    points: usize,
956    points_left_out: usize,
957    copies: usize,
958    later_documents: usize,
959    documents_left_out: usize,
960    /// Geometries that aren't tracks: polygons and models.
961    other_geometries: usize,
962    /// Geometries with no point.
963    empty_geometries: usize,
964    /// Comments in a document outside any `coordinates`.
965    loose_comments: usize,
966    /// Comments in a `coordinates` beside no point.
967    stray_comments: usize,
968    /// Comments beside a point in no known layout.
969    unknown_comments: usize,
970    /// Comments outside a document's root element: count, longest, and whether one opens
971    /// `BRBDATA`.
972    outside_comments: usize,
973    longest_outside: usize,
974    memory_dump: bool,
975    bad_tuples: usize,
976    bad_tuple_example: Option<String>,
977    out_of_range: usize,
978    bad_whens: usize,
979    bad_when_example: Option<String>,
980    notes: Notes,
981}
982
983impl<'a> Reader<'a> {
984    /// Reads one document's tracks and counts its comments.
985    fn read_document(&mut self, document: &'a Document<'a>, index: usize) {
986        for node in document.root().children() {
987            if node.is_comment() {
988                let text = node.text().unwrap_or_default();
989                self.outside_comments += 1;
990                self.longest_outside = self.longest_outside.max(text.chars().count());
991                self.memory_dump |= text.trim_start().starts_with("BRBDATA");
992            }
993        }
994        for node in document.root_element().descendants() {
995            if node.is_comment() {
996                if !node
997                    .parent()
998                    .is_some_and(|parent| parent.tag_name().name() == "coordinates")
999                {
1000                    self.loose_comments += 1;
1001                }
1002                continue;
1003            }
1004            if !node.is_element() {
1005                continue;
1006            }
1007            match node.tag_name().name() {
1008                "LineString" | "Point" | "Track" => self.read_geometry(node, index),
1009                "Polygon" | "Model" => self.other_geometries += 1,
1010                _ => {}
1011            }
1012        }
1013    }
1014
1015    /// Reads a geometry into a track.
1016    fn read_geometry(&mut self, node: Node<'a, 'a>, document: usize) {
1017        if self.tracks.len() >= MAX_TRACKS {
1018            self.tracks_left_out += 1;
1019            return;
1020        }
1021        let placemark = node
1022            .ancestors()
1023            .skip(1)
1024            .find(|ancestor| ancestor.is_element() && ancestor.tag_name().name() == "Placemark");
1025        let label = placemark
1026            .and_then(|placemark| child(placemark, "name"))
1027            .map(|name| clean(&all_text(name)))
1028            .filter(|name| !name.is_empty())
1029            .unwrap_or_else(|| "track".to_owned());
1030        let point = node.tag_name().name() == "Point";
1031        let mut track = Track {
1032            label,
1033            placemark: placemark.map(|placemark| (document, placemark.id())),
1034            point,
1035            mode: Mode::of(node),
1036            lat: Vec::new(),
1037            lon: Vec::new(),
1038            alt: Vec::new(),
1039            stamps: Vec::new(),
1040            remarks: Vec::new(),
1041        };
1042        if node.tag_name().name() == "Track" {
1043            self.read_gx_track(node, &mut track);
1044        } else if let Some(coordinates) = child(node, "coordinates") {
1045            self.read_coordinates(coordinates, &mut track);
1046        }
1047        if point
1048            && let Some(when) = placemark
1049                .and_then(|placemark| child(placemark, "TimeStamp"))
1050                .and_then(|stamp| child(stamp, "when"))
1051                .and_then(|when| when.text())
1052        {
1053            let stamp = self.stamp_of_when(when);
1054            track.stamps.fill(stamp);
1055        }
1056        if track.lat.is_empty() {
1057            self.empty_geometries += 1;
1058        } else {
1059            self.tracks.push(track);
1060        }
1061    }
1062
1063    /// Adds a point to a track, if the file's points aren't yet [`MAX_POINTS`]; whether it did.
1064    fn push(
1065        &mut self,
1066        track: &mut Track<'a>,
1067        raw: &str,
1068        read: Option<(f64, f64, Option<f64>)>,
1069    ) -> bool {
1070        if self.points >= MAX_POINTS {
1071            self.points_left_out += 1;
1072            return false;
1073        }
1074        self.points += 1;
1075        let (lon, lat, alt) = read.unwrap_or_else(|| {
1076            self.bad_tuples += 1;
1077            if self.bad_tuple_example.is_none() {
1078                self.bad_tuple_example = Some(short(raw));
1079            }
1080            (f64::NAN, f64::NAN, Some(f64::NAN))
1081        });
1082        let (lon, lat) =
1083            if lon.is_nan() || ((-180.0..=180.0).contains(&lon) && (-90.0..=90.0).contains(&lat)) {
1084                (lon, lat)
1085            } else {
1086                self.out_of_range += 1;
1087                (f64::NAN, f64::NAN)
1088            };
1089        track.lon.push(lon);
1090        track.lat.push(lat);
1091        track.alt.push(alt.unwrap_or(f64::NAN));
1092        track.stamps.push(None);
1093        track.remarks.push(None);
1094        true
1095    }
1096
1097    /// Reads a `coordinates` element's tuples and the comments beside them.
1098    fn read_coordinates(&mut self, coordinates: Node<'a, 'a>, track: &mut Track<'a>) {
1099        // Whether the last tuple read may still take the comment after it.
1100        let mut open = false;
1101        for node in coordinates.children() {
1102            if node.is_text() {
1103                for raw in tuples(node.text().unwrap_or_default()) {
1104                    open = self.push(track, &raw, tuple(&raw, false));
1105                }
1106            } else if node.is_comment() {
1107                let text = node.text().unwrap_or_default();
1108                if !open {
1109                    self.stray_comments += 1;
1110                    continue;
1111                }
1112                open = false;
1113                match (remark(text), track.remarks.last_mut()) {
1114                    (Some(read), Some(slot)) => *slot = Some(read),
1115                    _ => self.unknown_comments += 1,
1116                }
1117            }
1118        }
1119    }
1120
1121    /// Reads a `gx:Track`'s `when` and `gx:coord` pairs.
1122    fn read_gx_track(&mut self, node: Node<'a, 'a>, track: &mut Track<'a>) {
1123        let named = |name: &'static str| {
1124            node.children()
1125                .filter(move |child| child.is_element() && child.tag_name().name() == name)
1126        };
1127        let (whens, coords) = (named("when").count(), named("coord").count());
1128        if whens != coords {
1129            self.notes.push(format!(
1130                "a `gx:Track` of {:?} holds {whens} `when` and {coords} `gx:coord`, where the \
1131                 standard has as many of each. The first {} of each are paired, the rest left out",
1132                track.label,
1133                whens.min(coords)
1134            ));
1135        }
1136        for (when, coord) in named("when").zip(named("coord")) {
1137            let raw = coord.text().unwrap_or_default();
1138            if !self.push(track, raw, tuple(raw, true)) {
1139                break;
1140            }
1141            let stamp = self.stamp_of_when(when.text().unwrap_or_default());
1142            if let Some(slot) = track.stamps.last_mut() {
1143                *slot = stamp;
1144            }
1145        }
1146    }
1147
1148    /// A `when` as a point's time, counting one that isn't a time of day.
1149    fn stamp_of_when(&mut self, raw: &'a str) -> Option<Stamp<'a>> {
1150        let read = when_ns(raw).map(|(clock, ns)| Stamp {
1151            clock,
1152            ns,
1153            raw: raw.trim(),
1154        });
1155        if read.is_none() {
1156            self.bad_whens += 1;
1157            if self.bad_when_example.is_none() {
1158                self.bad_when_example = Some(short(raw.trim()));
1159            }
1160        }
1161        read
1162    }
1163
1164    /// The record: each track's channels, the events, the notes.
1165    fn finish(mut self, about: About) -> Result<FlightLog, LogError> {
1166        if self.tracks.is_empty() {
1167            return Err(LogError::NoData { format: FORMAT });
1168        }
1169        let mut notes = vec![
1170            "the record's altitude track is empty: a KML file holds tracks of positions, not an \
1171             altimeter's record over time, so every value is a channel"
1172                .to_owned(),
1173        ];
1174        notes.extend(about.note.clone());
1175        self.document_notes(&mut notes);
1176
1177        let altos_time = self.altos_time();
1178        if altos_time == AltosTime::Unset {
1179            notes.push(
1180                "the comments' `time` is 0 beside every point, as AltOS leaves it unset in \
1181                 most of its exports: those points have no time"
1182                    .to_owned(),
1183            );
1184        }
1185        self.stamp_from_remarks(matches!(altos_time, AltosTime::Seconds(_)));
1186        let midnights = self.pass_midnight();
1187        let times = self.times(&mut notes, midnights);
1188        let names = self.names();
1189        // AltOS's `alt` shows its unit where it equals the tuple's, meters by the standard.
1190        let altos_alt_meters = agreement(&self.tracks, Layout::AltOs).0 > 0;
1191
1192        let mut channels = Vec::new();
1193        let mut events = Vec::new();
1194        let mut decided = Decided::default();
1195        for ((track, time_s), name) in self.tracks.iter().zip(&times).zip(&names) {
1196            if track.point
1197                && let Some(&time) = time_s.first()
1198                && time.is_finite()
1199            {
1200                events.push(Event {
1201                    time_s: time,
1202                    name: track.label.clone(),
1203                });
1204            }
1205            let mut add = |suffix: &str, quantity: Quantity, values: Vec<f64>| {
1206                channels.push(Channel {
1207                    column: format!("{name} {suffix}"),
1208                    quantity,
1209                    time_s: time_s.clone(),
1210                    values,
1211                });
1212            };
1213            add("latitude", Quantity::Latitude, track.lat.clone());
1214            add("longitude", Quantity::Longitude, track.lon.clone());
1215            let altitudes = track.alt.iter().filter(|alt| !alt.is_nan()).count();
1216            let remark_alt: Vec<f64> = track
1217                .remarks
1218                .iter()
1219                .map(|remark| remark.map_or(f64::NAN, |remark| remark.alt))
1220                .collect();
1221            let differs =
1222                track.alt.iter().zip(&remark_alt).any(|(tuple, comment)| {
1223                    !comment.is_nan() && !(tuple - comment).abs().le(&1e-6)
1224                });
1225            let layout = track
1226                .remarks
1227                .iter()
1228                .flatten()
1229                .map(|remark| remark.layout)
1230                .next();
1231            // The points carrying both altitudes, and those where the two differ: an AltOS track
1232            // is the barometer's where they differ at more than half (all or none in the samples).
1233            let (both, differing) = track
1234                .alt
1235                .iter()
1236                .zip(&remark_alt)
1237                .filter(|(tuple, comment)| !tuple.is_nan() && !comment.is_nan())
1238                .fold((0, 0), |(both, differing), (tuple, comment)| {
1239                    (
1240                        both + 1,
1241                        differing + usize::from((tuple - comment).abs() > 1e-6),
1242                    )
1243                });
1244            let barometric = (layout == Some(Layout::AltOs) && differing * 2 > both)
1245                .then_some((both, differing));
1246            if altitudes > 0 {
1247                let (suffix, quantity) = decided.altitude(track, &about, barometric);
1248                add(suffix, quantity, track.alt.clone());
1249            }
1250            if differs {
1251                let (suffix, quantity) = decided.remark_altitude(layout, altos_alt_meters);
1252                add(suffix, quantity, remark_alt);
1253            }
1254            if matches!(altos_time, AltosTime::Unsettled(_)) && layout == Some(Layout::AltOs) {
1255                // The `time` as written: nanoseconds back to the decimal the comment wrote.
1256                let written: Vec<f64> = track
1257                    .remarks
1258                    .iter()
1259                    .map(|remark| {
1260                        remark
1261                            .and_then(|remark| remark.time)
1262                            .map_or(f64::NAN, |(ns, _)| ns as f64 / NS_PER_S as f64)
1263                    })
1264                    .collect();
1265                add("time", Quantity::Unrecognized, written);
1266            }
1267            let sats: Vec<f64> = track
1268                .remarks
1269                .iter()
1270                .map(|remark| remark.map_or(f64::NAN, |remark| remark.sats))
1271                .collect();
1272            if sats.iter().any(|sats| !sats.is_nan()) {
1273                add("satellites", Quantity::Number, sats);
1274            }
1275            let offsets: Vec<f64> = track
1276                .remarks
1277                .iter()
1278                .map(|remark| remark.map_or(f64::NAN, |remark| remark.offset))
1279                .collect();
1280            if offsets.iter().any(|offset| !offset.is_nan()) {
1281                add("offset", Quantity::Number, offsets);
1282            }
1283        }
1284        notes.extend(decided.notes(&self.tracks, altos_time));
1285        notes.extend(self.notes.into_vec());
1286
1287        Ok(FlightLog {
1288            format: LogFormat::Kml,
1289            logger: about.logger,
1290            serial_number: about.serial_number,
1291            firmware: about.firmware,
1292            flight_number: about.flight_number,
1293            stated: Stated {
1294                apogee_m: about.apogee_m,
1295                ..Stated::default()
1296            },
1297            time_s: Vec::new(),
1298            altitude_m: Vec::new(),
1299            vertical_speed_m_s: None,
1300            temperature_k: None,
1301            battery_v: None,
1302            channels,
1303            events,
1304            notes,
1305        })
1306    }
1307
1308    /// Notes on the documents, the comments and the points left out.
1309    fn document_notes(&self, notes: &mut Vec<String>) {
1310        if self.copies > 0 {
1311            notes.push(format!(
1312                "the file holds its KML document {} times over, one after another, each the same: \
1313                 it is read once",
1314                self.copies + 1
1315            ));
1316        }
1317        if self.later_documents > 0 {
1318            notes.push(format!(
1319                "the file holds {} more KML documents after the first, different from it: their \
1320                 tracks are read after the first's",
1321                self.later_documents
1322            ));
1323        }
1324        if self.documents_left_out > 0 {
1325            notes.push(format!(
1326                "the file holds more KML documents than the {MAX_DOCUMENTS} read: the rest are \
1327                 left out"
1328            ));
1329        }
1330        if self.outside_comments > 0 {
1331            let whose = if self.memory_dump {
1332                ", as Big Red Bee's BeeLine writes its memory in hexadecimal there"
1333            } else {
1334                ""
1335            };
1336            notes.push(format!(
1337                "the file holds {} comments outside its document, the longest {} characters{whose}: \
1338                 they are not read",
1339                self.outside_comments, self.longest_outside
1340            ));
1341        }
1342        if self.loose_comments > 0 {
1343            notes.push(format!(
1344                "the document holds {} comments outside any `coordinates`: they are not read",
1345                self.loose_comments
1346            ));
1347        }
1348        if self.stray_comments > 0 {
1349            notes.push(format!(
1350                "{} comments in `coordinates` follow no point's tuple: they are not read",
1351                self.stray_comments
1352            ));
1353        }
1354        if self.unknown_comments > 0 {
1355            notes.push(format!(
1356                "{} comments beside points are in no layout this reader knows: they are not read",
1357                self.unknown_comments
1358            ));
1359        }
1360        if self.bad_tuples > 0 {
1361            notes.push(format!(
1362                "{} coordinate tuples aren't two or three numbers, such as {:?}: their points are \
1363                 gaps",
1364                self.bad_tuples,
1365                self.bad_tuple_example.as_deref().unwrap_or_default()
1366            ));
1367        }
1368        if self.out_of_range > 0 {
1369            notes.push(format!(
1370                "{} points have a latitude beyond ±90° or a longitude beyond ±180°: their \
1371                 positions are gaps",
1372                self.out_of_range
1373            ));
1374        }
1375        if self.bad_whens > 0 {
1376            notes.push(format!(
1377                "{} `when` aren't a date and time of day, such as {:?}: those points have no time",
1378                self.bad_whens,
1379                self.bad_when_example.as_deref().unwrap_or_default()
1380            ));
1381        }
1382        if self.other_geometries > 0 {
1383            notes.push(format!(
1384                "the file holds {} polygons or models, which aren't tracks: they are not read",
1385                self.other_geometries
1386            ));
1387        }
1388        if self.empty_geometries > 0 {
1389            notes.push(format!(
1390                "{} geometries hold no point: they are left out",
1391                self.empty_geometries
1392            ));
1393        }
1394        if self.tracks_left_out > 0 {
1395            notes.push(format!(
1396                "the file holds {} more geometries than the {MAX_TRACKS} read: they are left out",
1397                self.tracks_left_out
1398            ));
1399        }
1400        if self.points_left_out > 0 {
1401            notes.push(format!(
1402                "the file holds {} more points than the {MAX_POINTS} read: they are left out",
1403                self.points_left_out
1404            ));
1405        }
1406    }
1407
1408    /// What AltOS's comment `time` is in this file: absent, unset (0 beside every point), or in
1409    /// seconds where the median step between a track's points of distinct times is within
1410    /// [`ALTOS_STEP_S`].
1411    fn altos_time(&self) -> AltosTime {
1412        let tracks = || {
1413            self.tracks.iter().map(|track| {
1414                track
1415                    .remarks
1416                    .iter()
1417                    .flatten()
1418                    .filter(|remark| remark.layout == Layout::AltOs)
1419                    .filter_map(|remark| remark.time.map(|(ns, _)| ns))
1420            })
1421        };
1422        let mut all = tracks().flatten().peekable();
1423        if all.peek().is_none() {
1424            return AltosTime::Absent;
1425        }
1426        if all.all(|ns| ns == 0) {
1427            return AltosTime::Unset;
1428        }
1429        let mut steps: Vec<i64> = Vec::new();
1430        for times in tracks() {
1431            let times: Vec<i64> = times.collect();
1432            steps.extend(
1433                times
1434                    .windows(2)
1435                    .map(|pair| pair[1].saturating_sub(pair[0]))
1436                    .filter(|step| *step > 0),
1437            );
1438        }
1439        steps.sort_unstable();
1440        let median = steps
1441            .get(steps.len() / 2)
1442            .map_or(f64::NAN, |step| *step as f64 / NS_PER_S as f64);
1443        if ALTOS_STEP_S.contains(&median) {
1444            AltosTime::Seconds(median)
1445        } else {
1446            AltosTime::Unsettled(median)
1447        }
1448    }
1449
1450    /// Gives each point without a time the one its comment states, if any; AltOS's only if
1451    /// `altos_seconds`.
1452    fn stamp_from_remarks(&mut self, altos_seconds: bool) {
1453        for track in &mut self.tracks {
1454            for (stamp, remark) in track.stamps.iter_mut().zip(&track.remarks) {
1455                let Some(remark) = remark else { continue };
1456                let clock = match remark.layout {
1457                    Layout::AltOs if !altos_seconds => continue,
1458                    Layout::AltOs => Clock::AltOs,
1459                    Layout::Seconds => Clock::Seconds,
1460                    Layout::BeeLine => Clock::TimeOfDay,
1461                };
1462                if stamp.is_none()
1463                    && let Some((ns, raw)) = remark.time
1464                {
1465                    *stamp = Some(Stamp { clock, ns, raw });
1466                }
1467            }
1468        }
1469    }
1470
1471    /// Carries a time of day past midnight: where it steps back by more than 12 h, a day is
1472    /// added from there on, up to [`MAX_MIDNIGHTS`] days. From a step back past that bound on,
1473    /// the times of day are gaps, as their day can't be told.
1474    fn pass_midnight(&mut self) -> Midnights {
1475        let mut days: i64 = 0;
1476        let mut previous: Option<i64> = None;
1477        let mut passed = Midnights::default();
1478        for stamp in self
1479            .tracks
1480            .iter_mut()
1481            .flat_map(|track| track.stamps.iter_mut())
1482            .filter(|stamp| stamp.is_some_and(|stamp| stamp.clock == Clock::TimeOfDay))
1483        {
1484            if passed.dropped > 0 {
1485                *stamp = None;
1486                passed.dropped += 1;
1487                continue;
1488            }
1489            let Some(read) = stamp.as_mut() else { continue };
1490            // A time of day is under 24 h and 61 s, and `days` at most `MAX_MIDNIGHTS`, so no
1491            // sum here comes near overflowing.
1492            let mut ns = read.ns + days * DAY_NS;
1493            if previous.is_some_and(|previous| ns < previous - DAY_NS / 2) {
1494                if days >= MAX_MIDNIGHTS {
1495                    *stamp = None;
1496                    passed.dropped = 1;
1497                    continue;
1498                }
1499                days += 1;
1500                ns += DAY_NS;
1501            }
1502            read.ns = ns;
1503            previous = Some(ns);
1504        }
1505        passed.days = usize::try_from(days).unwrap_or(0);
1506        passed
1507    }
1508
1509    /// Each track's times, s from the log's zero, and the notes on them.
1510    fn times(&self, notes: &mut Vec<String>, midnights: Midnights) -> Vec<Vec<f64>> {
1511        let all = || {
1512            self.tracks
1513                .iter()
1514                .flat_map(|track| track.stamps.iter().flatten())
1515        };
1516        let zero = all().next().copied();
1517        let points: usize = self.tracks.iter().map(|track| track.lat.len()).sum();
1518        let mut other_clock = 0;
1519        let times: Vec<Vec<f64>> = self
1520            .tracks
1521            .iter()
1522            .map(|track| {
1523                track
1524                    .stamps
1525                    .iter()
1526                    .map(|stamp| match (stamp, zero) {
1527                        (Some(stamp), Some(zero)) if stamp.clock == zero.clock => stamp
1528                            .ns
1529                            .checked_sub(zero.ns)
1530                            .map_or(f64::NAN, |ns| ns as f64 / NS_PER_S as f64),
1531                        (Some(_), _) => {
1532                            other_clock += 1;
1533                            f64::NAN
1534                        }
1535                        (None, _) => f64::NAN,
1536                    })
1537                    .collect()
1538            })
1539            .collect();
1540        let untimed = times.iter().flatten().filter(|time| time.is_nan()).count();
1541        match zero {
1542            None => notes.push(format!(
1543                "the file gives none of its {points} points a time: their times are gaps"
1544            )),
1545            Some(zero) => {
1546                let zone = match zero.clock {
1547                    Clock::TimeOfDay => " UTC",
1548                    _ => "",
1549                };
1550                notes.push(format!(
1551                    "the log's zero is the first point the file times: {} {}{zone}",
1552                    zero.clock.word(),
1553                    short(zero.raw)
1554                ));
1555                if untimed > 0 {
1556                    notes.push(format!(
1557                        "{untimed} of the file's {points} points have no time: their times are \
1558                         gaps"
1559                    ));
1560                }
1561            }
1562        }
1563        if other_clock > 0 {
1564            notes.push(format!(
1565                "{other_clock} points are timed on another clock than the first timed point's, \
1566                 so they can't share its zero: their times are gaps"
1567            ));
1568        }
1569        if midnights.days > 0 {
1570            notes.push(format!(
1571                "the time of day steps back past midnight {} times: a day is added at each",
1572                midnights.days
1573            ));
1574        }
1575        if midnights.dropped > 0 {
1576            notes.push(format!(
1577                "the time of day steps back past midnight more than {MAX_MIDNIGHTS} times, more \
1578                 than a logger's memory holds. The {} times of day from there on are gaps",
1579                midnights.dropped
1580            ));
1581        }
1582        let mut backs = 0;
1583        let mut largest: f64 = 0.0;
1584        for track in &times {
1585            let mut previous = f64::NAN;
1586            for &time in track.iter().filter(|time| !time.is_nan()) {
1587                if time < previous {
1588                    backs += 1;
1589                    largest = largest.max(previous - time);
1590                }
1591                previous = time;
1592            }
1593        }
1594        if backs > 0 {
1595            notes.push(format!(
1596                "the times go back {backs} times within a track, by up to {largest:.3} s: the \
1597                 points are kept in the file's order"
1598            ));
1599        }
1600        times
1601    }
1602
1603    /// Each track's name for its channels: its placemark's, numbered by part where a placemark
1604    /// holds several geometries, with ` (2)`, ` (3)` … where a name repeats.
1605    fn names(&self) -> Vec<String> {
1606        let mut parts: HashMap<(usize, NodeId), usize> = HashMap::new();
1607        for key in self.tracks.iter().filter_map(|track| track.placemark) {
1608            *parts.entry(key).or_default() += 1;
1609        }
1610        let mut seen_parts: HashMap<(usize, NodeId), usize> = HashMap::new();
1611        let mut used: HashMap<String, usize> = HashMap::new();
1612        self.tracks
1613            .iter()
1614            .map(|track| {
1615                let mut name = track.label.clone();
1616                if let Some(key) = track.placemark
1617                    && parts.get(&key).copied().unwrap_or(0) > 1
1618                {
1619                    let part = seen_parts.entry(key).or_default();
1620                    *part += 1;
1621                    name = format!("{name} part {part}");
1622                }
1623                let count = used.entry(name.clone()).or_default();
1624                *count += 1;
1625                if *count > 1 {
1626                    name = format!("{name} ({count})");
1627                }
1628                name
1629            })
1630            .collect()
1631    }
1632}
1633
1634/// What the file says about its writer and logger.
1635#[derive(Debug, Default)]
1636struct About {
1637    logger: String,
1638    writer: Writer,
1639    serial_number: Option<String>,
1640    firmware: Option<String>,
1641    flight_number: Option<u32>,
1642    apogee_m: Option<f64>,
1643    note: Option<String>,
1644}
1645
1646/// The program that wrote the file, as far as the file tells.
1647#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]
1648enum Writer {
1649    Fw2kml,
1650    Rtx,
1651    AltOs,
1652    BeeLine,
1653    GpsVisualizer,
1654    #[default]
1655    Unknown,
1656}
1657
1658impl About {
1659    /// The writer and logger, from the first document and the comments read.
1660    fn of(document: &Document<'_>, reader: &Reader<'_>) -> Self {
1661        let root = document.root_element();
1662        let top = child(root, "Document").unwrap_or(root);
1663        let title = child(top, "name").map(|name| clean(&all_text(name)));
1664        let snippet = child(top, "Snippet").map(|node| all_text(node));
1665        let mut about = Self::default();
1666        if let Some(rest) = title
1667            .as_deref()
1668            .and_then(|title| title.strip_prefix("AO Flight#"))
1669        {
1670            about.writer = Writer::AltOs;
1671            let digits: String = rest.chars().take_while(char::is_ascii_digit).collect();
1672            about.flight_number = digits.parse().ok();
1673            about.serial_number = rest
1674                .split_once("S/N:")
1675                .map(|(_, serial)| serial.trim().to_owned())
1676                .filter(|serial| !serial.is_empty());
1677            let mut product = None;
1678            for line in snippet.as_deref().unwrap_or_default().lines() {
1679                let Some((key, value)) = line.split_once(':') else {
1680                    continue;
1681                };
1682                let value = value.trim();
1683                match key.trim() {
1684                    "Product" if !value.is_empty() => product = Some(short(value)),
1685                    "Firmware" if !value.is_empty() => about.firmware = Some(short(value)),
1686                    "Max baro height" => about.apogee_m = stated_height_m(value),
1687                    _ => {}
1688                }
1689            }
1690            about.logger = product.map_or_else(|| "AltOS".to_owned(), |p| format!("AltOS {p}"));
1691            return about;
1692        }
1693        about.writer = if title.as_deref() == Some("RTx/GPS Flight") {
1694            Writer::Rtx
1695        } else if root.descendants().any(|node| {
1696            node.is_element()
1697                && node.tag_name().name() == "name"
1698                && node
1699                    .parent()
1700                    .is_some_and(|parent| parent.tag_name().name() == "Placemark")
1701                && all_text(node).trim_start().starts_with("fw2kml")
1702        }) {
1703            Writer::Fw2kml
1704        } else if snippet
1705            .as_deref()
1706            .is_some_and(|text| text.contains("GPS Visualizer"))
1707        {
1708            Writer::GpsVisualizer
1709        } else if reader.memory_dump
1710            || reader
1711                .tracks
1712                .iter()
1713                .flat_map(|track| track.remarks.iter().flatten())
1714                .any(|remark| remark.layout == Layout::BeeLine)
1715        {
1716            Writer::BeeLine
1717        } else {
1718            Writer::Unknown
1719        };
1720        about.logger = match about.writer {
1721            Writer::Fw2kml => "fw2kml",
1722            Writer::Rtx => "Missile Works RTx",
1723            Writer::BeeLine => "Big Red Bee BeeLine",
1724            Writer::GpsVisualizer => "GPS Visualizer",
1725            Writer::AltOs | Writer::Unknown => "KML",
1726        }
1727        .to_owned();
1728        about
1729    }
1730}
1731
1732/// A height AltOS's summary states, such as `5000 ft` or `1500 m`, in meters.
1733fn stated_height_m(text: &str) -> Option<f64> {
1734    let (value, unit) = text.trim().split_once(char::is_whitespace)?;
1735    let value = number(value, false)?;
1736    match unit.trim() {
1737        "ft" => Some(value * FOOT_M),
1738        "m" => Some(value),
1739        _ => None,
1740    }
1741}
1742
1743/// The unit decisions made over the file's tracks, for their notes.
1744#[derive(Default)]
1745struct Decided {
1746    /// Tracks whose altitude is read in meters from the standard.
1747    meters: usize,
1748    /// Of those, AltOS tracks read as the barometer's altitude.
1749    barometric: usize,
1750    /// Over those barometric tracks, the points carrying both altitudes and those where the two
1751    /// differ.
1752    barometric_both: usize,
1753    barometric_differing: usize,
1754    /// Tracks whose altitude GPS Visualizer wrote, kept as written.
1755    gps_visualizer: usize,
1756    /// Tracks whose altitude a viewer ignores, by mode.
1757    ignored: Vec<&'static str>,
1758    /// Tracks in a mode the standard doesn't name.
1759    unnamed: usize,
1760    /// Whether AltOS's comment `alt` became a channel, and if so whether in meters.
1761    altos_alt: Option<bool>,
1762    /// Whether the `Seconds` layout's `Alt` became a channel.
1763    seconds_alt: bool,
1764}
1765
1766impl Decided {
1767    /// A track's altitude channel: its name's suffix and quantity. `barometric` holds, for an
1768    /// AltOS track whose tuple altitude differs from its comments' `alt` at more than half of the
1769    /// points carrying both, how many carry both and how many differ.
1770    fn altitude(
1771        &mut self,
1772        track: &Track<'_>,
1773        about: &About,
1774        barometric: Option<(usize, usize)>,
1775    ) -> (&'static str, Quantity) {
1776        if about.writer == Writer::GpsVisualizer {
1777            self.gps_visualizer += 1;
1778            return ("altitude", Quantity::Unrecognized);
1779        }
1780        match track.mode {
1781            Mode::Absolute => {
1782                self.meters += 1;
1783                if let Some((both, differing)) = barometric {
1784                    self.barometric += 1;
1785                    self.barometric_both += both;
1786                    self.barometric_differing += differing;
1787                    ("altitude", Quantity::AltitudeMsl)
1788                } else {
1789                    ("altitude", Quantity::GnssAltitude)
1790                }
1791            }
1792            Mode::RelativeToGround => {
1793                self.meters += 1;
1794                ("height above ground", Quantity::Distance)
1795            }
1796            Mode::RelativeToSeaFloor => {
1797                self.meters += 1;
1798                ("height above sea floor", Quantity::Distance)
1799            }
1800            Mode::Ignored(mode) => {
1801                self.ignored
1802                    .push(mode.unwrap_or("clampToGround, the default, as none is stated"));
1803                ("altitude", Quantity::Unrecognized)
1804            }
1805            Mode::Unnamed => {
1806                self.unnamed += 1;
1807                ("altitude", Quantity::Unrecognized)
1808            }
1809        }
1810    }
1811
1812    /// The channel of a comment's altitude that differs from the tuple's: its name's suffix and
1813    /// quantity. AltOS's `alt` is the GPS altitude, in meters if `altos_meters` (it equals the
1814    /// tuple's somewhere in the file), else as written; the `Seconds` layout's `Alt` is kept as
1815    /// written.
1816    fn remark_altitude(
1817        &mut self,
1818        layout: Option<Layout>,
1819        altos_meters: bool,
1820    ) -> (&'static str, Quantity) {
1821        if layout == Some(Layout::AltOs) {
1822            self.altos_alt = Some(altos_meters);
1823            let quantity = if altos_meters {
1824                Quantity::GnssAltitude
1825            } else {
1826                Quantity::Unrecognized
1827            };
1828            ("GPS altitude", quantity)
1829        } else {
1830            self.seconds_alt = true;
1831            ("Alt", Quantity::Unrecognized)
1832        }
1833    }
1834
1835    /// One note per decision, with this file's evidence.
1836    fn notes(&self, tracks: &[Track<'_>], altos_time: AltosTime) -> Vec<String> {
1837        let mut notes = Vec::new();
1838        let total = tracks.len();
1839        if self.meters > 0 {
1840            notes.push(format!(
1841                "`coordinates` read in meters, from the KML standard: OGC 07-147r2 states a \
1842                 tuple's altitude in meters, and {} of the file's {total} tracks carry one",
1843                self.meters
1844            ));
1845        }
1846        if self.barometric > 0 {
1847            notes.push(format!(
1848                "`coordinates` read in meters as the barometer's altitude above sea level, from \
1849                 the GPS altitude AltOS writes beside each point. In {} tracks the tuple's altitude \
1850                 differs from the comment's `alt` at {} of the {} points that carry both, more \
1851                 than half. That is because AltOS's KML export has reported both altitudes since \
1852                 AltOS 1.8.3",
1853                self.barometric, self.barometric_differing, self.barometric_both
1854            ));
1855        }
1856        if self.gps_visualizer > 0 {
1857            let (first, highest) = extent(tracks.iter().flat_map(|track| track.alt.iter()));
1858            notes.push(format!(
1859                "`coordinates` kept as written, as GPS Visualizer takes a source's altitude as \
1860                 meters unless the source's header names feet. {} tracks carry an altitude, the \
1861                 highest {:.0} above the first",
1862                self.gps_visualizer,
1863                highest - first
1864            ));
1865        }
1866        if !self.ignored.is_empty() {
1867            let mut modes = self.ignored.clone();
1868            modes.sort_unstable();
1869            modes.dedup();
1870            notes.push(format!(
1871                "`coordinates` kept as written, in a track whose altitude mode tells a viewer to \
1872                 ignore its altitude: {} tracks, in mode {}",
1873                self.ignored.len(),
1874                modes.join(", ")
1875            ));
1876        }
1877        if self.unnamed > 0 {
1878            notes.push(format!(
1879                "`coordinates` kept as written, in an altitude mode the KML standard doesn't \
1880                 name: {} tracks",
1881                self.unnamed
1882            ));
1883        }
1884        let (equal, both) = agreement(tracks, Layout::AltOs);
1885        match self.altos_alt {
1886            Some(true) => notes.push(format!(
1887                "`alt` read in meters, from the coordinates. It equals the tuple's altitude, in \
1888                 meters by the KML standard, at {equal} of the {both} points that carry both"
1889            )),
1890            Some(false) => notes.push(format!(
1891                "`alt` kept as written, as it equals the tuple's altitude at no point, so nothing \
1892                 in the file shows its unit: {both} points carry both"
1893            )),
1894            None => {}
1895        }
1896        if self.seconds_alt {
1897            let (equal, both) = agreement(tracks, Layout::Seconds);
1898            notes.push(format!(
1899                "`Alt` kept as written, in a unit the file doesn't state: it equals the tuple's \
1900                 altitude at {equal} of the {both} points that carry both"
1901            ));
1902        }
1903        notes.extend(clock_notes(tracks, altos_time));
1904        notes
1905    }
1906}
1907
1908/// The first and highest of a run of values that aren't gaps (0 and 0 if none).
1909fn extent<'v>(values: impl Iterator<Item = &'v f64>) -> (f64, f64) {
1910    let mut first = None;
1911    let mut highest = f64::NEG_INFINITY;
1912    for &value in values.filter(|value| !value.is_nan()) {
1913        first.get_or_insert(value);
1914        highest = highest.max(value);
1915    }
1916    first.map_or((0.0, 0.0), |first| (first, highest))
1917}
1918
1919/// How a layout's comment altitude agrees with the tuples': at how many points it equals the
1920/// tuple's, of the points carrying both.
1921fn agreement(tracks: &[Track<'_>], layout: Layout) -> (usize, usize) {
1922    let mut both = 0;
1923    let mut equal = 0;
1924    for track in tracks {
1925        for (tuple, remark) in track.alt.iter().zip(&track.remarks) {
1926            if let Some(remark) = remark
1927                && remark.layout == layout
1928                && !remark.alt.is_nan()
1929                && !tuple.is_nan()
1930            {
1931                both += 1;
1932                equal += usize::from((tuple - remark.alt).abs() <= 1e-6);
1933            }
1934        }
1935    }
1936    (equal, both)
1937}
1938
1939/// The notes deciding each clock's unit, with this file's evidence.
1940fn clock_notes(tracks: &[Track<'_>], altos_time: AltosTime) -> Vec<String> {
1941    let mut notes = Vec::new();
1942    let stamps = || {
1943        tracks
1944            .iter()
1945            .flat_map(|track| track.stamps.iter().flatten())
1946    };
1947    let count = |clock: Clock| stamps().filter(|stamp| stamp.clock == clock).count();
1948    let span = |clock: Clock| {
1949        let (low, high) = stamps()
1950            .filter(|stamp| stamp.clock == clock)
1951            .fold((i64::MAX, i64::MIN), |(low, high), stamp| {
1952                (low.min(stamp.ns), high.max(stamp.ns))
1953            });
1954        if low > high {
1955            0.0
1956        } else {
1957            high.saturating_sub(low) as f64 / NS_PER_S as f64
1958        }
1959    };
1960    let utc = count(Clock::Utc);
1961    if utc > 0 {
1962        notes.push(format!(
1963            "`when` read in UTC, from the KML standard: {utc} times state their zone, `Z` or an \
1964             offset, as XML Schema's date-time allows"
1965        ));
1966    }
1967    let local = count(Clock::Local);
1968    if local > 0 {
1969        notes.push(format!(
1970            "`when` kept as written, in a zone the file doesn't state: {local} times state none, \
1971             so the log's clock has an unknown offset from UTC"
1972        ));
1973    }
1974    let (low, high) = (ALTOS_STEP_S.start(), ALTOS_STEP_S.end());
1975    match altos_time {
1976        AltosTime::Seconds(median) => notes.push(format!(
1977            "`time` read in seconds, from the steps between points. The median step between a \
1978             track's points of distinct times is {median:.2} s. That is within the {low} to \
1979             {high} s a GPS receiver reporting once a second gives"
1980        )),
1981        AltosTime::Unsettled(median) if median.is_nan() => notes.push(
1982            "`time` kept as written, as its steps between points don't show its unit. No track \
1983             holds two points of distinct times, so those points have no time"
1984                .to_owned(),
1985        ),
1986        AltosTime::Unsettled(median) => notes.push(format!(
1987            "`time` kept as written, as its steps between points don't show its unit. The \
1988             median step between a track's points of distinct times is {median:.3} read as \
1989             seconds. That is outside the {low} to {high} s a GPS receiver reporting once a \
1990             second gives, so those points have no time"
1991        )),
1992        AltosTime::Absent | AltosTime::Unset => {}
1993    }
1994    if count(Clock::Seconds) > 0 {
1995        notes.push(format!(
1996            "`Seconds` read in seconds, from its name: the points run {:.3} s from first to last",
1997            span(Clock::Seconds)
1998        ));
1999    }
2000    if count(Clock::TimeOfDay) > 0 {
2001        notes.push(format!(
2002            "`UTC` read in hours, minutes and seconds of the UTC day, from its name and layout: \
2003             the points run {:.0} s from first to last",
2004            span(Clock::TimeOfDay)
2005        ));
2006    }
2007    notes
2008}
2009
2010#[cfg(test)]
2011mod tests {
2012    use super::*;
2013
2014    /// A one-path document around a `coordinates` text.
2015    fn path(mode: &str, coordinates: &str) -> String {
2016        format!(
2017            "<?xml version=\"1.0\"?><kml xmlns=\"http://www.opengis.net/kml/2.2\"><Document>\
2018             <Placemark><name>Flight</name><LineString>{mode}<coordinates>{coordinates}\
2019             </coordinates></LineString></Placemark></Document></kml>"
2020        )
2021    }
2022
2023    #[test]
2024    fn a_kml_root_is_recognized_after_its_prolog() {
2025        for text in [
2026            "<kml xmlns=\"http://www.opengis.net/kml/2.2\">",
2027            "\u{feff}<?xml version=\"1.0\"?>\r\n<!-- a -->\n<!--b--><kml>",
2028            "  <kml/>",
2029        ] {
2030            assert!(recognizes(text), "{text:?}");
2031        }
2032        for text in [
2033            "<kmlx>",
2034            "<gpx>",
2035            "<?xml version=\"1.0\"?><gpx><kml/></gpx>",
2036            "<!-- unclosed <kml>",
2037            "Time,Altitude\n",
2038            "",
2039        ] {
2040            assert!(!recognizes(text), "{text:?}");
2041        }
2042    }
2043
2044    #[test]
2045    fn whens_read_with_their_zone() {
2046        let base = days_from_civil(2026, 5, 23) * DAY_NS;
2047        assert_eq!(days_from_civil(1970, 1, 1), 0);
2048        assert_eq!(days_from_civil(2000, 3, 1), 11_017);
2049        let hour = 3_600 * NS_PER_S;
2050        let cases = [
2051            (
2052                "2026-05-23T10:15:00Z",
2053                Clock::Utc,
2054                base + 10 * hour + 900 * NS_PER_S,
2055            ),
2056            (
2057                "2026-05-23T10:15:00.25Z",
2058                Clock::Utc,
2059                base + 10 * hour + 900_250_000_000,
2060            ),
2061            (
2062                "2026-05-23T12:15:00+02:00",
2063                Clock::Utc,
2064                base + 10 * hour + 900 * NS_PER_S,
2065            ),
2066            (
2067                "2026-05-23T05:15:00-05:00",
2068                Clock::Utc,
2069                base + 10 * hour + 900 * NS_PER_S,
2070            ),
2071            (
2072                " 2026-05-23T10:15:00 ",
2073                Clock::Local,
2074                base + 10 * hour + 900 * NS_PER_S,
2075            ),
2076            (
2077                "2024-02-29T00:00:00Z",
2078                Clock::Utc,
2079                days_from_civil(2024, 2, 29) * DAY_NS,
2080            ),
2081            (
2082                "2026-05-23T10:15:00+14:00",
2083                Clock::Utc,
2084                base - 4 * hour + 900 * NS_PER_S,
2085            ),
2086        ];
2087        for (text, clock, ns) in cases {
2088            assert_eq!(when_ns(text), Some((clock, ns)), "{text}");
2089        }
2090        for text in [
2091            "2026",
2092            "2026-05",
2093            "2026-05-23",
2094            "2026-02-29T00:00:00Z",
2095            "2026-13-01T00:00:00Z",
2096            "2026-05-23T24:00:00Z",
2097            "2026-05-23T10:15Z",
2098            "2026-05-23T10:15:00+2:00",
2099            "2026-05-23T10:15:00+15:00",
2100            "2026-05-23T10:15:00+14:01",
2101            "2026-05-23T10:15:00-14:30",
2102            "2026-05-23 10:15:00Z",
2103            "26-05-23T10:15:00Z",
2104            "2026-05-23T10:15:00.Z",
2105            "2026-05-23T10:15:00.5e3Z",
2106            "",
2107        ] {
2108            assert_eq!(when_ns(text), None, "{text}");
2109        }
2110    }
2111
2112    #[test]
2113    fn decimals_read_exactly_to_the_nanosecond() {
2114        assert_eq!(decimal_ns("123.4500000"), Some(123_450_000_000));
2115        assert_eq!(decimal_ns("-0.25"), Some(-250_000_000));
2116        assert_eq!(decimal_ns("1"), Some(NS_PER_S));
2117        assert_eq!(decimal_ns(".5"), Some(500_000_000));
2118        assert_eq!(decimal_ns("0.1234567899"), Some(123_456_789));
2119        for text in ["", "-", ".", "1e3", "1.2.3", "nan", "12345678901", "+-1"] {
2120            assert_eq!(decimal_ns(text), None, "{text}");
2121        }
2122        assert_eq!(time_of_day_ns("12:34:56"), Some(45_296 * NS_PER_S));
2123        assert_eq!(time_of_day_ns("00:00:00.5"), Some(NS_PER_S / 2));
2124        for text in [
2125            "24:00:00",
2126            "1:00:00",
2127            "12:60:00",
2128            "12:00:61",
2129            "12:00:+5",
2130            "12:00:-0",
2131            "12:00:+5.5",
2132            "12:00",
2133            "12:00:00:00",
2134        ] {
2135            assert_eq!(time_of_day_ns(text), None, "{text}");
2136        }
2137    }
2138
2139    #[test]
2140    fn tuples_take_two_or_three_numbers_whatever_the_spacing() {
2141        let read: Vec<Option<(f64, f64, Option<f64>)>> =
2142            tuples(" -97.1,35.2,402\n\t-97.1, 35.2 ,  415\r\n-97.2,35.3 -97.3,35.4,-0.5 ")
2143                .iter()
2144                .map(|raw| tuple(raw, false))
2145                .collect();
2146        assert_eq!(
2147            read,
2148            [
2149                Some((-97.1, 35.2, Some(402.0))),
2150                Some((-97.1, 35.2, Some(415.0))),
2151                Some((-97.2, 35.3, None)),
2152                Some((-97.3, 35.4, Some(-0.5))),
2153            ]
2154        );
2155        assert_eq!(
2156            tuple("-97.1,35.2,00850", false),
2157            Some((-97.1, 35.2, Some(850.0)))
2158        );
2159        for raw in [
2160            "-97.1",
2161            "-97.1,35.2,1,2",
2162            "-97.1,,1",
2163            "a,b",
2164            "-97.1,35.2,",
2165            "1,inf",
2166        ] {
2167            assert_eq!(tuple(raw, false), None, "{raw}");
2168        }
2169        assert_eq!(
2170            tuple(" -97.1  35.2 402.5 ", true),
2171            Some((-97.1, 35.2, Some(402.5)))
2172        );
2173        assert_eq!(tuple("-97.1 35.2", true), Some((-97.1, 35.2, None)));
2174        for raw in ["", "-97.1,35.2,402", "1 2 3 4"] {
2175            assert_eq!(tuple(raw, true), None, "{raw}");
2176        }
2177    }
2178
2179    #[test]
2180    fn each_comment_layout_reads() {
2181        let altos = remark(" alt    7.5000000 time   -0.2500000 sats 5 ").unwrap();
2182        assert_eq!(
2183            (altos.layout, altos.alt, altos.time, altos.sats),
2184            (Layout::AltOs, 7.5, Some((-250_000_000, "-0.2500000")), 5.0)
2185        );
2186        assert!(altos.offset.is_nan());
2187        let seconds = remark(" Alt 250.125 Seconds 9.5 ").unwrap();
2188        assert_eq!(
2189            (seconds.layout, seconds.alt, seconds.time),
2190            (Layout::Seconds, 250.125, Some((9_500_000_000, "9.5")))
2191        );
2192        assert!(seconds.sats.is_nan());
2193        let beeline = remark(" 1003 sats:8 UTC 12:34:56 ").unwrap();
2194        assert_eq!(
2195            (beeline.layout, beeline.offset, beeline.sats, beeline.time),
2196            (
2197                Layout::BeeLine,
2198                1_003.0,
2199                8.0,
2200                Some((45_296 * NS_PER_S, "12:34:56"))
2201            )
2202        );
2203        assert!(beeline.alt.is_nan());
2204        for text in [
2205            " Name       : a rocket ",
2206            " Capture Date: 01/02/2030 ",
2207            " base    : 0m or     0 feet ",
2208            " alt 9 time x sats 5 ",
2209            " alt 9 time 1 sats 5 extra ",
2210            " 1 sats:x UTC 12:34:56 ",
2211            " 1 sats:4 UTC 25:00:00 ",
2212            "",
2213        ] {
2214            assert_eq!(remark(text), None, "{text:?}");
2215        }
2216    }
2217
2218    #[test]
2219    fn a_comment_belongs_to_the_tuple_right_before_it() {
2220        let log = read(&path(
2221            "<altitudeMode>absolute</altitudeMode>",
2222            "<!-- header -->\n-97.1,35.2,400 <!-- alt 401 time 0.5 sats 4 -->\n\
2223             -97.1,35.2,410 <!-- alt 411 time 1.5 sats 5 --> <!-- second -->\n-97.1,35.2,420",
2224        ))
2225        .unwrap();
2226        let columns: Vec<&str> = log.channels.iter().map(|c| c.column.as_str()).collect();
2227        assert_eq!(
2228            columns,
2229            [
2230                "Flight latitude",
2231                "Flight longitude",
2232                "Flight altitude",
2233                "Flight GPS altitude",
2234                "Flight satellites"
2235            ]
2236        );
2237        let gps = &log.channels[3];
2238        assert_eq!(gps.values[..2], [401.0, 411.0]);
2239        assert!(gps.values[2].is_nan());
2240        assert_eq!(gps.time_s[..2], [0.0, 1.0]);
2241        assert!(gps.time_s[2].is_nan());
2242        assert_eq!(log.channels[2].quantity, Quantity::AltitudeMsl);
2243        // `header` precedes every tuple and `second` follows a comment: neither is a point's.
2244        for expected in [
2245            "2 comments in `coordinates` follow no point's",
2246            "1 of the file's 3 points",
2247        ] {
2248            assert!(
2249                log.notes.iter().any(|note| note.contains(expected)),
2250                "{expected}: {:?}",
2251                log.notes
2252            );
2253        }
2254    }
2255
2256    #[test]
2257    fn the_altitude_mode_sets_the_quantity() {
2258        let quantity = |mode: &str| {
2259            let log = read(&path(mode, "-97.1,35.2,400 -97.1,35.2,410")).unwrap();
2260            (log.channels[2].column.clone(), log.channels[2].quantity)
2261        };
2262        assert_eq!(
2263            quantity("<altitudeMode>absolute</altitudeMode>"),
2264            ("Flight altitude".to_owned(), Quantity::GnssAltitude)
2265        );
2266        assert_eq!(
2267            quantity("<altitudeMode>relativeToGround</altitudeMode>"),
2268            ("Flight height above ground".to_owned(), Quantity::Distance)
2269        );
2270        assert_eq!(
2271            quantity(
2272                "<gx:altitudeMode xmlns:gx=\"http://www.google.com/kml/ext/2.2\">relativeToSeaFloor</gx:altitudeMode>"
2273            ),
2274            (
2275                "Flight height above sea floor".to_owned(),
2276                Quantity::Distance
2277            )
2278        );
2279        for mode in [
2280            "",
2281            "<altitudeMode>clampToGround</altitudeMode>",
2282            "<altitudeMode>up</altitudeMode>",
2283        ] {
2284            assert_eq!(
2285                quantity(mode),
2286                ("Flight altitude".to_owned(), Quantity::Unrecognized),
2287                "{mode}"
2288            );
2289        }
2290        // Two numbers a tuple: no altitude channel.
2291        let log = read(&path("", "-97.1,35.2 -97.1,35.3")).unwrap();
2292        assert_eq!(log.channels.len(), 2);
2293    }
2294
2295    #[test]
2296    fn concatenated_documents_split_at_each_declaration() {
2297        let one = path("<altitudeMode>absolute</altitudeMode>", "-97.1,35.2,400");
2298        let twice = format!("{one}\n{one}\n");
2299        let (pieces, more) = split_documents(&twice, MAX_NODES).unwrap();
2300        assert_eq!(pieces.len(), 2);
2301        assert!(!more);
2302        assert!(pieces.iter().all(|piece| piece.trim() == one));
2303        let log = read(&format!("{one}\n{one}\n{one}")).unwrap();
2304        assert_eq!(log.channels.len(), 3);
2305        assert!(
2306            log.notes.iter().any(|n| n.contains("3 times over")),
2307            "{:?}",
2308            log.notes
2309        );
2310        let other = path("<altitudeMode>absolute</altitudeMode>", "-97.2,35.3,500");
2311        let log = read(&format!("{one}{other}")).unwrap();
2312        let columns: Vec<&str> = log.channels.iter().map(|c| c.column.as_str()).collect();
2313        assert_eq!(columns[3], "Flight (2) latitude");
2314        assert!(log.notes.iter().any(|n| n.contains("1 more KML documents")));
2315        // Trailing text that isn't a document is refused, not skipped.
2316        assert!(matches!(
2317            read(&format!("{one}<kml/>")),
2318            Err(LogError::Syntax { .. })
2319        ));
2320    }
2321
2322    #[test]
2323    fn hostile_documents_are_refused() {
2324        let dtd = "<?xml version=\"1.0\"?><!DOCTYPE kml [<!ENTITY a \"aaaa\">]><kml>&a;</kml>";
2325        let error = read(dtd).unwrap_err();
2326        assert!(error.to_string().contains("document type"), "{error}");
2327        assert!(matches!(
2328            read("<kml><Placemark>"),
2329            Err(LogError::Syntax { .. })
2330        ));
2331        assert!(matches!(read("<kml/>"), Err(LogError::NoData { .. })));
2332        assert!(matches!(
2333            read("<gpx/>"),
2334            Err(LogError::NotThisFormat { .. })
2335        ));
2336    }
2337
2338    #[test]
2339    fn tracks_past_the_cap_are_counted() {
2340        let pins: String = (0..MAX_TRACKS + 3)
2341            .map(|index| {
2342                format!("<Placemark><Point><coordinates>-100,40,{index}</coordinates></Point></Placemark>")
2343            })
2344            .collect();
2345        let log = read(&format!("<kml><Document>{pins}</Document></kml>")).unwrap();
2346        // Latitude, longitude and an altitude kept as written, no mode being stated.
2347        assert_eq!(log.channels.len(), 3 * MAX_TRACKS);
2348        assert_eq!(log.channels[3].column, "track (2) latitude");
2349        assert!(
2350            log.notes
2351                .iter()
2352                .any(|note| note.starts_with("the file holds 3 more geometries than the 256")),
2353            "{:?}",
2354            log.notes
2355        );
2356    }
2357
2358    #[test]
2359    fn a_document_type_in_the_prolog_is_stepped_past() {
2360        for text in [
2361            "<?xml version=\"1.0\"?><!DOCTYPE kml><kml/>",
2362            "<!DOCTYPE kml [<!ENTITY a \"x>y\"> <!ENTITY b 'z]'>]>\n<!-- c --><kml>&a;</kml>",
2363        ] {
2364            assert!(recognizes(text), "{text:?}");
2365        }
2366        for text in ["<!DOCTYPE kml [<!ENTITY a \"x\">", "<!DOCTYPE gpx><gpx/>"] {
2367            assert!(!recognizes(text), "{text:?}");
2368        }
2369    }
2370
2371    #[test]
2372    fn nesting_is_counted_past_comments_quotes_and_closed_tags() {
2373        assert_eq!(
2374            nesting("<a><b/><c x='>' y=\"<d>\"><!-- <e> --></c></a>"),
2375            (2, 0)
2376        );
2377        assert_eq!(nesting("<a><![CDATA[<b><c>]]><?p <q>?></a>"), (1, 0));
2378        let deep = format!("<k>\n{}", "<a>".repeat(MAX_DEPTH));
2379        assert_eq!(nesting(&deep), (MAX_DEPTH + 1, 2));
2380        let error = read(&deep).unwrap_err();
2381        assert!(
2382            matches!(&error, LogError::Syntax { line: 2, message, .. }
2383                if message.contains(&format!("nests elements {} deep", MAX_DEPTH + 1))),
2384            "{error:?}"
2385        );
2386    }
2387
2388    #[test]
2389    fn the_node_limit_is_the_files_over_all_its_documents() {
2390        let one = path("<altitudeMode>absolute</altitudeMode>", "-97.1,35.2,400");
2391        let other = path("<altitudeMode>absolute</altitudeMode>", "-97.2,35.3,500");
2392        let nodes = u32::try_from(Document::parse(&one).unwrap().descendants().count()).unwrap();
2393        // Each document fits alone; the two together don't, nor do they one node short.
2394        assert!(read_within(&one, nodes).is_ok());
2395        assert!(read_within(&other, nodes).is_ok());
2396        let both = format!("{one}{other}");
2397        for budget in [nodes, nodes + 1, 2 * nodes - 1] {
2398            let error = read_within(&both, budget).unwrap_err();
2399            assert!(
2400                error.to_string().contains("XML nodes over its documents"),
2401                "{budget}: {error}"
2402            );
2403        }
2404        assert!(read_within(&both, 2 * nodes).is_ok());
2405        // A copy of the first document isn't parsed again, so it takes nothing from the budget.
2406        assert!(read_within(&format!("{one}\n{one}"), nodes).is_ok());
2407    }
2408
2409    /// A BeeLine path whose comments give its points these times of day, in turn.
2410    fn beeline<'t>(times: impl Iterator<Item = &'t str>) -> String {
2411        let coordinates: String = times
2412            .enumerate()
2413            .map(|(index, time)| format!("-100,40,{index} <!-- {index} sats:8 UTC {time} -->\n"))
2414            .collect();
2415        path("<altitudeMode>absolute</altitudeMode>", &coordinates)
2416    }
2417
2418    #[test]
2419    fn midnight_is_passed_at_most_max_midnights_times() {
2420        let alternate = |count| beeline(["23:00:00", "00:00:00"].into_iter().cycle().take(count));
2421        let day_s = 86_400.0;
2422        // 15 points pass midnight 7 times, the bound: every point keeps its time.
2423        let log = read(&alternate(15)).unwrap();
2424        let time = &log.channels[0].time_s;
2425        assert!(time.iter().all(|time| time.is_finite()), "{time:?}");
2426        assert_eq!(time[13], 7.0 * day_s - 23.0 * 3_600.0);
2427        assert_eq!(time[14], 7.0 * day_s);
2428        assert!(
2429            log.notes
2430                .iter()
2431                .any(|note| note.contains("midnight 7 times"))
2432        );
2433        // A 16th point would pass it an 8th time: its time is a gap, with a note.
2434        let log = read(&alternate(16)).unwrap();
2435        assert!(log.channels[0].time_s[15].is_nan());
2436        assert!(log.channels[0].time_s[..15].iter().all(|t| t.is_finite()));
2437        assert!(
2438            log.notes.iter().any(|note| note.starts_with(
2439                "the time of day steps back past midnight more than 7 times, more than a \
2440                 logger's memory holds. The 1 times of day from there on are gaps"
2441            )),
2442            "{:?}",
2443            log.notes
2444        );
2445        // 230,000 points stepping back at every other one: no day count overflows, and every
2446        // time past the bound is a gap.
2447        let log = read(&alternate(230_000)).unwrap();
2448        let time = &log.channels[0].time_s;
2449        assert_eq!(time.iter().filter(|time| time.is_finite()).count(), 15);
2450        assert!(
2451            log.notes
2452                .iter()
2453                .any(|note| note.contains("The 229985 times of day from there on are gaps")),
2454            "{:?}",
2455            log.notes
2456        );
2457    }
2458
2459    /// A three-point AltOS path, the tuples' altitudes 100, 200 and 300, with these comment
2460    /// altitudes and times.
2461    fn altos(alts: [&str; 3], times: [&str; 3]) -> String {
2462        let coordinates: String = (0..3)
2463            .map(|index| {
2464                format!(
2465                    "-100,40,{} <!-- alt {} time {} sats 5 -->\n",
2466                    100 * (index + 1),
2467                    alts[index],
2468                    times[index]
2469                )
2470            })
2471            .collect();
2472        path("<altitudeMode>absolute</altitudeMode>", &coordinates)
2473    }
2474
2475    /// The quantity of a log's channel by its column, if it has one.
2476    fn quantity_of(log: &FlightLog, column: &str) -> Option<Quantity> {
2477        log.channels
2478            .iter()
2479            .find(|channel| channel.column == column)
2480            .map(|channel| channel.quantity)
2481    }
2482
2483    /// Whether a note opens with the text.
2484    fn noted(log: &FlightLog, opening: &str) -> bool {
2485        log.notes.iter().any(|note| note.starts_with(opening))
2486    }
2487
2488    #[test]
2489    fn an_altos_track_is_the_barometers_where_most_of_its_points_differ() {
2490        let seconds = ["1", "2", "3"];
2491        let barometric = "`coordinates` read in meters as the barometer's altitude above sea \
2492                          level, from the GPS altitude AltOS writes beside each point. ";
2493        // One point of three differs: the tuple's is the GPS altitude, and the comment's a
2494        // channel in meters, as it equals the tuple's elsewhere.
2495        let log = read(&altos(["100", "200", "333"], seconds)).unwrap();
2496        assert_eq!(
2497            quantity_of(&log, "Flight altitude"),
2498            Some(Quantity::GnssAltitude)
2499        );
2500        assert_eq!(
2501            quantity_of(&log, "Flight GPS altitude"),
2502            Some(Quantity::GnssAltitude)
2503        );
2504        assert!(!noted(&log, barometric), "{:?}", log.notes);
2505        assert!(noted(
2506            &log,
2507            "`alt` read in meters, from the coordinates. It equals the tuple's altitude, in meters \
2508             by the KML standard, at 2 of the 3 points that carry both"
2509        ));
2510        // Two of three differ: the tuple's is the barometer's.
2511        let log = read(&altos(["100", "222", "333"], seconds)).unwrap();
2512        assert_eq!(
2513            quantity_of(&log, "Flight altitude"),
2514            Some(Quantity::AltitudeMsl)
2515        );
2516        assert_eq!(
2517            quantity_of(&log, "Flight GPS altitude"),
2518            Some(Quantity::GnssAltitude)
2519        );
2520        assert!(
2521            noted(
2522                &log,
2523                &format!(
2524                    "{barometric}In 1 tracks the tuple's altitude differs from the comment's \
2525                     `alt` at 2 of the 3 points that carry both"
2526                )
2527            ),
2528            "{:?}",
2529            log.notes
2530        );
2531        // None equal: the comment's altitude shows no unit, and is kept as written.
2532        let log = read(&altos(["111", "222", "333"], seconds)).unwrap();
2533        assert_eq!(
2534            quantity_of(&log, "Flight GPS altitude"),
2535            Some(Quantity::Unrecognized)
2536        );
2537        assert!(noted(
2538            &log,
2539            "`alt` kept as written, as it equals the tuple's altitude at no point, so nothing in \
2540             the file shows its unit: 3 points carry both"
2541        ));
2542        // All equal: the comment's altitude adds nothing.
2543        let log = read(&altos(["100", "200", "300"], seconds)).unwrap();
2544        assert_eq!(
2545            quantity_of(&log, "Flight altitude"),
2546            Some(Quantity::GnssAltitude)
2547        );
2548        assert_eq!(quantity_of(&log, "Flight GPS altitude"), None);
2549        assert!(!log.notes.iter().any(|note| note.starts_with("`alt`")));
2550    }
2551
2552    #[test]
2553    fn altos_time_is_read_in_seconds_only_where_its_steps_are_about_a_second() {
2554        let alts = ["100", "200", "300"];
2555        let log = read(&altos(alts, ["10", "11", "12"])).unwrap();
2556        assert_eq!(log.channels[0].time_s, [0.0, 1.0, 2.0]);
2557        assert_eq!(quantity_of(&log, "Flight time"), None);
2558        assert!(noted(
2559            &log,
2560            "`time` read in seconds, from the steps between points. The median step between a \
2561             track's points of distinct times is 1.00 s. That is within the 0.5 to 2 s"
2562        ));
2563        // The bounds read; just past them, and steps of 100, don't.
2564        for (times, seconds) in [
2565            (["0", "0.5", "1"], true),
2566            (["0", "2", "4"], true),
2567            (["0", "0.49", "0.98"], false),
2568            (["0", "2.01", "4.02"], false),
2569            (["100", "200", "300"], false),
2570        ] {
2571            let log = read(&altos(alts, times)).unwrap();
2572            let timed = log.channels[0].time_s.iter().all(|time| time.is_finite());
2573            assert_eq!(timed, seconds, "{times:?}");
2574            assert_eq!(
2575                quantity_of(&log, "Flight time").is_none(),
2576                seconds,
2577                "{times:?}"
2578            );
2579        }
2580        // Kept as written: a channel of its own, no time, and a note.
2581        let log = read(&altos(alts, ["100", "200", "300"])).unwrap();
2582        assert!(log.channels[0].time_s.iter().all(|time| time.is_nan()));
2583        let time = log
2584            .channels
2585            .iter()
2586            .find(|channel| channel.column == "Flight time")
2587            .unwrap();
2588        assert_eq!(
2589            (time.quantity, &time.values[..]),
2590            (Quantity::Unrecognized, &[100.0, 200.0, 300.0][..])
2591        );
2592        assert!(noted(
2593            &log,
2594            "`time` kept as written, as its steps between points don't show its unit. The median \
2595             step between a track's points of distinct times is 100.000 read as seconds."
2596        ));
2597        // A single point has no step to show it.
2598        let log = read(&path(
2599            "<altitudeMode>absolute</altitudeMode>",
2600            "-100,40,100 <!-- alt 100 time 5 sats 5 -->",
2601        ))
2602        .unwrap();
2603        assert!(noted(
2604            &log,
2605            "`time` kept as written, as its steps between points don't show its unit. No track \
2606             holds two points of distinct times"
2607        ));
2608    }
2609
2610    proptest::proptest! {
2611        /// Any text is read or refused, never a panic; what is read has a time and a value for
2612        /// each sample on every channel, and events at finite times.
2613        #[test]
2614        fn any_text_is_read_or_refused(
2615            mode in "(absolute|relativeToGround|clampToGround|x|)",
2616            coordinates in "[-0-9.,:\\s]{0,60}",
2617            comment in "(alt|Alt|time|Seconds|sats|sats:|UTC|[0-9.:-]| ){0,40}",
2618            when in "[-0-9:TZ.+]{0,30}",
2619            raw in "\\PC{0,80}",
2620        ) {
2621            let texts = [
2622                path(&format!("<altitudeMode>{mode}</altitudeMode>"), &format!("{coordinates}<!--{comment}-->{coordinates}")),
2623                format!("<kml><Placemark><name>p</name><gx:Track xmlns:gx=\"g\"><when>{when}</when><gx:coord>{coordinates}</gx:coord></gx:Track></Placemark></kml>"),
2624                format!("<kml><Placemark><TimeStamp><when>{when}</when></TimeStamp><Point><coordinates>{coordinates}</coordinates></Point></Placemark></kml>"),
2625                format!("<kml>{raw}</kml>"),
2626                raw.clone(),
2627            ];
2628            for text in texts {
2629                if let Ok(log) = read(&text) {
2630                    proptest::prop_assert!(log.time_s.is_empty() && log.altitude_m.is_empty());
2631                    for channel in &log.channels {
2632                        proptest::prop_assert_eq!(channel.time_s.len(), channel.values.len());
2633                    }
2634                    for event in &log.events {
2635                        proptest::prop_assert!(event.time_s.is_finite());
2636                    }
2637                }
2638            }
2639        }
2640    }
2641}