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