Skip to main content

printobserver_core/
gcode_index.rs

1//! What the slicer planned to print at each height, indexed once per print
2//! from the print's own G-code.
3//!
4//! A supervising agent judging a frame needs to know what *should* be there:
5//! a support tower, a bridge or an overhang the slicer planned looks, to a
6//! camera, much like a defect. The slicer wrote that plan into the file, and
7//! this module reads it: one streamed pass over the whole file builds a
8//! [`GcodeIndex`], and every check after that reads the plan at the print's
9//! current file position from the index rather than from the file. The agent
10//! is handed only what is derived — a [`SlicerPlan`] — and never a line of
11//! G-code.
12//!
13//! # What is read
14//!
15//! * `;LAYER_CHANGE` starts a layer and the `;Z:` after it is its height: the
16//!   markers `PrusaSlicer` writes. The last layer's height is the final one.
17//! * `;TYPE:<name>` names what the moves after it extrude — `Perimeter`,
18//!   `Support material`, `Bridge infill` — and a layer's types are those under
19//!   which any move of that layer laid material. `Custom` is left out: it
20//!   labels the slicer's own start and end G-code rather than the part.
21//!   `;WIDTH:<mm>` is the extrusion width the moves after it are laid at,
22//!   which a layer's toolpath carries on each segment.
23//! * `M73 P<percent> R<minutes>` is the slicer's own estimate of the time
24//!   left, in the normal mode. The silent mode's `M73 Q<percent> S<minutes>`
25//!   is ignored.
26//! * `M221 S<percent>` sets the flow factor and `M106 S<0–255>` the part
27//!   cooling fan, which `M107` turns off; a fan named by a `P` other than `0`
28//!   is not the part-cooling fan.
29//! * `M486 S<n>` starts laying down object `n` and `M486 S-1` stops; an
30//!   `M486 A<name>` labels the file's objects too, though no name is kept. An
31//!   object's bed area is the rectangle every move laying material for it
32//!   reached — an arc's the extremes of the part of its circle it sweeps, so a
33//!   footprint is never smaller than what was laid and a nearly straight arc
34//!   about a far centre is no larger than the line it nearly is — read to the
35//!   nearest tenth of a millimetre and then widened to whole millimetres.
36//! * `M600` is a planned colour change and `M601` a planned pause, each a
37//!   [`PlannedChange`] at the offset of its line's first byte. The layer it
38//!   belongs to is the first that lays material after it, which in
39//!   `PrusaSlicer`'s output is the layer whose `;LAYER_CHANGE` it follows. An
40//!   `M600`'s colour is the `;COLOR_CHANGE,T<n>,#RRGGBB` on the line just
41//!   before it; the colour before the first change is the config block's
42//!   `; filament_colour = `, the first tool's when it lists several.
43//! * `M73 C<minutes>` is the slicer's count of the minutes to the next change.
44//!   The filament each stretch between changes feeds is the net of its
45//!   extrusion moves, counted as `OctoPrint`'s own reader counts what a print
46//!   fed, so a stretch's length is what the spool feeding it is charged.
47//!
48//! Everything else is a move or nothing to this reader: `G0`–`G3` with
49//! `G90`/`G91`, `M82`/`M83`, `G92` and `G28` are followed so that what laid
50//! material, and where, is known; a comment is not a command, a leading
51//! `N<line number>` is not a word, and `*<checksum>` ends the line.
52//!
53//! # The planned geometry
54//!
55//! The same read records each object's outline, where each object's labelled
56//! block starts and each layer's byte range, and — when the supervisor is
57//! given a spool directory — copies the file's bytes to a per-print spool, so
58//! a layer's toolpath ([`crate::toolpath`]) is read back from the spool rather
59//! than from a second read of the printer's file. The spool is deleted when
60//! the print closes, and at start-up for any print no longer open.
61//!
62//! # Where a position falls
63//!
64//! A line counts when every byte of it, its newline included, lies before the
65//! position — `OctoPrint`'s file position is the offset after the last line it
66//! read. So a marker the printer has read is in force, and one it is part-way
67//! through is not yet.
68//!
69//! # Once per print
70//!
71//! [`GcodeIndexes`] holds each print's index in memory for as long as this
72//! process runs. The first check or context read after a print starts builds
73//! it; a read arriving while it is being built waits for that build rather
74//! than starting a second, and no read after it touches the file. A read that
75//! failed builds nothing, so the next one tries again; a file whose markers
76//! are missing builds an index that says so ([`PlanFact`]), which is not a
77//! failure.
78
79use core::future::Future;
80use core::ops::ControlFlow;
81use core::pin::Pin;
82use core::task::{Context, Poll, Waker};
83use std::collections::BTreeMap;
84use std::sync::{Arc, Mutex, PoisonError};
85
86use printobserver_printer_api::GcodeSink;
87use printobserver_types::contract::Sample;
88use printobserver_types::schemars::JsonSchema;
89use printobserver_types::serde::{Deserialize, Serialize};
90use printobserver_types::{PrintId, Timestamp};
91
92use crate::toolpath::{
93    ChangeFact, ExtrusionKind, LayerFacts, LayerRef, LayerToolpath, ObjectOutline, Reach,
94    SpoolError, ToolpathSegment,
95};
96
97/// The longest line this reader holds; anything longer is no line it reads.
98///
99/// G-code lines are tens of bytes. A bound keeps a file that is not G-code
100/// from being held in memory a line at a time.
101const LINE_LIMIT: usize = 4096;
102
103/// The most distinct extrusion types one index names; a file naming more is
104/// no slicer's output, and its further types are not recorded.
105const TYPE_LIMIT: usize = 64;
106
107/// How long before a check an earlier frame is, at the least, for the height
108/// laid since it to be one a camera shows: half an hour.
109const RISE_WINDOW_S: i64 = 30 * 60;
110
111/// How many layers below the current one a frame shows, and so how far down a
112/// bridge or an overhang the fan should still be cooling is looked for.
113const LAYERS_SHOWN_BELOW: usize = 5;
114
115/// The flow factor under which a wall is laid starved of material.
116const FLOW_WELL_UNDER_ONE: f64 = 0.9;
117
118/// The types a part-cooling fan holds up: what is laid over air.
119const OVER_AIR: [&str; 2] = ["Bridge infill", "Overhang perimeter"];
120
121/// The types that hold a part up rather than make it.
122const SUPPORTS: [&str; 2] = ["Support material", "Support material interface"];
123
124/// The types a wall is laid as.
125const WALLS: [&str; 2] = ["Perimeter", "External perimeter"];
126
127/// The most objects one index names, for the same reason.
128const OBJECT_LIMIT: usize = 1024;
129
130/// The largest axis word read as a place, in millimetres: ten metres, far
131/// past any machine's travel. A word beyond it is no place a head can be.
132const AXIS_LIMIT: f64 = 1e4;
133
134/// The largest number any word is read as: ten kilometres of filament as an
135/// absolute `E`, far past any spool. A word beyond it is no figure a file sets.
136const WORD_LIMIT: f64 = 1e7;
137
138/// The most words one command is read as; G-code commands carry a handful.
139const WORD_COUNT: usize = 8;
140
141/// The XY travel below which a move counts as no travel at all.
142const TRAVEL_MM: f64 = 1e-6;
143
144/// The type label naming the slicer's own start and end G-code.
145const NOT_THE_PART: &str = "Custom";
146
147/// What `M106` sets the fan to with no `S` word, and what full speed is.
148const FAN_FULL: f64 = 255.0;
149
150/// The longest chord an arc's toolpath is cut into, in millimetres.
151const CHORD_MM: f64 = 0.5;
152
153/// How far past a planned change's line a job's file position may stand and
154/// still be waiting at it, in bytes.
155///
156/// `OctoPrint`'s position is the offset after the last line it sent, and it
157/// goes on sending the few lines after an `M600` the firmware's command queue
158/// takes before the change blocks it: the prime and a handful of moves, a few
159/// hundred bytes. Four kilobytes holds every queue a firmware keeps, and a
160/// print that has carried on from the change is past it within seconds.
161pub const PLANNED_CHANGE_REACH_BYTES: u64 = 4096;
162
163/// The most planned changes one index names; a file planning more is no
164/// slicer's colour plan, and its further changes are not recorded.
165const CHANGE_LIMIT: usize = 1024;
166
167/// Where the reader stood at one point of the file: what a toolpath read of
168/// a layer starts from.
169#[derive(Debug, Clone, Copy, PartialEq)]
170struct Head {
171    /// Where the head is in X, Y and Z.
172    at: [f64; 3],
173    /// The extruder's position.
174    e: f64,
175    /// What `G90`/`G91` last said.
176    axes: Positioning,
177    /// What `M82`/`M83` last said.
178    extruder: Positioning,
179    /// The type being extruded, as a bit of the type table.
180    current_type: Option<usize>,
181    /// The last `;WIDTH:` read, in millimetres; 0 before any.
182    width_mm: f32,
183}
184
185/// One layer, from its `;LAYER_CHANGE` to the next.
186#[derive(Debug, Clone, PartialEq)]
187struct Layer {
188    /// The offset of its `;LAYER_CHANGE` line's first byte.
189    begins: u64,
190    /// The offset just past its `;LAYER_CHANGE` line.
191    at: u64,
192    /// Where the reader stood just past that line.
193    head: Head,
194    /// Its height, from the `;Z:` after it.
195    z_mm: Option<f64>,
196    /// The types any of its moves laid material under, as bits of the index's
197    /// type table.
198    types: u64,
199}
200
201/// A value a file set, and the offset just past the line that set it.
202#[derive(Debug, Clone, Copy, PartialEq)]
203struct Mark<T> {
204    /// The offset just past the line.
205    at: u64,
206    /// What it set.
207    value: T,
208}
209
210/// An object as the reader has seen it so far.
211#[derive(Debug, Clone, Default, PartialEq)]
212struct ObjectDraft {
213    /// The rectangle its material reached: least X, least Y, most X, most Y.
214    bounds: Option<[f64; 4]>,
215    /// How far its material reached in every outline direction.
216    reach: Reach,
217}
218
219/// One file's slicer plan, by file position.
220#[derive(Debug, Clone, PartialEq)]
221pub struct GcodeIndex {
222    /// How many bytes were read.
223    bytes: u64,
224    /// How many lines were read.
225    lines: u64,
226    /// Every layer, in file order.
227    layers: Vec<Layer>,
228    /// The extrusion types, in the order the file first names them.
229    type_names: Vec<String>,
230    /// Whether the file names any extrusion type.
231    labelled_types: bool,
232    /// The slicer's normal-mode estimates of the minutes left.
233    time_left: Vec<Mark<i64>>,
234    /// The flow factors the file sets, one meaning one hundred percent.
235    flow: Vec<Mark<f64>>,
236    /// The part-cooling fan speeds the file sets, in percent.
237    fan: Vec<Mark<f64>>,
238    /// Every object the file labels and lays material for, by its number.
239    objects: Vec<BedArea>,
240    /// Whether the file labels any object.
241    labelled_objects: bool,
242    /// Each object's outline, in the order of `objects`; one over all the
243    /// part's extrusion when the file labels none.
244    outlines: Vec<ObjectOutline>,
245    /// Where each labelled object's block starts — the offset just past its
246    /// `M486 S<n>` — and the outline it lays, in file order.
247    blocks: Vec<(u64, Option<usize>)>,
248    /// The spool the file's bytes were copied to as it was read.
249    spool: Option<std::path::PathBuf>,
250    /// Every planned change, in file order.
251    changes: Vec<ChangeMark>,
252    /// The slicer's counts of the minutes to the next change.
253    change_minutes: Vec<Mark<i64>>,
254    /// The colour the file was sliced to start in, from its config block.
255    first_colour: Option<String>,
256    /// The net filament the whole file feeds, in millimetres.
257    extruded_mm: f64,
258}
259
260/// One planned change as the index holds it.
261#[derive(Debug, Clone, PartialEq)]
262struct ChangeMark {
263    /// What a client is told of it.
264    change: PlannedChange,
265    /// The offset just past its line.
266    at: u64,
267    /// The net filament the file had fed before it, in millimetres.
268    fed_before_mm: f64,
269}
270
271/// What a file set one adjustable to, as of a file position: the value, and
272/// the offset just past the line that set it.
273#[derive(Debug, Clone, Copy, PartialEq)]
274pub struct SetInFile {
275    /// What it set.
276    pub value: f64,
277    /// The offset just past the line that set it.
278    pub at: u64,
279}
280
281impl GcodeIndex {
282    /// How many bytes the index was built from.
283    #[must_use]
284    pub const fn bytes(&self) -> u64 {
285        self.bytes
286    }
287
288    /// How many lines the index was built from.
289    #[must_use]
290    pub const fn lines(&self) -> u64 {
291        self.lines
292    }
293
294    /// How many layers the file plans.
295    #[must_use]
296    pub const fn layer_count(&self) -> usize {
297        self.layers.len()
298    }
299
300    /// How many entries the index holds: layers, time marks, flow and fan
301    /// settings, and objects.
302    #[must_use]
303    pub const fn entries(&self) -> usize {
304        self.layers.len()
305            + self.time_left.len()
306            + self.flow.len()
307            + self.fan.len()
308            + self.objects.len()
309            + self.changes.len()
310            + self.change_minutes.len()
311    }
312
313    /// How many bytes the index itself holds on the heap and inline, which is
314    /// what keeping it in memory for a print costs.
315    #[must_use]
316    pub fn resident_bytes(&self) -> usize {
317        let names: usize = self.type_names.iter().map(String::capacity).sum();
318        core::mem::size_of::<Self>()
319            + self.layers.capacity() * core::mem::size_of::<Layer>()
320            + self.type_names.capacity() * core::mem::size_of::<String>()
321            + names
322            + self.time_left.capacity() * core::mem::size_of::<Mark<i64>>()
323            + self.flow.capacity() * core::mem::size_of::<Mark<f64>>()
324            + self.fan.capacity() * core::mem::size_of::<Mark<f64>>()
325            + self.objects.capacity() * core::mem::size_of::<BedArea>()
326            + self.outlines.capacity() * core::mem::size_of::<ObjectOutline>()
327            + self
328                .outlines
329                .iter()
330                .map(|outline| outline.hull_mm.capacity() * core::mem::size_of::<[f32; 2]>())
331                .sum::<usize>()
332            + self.blocks.capacity() * core::mem::size_of::<(u64, Option<usize>)>()
333            + self.changes.capacity() * core::mem::size_of::<ChangeMark>()
334            + self
335                .changes
336                .iter()
337                .filter_map(|mark| mark.change.color.as_ref())
338                .map(String::capacity)
339                .sum::<usize>()
340            + self.change_minutes.capacity() * core::mem::size_of::<Mark<i64>>()
341            + self.first_colour.as_ref().map_or(0, String::capacity)
342    }
343
344    /// Every change the file plans, in file order: none for a file that plans
345    /// none.
346    #[must_use]
347    pub fn planned_changes(&self) -> Vec<PlannedChange> {
348        self.changes
349            .iter()
350            .map(|mark| mark.change.clone())
351            .collect()
352    }
353
354    /// One planned change, by its index.
355    #[must_use]
356    pub fn planned_change(&self, index: u32) -> Option<&PlannedChange> {
357        self.changes
358            .iter()
359            .map(|mark| &mark.change)
360            .find(|change| change.index == index)
361    }
362
363    /// The stretches of the file between its planned changes, each with its
364    /// colour and the filament it feeds: none for a file that plans no change.
365    #[must_use]
366    pub fn planned_segments(&self) -> Vec<PlannedSegment> {
367        if self.changes.is_empty() {
368            return Vec::new();
369        }
370        // Segment n runs from change n-1 (or the start) to change n (or the
371        // end), in the colour that change (or the file's start) loaded.
372        let colours = core::iter::once(&self.first_colour)
373            .chain(self.changes.iter().map(|mark| &mark.change.color));
374        let fed = core::iter::once(0.0)
375            .chain(self.changes.iter().map(|mark| mark.fed_before_mm))
376            .zip(
377                self.changes
378                    .iter()
379                    .map(|mark| mark.fed_before_mm)
380                    .chain(core::iter::once(self.extruded_mm)),
381            );
382        let segments: Vec<PlannedSegment> = (0_u32..)
383            .zip(colours.zip(fed))
384            .map(|(segment, (colour, (from, to)))| PlannedSegment {
385                segment,
386                color: colour.clone(),
387                filament_mm: millimetres(to - from),
388            })
389            .collect();
390        segments
391    }
392
393    /// The planned change a job standing at a file position is waiting at: the
394    /// last one whose line it has reached, when it is no further than
395    /// [`PLANNED_CHANGE_REACH_BYTES`] past it.
396    #[must_use]
397    pub fn change_waiting_at(&self, file_position_bytes: u64) -> Option<&PlannedChange> {
398        self.changes
399            .iter()
400            .rev()
401            .map(|mark| &mark.change)
402            .find(|change| change.offset_bytes <= file_position_bytes)
403            .filter(|change| waits_at(change, file_position_bytes))
404    }
405
406    /// How many planned changes a file position has read the line of.
407    fn changes_read(&self, position: i64) -> usize {
408        u64::try_from(position).map_or(0, |position| {
409            self.changes.partition_point(|mark| mark.at <= position)
410        })
411    }
412
413    /// The colour the print should be laying at a file position: the
414    /// colour of the stretch the position is in, a planned change counting
415    /// from the moment its line is read. Nothing for a file that plans no
416    /// change, or a stretch whose colour the file does not name.
417    #[must_use]
418    pub fn expected_color_at(&self, position: i64) -> Option<String> {
419        if self.changes.is_empty() {
420            return None;
421        }
422        match self.changes_read(position).checked_sub(1) {
423            None => self.first_colour.clone(),
424            Some(last) => self.changes[last].change.color.clone(),
425        }
426    }
427
428    /// Each object's footprint outline, in [`SlicerPlan::objects`]' order;
429    /// one outline over all the part's extrusion when the file labels no
430    /// objects, and none when it lays nothing.
431    #[must_use]
432    pub fn object_outlines(&self) -> &[ObjectOutline] {
433        &self.outlines
434    }
435
436    /// Which object the printer is laying at a file position, as an index
437    /// into [`object_outlines`](Self::object_outlines): the object whose
438    /// labelled block holds it, else the last laid before it; 0 for a file
439    /// labelling none. Nothing before any object is laid.
440    #[must_use]
441    pub fn object_at(&self, file_position_bytes: u64) -> Option<usize> {
442        if !self.labelled_objects {
443            return (!self.outlines.is_empty()).then_some(0);
444        }
445        let started = self
446            .blocks
447            .partition_point(|(start, _)| *start <= file_position_bytes);
448        self.blocks[..started]
449            .iter()
450            .rev()
451            .find_map(|(_, outline)| *outline)
452    }
453
454    /// The layer the printer is laying at a file position.
455    #[must_use]
456    pub fn layer_at(&self, file_position_bytes: u64) -> Option<LayerRef> {
457        self.layers
458            .iter()
459            .rposition(|layer| layer.at <= file_position_bytes)
460            .map(LayerRef)
461    }
462
463    /// One layer's height, when the file states it.
464    #[must_use]
465    pub fn layer_z_mm(&self, layer: LayerRef) -> Option<f64> {
466        self.layers.get(layer.0).and_then(|held| held.z_mm)
467    }
468
469    /// Whether a layer lays object extrusion, which the planned-geometry
470    /// contract defines as anything but supports: skirt, brim and unlabelled
471    /// moves count, because the first layer's brim is part of what the
472    /// alignment check matches.
473    fn lays_object(&self, layer: &Layer) -> bool {
474        layer.types & !self.type_bits(&SUPPORTS) != 0
475    }
476
477    /// The nearest layer at or below one that lays the part rather than its
478    /// supports alone, so a support-only layer still shows the part.
479    #[must_use]
480    pub fn object_layer_at_or_below(&self, layer: LayerRef) -> Option<LayerRef> {
481        let held = self.layers.get(..=layer.0)?;
482        held.iter()
483            .rposition(|layer| self.lays_object(layer))
484            .map(LayerRef)
485    }
486
487    /// The first layer laying the part, and the file position at which it
488    /// ends: the first byte of the next layer's `;LAYER_CHANGE`.
489    #[must_use]
490    pub fn first_object_layer(&self) -> Option<(LayerRef, u64)> {
491        let first = self
492            .layers
493            .iter()
494            .position(|layer| self.lays_object(layer))?;
495        Some((LayerRef(first), self.layer_end(first)))
496    }
497
498    /// Where a layer's bytes end.
499    fn layer_end(&self, index: usize) -> u64 {
500        self.layers
501            .get(index + 1)
502            .map_or(self.bytes, |next| next.begins)
503    }
504
505    /// One layer's planned toolpath, read from that layer's byte range of the
506    /// print's spool and never from a fresh read of the printer's file.
507    ///
508    /// # Errors
509    ///
510    /// [`SpoolError::NoSpool`] for an index built with no spool,
511    /// [`SpoolError::UnknownLayer`] for a layer not this index's, and
512    /// [`SpoolError::Io`] when the spool cannot be read to the layer's end.
513    pub fn layer_toolpath(&self, layer: LayerRef) -> Result<LayerToolpath, SpoolError> {
514        use std::io::{Read as _, Seek as _, SeekFrom};
515
516        let held = self.layers.get(layer.0).ok_or(SpoolError::UnknownLayer)?;
517        let path = self.spool.as_ref().ok_or(SpoolError::NoSpool)?;
518        let io = |error: std::io::Error| SpoolError::Io {
519            detail: error.to_string(),
520        };
521        let length =
522            usize::try_from(self.layer_end(layer.0).saturating_sub(held.at)).map_err(|_| {
523                SpoolError::Io {
524                    detail: "a layer too long to hold".to_owned(),
525                }
526            })?;
527        let mut file = std::fs::File::open(path).map_err(io)?;
528        file.seek(SeekFrom::Start(held.at)).map_err(io)?;
529        let mut bytes = vec![0; length];
530        file.read_exact(&mut bytes).map_err(io)?;
531        let mut builder = IndexBuilder::reading_layer(self.type_names.clone(), held.head, held.at);
532        let _ = builder.take(&bytes);
533        if !builder.line.is_empty() {
534            builder.end_line();
535        }
536        #[expect(
537            clippy::cast_possible_truncation,
538            reason = "a layer height is a few hundred millimetres at most"
539        )]
540        let z_mm = held.z_mm.unwrap_or(0.0) as f32;
541        Ok(LayerToolpath {
542            z_mm,
543            segments: builder.collected.unwrap_or_default(),
544        })
545    }
546
547    /// Where the plan has the nozzle in X and Y, in bed millimetres, once the
548    /// file has been read up to `file_position_bytes`: the last place a whole
549    /// line moved it to, read from the layer's byte range of the print's
550    /// spool. Nothing before the file's first layer.
551    ///
552    /// # Errors
553    ///
554    /// As [`layer_toolpath`](Self::layer_toolpath)'s, for the layer holding the
555    /// position.
556    pub fn planned_head_at(
557        &self,
558        file_position_bytes: u64,
559    ) -> Result<Option<[f64; 2]>, SpoolError> {
560        Ok(self
561            .planned_heads_before(file_position_bytes, 0)?
562            .map(|trail| trail.last))
563    }
564
565    /// Where the plan has had the nozzle over the last `moves` moves a job at
566    /// `file_position_bytes` has sent, in bed millimetres, oldest first, and
567    /// where it stands after them: what a printer still working through its
568    /// queue of moves can be anywhere along. Read from the layer's byte range
569    /// of the print's spool, from the layer's start at the earliest. Nothing
570    /// before the file's first layer.
571    ///
572    /// # Errors
573    ///
574    /// As [`layer_toolpath`](Self::layer_toolpath)'s, for the layer holding the
575    /// position.
576    pub fn planned_heads_before(
577        &self,
578        file_position_bytes: u64,
579        moves: usize,
580    ) -> Result<Option<PlannedHeads>, SpoolError> {
581        use std::io::{Read as _, Seek as _, SeekFrom};
582
583        let Some(layer) = self.layer_at(file_position_bytes) else {
584            return Ok(None);
585        };
586        let held = &self.layers[layer.0];
587        let path = self.spool.as_ref().ok_or(SpoolError::NoSpool)?;
588        let io = |error: std::io::Error| SpoolError::Io {
589            detail: error.to_string(),
590        };
591        let end = file_position_bytes.min(self.layer_end(layer.0));
592        let length = usize::try_from(end.saturating_sub(held.at)).map_err(|_| SpoolError::Io {
593            detail: "a layer too long to hold".to_owned(),
594        })?;
595        let mut file = std::fs::File::open(path).map_err(io)?;
596        file.seek(SeekFrom::Start(held.at)).map_err(io)?;
597        let mut bytes = vec![0; length];
598        file.read_exact(&mut bytes).map_err(io)?;
599        let mut builder = IndexBuilder::reading_layer(self.type_names.clone(), held.head, held.at);
600        builder.trail = Some(vec![[held.head.at[0], held.head.at[1]]]);
601        // A line the position stops inside is one the printer has not
602        // finished, so only whole lines move the head.
603        let _ = builder.take(&bytes);
604        let [x, y, _] = builder.at;
605        let mut trail = builder.trail.unwrap_or_default();
606        let keep = trail.len().saturating_sub(moves.saturating_add(1));
607        trail.drain(..keep);
608        Ok(Some(PlannedHeads {
609            last: [x, y],
610            trail,
611        }))
612    }
613
614    /// The most extrusion types any one layer lays material under, and the
615    /// file position just past that layer's `;LAYER_CHANGE`: where the plan
616    /// names the most.
617    #[must_use]
618    pub fn busiest_layer(&self) -> Option<(usize, i64)> {
619        self.layers
620            .iter()
621            .map(|layer| {
622                (
623                    usize::try_from(layer.types.count_ones()).unwrap_or(usize::MAX),
624                    i64::try_from(layer.at).unwrap_or(i64::MAX),
625                )
626            })
627            .reduce(|best, next| if next.0 > best.0 { next } else { best })
628    }
629
630    /// What a check is told of the layer a job at `file_position_bytes`
631    /// stands in, given that layer's toolpath: nothing before the file's
632    /// first layer.
633    #[must_use]
634    pub fn layer_facts(
635        &self,
636        file_position_bytes: u64,
637        toolpath: &LayerToolpath,
638    ) -> Option<LayerFacts> {
639        let layer = self.layer_at(file_position_bytes)?;
640        let number = layer.0 + 1;
641        let position = i64::try_from(file_position_bytes).unwrap_or(i64::MAX);
642        // A file planning no change names only the colour it was sliced in,
643        // which says nothing of the spool loaded: none is expected then, as
644        // the context's `expected_colour` is absent.
645        let expected_colour = self.expected_color_at(position);
646        let fact = |mark: &ChangeMark, just_made: bool| ChangeFact {
647            just_made,
648            number: mark.change.index.saturating_add(1),
649            colour_change: mark.change.kind == PlannedChangeKind::ColorChange,
650            layer: mark.change.layer,
651            z_mm: mark.change.z_mm,
652            colour: mark.change.color.clone(),
653        };
654        let read = self.changes_read(position);
655        let just_made = read
656            .checked_sub(1)
657            .map(|last| &self.changes[last])
658            .filter(|mark| usize::try_from(mark.change.layer).ok() == Some(number))
659            .map(|mark| fact(mark, true));
660        let change = just_made.or_else(|| self.changes.get(read).map(|mark| fact(mark, false)));
661        Some(LayerFacts {
662            number,
663            count: self.layers.len(),
664            z_mm: self
665                .layer_z_mm(layer)
666                .unwrap_or_else(|| f64::from(toolpath.z_mm)),
667            expected_colour,
668            change,
669            progress: toolpath.progress(file_position_bytes),
670        })
671    }
672
673    /// The flow factor the file had set by a position, when it had set one.
674    #[must_use]
675    pub fn flow_at(&self, position: i64) -> Option<SetInFile> {
676        last_at(&self.flow, position).map(|mark| SetInFile {
677            value: mark.value,
678            at: mark.at,
679        })
680    }
681
682    /// The part-cooling fan speed the file had set by a position, in percent,
683    /// when it had set one.
684    #[must_use]
685    pub fn fan_at(&self, position: i64) -> Option<SetInFile> {
686        last_at(&self.fan, position).map(|mark| SetInFile {
687            value: mark.value,
688            at: mark.at,
689        })
690    }
691
692    /// The slicer's plan at one file position, with no change made through
693    /// this program beside what the file set.
694    #[must_use]
695    pub fn plan_at(&self, position: i64) -> SlicerPlan {
696        self.plan_with(position, None, None)
697    }
698
699    /// The slicer's plan at one file position, with the flow factor and fan
700    /// speed changed through this program since the file last set each, when
701    /// there was such a change.
702    #[must_use]
703    pub fn plan_with(
704        &self,
705        position: i64,
706        flow_changed: Option<f64>,
707        fan_changed: Option<f64>,
708    ) -> SlicerPlan {
709        let mut unknown = Vec::new();
710        let layer_index = self
711            .layers
712            .iter()
713            .rposition(|layer| reached(layer.at, position));
714        let final_z_mm = self.layers.last().and_then(|layer| layer.z_mm);
715        if self.layers.is_empty() {
716            unknown.push(PlanFact::Layer);
717        }
718        if final_z_mm.is_none() {
719            unknown.push(PlanFact::FinalZ);
720        }
721        if !self.labelled_types {
722            unknown.push(PlanFact::Types);
723        }
724        let types = layer_index.map_or_else(Vec::new, |index| {
725            let bits = self.layers[index].types;
726            self.type_names
727                .iter()
728                .enumerate()
729                .filter(|(bit, _)| bits & (1 << bit) != 0)
730                .map(|(_, name)| name.clone())
731                .collect()
732        });
733        let minutes_left = last_at(&self.time_left, position).map(|mark| mark.value);
734        if minutes_left.is_none() {
735            unknown.push(PlanFact::MinutesLeft);
736        }
737        let flow_factor = set_value(
738            self.flow_at(position).map(|set| set.value),
739            flow_changed,
740            PlanFact::FlowFactor,
741            &mut unknown,
742        );
743        let fan_percent = set_value(
744            self.fan_at(position).map(|set| set.value),
745            fan_changed,
746            PlanFact::FanPercent,
747            &mut unknown,
748        );
749        if !self.labelled_objects {
750            unknown.push(PlanFact::Objects);
751        }
752        unknown.sort_unstable();
753        let in_force =
754            |set: &Option<SetValue>| set.as_ref().and_then(|set| set.changed.or(set.file));
755        let mut at_odds = Vec::new();
756        if let Some(index) = layer_index {
757            let shown = self.layers[index.saturating_sub(LAYERS_SHOWN_BELOW)..=index]
758                .iter()
759                .fold(0, |bits, layer| bits | layer.types);
760            if in_force(&fan_percent).is_some_and(|fan| fan <= 0.0)
761                && shown & self.type_bits(&OVER_AIR) != 0
762            {
763                at_odds.push(PlanMismatch::FanOffOverBridges);
764            }
765            if in_force(&flow_factor).is_some_and(|flow| flow < FLOW_WELL_UNDER_ONE)
766                && self.layers[index].types & self.type_bits(&WALLS) != 0
767            {
768                at_odds.push(PlanMismatch::FlowLowOverWalls);
769            }
770        }
771        let next_change = self
772            .changes
773            .get(self.changes_read(position))
774            .map(|mark| mark.change.clone());
775        let minutes_to_next_change = next_change
776            .as_ref()
777            .and_then(|_| last_at(&self.change_minutes, position))
778            .map(|mark| mark.value);
779        SlicerPlan {
780            expected_color: self.expected_color_at(position),
781            next_change,
782            minutes_to_next_change,
783            change_waiting: None,
784            layer: layer_index.map(|index| index + 1),
785            z_mm: layer_index.and_then(|index| self.layers[index].z_mm),
786            final_z_mm,
787            types,
788            minutes_left,
789            flow_factor,
790            fan_percent,
791            object_count: self.labelled_objects.then_some(self.objects.len()),
792            objects: self.objects.clone(),
793            rise: None,
794            at_odds,
795            unknown,
796        }
797    }
798
799    /// The bits of the type table the named types hold, those the file names.
800    fn type_bits(&self, names: &[&str]) -> u64 {
801        self.type_names
802            .iter()
803            .enumerate()
804            .filter(|(_, name)| names.contains(&name.as_str()))
805            .fold(0, |bits, (bit, _)| bits | (1 << bit))
806    }
807
808    /// The height the parts themselves have gained between two positions, in
809    /// millimetres to a tenth: each layer after the earlier one's, up to the
810    /// later one's, that lays anything but supports adds its rise over the
811    /// part's top so far, and a layer laying supports alone adds nothing,
812    /// because nothing a camera watches grows there — so a support layer
813    /// slicer-interleaved between two of the part's is not the floor the next
814    /// one rises from. Nothing where a position has no
815    /// layer with a height.
816    #[must_use]
817    pub fn risen_since(&self, earlier: i64, now: i64) -> Option<f64> {
818        self.height_and_rise_since(earlier, now)
819            .map(|[_, risen]| risen)
820    }
821
822    /// The part's own top at an earlier position and the height it gains from
823    /// there to a later one, each in millimetres to a tenth, as
824    /// [`risen_since`](Self::risen_since) counts the gain.
825    #[must_use]
826    pub fn height_and_rise_since(&self, earlier: i64, now: i64) -> Option<[f64; 2]> {
827        let at = |position| {
828            self.layers
829                .iter()
830                .rposition(|layer| reached(layer.at, position))
831                .filter(|index| self.layers[*index].z_mm.is_some())
832        };
833        let (then, now) = (at(earlier)?, at(now)?);
834        let supports = self.type_bits(&SUPPORTS);
835        let lays_the_part = |layer: &&Layer| layer.types & !supports != 0;
836        // The part's own top as of the earlier position: the last layer up to
837        // it that laid the part, or that position's own layer before any did.
838        let mut top = self.layers[..=then]
839            .iter()
840            .rev()
841            .filter(lays_the_part)
842            .find_map(|layer| layer.z_mm)
843            .or(self.layers[then].z_mm)?;
844        let height = top;
845        let mut risen = 0.0;
846        for layer in self
847            .layers
848            .iter()
849            .take(now + 1)
850            .skip(then + 1)
851            .filter(lays_the_part)
852        {
853            let Some(z) = layer.z_mm else { continue };
854            risen += (z - top).max(0.0);
855            top = top.max(z);
856        }
857        let tenth = |mm: f64| (mm * 10.0).round() / 10.0;
858        Some([tenth(height), tenth(risen)])
859    }
860}
861
862/// One adjustable as the file set it and as this program changed it since,
863/// recording the fact as unknown when the file had set nothing.
864fn set_value(
865    file: Option<f64>,
866    changed: Option<f64>,
867    fact: PlanFact,
868    unknown: &mut Vec<PlanFact>,
869) -> Option<SetValue> {
870    if file.is_none() {
871        unknown.push(fact);
872    }
873    (file.is_some() || changed.is_some()).then_some(SetValue { file, changed })
874}
875
876/// Whether a job at a file position is waiting at one planned change.
877const fn waits_at(change: &PlannedChange, position: u64) -> bool {
878    position >= change.offset_bytes && position - change.offset_bytes <= PLANNED_CHANGE_REACH_BYTES
879}
880
881/// A length of filament to the nearest thousandth of a millimetre.
882fn millimetres(length: f64) -> f64 {
883    (length.max(0.0) * 1000.0).round() / 1000.0
884}
885
886/// Whether a line ending at `at` lies wholly before `position`.
887fn reached(at: u64, position: i64) -> bool {
888    u64::try_from(position).is_ok_and(|position| at <= position)
889}
890
891/// The last mark a position has reached.
892fn last_at<T: Copy>(marks: &[Mark<T>], position: i64) -> Option<Mark<T>> {
893    let Ok(position) = u64::try_from(position) else {
894        return None;
895    };
896    let reached = marks.partition_point(|mark| mark.at <= position);
897    reached.checked_sub(1).map(|index| marks[index])
898}
899
900/// One adjustable as the print's file set it at the current position, and as
901/// a change made through this program since then left it.
902#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
903#[serde(crate = "printobserver_types::serde", deny_unknown_fields)]
904#[schemars(crate = "printobserver_types::schemars")]
905pub struct SetValue {
906    /// What the file's own commands set it to, by the current position.
907    #[serde(default, skip_serializing_if = "Option::is_none")]
908    pub file: Option<f64>,
909    /// What the latest change made through this program set it to, when one
910    /// was made after the file last set it.
911    #[serde(default, skip_serializing_if = "Option::is_none")]
912    pub changed: Option<f64>,
913}
914
915/// The bed area one object of the print covers: the rectangle
916/// `[x_min, y_min, x_max, y_max]` its material reaches, in whole millimetres —
917/// each edge read to the nearest tenth, then each least edge rounded down and
918/// each most edge up, so that it holds every move laying that object down.
919pub type BedArea = [i64; 4];
920
921/// How far the plan has risen since one earlier frame of this print that was
922/// seen: the height a camera should show the parts to have gained since then.
923#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
924#[serde(crate = "printobserver_types::serde", deny_unknown_fields)]
925#[schemars(crate = "printobserver_types::schemars")]
926pub struct Rise {
927    /// When that earlier frame was captured: the newest frame at least half
928    /// an hour old that a check of this print — a periodic observation or an
929    /// alert — or a look at it was given, as that check or look states its
930    /// capture time.
931    pub since: Timestamp,
932    /// Two heights of the print's highest point, in millimetres: the first
933    /// is where the plan had it when that frame was captured, the second how
934    /// far it should have risen since — the rise of every layer since that
935    /// lays anything but supports. They are the plate's, not every part's: a
936    /// part the plan has finished does not grow with it.
937    pub mm: [f64; 2],
938}
939
940/// Declare every field of an object whose value may be null required — and
941/// of each object written inline as one of its fields, as an enum variant's
942/// body is — so such a field is always sent, its null meaning what its
943/// description says, rather than left out.
944///
945/// The derive reads an `Option` as a field that may be absent, and its own
946/// `required` attribute drops the null with the absence; this keeps the null.
947pub(crate) fn null_is_sent(schema: &mut printobserver_types::schemars::Schema) {
948    use printobserver_types::serde_json::Value;
949    if let Some(Value::Object(properties)) = schema.get_mut("properties") {
950        for property in properties.values_mut() {
951            if property.get("properties").is_some()
952                && let Ok(inline) =
953                    printobserver_types::schemars::Schema::try_from(core::mem::take(property))
954            {
955                let mut inline = inline;
956                null_is_sent(&mut inline);
957                *property = inline.to_value();
958            }
959        }
960    }
961    let nullable = |property: &Value| match property.get("type") {
962        Some(Value::Array(types)) => types.iter().any(|named| named == "null"),
963        _ => property
964            .get("anyOf")
965            .and_then(Value::as_array)
966            .is_some_and(|arms| {
967                arms.iter()
968                    .any(|arm| arm.get("type") == Some(&Value::from("null")))
969            }),
970    };
971    let sent: Vec<Value> = schema
972        .get("properties")
973        .and_then(Value::as_object)
974        .map(|properties| {
975            properties
976                .iter()
977                .filter(|(_, property)| nullable(property))
978                .map(|(name, _)| Value::from(name.as_str()))
979                .collect()
980        })
981        .unwrap_or_default();
982    if sent.is_empty() {
983        return;
984    }
985    let required = schema
986        .ensure_object()
987        .entry("required")
988        .or_insert_with(|| Value::Array(Vec::new()));
989    if let Value::Array(required) = required {
990        for name in sent {
991            if !required.contains(&name) {
992                required.push(name);
993            }
994        }
995    }
996}
997
998/// Where the plan has had the nozzle over a job's last moves sent.
999#[derive(Debug, Clone, PartialEq)]
1000pub struct PlannedHeads {
1001    /// Where the last whole line sent left it.
1002    pub last: [f64; 2],
1003    /// Where it stood before each of those moves and after the last, oldest
1004    /// first: at most one more point than the moves asked for.
1005    pub trail: Vec<[f64; 2]>,
1006}
1007
1008/// What a planned change stops the print for.
1009#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
1010#[serde(crate = "printobserver_types::serde", rename_all = "snake_case")]
1011#[schemars(crate = "printobserver_types::schemars")]
1012pub enum PlannedChangeKind {
1013    /// An `M600`: the firmware stops so a person can load the next colour.
1014    ColorChange,
1015    /// An `M601`: the firmware pauses until a person resumes it.
1016    Pause,
1017}
1018
1019/// One stop the print's own G-code plans: an `M600` colour change or an
1020/// `M601` pause, where the firmware waits for a person.
1021#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
1022#[serde(crate = "printobserver_types::serde", deny_unknown_fields)]
1023#[schemars(crate = "printobserver_types::schemars", transform = null_is_sent)]
1024pub struct PlannedChange {
1025    /// Its place among the file's changes, counting from 0 in file order.
1026    pub index: u32,
1027    /// What it stops the print for.
1028    pub kind: PlannedChangeKind,
1029    /// The byte offset of the first byte of its `M600` or `M601` line.
1030    pub offset_bytes: u64,
1031    /// The first layer printed after it, counting the first as 1: the layer
1032    /// whose `;Z:` is the change's height.
1033    pub layer: u32,
1034    /// That layer's height, in millimetres.
1035    pub z_mm: f64,
1036    /// The colour loaded at it, as `#RRGGBB` in upper case, from the
1037    /// `;COLOR_CHANGE,T<n>,#RRGGBB` line just before its `M600`; null for an
1038    /// `M601`, and for an `M600` with no such line.
1039    pub color: Option<String>,
1040}
1041
1042/// One stretch of the print between its planned changes.
1043#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
1044#[serde(crate = "printobserver_types::serde", deny_unknown_fields)]
1045#[schemars(crate = "printobserver_types::schemars", transform = null_is_sent)]
1046pub struct PlannedSegment {
1047    /// Its number: segment 0 runs from the file's start to change 0, and
1048    /// segment n from change n-1 to change n, or to the file's end.
1049    pub segment: u32,
1050    /// Its colour as `#RRGGBB`: segment 0's the file's `filament_colour`, every
1051    /// later one its change's; null where the file names none.
1052    pub color: Option<String>,
1053    /// The filament it feeds, in millimetres: the net of its extrusion moves.
1054    pub filament_mm: f64,
1055}
1056
1057/// A print's planned changes as the status read answers them.
1058#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
1059#[serde(crate = "printobserver_types::serde", deny_unknown_fields)]
1060#[schemars(crate = "printobserver_types::schemars", transform = null_is_sent)]
1061pub struct PlannedChanges {
1062    /// Every change the file plans, in file order.
1063    pub changes: Vec<PlannedChange>,
1064    /// The stretches between them, in file order.
1065    pub segments: Vec<PlannedSegment>,
1066    /// The index of the change the printer is waiting at now; null when it is
1067    /// waiting at none.
1068    pub waiting: Option<u32>,
1069    /// The colour expected at the job's current position, as `#RRGGBB`; null
1070    /// when the file names none there or the position is unknown.
1071    pub expected_color: Option<String>,
1072}
1073
1074impl Sample for PlannedChange {
1075    fn sample_full() -> Self {
1076        Self {
1077            index: 0,
1078            kind: PlannedChangeKind::ColorChange,
1079            offset_bytes: 48_213,
1080            layer: 12,
1081            z_mm: 2.4,
1082            color: Some("#FF0000".to_owned()),
1083        }
1084    }
1085
1086    fn sample_alternates() -> Vec<Self> {
1087        vec![Self {
1088            index: 1,
1089            kind: PlannedChangeKind::Pause,
1090            offset_bytes: 96_410,
1091            layer: 24,
1092            z_mm: 4.8,
1093            color: None,
1094        }]
1095    }
1096}
1097
1098impl Sample for PlannedSegment {
1099    fn sample_full() -> Self {
1100        Self {
1101            segment: 1,
1102            color: Some("#FF0000".to_owned()),
1103            filament_mm: 812.4,
1104        }
1105    }
1106
1107    fn sample_alternates() -> Vec<Self> {
1108        vec![Self {
1109            segment: 0,
1110            color: None,
1111            filament_mm: 0.0,
1112        }]
1113    }
1114}
1115
1116impl Sample for PlannedChanges {
1117    fn sample_full() -> Self {
1118        Self {
1119            changes: vec![PlannedChange::sample_full()],
1120            segments: vec![
1121                PlannedSegment {
1122                    segment: 0,
1123                    color: Some("#FFFFFF".to_owned()),
1124                    filament_mm: 301.7,
1125                },
1126                PlannedSegment::sample_full(),
1127            ],
1128            waiting: Some(0),
1129            expected_color: Some("#FF0000".to_owned()),
1130        }
1131    }
1132
1133    fn sample_alternates() -> Vec<Self> {
1134        vec![Self {
1135            waiting: None,
1136            expected_color: None,
1137            ..Self::sample_full()
1138        }]
1139    }
1140}
1141
1142/// A setting in force that the plan at this height says is wrong for what is
1143/// being laid.
1144#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
1145#[serde(crate = "printobserver_types::serde", rename_all = "snake_case")]
1146#[schemars(crate = "printobserver_types::schemars")]
1147pub enum PlanMismatch {
1148    /// The part-cooling fan is off while the current layer or the few below
1149    /// it, which a frame shows, bridge or overhang.
1150    FanOffOverBridges,
1151    /// The flow factor is well under one while the current layer lays walls.
1152    FlowLowOverWalls,
1153}
1154
1155/// A fact of the plan the print's file does not state.
1156#[derive(
1157    Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize, JsonSchema,
1158)]
1159#[serde(crate = "printobserver_types::serde", rename_all = "snake_case")]
1160#[schemars(crate = "printobserver_types::schemars")]
1161pub enum PlanFact {
1162    /// The file marks no layers.
1163    Layer,
1164    /// The file states no final height.
1165    FinalZ,
1166    /// The file labels no extrusion types.
1167    Types,
1168    /// The file carries no estimate of the time left, by the current position.
1169    MinutesLeft,
1170    /// The file sets no flow factor, by the current position.
1171    FlowFactor,
1172    /// The file sets no part-cooling fan speed, by the current position.
1173    FanPercent,
1174    /// The file labels no objects.
1175    Objects,
1176    /// No frame of this print is half an hour old with a position to rise
1177    /// from, so how far the parts should have grown is not known, and no
1178    /// growth can be judged from frames closer together.
1179    Rise,
1180}
1181
1182/// What the slicer planned at the print's current file position: the shape
1183/// and place of what should be printing, read from the print's own G-code.
1184///
1185/// These are the slicer's plan rather than an observation: a feature named
1186/// here is part of the design at this height, and nothing here says how well
1187/// it printed.
1188#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
1189#[serde(crate = "printobserver_types::serde", deny_unknown_fields)]
1190#[schemars(crate = "printobserver_types::schemars")]
1191pub struct SlicerPlan {
1192    /// The colour the print should be laying at the current position, as
1193    /// `#RRGGBB`; absent when the file plans no change or names no colour
1194    /// there.
1195    #[serde(default, skip_serializing_if = "Option::is_none")]
1196    pub expected_color: Option<String>,
1197    /// The next change the file plans after the current position; absent when
1198    /// it plans none there.
1199    #[serde(default, skip_serializing_if = "Option::is_none")]
1200    pub next_change: Option<PlannedChange>,
1201    /// The slicer's own count of the minutes to that change, from the latest
1202    /// `M73 C` the position has reached; absent when there is no next change
1203    /// or no count.
1204    #[serde(default, skip_serializing_if = "Option::is_none")]
1205    pub minutes_to_next_change: Option<i64>,
1206    /// The planned change the printer is waiting at now, for a person to
1207    /// finish; absent when it is waiting at none.
1208    #[serde(default, skip_serializing_if = "Option::is_none")]
1209    pub change_waiting: Option<PlannedChange>,
1210    /// The layer the print is in, counting the first as 1; absent before the
1211    /// first.
1212    #[serde(default, skip_serializing_if = "Option::is_none")]
1213    pub layer: Option<usize>,
1214    /// The current layer's height, in millimetres.
1215    #[serde(default, skip_serializing_if = "Option::is_none")]
1216    pub z_mm: Option<f64>,
1217    /// The final layer's height, in millimetres.
1218    #[serde(default, skip_serializing_if = "Option::is_none")]
1219    pub final_z_mm: Option<f64>,
1220    /// What the current layer lays material as, in the order the file first
1221    /// names each: `Perimeter`, `Support material`, `Bridge infill`.
1222    #[serde(default, skip_serializing_if = "Vec::is_empty")]
1223    pub types: Vec<String>,
1224    /// The slicer's own estimate of the minutes left, at the current position.
1225    #[serde(default, skip_serializing_if = "Option::is_none")]
1226    pub minutes_left: Option<i64>,
1227    /// The flow factor, one meaning one hundred percent.
1228    #[serde(default, skip_serializing_if = "Option::is_none")]
1229    pub flow_factor: Option<SetValue>,
1230    /// The part-cooling fan speed, in percent.
1231    #[serde(default, skip_serializing_if = "Option::is_none")]
1232    pub fan_percent: Option<SetValue>,
1233    /// How many objects the file lays down; absent when it labels none.
1234    #[serde(default, skip_serializing_if = "Option::is_none")]
1235    pub object_count: Option<usize>,
1236    /// The bed area each object the file lays down covers, unnamed, as
1237    /// `[x_min, y_min, x_max, y_max]` in whole millimetres, in the order of
1238    /// the file's object numbers.
1239    #[serde(default, skip_serializing_if = "Vec::is_empty")]
1240    pub objects: Vec<BedArea>,
1241    /// How far the plan has risen since an earlier frame; absent before any
1242    /// frame is half an hour old.
1243    #[serde(default, skip_serializing_if = "Option::is_none")]
1244    pub rise: Option<Rise>,
1245    /// Each setting in force the plan at this height says is wrong.
1246    #[serde(default, skip_serializing_if = "Vec::is_empty")]
1247    pub at_odds: Vec<PlanMismatch>,
1248    /// The facts the file does not state, which are therefore unknown rather
1249    /// than absent.
1250    #[serde(default, skip_serializing_if = "Vec::is_empty")]
1251    pub unknown: Vec<PlanFact>,
1252}
1253
1254impl Sample for SlicerPlan {
1255    fn sample_full() -> Self {
1256        Self {
1257            expected_color: Some("#FF0000".to_owned()),
1258            next_change: Some(PlannedChange::sample_full()),
1259            minutes_to_next_change: Some(17),
1260            change_waiting: Some(PlannedChange::sample_full()),
1261            layer: Some(12),
1262            z_mm: Some(2.4),
1263            types: vec![
1264                "Perimeter".to_owned(),
1265                "External perimeter".to_owned(),
1266                "Support material".to_owned(),
1267            ],
1268            final_z_mm: Some(30.0),
1269            minutes_left: Some(42),
1270            flow_factor: Some(SetValue {
1271                file: Some(1.0),
1272                changed: Some(0.95),
1273            }),
1274            fan_percent: Some(SetValue {
1275                file: Some(100.0),
1276                changed: None,
1277            }),
1278            object_count: Some(1),
1279            objects: vec![[100, 99, 150, 117]],
1280            rise: Some(Rise {
1281                since: Timestamp::sample_full(),
1282                mm: [7.2, 4.8],
1283            }),
1284            at_odds: vec![PlanMismatch::FlowLowOverWalls],
1285            unknown: vec![PlanFact::Objects],
1286        }
1287    }
1288
1289    fn sample_minimal() -> Self {
1290        Self {
1291            expected_color: None,
1292            next_change: None,
1293            minutes_to_next_change: None,
1294            change_waiting: None,
1295            layer: None,
1296            z_mm: None,
1297            final_z_mm: None,
1298            types: Vec::new(),
1299            minutes_left: None,
1300            flow_factor: None,
1301            fan_percent: None,
1302            object_count: None,
1303            objects: Vec::new(),
1304            rise: None,
1305            at_odds: Vec::new(),
1306            unknown: Vec::new(),
1307        }
1308    }
1309}
1310
1311/// How a coordinate is read: as a place, or as a distance from the last one.
1312#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]
1313enum Positioning {
1314    /// A place: `M82` for `E`, `G90` for the axes. What a firmware starts in.
1315    #[default]
1316    Absolute,
1317    /// A distance: `M83` for `E`, `G91` for the axes.
1318    Relative,
1319}
1320
1321/// Builds a [`GcodeIndex`] from a file streamed into it, a piece at a time,
1322/// in one pass: the [`GcodeSink`] the printer port's whole-file read feeds.
1323#[derive(Debug, Default)]
1324pub struct IndexBuilder {
1325    /// The line being read, up to [`LINE_LIMIT`].
1326    line: Vec<u8>,
1327    /// Whether the line being read has run past [`LINE_LIMIT`].
1328    overlong: bool,
1329    /// How many bytes have been read.
1330    read: u64,
1331    /// How many lines have been read.
1332    lines: u64,
1333    /// Every layer so far.
1334    layers: Vec<Layer>,
1335    /// The extrusion types so far.
1336    type_names: Vec<String>,
1337    /// Whether any type was named.
1338    labelled_types: bool,
1339    /// The type the moves being read extrude, as a bit of the type table.
1340    current_type: Option<usize>,
1341    /// The last `;WIDTH:` read, in millimetres; 0 before any.
1342    width_mm: f32,
1343    /// The file offset a layer read's bytes start at, which each collected
1344    /// segment's own offset is counted from.
1345    read_from: u64,
1346    /// The time estimates so far.
1347    time_left: Vec<Mark<i64>>,
1348    /// The flow factors so far.
1349    flow: Vec<Mark<f64>>,
1350    /// The fan speeds so far.
1351    fan: Vec<Mark<f64>>,
1352    /// Every object labelled so far, in the order first labelled.
1353    objects: Vec<ObjectDraft>,
1354    /// Where each object's number is in `objects`.
1355    object_numbers: BTreeMap<i64, usize>,
1356    /// The object the moves being read lay material for, by its place in
1357    /// `objects`.
1358    current_object: Option<usize>,
1359    /// Whether any object was labelled.
1360    labelled_objects: bool,
1361    /// Where the head is in X, Y and Z.
1362    at: [f64; 3],
1363    /// The extruder's position.
1364    e: f64,
1365    /// What `G90`/`G91` last said.
1366    axes: Positioning,
1367    /// What `M82`/`M83` last said.
1368    extruder: Positioning,
1369    /// Where the line being read began.
1370    line_began: u64,
1371    /// How far the part's extrusion reached, for a file labelling no object.
1372    all: Reach,
1373    /// Where each labelled object's block starts, and its place in
1374    /// `objects`.
1375    blocks: Vec<(u64, usize)>,
1376    /// Where the file's bytes are copied as they are read.
1377    spool: Option<Spooling>,
1378    /// The segments of a toolpath read, when this builder is one.
1379    collected: Option<Vec<ToolpathSegment>>,
1380    /// Where each move of a head read left the nozzle, in X and Y, when
1381    /// this builder is one.
1382    trail: Option<Vec<[f64; 2]>>,
1383    /// Where the last move an outline reached ended.
1384    reached_last: Option<[f64; 2]>,
1385    /// The planned changes so far.
1386    changes: Vec<ChangeDraft>,
1387    /// The minutes-to-change counts so far.
1388    change_minutes: Vec<Mark<i64>>,
1389    /// The last `;COLOR_CHANGE` read: the line it was on and its colour.
1390    colour_comment: Option<(u64, String)>,
1391    /// The config block's first `filament_colour`.
1392    first_colour: Option<String>,
1393    /// The net filament fed so far, in millimetres.
1394    extruded_mm: f64,
1395    /// How many layers had begun when material was last laid: the layer being
1396    /// read has laid material when it equals the layers begun.
1397    laid_in_layers: usize,
1398}
1399
1400/// A planned change as the reader has seen it so far: its layer is settled
1401/// once the file is read.
1402#[derive(Debug, Clone, PartialEq)]
1403struct ChangeDraft {
1404    /// What it stops the print for.
1405    kind: PlannedChangeKind,
1406    /// The offset of its line's first byte.
1407    offset: u64,
1408    /// The offset just past its line.
1409    at: u64,
1410    /// The layer it belongs to, by its place among the layers: the one being
1411    /// read when it has laid nothing yet, else the next.
1412    layer: usize,
1413    /// Its colour, when the line before named one.
1414    color: Option<String>,
1415    /// The net filament fed before it.
1416    fed_before_mm: f64,
1417}
1418
1419/// A spool being written.
1420#[derive(Debug)]
1421struct Spooling {
1422    /// The spool file, removed again when any write to it fails.
1423    path: std::path::PathBuf,
1424    /// The open file, buffered.
1425    writer: std::io::BufWriter<std::fs::File>,
1426    /// Whether a write failed, which leaves no spool.
1427    failed: bool,
1428}
1429
1430impl GcodeSink for IndexBuilder {
1431    fn take(&mut self, piece: &[u8]) -> ControlFlow<()> {
1432        // Plain index loops rather than iterator adaptors throughout this
1433        // reader: it runs over every byte of a print, and is as fast in a
1434        // build without optimisation as in one with it only written so.
1435        // A write the filesystem refuses — a full disk — is proved by no test:
1436        // making one fail needs a filesystem made to fail mid-stream, which no
1437        // host the suite runs on offers without privileges. What it leads to
1438        // is the same index with no spool, which
1439        // `a_spool_that_cannot_be_created_leaves_the_plan_without_toolpaths`
1440        // proves end to end.
1441        if let Some(spool) = self.spool.as_mut().filter(|spool| !spool.failed) {
1442            use std::io::Write as _;
1443            spool.failed = spool.writer.write_all(piece).is_err();
1444        }
1445        let mut start = 0;
1446        let mut at = 0;
1447        while at < piece.len() {
1448            if piece[at] == b'\n' {
1449                let head = &piece[start..at];
1450                self.read += u64::try_from(at + 1 - start).unwrap_or(u64::MAX);
1451                if self.line.is_empty() && !self.overlong {
1452                    // The whole line is in this piece: read it where it lies.
1453                    self.lines += 1;
1454                    if head.len() <= LINE_LIMIT {
1455                        self.read_line(head);
1456                    }
1457                } else {
1458                    self.hold(head);
1459                    self.end_line();
1460                }
1461                self.line_began = self.read;
1462                start = at + 1;
1463            }
1464            at += 1;
1465        }
1466        let rest = &piece[start..];
1467        self.hold(rest);
1468        self.read += u64::try_from(rest.len()).unwrap_or(u64::MAX);
1469        ControlFlow::Continue(())
1470    }
1471}
1472
1473impl IndexBuilder {
1474    /// A builder that has read nothing.
1475    #[must_use]
1476    pub fn new() -> Self {
1477        Self::default()
1478    }
1479
1480    /// A builder that has read nothing and copies every byte it is given to
1481    /// a spool file at `path`, created or truncated now, which the index it
1482    /// builds reads each layer's toolpath back from.
1483    ///
1484    /// # Errors
1485    ///
1486    /// The filesystem's own error when the file cannot be created.
1487    pub fn spooling(path: std::path::PathBuf) -> std::io::Result<Self> {
1488        let file = std::fs::File::create(&path)?;
1489        Ok(Self {
1490            spool: Some(Spooling {
1491                path,
1492                writer: std::io::BufWriter::with_capacity(1 << 16, file),
1493                failed: false,
1494            }),
1495            ..Self::default()
1496        })
1497    }
1498
1499    /// A builder reading one layer's bytes from where the reader stood at
1500    /// its start, collecting its extrusion moves.
1501    fn reading_layer(type_names: Vec<String>, head: Head, start: u64) -> Self {
1502        Self {
1503            type_names,
1504            labelled_types: true,
1505            current_type: head.current_type,
1506            width_mm: head.width_mm,
1507            read_from: start,
1508            at: head.at,
1509            e: head.e,
1510            axes: head.axes,
1511            extruder: head.extruder,
1512            collected: Some(Vec::new()),
1513            ..Self::default()
1514        }
1515    }
1516
1517    /// The index of everything read, the file's last line counting whether or
1518    /// not it ended in a newline.
1519    #[must_use]
1520    pub fn finish(mut self) -> GcodeIndex {
1521        if !self.line.is_empty() || self.overlong {
1522            self.end_line();
1523        }
1524        let mut drafts: Vec<Option<ObjectDraft>> = self.objects.into_iter().map(Some).collect();
1525        let mut objects = Vec::new();
1526        let mut outlines = Vec::new();
1527        let mut outline_of = vec![None; drafts.len()];
1528        for place in self.object_numbers.into_values() {
1529            let Some(draft) = drafts.get_mut(place).and_then(Option::take) else {
1530                continue;
1531            };
1532            let Some([least_x, least_y, most_x, most_y]) = draft.bounds else {
1533                continue;
1534            };
1535            objects.push([
1536                whole(tenth(least_x).floor()),
1537                whole(tenth(least_y).floor()),
1538                whole(tenth(most_x).ceil()),
1539                whole(tenth(most_y).ceil()),
1540            ]);
1541            outline_of[place] = Some(outlines.len());
1542            outlines.push(draft.reach.outline().unwrap_or(ObjectOutline {
1543                hull_mm: Vec::new(),
1544            }));
1545        }
1546        if !self.labelled_objects {
1547            outlines.extend(self.all.outline());
1548        }
1549        let blocks = self
1550            .blocks
1551            .into_iter()
1552            .map(|(start, place)| (start, outline_of.get(place).copied().flatten()))
1553            .collect();
1554        let spool = self.spool.and_then(|mut spool| {
1555            use std::io::Write as _;
1556            if spool.failed || spool.writer.flush().is_err() {
1557                drop(spool.writer);
1558                let _ = std::fs::remove_file(&spool.path);
1559                return None;
1560            }
1561            Some(spool.path)
1562        });
1563        let changes = (0_u32..)
1564            .zip(self.changes)
1565            .map(|(index, draft)| {
1566                // A change after the last layer began, laid in it, belongs to
1567                // that last layer: there is no later one.
1568                let layer = draft.layer.min(self.layers.len().saturating_sub(1));
1569                ChangeMark {
1570                    change: PlannedChange {
1571                        index,
1572                        kind: draft.kind,
1573                        offset_bytes: draft.offset,
1574                        layer: u32::try_from(layer + 1).unwrap_or(u32::MAX),
1575                        z_mm: self
1576                            .layers
1577                            .get(layer)
1578                            .and_then(|held| held.z_mm)
1579                            .unwrap_or(0.0),
1580                        color: draft.color,
1581                    },
1582                    at: draft.at,
1583                    fed_before_mm: draft.fed_before_mm,
1584                }
1585            })
1586            .collect();
1587        GcodeIndex {
1588            bytes: self.read,
1589            lines: self.lines,
1590            changes,
1591            change_minutes: self.change_minutes,
1592            first_colour: self.first_colour,
1593            extruded_mm: self.extruded_mm,
1594            layers: self.layers,
1595            type_names: self.type_names,
1596            labelled_types: self.labelled_types,
1597            time_left: self.time_left,
1598            flow: self.flow,
1599            fan: self.fan,
1600            objects,
1601            labelled_objects: self.labelled_objects,
1602            outlines,
1603            blocks,
1604            spool,
1605        }
1606    }
1607
1608    /// Hold more of the line being read, up to its bound.
1609    fn hold(&mut self, bytes: &[u8]) {
1610        if self.overlong {
1611            return;
1612        }
1613        if self.line.len() + bytes.len() > LINE_LIMIT {
1614            self.overlong = true;
1615            self.line.clear();
1616            return;
1617        }
1618        self.line.extend_from_slice(bytes);
1619    }
1620
1621    /// Read the line held, which ended at the offset read so far.
1622    fn end_line(&mut self) {
1623        self.lines += 1;
1624        let line = core::mem::take(&mut self.line);
1625        if !self.overlong {
1626            self.read_line(&line);
1627        }
1628        self.overlong = false;
1629        self.line = line;
1630        self.line.clear();
1631    }
1632
1633    /// Read one whole line, without its newline.
1634    fn read_line(&mut self, raw: &[u8]) {
1635        let raw = raw.trim_ascii();
1636        if let Some(comment) = raw.strip_prefix(b";") {
1637            if let Ok(comment) = core::str::from_utf8(comment) {
1638                self.comment(comment.trim_end());
1639            }
1640            return;
1641        }
1642        // A move is nearly every line of a print, so `G0`–`G3` written as a
1643        // slicer writes them are read by their own one pass.
1644        if let [b'G', code @ b'0'..=b'3', b' ', rest @ ..] = raw {
1645            self.motion(u32::from(code - b'0'), &move_of(rest));
1646            return;
1647        }
1648        let held = words(raw);
1649        let mut words = held.as_slice();
1650        // A leading `N<line number>` numbers the line and is no word of it.
1651        if let Some((Word { letter: b'N', .. }, rest)) = words.split_first() {
1652            words = rest;
1653        }
1654        let Some(first) = words.first() else {
1655            return;
1656        };
1657        let code = if held.numbered {
1658            held.second_code
1659        } else {
1660            held.first_code
1661        };
1662        match (char::from(first.letter), code) {
1663            ('G', Some(code @ 0..=3)) => self.motion(code, &Move::of(&words[1..])),
1664            ('G', Some(28)) => self.home(&words[1..]),
1665            ('G', Some(90)) => self.axes = Positioning::Absolute,
1666            ('G', Some(91)) => self.axes = Positioning::Relative,
1667            ('G', Some(92)) => self.declare(&words[1..]),
1668            ('M', Some(82)) => self.extruder = Positioning::Absolute,
1669            ('M', Some(83)) => self.extruder = Positioning::Relative,
1670            ('M', Some(73)) => self.estimate(&words[1..]),
1671            ('M', Some(221)) => self.flow_factor(&words[1..]),
1672            ('M', Some(106)) => self.fan_speed(&words[1..], Fan::Set),
1673            ('M', Some(107)) => self.fan_speed(&words[1..], Fan::Off),
1674            ('M', Some(486)) => self.object(raw, &words[1..]),
1675            ('M', Some(600)) => self.planned(PlannedChangeKind::ColorChange),
1676            ('M', Some(601)) => self.planned(PlannedChangeKind::Pause),
1677            _ => {}
1678        }
1679    }
1680
1681    /// A comment line: a layer change, a height, or an extrusion type.
1682    fn comment(&mut self, comment: &str) {
1683        if comment == "LAYER_CHANGE" {
1684            self.layers.push(Layer {
1685                begins: self.line_began,
1686                head: Head {
1687                    at: self.at,
1688                    e: self.e,
1689                    axes: self.axes,
1690                    extruder: self.extruder,
1691                    current_type: self.current_type,
1692                    width_mm: self.width_mm,
1693                },
1694                at: self.read,
1695                z_mm: None,
1696                types: 0,
1697            });
1698        } else if let Some(z) = comment.strip_prefix("Z:") {
1699            if let Some(layer) = self.layers.last_mut()
1700                && layer.z_mm.is_none()
1701            {
1702                // A height is a place on the Z axis: no lower than the bed and
1703                // no further than any machine reaches.
1704                layer.z_mm = z
1705                    .trim()
1706                    .parse::<f64>()
1707                    .ok()
1708                    .filter(|z| (0.0..=AXIS_LIMIT).contains(z));
1709            }
1710        } else if let Some(change) = comment.strip_prefix("COLOR_CHANGE,") {
1711            // `T<n>,#RRGGBB`: the tool and the colour loaded at the change.
1712            self.colour_comment = change
1713                .split(',')
1714                .nth(1)
1715                .and_then(colour_of)
1716                .map(|colour| (self.lines, colour));
1717        } else if let Some(colours) = comment.trim_start().strip_prefix("filament_colour = ") {
1718            if self.first_colour.is_none() {
1719                self.first_colour = colours.split(';').next().and_then(colour_of);
1720            }
1721        } else if let Some(width) = comment.strip_prefix("WIDTH:") {
1722            // A width is a nozzle's few tenths of a millimetre: anything
1723            // that is not one leaves the last.
1724            #[expect(
1725                clippy::cast_possible_truncation,
1726                reason = "an extrusion width is drawn, not measured"
1727            )]
1728            if let Some(width) = width
1729                .trim()
1730                .parse::<f64>()
1731                .ok()
1732                .filter(|width| (0.0..=AXIS_LIMIT).contains(width))
1733            {
1734                self.width_mm = width as f32;
1735            }
1736        } else if let Some(name) = comment.strip_prefix("TYPE:") {
1737            let name = name.trim();
1738            self.labelled_types = true;
1739            self.current_type = if name == NOT_THE_PART {
1740                None
1741            } else {
1742                self.intern(name)
1743            };
1744        }
1745    }
1746
1747    /// The bit of the type table one name is, adding it when there is room.
1748    fn intern(&mut self, name: &str) -> Option<usize> {
1749        if let Some(bit) = self.type_names.iter().position(|held| held == name) {
1750            return Some(bit);
1751        }
1752        if self.type_names.len() >= TYPE_LIMIT {
1753            return None;
1754        }
1755        self.type_names.push(name.to_owned());
1756        Some(self.type_names.len() - 1)
1757    }
1758
1759    /// A move: where the head goes, and whether it laid material on the way.
1760    fn motion(&mut self, code: u32, words: &Move) {
1761        // Plain statements rather than iterators and closures: this runs for
1762        // every move of a print.
1763        let start = self.at;
1764        let relative = self.axes == Positioning::Relative;
1765        if let Some(x) = words.x {
1766            self.place(0, x, relative);
1767        }
1768        if let Some(y) = words.y {
1769            self.place(1, y, relative);
1770        }
1771        if let Some(z) = words.z {
1772            self.place(2, z, relative);
1773        }
1774        let mut fed = 0.0;
1775        if let Some(value) = words.e {
1776            if relative || self.extruder == Positioning::Relative {
1777                self.e += value;
1778                fed = value;
1779            } else {
1780                fed = value - self.e;
1781                self.e = value;
1782            }
1783        }
1784        let travel = (self.at[0] - start[0]).hypot(self.at[1] - start[1]);
1785        if let Some(trail) = self.trail.as_mut()
1786            && travel > 0.0
1787        {
1788            trail.push([self.at[0], self.at[1]]);
1789        }
1790        self.extruded_mm += fed;
1791        if fed <= 0.0 || (travel <= TRAVEL_MM && code < 2) {
1792            return;
1793        }
1794        self.laid_in_layers = self.layers.len();
1795        if let (Some(layer), Some(bit)) = (self.layers.last_mut(), self.current_type) {
1796            layer.types |= 1 << bit;
1797        }
1798        let end = self.at;
1799        let turn = match code {
1800            2 => Some(Turn::Clockwise),
1801            3 => Some(Turn::CounterClockwise),
1802            _ => None,
1803        };
1804        let arc = turn.and_then(|turn| arc_of(words, turn, start, end));
1805        if let Some(collected) = self.collected.as_mut() {
1806            let kind = self
1807                .current_type
1808                .and_then(|bit| self.type_names.get(bit))
1809                .map_or(ExtrusionKind::Other, |name| ExtrusionKind::of_type(name));
1810            let laid = Laid {
1811                kind,
1812                width_mm: self.width_mm,
1813                ends_at: self.read_from.saturating_add(self.read),
1814            };
1815            collect_segments(collected, laid, start, end, arc);
1816            return;
1817        }
1818        let part_of_plan = !(self.labelled_types && self.current_type.is_none());
1819        let reach = if let Some(object) = self.current_object {
1820            let draft = &mut self.objects[object];
1821            grow(&mut draft.bounds, start[0], start[1]);
1822            grow(&mut draft.bounds, end[0], end[1]);
1823            if let Some(turn) = turn {
1824                for [x, y] in arc_extremes(words, turn, start, end) {
1825                    grow(&mut draft.bounds, x, y);
1826                }
1827            }
1828            &mut draft.reach
1829        } else if !self.labelled_objects && part_of_plan {
1830            &mut self.all
1831        } else {
1832            return;
1833        };
1834        // A move continuing the last one starts where that one ended, which
1835        // has been reached already.
1836        if self.reached_last != Some([start[0], start[1]]) {
1837            reach.point(start[0], start[1]);
1838        }
1839        reach.point(end[0], end[1]);
1840        self.reached_last = Some([end[0], end[1]]);
1841        if let Some(arc) = arc {
1842            reach.arc(arc.centre, arc.radius, arc.base, arc.sweep);
1843        }
1844    }
1845
1846    /// Move one axis to a place, or by a distance, when where it lands is
1847    /// within reach: a run of distances each within reach can carry the head
1848    /// past it, and a place beyond it is no place a head can be.
1849    fn place(&mut self, axis: usize, value: f64, relative: bool) {
1850        let landed = if relative {
1851            self.at[axis] + value
1852        } else {
1853            value
1854        };
1855        if landed.abs() <= AXIS_LIMIT {
1856            self.at[axis] = landed;
1857        }
1858    }
1859
1860    /// `G28`: the axes it names, or every axis when it names none, go home.
1861    fn home(&mut self, words: &[Word]) {
1862        let named: Vec<usize> = ['X', 'Y', 'Z']
1863            .into_iter()
1864            .enumerate()
1865            .filter(|(_, letter)| words.iter().any(|word| char::from(word.letter) == *letter))
1866            .map(|(axis, _)| axis)
1867            .collect();
1868        if named.is_empty() {
1869            self.at = [0.0; 3];
1870        } else {
1871            for axis in named {
1872                self.at[axis] = 0.0;
1873            }
1874        }
1875    }
1876
1877    /// `G92`: where the named axes are, without moving them; bare, every axis
1878    /// and the extruder are at zero.
1879    fn declare(&mut self, words: &[Word]) {
1880        if words.is_empty() {
1881            self.at = [0.0; 3];
1882            self.e = 0.0;
1883            return;
1884        }
1885        for (axis, letter) in ['X', 'Y', 'Z'].into_iter().enumerate() {
1886            if let Some(value) = number(words, letter).filter(|value| value.abs() <= AXIS_LIMIT) {
1887                self.at[axis] = value;
1888            }
1889        }
1890        if let Some(value) = number(words, 'E') {
1891            self.e = value;
1892        }
1893    }
1894
1895    /// `M73`: the normal mode's estimate of the minutes left, `P` and `R`, and
1896    /// the minutes to the next planned change, `C`.
1897    fn estimate(&mut self, words: &[Word]) {
1898        if let Some(minutes) = number(words, 'C').filter(|minutes| *minutes >= 0.0) {
1899            self.change_minutes.push(Mark {
1900                at: self.read,
1901                value: whole(minutes),
1902            });
1903        }
1904        if number(words, 'P').is_none() {
1905            return;
1906        }
1907        if let Some(minutes) = number(words, 'R').filter(|minutes| *minutes >= 0.0) {
1908            self.time_left.push(Mark {
1909                at: self.read,
1910                value: whole(minutes),
1911            });
1912        }
1913    }
1914
1915    /// `M600` or `M601`: a stop the file plans, carrying the colour the line
1916    /// just before it named.
1917    fn planned(&mut self, kind: PlannedChangeKind) {
1918        let named = self.colour_comment.take();
1919        if self.changes.len() >= CHANGE_LIMIT {
1920            return;
1921        }
1922        let color = match kind {
1923            PlannedChangeKind::ColorChange => named
1924                .filter(|(line, _)| line + 1 == self.lines)
1925                .map(|(_, colour)| colour),
1926            PlannedChangeKind::Pause => None,
1927        };
1928        let layer = if self.laid_in_layers == self.layers.len() {
1929            self.layers.len()
1930        } else {
1931            self.layers.len() - 1
1932        };
1933        self.changes.push(ChangeDraft {
1934            kind,
1935            offset: self.line_began,
1936            at: self.read,
1937            layer,
1938            color,
1939            fed_before_mm: self.extruded_mm,
1940        });
1941    }
1942
1943    /// `M221 S<percent>`: the flow factor.
1944    fn flow_factor(&mut self, words: &[Word]) {
1945        if let Some(percent) = number(words, 'S').filter(|percent| *percent >= 0.0) {
1946            mark_setting(&mut self.flow, self.read, percent / 100.0);
1947        }
1948    }
1949
1950    /// `M106 S<speed>` or `M107`: the part-cooling fan, in percent.
1951    fn fan_speed(&mut self, words: &[Word], command: Fan) {
1952        if number(words, 'P').is_some_and(|fan| fan != 0.0) {
1953            return;
1954        }
1955        let speed = match command {
1956            Fan::Off => 0.0,
1957            Fan::Set => number(words, 'S').unwrap_or(FAN_FULL),
1958        };
1959        let percent = (speed.clamp(0.0, FAN_FULL) / FAN_FULL * 100.0).round();
1960        mark_setting(&mut self.fan, self.read, percent);
1961    }
1962
1963    /// `M486`: an object starting, stopping, or being named.
1964    fn object(&mut self, raw: &[u8], words: &[Word]) {
1965        // A name labels the file's objects, though none is kept: an object is
1966        // its place on the bed.
1967        if raw
1968            .strip_prefix(b"M486")
1969            .is_some_and(|rest| rest.trim_ascii_start().starts_with(b"A"))
1970        {
1971            self.labelled_objects = true;
1972            return;
1973        }
1974        // An object is a whole number, and `-1` alone stops laying one down;
1975        // any other number names no object and changes nothing.
1976        let Some(number) = number(words, 'S')
1977            .filter(|number| (number - number.round()).abs() < f64::EPSILON && *number >= -1.0)
1978        else {
1979            return;
1980        };
1981        self.labelled_objects = true;
1982        if number < 0.0 {
1983            self.current_object = None;
1984            self.reached_last = None;
1985            return;
1986        }
1987        let id = whole(number);
1988        let place = if let Some(place) = self.object_numbers.get(&id) {
1989            *place
1990        } else if self.objects.len() >= OBJECT_LIMIT {
1991            self.current_object = None;
1992            self.reached_last = None;
1993            return;
1994        } else {
1995            self.objects.push(ObjectDraft::default());
1996            self.object_numbers.insert(id, self.objects.len() - 1);
1997            self.objects.len() - 1
1998        };
1999        self.current_object = Some(place);
2000        self.reached_last = None;
2001        self.blocks.push((self.read, place));
2002    }
2003}
2004
2005/// A colour written `#RRGGBB`, upper-cased; nothing for anything else.
2006fn colour_of(text: &str) -> Option<String> {
2007    let text = text.trim();
2008    let hex = text.strip_prefix('#')?;
2009    (hex.len() == 6 && hex.bytes().all(|byte| byte.is_ascii_hexdigit()))
2010        .then(|| text.to_ascii_uppercase())
2011}
2012
2013/// Record a value a file set, where it set it — every time, the same value
2014/// included, because a command repeating a value still puts it back over a
2015/// change made since.
2016fn mark_setting(marks: &mut Vec<Mark<f64>>, at: u64, value: f64) {
2017    marks.push(Mark { at, value });
2018}
2019
2020/// The whole number nearest a value a file wrote, which every word is
2021/// bounded well inside [`i64`] by.
2022fn whole(value: f64) -> i64 {
2023    format!("{:.0}", value.round()).parse().unwrap_or_default()
2024}
2025
2026/// A length rounded to a tenth of a millimetre before a bed area is widened
2027/// to whole millimetres, so that an arc's extreme computed a hair past a whole
2028/// number does not widen it by a millimetre more.
2029fn tenth(value: f64) -> f64 {
2030    (value * 10.0).round() / 10.0
2031}
2032
2033/// Grow a rectangle to reach a point.
2034fn grow(bounds: &mut Option<[f64; 4]>, x: f64, y: f64) {
2035    *bounds = Some(match *bounds {
2036        None => [x, y, x, y],
2037        Some([least_x, least_y, most_x, most_y]) => {
2038            [least_x.min(x), least_y.min(y), most_x.max(x), most_y.max(y)]
2039        }
2040    });
2041}
2042
2043/// Which way an arc turns: `G2` clockwise, `G3` counter-clockwise.
2044#[derive(Debug, Clone, Copy, PartialEq, Eq)]
2045enum Turn {
2046    /// `G2`.
2047    Clockwise,
2048    /// `G3`.
2049    CounterClockwise,
2050}
2051
2052/// What a part-cooling fan command does: `M106` sets a speed, `M107` turns
2053/// the fan off.
2054#[derive(Debug, Clone, Copy, PartialEq, Eq)]
2055enum Fan {
2056    /// `M106`, at its `S` speed or full.
2057    Set,
2058    /// `M107`.
2059    Off,
2060}
2061
2062/// The points of an arc's circle at which it reaches furthest along X or Y,
2063/// of the part of the circle the arc sweeps: what an arc lays beyond its two
2064/// ends.
2065///
2066/// The centre is the one `I` and `J` name, or for the `R` form the one on the
2067/// side of the chord the direction and the radius's sign choose. `G2` sweeps
2068/// clockwise and `G3` counter-clockwise; an arc ending where it began is the
2069/// whole circle.
2070fn arc_extremes(
2071    words: &Move,
2072    turn: Turn,
2073    start: [f64; 3],
2074    end: [f64; 3],
2075) -> impl Iterator<Item = [f64; 2]> {
2076    let reach = arc_of(words, turn, start, end).map(|arc| {
2077        let ArcGeometry {
2078            centre,
2079            radius,
2080            base,
2081            sweep,
2082            ..
2083        } = arc;
2084        let tau = core::f64::consts::TAU;
2085        (0..4).filter_map(move |quarter| {
2086            let angle = core::f64::consts::FRAC_PI_2 * f64::from(quarter);
2087            ((angle - base).rem_euclid(tau) <= sweep + 1e-9).then(|| {
2088                [
2089                    centre[0] + radius * angle.cos(),
2090                    centre[1] + radius * angle.sin(),
2091                ]
2092            })
2093        })
2094    });
2095    reach.into_iter().flatten()
2096}
2097
2098/// One arc's circle and the part of it swept.
2099#[derive(Debug, Clone, Copy)]
2100struct ArcGeometry {
2101    /// The circle's centre in bed mm, from `I`/`J` or the `R` form.
2102    centre: [f64; 2],
2103    /// The distance from that centre to the move's start, in mm.
2104    radius: f64,
2105    /// The angle the sweep starts at, counter-clockwise: the arc's start for
2106    /// `G3`, its end for `G2`.
2107    base: f64,
2108    /// How far it turns, as a positive angle; a whole turn for an arc ending
2109    /// where it began.
2110    sweep: f64,
2111    /// The direction it is laid in.
2112    turn: Turn,
2113}
2114
2115/// The circle an arc lies on and the part of it swept: the centre `I` and `J`
2116/// name, or for the `R` form the one [`centre_of_radius`] finds. Nothing for
2117/// an `R` arc with no circle.
2118fn arc_of(words: &Move, turn: Turn, start: [f64; 3], end: [f64; 3]) -> Option<ArcGeometry> {
2119    let centre = words.r.map_or_else(
2120        || {
2121            Some([
2122                start[0] + words.i.unwrap_or(0.0),
2123                start[1] + words.j.unwrap_or(0.0),
2124            ])
2125        },
2126        |radius| centre_of_radius(radius, turn, start, end),
2127    )?;
2128    let radius = (start[0] - centre[0]).hypot(start[1] - centre[1]);
2129    let from = (start[1] - centre[1]).atan2(start[0] - centre[0]);
2130    let to = (end[1] - centre[1]).atan2(end[0] - centre[0]);
2131    let tau = core::f64::consts::TAU;
2132    // How far the arc turns, counter-clockwise from `base`, as a positive
2133    // sweep: a clockwise arc is the same sweep taken from its end.
2134    let (base, sweep) = match turn {
2135        Turn::Clockwise => (to, (from - to).rem_euclid(tau)),
2136        Turn::CounterClockwise => (from, (to - from).rem_euclid(tau)),
2137    };
2138    let sweep = if sweep < 1e-9 { tau } else { sweep };
2139    Some(ArcGeometry {
2140        centre,
2141        radius,
2142        base,
2143        sweep,
2144        turn,
2145    })
2146}
2147
2148/// What one move lays, which each of its segments carries.
2149#[derive(Debug, Clone, Copy)]
2150struct Laid {
2151    /// What it lays.
2152    kind: ExtrusionKind,
2153    /// At what width.
2154    width_mm: f32,
2155    /// The file offset just past its line.
2156    ends_at: u64,
2157}
2158
2159/// A move's toolpath segments: the move itself, or an arc cut into chords
2160/// of at most [`CHORD_MM`] from its start to its end, in the direction laid.
2161fn collect_segments(
2162    collected: &mut Vec<ToolpathSegment>,
2163    laid: Laid,
2164    start: [f64; 3],
2165    end: [f64; 3],
2166    arc: Option<ArcGeometry>,
2167) {
2168    #[expect(
2169        clippy::cast_possible_truncation,
2170        reason = "bed millimetres are far inside f32's range; a toolpath is drawn, not measured"
2171    )]
2172    let at = |x: f64, y: f64| [x as f32, y as f32];
2173    let Some(arc) = arc else {
2174        collected.push(ToolpathSegment {
2175            from_mm: at(start[0], start[1]),
2176            to_mm: at(end[0], end[1]),
2177            kind: laid.kind,
2178            width_mm: laid.width_mm,
2179            ends_at: laid.ends_at,
2180        });
2181        return;
2182    };
2183    let length = arc.sweep * arc.radius;
2184    let chords = (length / CHORD_MM).ceil().clamp(1.0, 4096.0);
2185    let (from, step) = match arc.turn {
2186        Turn::CounterClockwise => (arc.base, arc.sweep / chords),
2187        Turn::Clockwise => (arc.base + arc.sweep, -arc.sweep / chords),
2188    };
2189    let mut previous = at(start[0], start[1]);
2190    let mut k = 1.0;
2191    while k < chords {
2192        let angle = from + step * k;
2193        let next = at(
2194            arc.centre[0] + arc.radius * angle.cos(),
2195            arc.centre[1] + arc.radius * angle.sin(),
2196        );
2197        collected.push(ToolpathSegment {
2198            from_mm: previous,
2199            to_mm: next,
2200            kind: laid.kind,
2201            width_mm: laid.width_mm,
2202            ends_at: laid.ends_at,
2203        });
2204        previous = next;
2205        k += 1.0;
2206    }
2207    collected.push(ToolpathSegment {
2208        from_mm: previous,
2209        to_mm: at(end[0], end[1]),
2210        kind: laid.kind,
2211        width_mm: laid.width_mm,
2212        ends_at: laid.ends_at,
2213    });
2214}
2215
2216/// The centre of an `R`-form arc: on the chord's perpendicular, on the side a
2217/// clockwise or counter-clockwise turn of a short arc puts it, and on the other
2218/// side for a negative radius, which asks for the long way round. Nothing when
2219/// the chord is longer than the circle allows, or the arc ends where it began.
2220fn centre_of_radius(radius: f64, turn: Turn, start: [f64; 3], end: [f64; 3]) -> Option<[f64; 2]> {
2221    let chord = [end[0] - start[0], end[1] - start[1]];
2222    let length = chord[0].hypot(chord[1]);
2223    if length <= TRAVEL_MM || length > 2.0 * radius.abs() {
2224        return None;
2225    }
2226    let rise = (radius * radius - length * length / 4.0).max(0.0).sqrt();
2227    let left = match turn {
2228        Turn::Clockwise => -1.0,
2229        Turn::CounterClockwise => 1.0,
2230    };
2231    let side = left * radius.signum() * rise / length;
2232    Some([
2233        start[0] + chord[0] / 2.0 - chord[1] * side,
2234        start[1] + chord[1] / 2.0 + chord[0] * side,
2235    ])
2236}
2237
2238/// The words of a command, each a letter, the text after it and the number
2239/// that text is when it is one, up to [`WORD_COUNT`] of them: up to the `;`
2240/// a comment starts at or the `*` a checksum does.
2241///
2242/// Each number is read by [`number_at`].
2243fn words(command: &[u8]) -> Words {
2244    let mut found = Words {
2245        held: [Word {
2246            letter: 0,
2247            value: f64::NAN,
2248        }; WORD_COUNT],
2249        len: 0,
2250        first_code: None,
2251        second_code: None,
2252        numbered: false,
2253    };
2254    let length = command.len();
2255    let mut at = 0;
2256    while at < length {
2257        let letter = command[at];
2258        if letter == b';' || letter == b'*' {
2259            break;
2260        }
2261        at += 1;
2262        let upper = match letter {
2263            b'a'..=b'z' => letter - (b'a' - b'A'),
2264            b'A'..=b'Z' => letter,
2265            _ => continue,
2266        };
2267        let start = at;
2268        let (value, next) = number_at(command, at);
2269        at = next;
2270        let text = &command[start..at];
2271        // A command's code is the first word's, or the second's after a
2272        // line number, read as the whole number it is written as.
2273        if found.len == 0 {
2274            found.first_code = whole_number(text);
2275            found.numbered = upper == b'N';
2276        } else if found.len == 1 {
2277            found.second_code = whole_number(text);
2278        }
2279        if found.len < WORD_COUNT {
2280            found.held[found.len] = Word {
2281                letter: upper,
2282                value,
2283            };
2284            found.len += 1;
2285        }
2286    }
2287    found
2288}
2289
2290/// The number a word carries, read from `at` to the next space, letter, `;`
2291/// or `*`, and the offset just past it; a word that is no number is not a
2292/// number.
2293///
2294/// The end is found with a plain loop rather than an iterator adaptor, and the
2295/// number is read by the standard library's own parse, which is compiled
2296/// optimised whatever this crate is built as: this runs for every number of
2297/// every move of a print.
2298fn number_at(line: &[u8], mut at: usize) -> (f64, usize) {
2299    let start = at;
2300    while at < line.len()
2301        && !matches!(line[at], b' ' | b'\t' | b';' | b'*' | b'A'..=b'Z' | b'a'..=b'z')
2302    {
2303        at += 1;
2304    }
2305    (decimal(&line[start..at]).unwrap_or(f64::NAN), at)
2306}
2307
2308/// The words of a move this reader uses, each a number within reach when the
2309/// move carries it: where it goes, what it feeds, and an arc's centre or
2310/// radius.
2311#[derive(Debug, Clone, Copy, Default)]
2312struct Move {
2313    /// `X`.
2314    x: Option<f64>,
2315    /// `Y`.
2316    y: Option<f64>,
2317    /// `Z`.
2318    z: Option<f64>,
2319    /// `E`.
2320    e: Option<f64>,
2321    /// `I`.
2322    i: Option<f64>,
2323    /// `J`.
2324    j: Option<f64>,
2325    /// `R`.
2326    r: Option<f64>,
2327}
2328
2329impl Move {
2330    /// A move's words, from a command read word by word.
2331    fn of(words: &[Word]) -> Self {
2332        Self {
2333            x: number(words, 'X'),
2334            y: number(words, 'Y'),
2335            z: number(words, 'Z'),
2336            e: number(words, 'E'),
2337            i: number(words, 'I'),
2338            j: number(words, 'J'),
2339            r: number(words, 'R'),
2340        }
2341    }
2342}
2343
2344/// A move's words, read in one pass from what follows its `G0`–`G3`: the
2345/// first of each letter it uses, up to the `;` a comment starts at or the `*`
2346/// a checksum does. Every other word — the feedrate above all — is passed
2347/// over unread, which is what keeps this the cheap path through a print.
2348fn move_of(line: &[u8]) -> Move {
2349    let mut found = Move::default();
2350    let length = line.len();
2351    let mut at = 0;
2352    while at < length {
2353        let letter = line[at];
2354        at += 1;
2355        let slot = match letter {
2356            b';' | b'*' => break,
2357            b'X' | b'x' => &mut found.x,
2358            b'Y' | b'y' => &mut found.y,
2359            b'Z' | b'z' => &mut found.z,
2360            b'E' | b'e' => &mut found.e,
2361            b'I' | b'i' => &mut found.i,
2362            b'J' | b'j' => &mut found.j,
2363            b'R' | b'r' => &mut found.r,
2364            b'A'..=b'Z' | b'a'..=b'z' => {
2365                while at < length && !matches!(line[at], b' ' | b'\t' | b';' | b'*') {
2366                    at += 1;
2367                }
2368                continue;
2369            }
2370            _ => continue,
2371        };
2372        let (value, next) = number_at(line, at);
2373        at = next;
2374        if slot.is_none() {
2375            *slot = Some(value).filter(|value| value.is_finite() && value.abs() <= WORD_LIMIT);
2376        }
2377    }
2378    found
2379}
2380
2381/// One word of a command: its letter, upper-cased, and the number it carries,
2382/// not a number when it carries none.
2383#[derive(Debug, Clone, Copy)]
2384struct Word {
2385    /// The letter.
2386    letter: u8,
2387    /// The number, `NaN` when the word's text is none.
2388    value: f64,
2389}
2390
2391/// One command's words, held without allocating.
2392struct Words {
2393    /// The words, the first `len` of them read.
2394    held: [Word; WORD_COUNT],
2395    /// How many were read.
2396    len: usize,
2397    /// The first word's text, as a whole number when it is one.
2398    first_code: Option<u32>,
2399    /// The second word's text, as a whole number when it is one.
2400    second_code: Option<u32>,
2401    /// Whether the first word is a line number.
2402    numbered: bool,
2403}
2404
2405impl Words {
2406    /// The words read.
2407    fn as_slice(&self) -> &[Word] {
2408        &self.held[..self.len]
2409    }
2410}
2411
2412/// The whole number a command's code is, when it is digits alone.
2413fn whole_number(text: &[u8]) -> Option<u32> {
2414    let mut value: u32 = 0;
2415    let mut at = 0;
2416    while at < text.len() {
2417        let byte = text[at];
2418        if !byte.is_ascii_digit() {
2419            return None;
2420        }
2421        value = value.checked_mul(10)?.checked_add(u32::from(byte - b'0'))?;
2422        at += 1;
2423    }
2424    (!text.is_empty()).then_some(value)
2425}
2426
2427/// The number a word's text is, by the standard library's own parse.
2428fn decimal(text: &[u8]) -> Option<f64> {
2429    core::str::from_utf8(text).ok()?.parse::<f64>().ok()
2430}
2431
2432/// The number one word carries, when the command has that word and it is a
2433/// number within reach.
2434fn number(words: &[Word], letter: char) -> Option<f64> {
2435    let mut at = 0;
2436    while at < words.len() {
2437        let Word {
2438            letter: word,
2439            value,
2440        } = words[at];
2441        if char::from(word) == letter {
2442            return Some(value).filter(|value| value.is_finite() && value.abs() <= WORD_LIMIT);
2443        }
2444        at += 1;
2445    }
2446    None
2447}
2448
2449/// Build one file's index from its pieces, in order — what the whole-file
2450/// read does with the pieces it is handed.
2451#[must_use]
2452pub fn index_of(pieces: &[&[u8]]) -> GcodeIndex {
2453    let mut builder = IndexBuilder::new();
2454    for piece in pieces {
2455        let _ = builder.take(piece);
2456    }
2457    builder.finish()
2458}
2459
2460/// One print's index, as the cache holds it.
2461#[derive(Debug, Default)]
2462enum Slot {
2463    /// Nothing is built and nothing is building.
2464    #[default]
2465    Empty,
2466    /// A build is under way, and these are waiting for it.
2467    Building(Vec<Waker>),
2468    /// Built.
2469    Ready(Arc<GcodeIndex>),
2470}
2471
2472/// Every print's index, held for as long as this process runs.
2473#[derive(Debug, Default)]
2474pub struct GcodeIndexes {
2475    /// One slot per print that has been asked for.
2476    slots: Mutex<BTreeMap<PrintId, Slot>>,
2477    /// The frames each print's looks were given, by their capture time, with
2478    /// the file position the job had reached as each was taken: a look's
2479    /// record keeps no job, so a rise since one is measured from this. It is
2480    /// this process's alone, as the indexes are: a restarted one measures
2481    /// from periodic observations until its own looks are old enough.
2482    looked: Mutex<BTreeMap<PrintId, Vec<(Timestamp, i64)>>>,
2483}
2484
2485/// What asking for one print's index answered.
2486#[derive(Debug)]
2487pub enum Claimed<'a> {
2488    /// It is built.
2489    Ready(Arc<GcodeIndex>),
2490    /// Nothing is building it, and this caller is to: it holds the claim.
2491    Build(BuildClaim<'a>),
2492}
2493
2494/// The one caller building a print's index. Dropping it unfinished hands the
2495/// build to whoever asks next, and wakes everyone waiting.
2496#[derive(Debug)]
2497pub struct BuildClaim<'a> {
2498    /// The cache it was claimed from.
2499    indexes: &'a GcodeIndexes,
2500    /// The print it is building for.
2501    print_id: PrintId,
2502    /// Whether it has finished.
2503    done: bool,
2504}
2505
2506impl BuildClaim<'_> {
2507    /// Hand the built index over, waking every caller waiting for it.
2508    #[must_use]
2509    pub fn finish(mut self, index: GcodeIndex) -> Arc<GcodeIndex> {
2510        let index = Arc::new(index);
2511        self.settle(Slot::Ready(Arc::clone(&index)));
2512        self.done = true;
2513        index
2514    }
2515
2516    /// Put the slot into its next state and wake whoever waited.
2517    fn settle(&self, next: Slot) {
2518        let waiting = {
2519            let mut slots = self.indexes.held();
2520            let slot = slots.entry(self.print_id).or_default();
2521            match core::mem::replace(slot, next) {
2522                Slot::Building(waiting) => waiting,
2523                Slot::Empty | Slot::Ready(_) => Vec::new(),
2524            }
2525        };
2526        for waker in waiting {
2527            waker.wake();
2528        }
2529    }
2530}
2531
2532impl Drop for BuildClaim<'_> {
2533    fn drop(&mut self) {
2534        if !self.done {
2535            self.settle(Slot::Empty);
2536        }
2537    }
2538}
2539
2540impl GcodeIndexes {
2541    /// The slots, held for one read or write.
2542    fn held(&self) -> std::sync::MutexGuard<'_, BTreeMap<PrintId, Slot>> {
2543        self.slots.lock().unwrap_or_else(PoisonError::into_inner)
2544    }
2545
2546    /// One print's index when it is built, or the claim to build it, waiting
2547    /// while another caller is building it.
2548    pub const fn claim(&self, print_id: PrintId) -> Claim<'_> {
2549        Claim {
2550            indexes: self,
2551            print_id,
2552        }
2553    }
2554
2555    /// One print's index, when it is built.
2556    #[must_use]
2557    pub fn built(&self, print_id: PrintId) -> Option<Arc<GcodeIndex>> {
2558        match self.held().get(&print_id) {
2559            Some(Slot::Ready(index)) => Some(Arc::clone(index)),
2560            _ => None,
2561        }
2562    }
2563}
2564
2565/// The future [`GcodeIndexes::claim`] answers.
2566#[derive(Debug)]
2567pub struct Claim<'a> {
2568    /// The cache.
2569    indexes: &'a GcodeIndexes,
2570    /// The print.
2571    print_id: PrintId,
2572}
2573
2574impl<'a> Future for Claim<'a> {
2575    type Output = Claimed<'a>;
2576
2577    fn poll(self: Pin<&mut Self>, context: &mut Context<'_>) -> Poll<Self::Output> {
2578        let mut slots = self.indexes.held();
2579        let slot = slots.entry(self.print_id).or_default();
2580        match slot {
2581            Slot::Ready(index) => Poll::Ready(Claimed::Ready(Arc::clone(index))),
2582            Slot::Building(waiting) => {
2583                if !waiting.iter().any(|held| held.will_wake(context.waker())) {
2584                    waiting.push(context.waker().clone());
2585                }
2586                Poll::Pending
2587            }
2588            Slot::Empty => {
2589                *slot = Slot::Building(Vec::new());
2590                Poll::Ready(Claimed::Build(BuildClaim {
2591                    indexes: self.indexes,
2592                    print_id: self.print_id,
2593                    done: false,
2594                }))
2595            }
2596        }
2597    }
2598}
2599
2600/// The most indexes held at once. A print's index is a few tens of kilobytes,
2601/// and a supervisor watches one print at a time; this bounds what a server
2602/// running for months holds of prints long finished.
2603const HELD_INDEXES: usize = 16;
2604
2605impl GcodeIndexes {
2606    /// Remember that a look or a check of one print was given a frame captured
2607    /// at `captured`, with the job at `position`, and forget what no rise can be
2608    /// measured from any more: every look older than the newest one already
2609    /// half an hour old before `now`, and the looks of prints beyond
2610    /// [`HELD_INDEXES`], oldest print first.
2611    pub(crate) fn note_look(
2612        &self,
2613        print_id: PrintId,
2614        captured: Timestamp,
2615        position: i64,
2616        now: Timestamp,
2617    ) {
2618        let mut looked = self.looked.lock().unwrap_or_else(PoisonError::into_inner);
2619        let frames = looked.entry(print_id).or_default();
2620        frames.push((captured, position));
2621        frames.sort_by_key(|(captured, _)| *captured);
2622        if let Ok(until) = now.plus_seconds(-RISE_WINDOW_S) {
2623            let aged = frames.partition_point(|(captured, _)| *captured <= until);
2624            frames.drain(..aged.saturating_sub(1));
2625        }
2626        while looked.len() > HELD_INDEXES {
2627            let Some(oldest) = looked.keys().next().copied() else {
2628                break;
2629            };
2630            let _ = looked.remove(&oldest);
2631        }
2632    }
2633
2634    /// The newest look at one print whose frame was captured no later than
2635    /// `until`: its capture time and the job's position then.
2636    fn newest_look_until(&self, print_id: PrintId, until: Timestamp) -> Option<(Timestamp, i64)> {
2637        let looked = self.looked.lock().unwrap_or_else(PoisonError::into_inner);
2638        looked
2639            .get(&print_id)?
2640            .iter()
2641            .rev()
2642            .find(|(captured, _)| *captured <= until)
2643            .copied()
2644    }
2645
2646    /// Let go of finished indexes beyond [`HELD_INDEXES`], keeping `keep`.
2647    fn trim(&self, keep: PrintId) {
2648        let mut slots = self.held();
2649        let ready: Vec<PrintId> = slots
2650            .iter()
2651            .filter(|(print_id, slot)| **print_id != keep && matches!(slot, Slot::Ready(_)))
2652            .map(|(print_id, _)| *print_id)
2653            .collect();
2654        let over = slots.len().saturating_sub(HELD_INDEXES);
2655        for print_id in ready.into_iter().take(over) {
2656            slots.remove(&print_id);
2657        }
2658    }
2659}
2660
2661impl crate::supervisor::Supervisor {
2662    /// What the slicer planned at the job's current file position, building
2663    /// the print's index first when this supervisor has none for it.
2664    ///
2665    /// Nothing when the print is over, the job is not this print's file, the
2666    /// job reports no position, or the file could not be read — a read that
2667    /// failed builds nothing, so the next one tries again.
2668    ///
2669    /// # Errors
2670    ///
2671    /// The store's own error when the print's actions could not be read, as
2672    /// every other store read of the context answers it.
2673    pub(crate) async fn slicer_plan(
2674        &self,
2675        print: &crate::records::PrintRecord,
2676        job: Option<&printobserver_printer_api::JobSnapshot>,
2677        interventions: &[crate::records::Intervention],
2678    ) -> Result<Option<SlicerPlan>, crate::error::CoreError> {
2679        let Some((position, file)) = job
2680            .and_then(|job| job.file_position_bytes.zip(job.file_name.as_deref()))
2681            .filter(|(_, file)| {
2682                print.ended_at.is_none() && print.file_name.as_deref() == Some(*file)
2683            })
2684        else {
2685            return Ok(None);
2686        };
2687        let Some(index) = self.index_of(print.id, file).await else {
2688            return Ok(None);
2689        };
2690        let (flow, fan) = self
2691            .changes_since(print.id, &index, position, interventions)
2692            .await?;
2693        let mut plan = index.plan_with(position, flow, fan);
2694        plan.change_waiting = self
2695            .planned_change_waiting(print.id)
2696            .await?
2697            .map(|waiting| waiting.reached.change);
2698        plan.rise = self.rise_of(print.id, &index, position).await?;
2699        if plan.rise.is_none() {
2700            plan.unknown.push(PlanFact::Rise);
2701            plan.unknown.sort_unstable();
2702        }
2703        Ok(Some(plan))
2704    }
2705
2706    /// How far the plan has risen since the newest frame at least
2707    /// [`RISE_WINDOW_S`] old that was seen — a periodic observation's, when it
2708    /// carries a position, or one a check or a look noted — and where the plan
2709    /// had the top then.
2710    async fn rise_of(
2711        &self,
2712        print_id: PrintId,
2713        index: &GcodeIndex,
2714        position: i64,
2715    ) -> Result<Option<Rise>, crate::error::CoreError> {
2716        use printobserver_types::EventPayload as _;
2717
2718        use crate::kinds::PeriodicObservationPayload;
2719
2720        let now = self.clock().now();
2721        let Ok(until) = now.plus_seconds(-RISE_WINDOW_S) else {
2722            return Ok(None);
2723        };
2724        let events = self
2725            .stores()
2726            .events
2727            .history(crate::store::HistoryQuery {
2728                print_id,
2729                kinds: printobserver_types::EventKind::new(PeriodicObservationPayload::KIND)
2730                    .into_iter()
2731                    .collect(),
2732                since: None,
2733                until: Some(until),
2734                limit: Some(1),
2735            })
2736            .await?;
2737        let observed = events.first().and_then(|event| {
2738            let observed = event.payload_as::<PeriodicObservationPayload>()?.ok()?;
2739            let earlier = observed.job?.file_position_bytes?;
2740            Some((
2741                observed.frame_captured_at.unwrap_or(event.received_at),
2742                earlier,
2743            ))
2744        });
2745        let looked = self.gcode_indexes().newest_look_until(print_id, until);
2746        let newest = match (observed, looked) {
2747            (Some(observed), Some(looked)) => Some(if looked.0 > observed.0 {
2748                looked
2749            } else {
2750                observed
2751            }),
2752            (observed, looked) => observed.or(looked),
2753        };
2754        Ok(newest.and_then(|(since, earlier)| {
2755            Some(Rise {
2756                since,
2757                mm: index.height_and_rise_since(earlier, position)?,
2758            })
2759        }))
2760    }
2761
2762    /// One open print's G-code index, built from its file — and spooled —
2763    /// when this supervisor has none for it yet; nothing for a print the
2764    /// store does not hold or could not read, that has ended, names no file,
2765    /// or whose file could not be read.
2766    pub async fn print_gcode_index(&self, print_id: PrintId) -> Option<Arc<GcodeIndex>> {
2767        // A store that cannot be read answers nothing, as a print it does not
2768        // hold does, and its caller asks again at the next read. No test makes
2769        // the store fail here, since every store fake failure lands on the read
2770        // before this one; the same `None` for a print the store does not
2771        // hold is proved by `the_spool_goes_when_the_print_closes_and_strays_are_swept`,
2772        // and the alignment check's asking again by its retried-fetch journey.
2773        let print = self.stores().prints.print(print_id).await.ok()??;
2774        if print.ended_at.is_some() {
2775            return None;
2776        }
2777        self.index_of(print.id, print.file_name.as_deref()?).await
2778    }
2779
2780    /// Delete one print's G-code spool, when there is one.
2781    pub(crate) fn drop_gcode_spool(&self, print_id: PrintId) {
2782        if let Some(directory) = self.config().gcode_spool_dir.as_deref() {
2783            let _ = std::fs::remove_file(crate::toolpath::spool_path(directory, print_id));
2784        }
2785    }
2786
2787    /// Delete every G-code spool of a print that is not open: what a print
2788    /// closed while no supervisor was running left behind.
2789    ///
2790    /// # Errors
2791    ///
2792    /// The store's own error when the open prints could not be read.
2793    pub async fn sweep_gcode_spools(&self) -> Result<(), crate::error::CoreError> {
2794        let Some(directory) = self.config().gcode_spool_dir.clone() else {
2795            return Ok(());
2796        };
2797        let open: Vec<String> = self
2798            .stores()
2799            .prints
2800            .open_prints()
2801            .await?
2802            .iter()
2803            .map(|print| print.id.to_string())
2804            .collect();
2805        // A directory that cannot be listed, an entry that cannot be read and
2806        // a spool that cannot be removed each leave a file behind, which the
2807        // next start's sweep tries again. No test makes the filesystem refuse
2808        // them, since that needs one made to fail beneath a running server;
2809        // what proves the sweep is that it removes exactly the spools of
2810        // closed prints and nothing else, at start and on a close
2811        // (`the_spool_goes_when_the_print_closes_and_strays_are_swept`).
2812        let Ok(entries) = std::fs::read_dir(&directory) else {
2813            return Ok(());
2814        };
2815        for entry in entries.flatten() {
2816            let name = entry.file_name();
2817            // Only a file named for a print is a spool; anything else is left.
2818            let Some(print) = name
2819                .to_str()
2820                .and_then(|name| name.strip_suffix(crate::toolpath::SPOOL_SUFFIX))
2821                .filter(|print| print.parse::<PrintId>().is_ok())
2822            else {
2823                continue;
2824            };
2825            if !open.iter().any(|id| id == print) {
2826                let _ = std::fs::remove_file(entry.path());
2827            }
2828        }
2829        Ok(())
2830    }
2831
2832    /// One print's index, built from its file when there is none yet.
2833    async fn index_of(&self, print_id: PrintId, file: &str) -> Option<Arc<GcodeIndex>> {
2834        // A name no file could carry is no file to read.
2835        let file_name = printobserver_types::FileName::new(file).ok()?;
2836        let claim = match self.gcode_indexes().claim(print_id).await {
2837            Claimed::Ready(index) => return Some(index),
2838            Claimed::Build(claim) => claim,
2839        };
2840        // A spool that cannot be created leaves an index with no toolpaths,
2841        // which is no reason to go without the plan.
2842        let mut builder = self
2843            .config()
2844            .gcode_spool_dir
2845            .as_deref()
2846            .and_then(|directory| {
2847                IndexBuilder::spooling(crate::toolpath::spool_path(directory, print_id)).ok()
2848            })
2849            .unwrap_or_default();
2850        self.read_gcode(file_name.clone(), &mut builder)
2851            .await
2852            .ok()?;
2853        let index = claim.finish(builder.finish());
2854        self.gcode_indexes().trim(print_id);
2855        if let Ok(body) = printobserver_types::EventBody::of(&crate::kinds::GcodeIndexedPayload {
2856            file_name,
2857            bytes: index.bytes(),
2858            layers: u64::try_from(index.layer_count()).unwrap_or(u64::MAX),
2859        }) {
2860            // The index is built whether or not the store takes the record of
2861            // it, and a check goes on without it.
2862            let _ = self.append_system_event(print_id, body).await;
2863        }
2864        Some(index)
2865    }
2866
2867    /// The flow factor and the fan speed the latest change made through this
2868    /// program set, each when it was made after the file last set the same
2869    /// thing and still stands.
2870    ///
2871    /// A change is placed against the file by the position the print had last
2872    /// been read to have reached when it was made, at the file's start when no
2873    /// position had been read yet; a change whose bounded intervention has
2874    /// since expired stands no more.
2875    async fn changes_since(
2876        &self,
2877        print_id: PrintId,
2878        index: &GcodeIndex,
2879        position: i64,
2880        interventions: &[crate::records::Intervention],
2881    ) -> Result<(Option<f64>, Option<f64>), crate::error::CoreError> {
2882        use printobserver_types::EventPayload as _;
2883
2884        use crate::kinds::{ActionExecutedPayload, ActionRequestedPayload};
2885        use crate::records::PrintAction;
2886
2887        let kinds = [ActionRequestedPayload::KIND, ActionExecutedPayload::KIND]
2888            .iter()
2889            .filter_map(|kind| printobserver_types::EventKind::new(*kind).ok())
2890            .collect();
2891        let events = self
2892            .stores()
2893            .events
2894            .history(crate::store::HistoryQuery {
2895                print_id,
2896                kinds,
2897                since: None,
2898                until: None,
2899                limit: Some(crate::store::MAX_HISTORY_LIMIT),
2900            })
2901            .await?;
2902        let requested: BTreeMap<crate::records::ActionId, PrintAction> = events
2903            .iter()
2904            .filter_map(printobserver_types::EventRecord::payload_as::<ActionRequestedPayload>)
2905            .filter_map(Result::ok)
2906            .map(|payload| (payload.action_id, payload.action))
2907            .collect();
2908        let mut flow = None;
2909        let mut fan = None;
2910        // Newest first, so the first change of each kind is the latest.
2911        for executed in events
2912            .iter()
2913            .filter_map(printobserver_types::EventRecord::payload_as::<ActionExecutedPayload>)
2914            .filter_map(Result::ok)
2915        {
2916            let standing = executed
2917                .intervention_id
2918                .is_none_or(|opened| interventions.iter().any(|active| active.id == opened));
2919            // Where in the file the change was made; one made before any
2920            // position was known is placed at the file's start.
2921            let made = executed
2922                .file_position_bytes
2923                .and_then(|made| u64::try_from(made).ok())
2924                .unwrap_or(0);
2925            let after = |set: Option<SetInFile>| set.is_none_or(|set| made >= set.at);
2926            match requested.get(&executed.action_id) {
2927                Some(PrintAction::SetFlowrateFactor { factor, .. }) if flow.is_none() => {
2928                    flow = Some((standing && after(index.flow_at(position))).then_some(*factor));
2929                }
2930                Some(PrintAction::SetFanPercent { percent, .. }) if fan.is_none() => {
2931                    fan = Some((standing && after(index.fan_at(position))).then_some(*percent));
2932                }
2933                _ => {}
2934            }
2935        }
2936        Ok((flow.flatten(), fan.flatten()))
2937    }
2938}
2939
2940#[cfg(test)]
2941mod tests {
2942    use super::{GcodeIndexes, HELD_INDEXES, OVER_AIR, RISE_WINDOW_S, SUPPORTS, WALLS};
2943    use crate::toolpath::ExtrusionKind;
2944
2945    /// The type names the plan's facts single out are the ones the toolpath
2946    /// draws in the same kinds: a wall is drawn as a wall, a support as a
2947    /// support, and what is laid over air as a bridge or an overhang.
2948    #[test]
2949    fn the_plans_type_names_map_to_the_kinds_the_toolpath_draws() {
2950        for name in WALLS {
2951            assert_eq!(ExtrusionKind::of_type(name), ExtrusionKind::Wall, "{name}");
2952        }
2953        for name in SUPPORTS {
2954            assert_eq!(
2955                ExtrusionKind::of_type(name),
2956                ExtrusionKind::Support,
2957                "{name}"
2958            );
2959        }
2960        for name in OVER_AIR {
2961            assert!(
2962                matches!(
2963                    ExtrusionKind::of_type(name),
2964                    ExtrusionKind::Bridge | ExtrusionKind::Overhang
2965                ),
2966                "{name}"
2967            );
2968        }
2969    }
2970    use printobserver_types::{PrintId, Timestamp};
2971
2972    /// An instant some seconds after another.
2973    fn after(start: Timestamp, seconds: i64) -> Timestamp {
2974        start.plus_seconds(seconds).expect("an instant")
2975    }
2976
2977    /// What is remembered of one print's looks, oldest first.
2978    fn held(indexes: &GcodeIndexes, print_id: PrintId) -> Vec<(Timestamp, i64)> {
2979        indexes
2980            .looked
2981            .lock()
2982            .expect("the looks are held")
2983            .get(&print_id)
2984            .cloned()
2985            .unwrap_or_default()
2986    }
2987
2988    /// Of the looks already half an hour old, only the newest is kept: it is
2989    /// the one a rise is measured from until a newer look ages.
2990    #[test]
2991    fn the_newest_aged_look_is_kept_and_every_older_one_let_go() {
2992        let indexes = GcodeIndexes::default();
2993        let print = PrintId::new();
2994        let start = Timestamp::now();
2995        indexes.note_look(print, start, 10, start);
2996        indexes.note_look(print, after(start, 60), 20, after(start, 60));
2997        let now = after(start, 60 + RISE_WINDOW_S + 30);
2998        indexes.note_look(print, now, 30, now);
2999
3000        assert_eq!(
3001            held(&indexes, print),
3002            vec![(after(start, 60), 20), (now, 30)]
3003        );
3004        assert_eq!(
3005            indexes.newest_look_until(print, after(now, -RISE_WINDOW_S)),
3006            Some((after(start, 60), 20))
3007        );
3008        assert_eq!(indexes.newest_look_until(print, after(start, 30)), None);
3009    }
3010
3011    /// Past as many prints as indexes are held, the looks of the oldest print
3012    /// are let go first.
3013    #[test]
3014    fn the_looks_of_prints_beyond_the_held_count_are_let_go_oldest_first() {
3015        let indexes = GcodeIndexes::default();
3016        let now = Timestamp::now();
3017        let mut prints: Vec<PrintId> = (0..=HELD_INDEXES).map(|_| PrintId::new()).collect();
3018        prints.sort_unstable();
3019        for print in &prints {
3020            indexes.note_look(*print, now, 1, now);
3021        }
3022
3023        assert!(held(&indexes, prints[0]).is_empty());
3024        for print in &prints[1..] {
3025            assert_eq!(held(&indexes, *print), vec![(now, 1)]);
3026        }
3027    }
3028}