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