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 periodic observation or a look at this print was
653    /// given, as that observation or look states its capture time.
654    pub since: Timestamp,
655    /// Two heights of the print's highest point, in millimetres: the first
656    /// is where the plan had it when that frame was captured, the second how
657    /// far it should have risen since — the rise of every layer since that
658    /// lays anything but supports. They are the plate's, not every part's: a
659    /// part the plan has finished does not grow with it.
660    pub mm: [f64; 2],
661}
662
663/// A setting in force that the plan at this height says is wrong for what is
664/// being laid.
665#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
666#[serde(crate = "printobserver_types::serde", rename_all = "snake_case")]
667#[schemars(crate = "printobserver_types::schemars")]
668pub enum PlanMismatch {
669    /// The part-cooling fan is off while the current layer or the few below
670    /// it, which a frame shows, bridge or overhang.
671    FanOffOverBridges,
672    /// The flow factor is well under one while the current layer lays walls.
673    FlowLowOverWalls,
674}
675
676/// A fact of the plan the print's file does not state.
677#[derive(
678    Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize, JsonSchema,
679)]
680#[serde(crate = "printobserver_types::serde", rename_all = "snake_case")]
681#[schemars(crate = "printobserver_types::schemars")]
682pub enum PlanFact {
683    /// The file marks no layers.
684    Layer,
685    /// The file states no final height.
686    FinalZ,
687    /// The file labels no extrusion types.
688    Types,
689    /// The file carries no estimate of the time left, by the current position.
690    MinutesLeft,
691    /// The file sets no flow factor, by the current position.
692    FlowFactor,
693    /// The file sets no part-cooling fan speed, by the current position.
694    FanPercent,
695    /// The file labels no objects.
696    Objects,
697    /// No frame of this print is half an hour old with a position to rise
698    /// from, so how far the parts should have grown is not known, and no
699    /// growth can be judged from frames closer together.
700    Rise,
701}
702
703/// What the slicer planned at the print's current file position: the shape
704/// and place of what should be printing, read from the print's own G-code.
705///
706/// These are the slicer's plan rather than an observation: a feature named
707/// here is part of the design at this height, and nothing here says how well
708/// it printed.
709#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
710#[serde(crate = "printobserver_types::serde", deny_unknown_fields)]
711#[schemars(crate = "printobserver_types::schemars")]
712pub struct SlicerPlan {
713    /// The layer the print is in, counting the first as 1; absent before the
714    /// first.
715    #[serde(default, skip_serializing_if = "Option::is_none")]
716    pub layer: Option<usize>,
717    /// The current layer's height, in millimetres.
718    #[serde(default, skip_serializing_if = "Option::is_none")]
719    pub z_mm: Option<f64>,
720    /// The final layer's height, in millimetres.
721    #[serde(default, skip_serializing_if = "Option::is_none")]
722    pub final_z_mm: Option<f64>,
723    /// What the current layer lays material as, in the order the file first
724    /// names each: `Perimeter`, `Support material`, `Bridge infill`.
725    #[serde(default, skip_serializing_if = "Vec::is_empty")]
726    pub types: Vec<String>,
727    /// The slicer's own estimate of the minutes left, at the current position.
728    #[serde(default, skip_serializing_if = "Option::is_none")]
729    pub minutes_left: Option<i64>,
730    /// The flow factor, one meaning one hundred percent.
731    #[serde(default, skip_serializing_if = "Option::is_none")]
732    pub flow_factor: Option<SetValue>,
733    /// The part-cooling fan speed, in percent.
734    #[serde(default, skip_serializing_if = "Option::is_none")]
735    pub fan_percent: Option<SetValue>,
736    /// How many objects the file lays down; absent when it labels none.
737    #[serde(default, skip_serializing_if = "Option::is_none")]
738    pub object_count: Option<usize>,
739    /// The bed area each object the file lays down covers, unnamed, as
740    /// `[x_min, y_min, x_max, y_max]` in whole millimetres, in the order of
741    /// the file's object numbers.
742    #[serde(default, skip_serializing_if = "Vec::is_empty")]
743    pub objects: Vec<BedArea>,
744    /// How far the plan has risen since an earlier frame; absent before any
745    /// frame is half an hour old.
746    #[serde(default, skip_serializing_if = "Option::is_none")]
747    pub rise: Option<Rise>,
748    /// Each setting in force the plan at this height says is wrong.
749    #[serde(default, skip_serializing_if = "Vec::is_empty")]
750    pub at_odds: Vec<PlanMismatch>,
751    /// The facts the file does not state, which are therefore unknown rather
752    /// than absent.
753    #[serde(default, skip_serializing_if = "Vec::is_empty")]
754    pub unknown: Vec<PlanFact>,
755}
756
757impl Sample for SlicerPlan {
758    fn sample_full() -> Self {
759        Self {
760            layer: Some(12),
761            z_mm: Some(2.4),
762            types: vec![
763                "Perimeter".to_owned(),
764                "External perimeter".to_owned(),
765                "Support material".to_owned(),
766            ],
767            final_z_mm: Some(30.0),
768            minutes_left: Some(42),
769            flow_factor: Some(SetValue {
770                file: Some(1.0),
771                changed: Some(0.95),
772            }),
773            fan_percent: Some(SetValue {
774                file: Some(100.0),
775                changed: None,
776            }),
777            object_count: Some(1),
778            objects: vec![[100, 99, 150, 117]],
779            rise: Some(Rise {
780                since: Timestamp::sample_full(),
781                mm: [7.2, 4.8],
782            }),
783            at_odds: vec![PlanMismatch::FlowLowOverWalls],
784            unknown: vec![PlanFact::Objects],
785        }
786    }
787
788    fn sample_minimal() -> Self {
789        Self {
790            layer: None,
791            z_mm: None,
792            final_z_mm: None,
793            types: Vec::new(),
794            minutes_left: None,
795            flow_factor: None,
796            fan_percent: None,
797            object_count: None,
798            objects: Vec::new(),
799            rise: None,
800            at_odds: Vec::new(),
801            unknown: Vec::new(),
802        }
803    }
804}
805
806/// How a coordinate is read: as a place, or as a distance from the last one.
807#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]
808enum Positioning {
809    /// A place: `M82` for `E`, `G90` for the axes. What a firmware starts in.
810    #[default]
811    Absolute,
812    /// A distance: `M83` for `E`, `G91` for the axes.
813    Relative,
814}
815
816/// Builds a [`GcodeIndex`] from a file streamed into it, a piece at a time,
817/// in one pass: the [`GcodeSink`] the printer port's whole-file read feeds.
818#[derive(Debug, Default)]
819pub struct IndexBuilder {
820    /// The line being read, up to [`LINE_LIMIT`].
821    line: Vec<u8>,
822    /// Whether the line being read has run past [`LINE_LIMIT`].
823    overlong: bool,
824    /// How many bytes have been read.
825    read: u64,
826    /// How many lines have been read.
827    lines: u64,
828    /// Every layer so far.
829    layers: Vec<Layer>,
830    /// The extrusion types so far.
831    type_names: Vec<String>,
832    /// Whether any type was named.
833    labelled_types: bool,
834    /// The type the moves being read extrude, as a bit of the type table.
835    current_type: Option<usize>,
836    /// The time estimates so far.
837    time_left: Vec<Mark<i64>>,
838    /// The flow factors so far.
839    flow: Vec<Mark<f64>>,
840    /// The fan speeds so far.
841    fan: Vec<Mark<f64>>,
842    /// Every object labelled so far, in the order first labelled.
843    objects: Vec<ObjectDraft>,
844    /// Where each object's number is in `objects`.
845    object_numbers: BTreeMap<i64, usize>,
846    /// The object the moves being read lay material for, by its place in
847    /// `objects`.
848    current_object: Option<usize>,
849    /// Whether any object was labelled.
850    labelled_objects: bool,
851    /// Where the head is in X, Y and Z.
852    at: [f64; 3],
853    /// The extruder's position.
854    e: f64,
855    /// What `G90`/`G91` last said.
856    axes: Positioning,
857    /// What `M82`/`M83` last said.
858    extruder: Positioning,
859    /// Where the line being read began.
860    line_began: u64,
861    /// How far the part's extrusion reached, for a file labelling no object.
862    all: Reach,
863    /// Where each labelled object's block starts, and its place in
864    /// `objects`.
865    blocks: Vec<(u64, usize)>,
866    /// Where the file's bytes are copied as they are read.
867    spool: Option<Spooling>,
868    /// The segments of a toolpath read, when this builder is one.
869    collected: Option<Vec<ToolpathSegment>>,
870    /// Where the last move an outline reached ended.
871    reached_last: Option<[f64; 2]>,
872}
873
874/// A spool being written.
875#[derive(Debug)]
876struct Spooling {
877    /// The spool file, removed again when any write to it fails.
878    path: std::path::PathBuf,
879    /// The open file, buffered.
880    writer: std::io::BufWriter<std::fs::File>,
881    /// Whether a write failed, which leaves no spool.
882    failed: bool,
883}
884
885impl GcodeSink for IndexBuilder {
886    fn take(&mut self, piece: &[u8]) -> ControlFlow<()> {
887        // Plain index loops rather than iterator adaptors throughout this
888        // reader: it runs over every byte of a print, and is as fast in a
889        // build without optimisation as in one with it only written so.
890        // A write the filesystem refuses — a full disk — is proved by no test:
891        // making one fail needs a filesystem made to fail mid-stream, which no
892        // host the suite runs on offers without privileges. What it leads to
893        // is the same index with no spool, which
894        // `a_spool_that_cannot_be_created_leaves_the_plan_without_toolpaths`
895        // proves end to end.
896        if let Some(spool) = self.spool.as_mut().filter(|spool| !spool.failed) {
897            use std::io::Write as _;
898            spool.failed = spool.writer.write_all(piece).is_err();
899        }
900        let mut start = 0;
901        let mut at = 0;
902        while at < piece.len() {
903            if piece[at] == b'\n' {
904                let head = &piece[start..at];
905                self.read += u64::try_from(at + 1 - start).unwrap_or(u64::MAX);
906                if self.line.is_empty() && !self.overlong {
907                    // The whole line is in this piece: read it where it lies.
908                    self.lines += 1;
909                    if head.len() <= LINE_LIMIT {
910                        self.read_line(head);
911                    }
912                } else {
913                    self.hold(head);
914                    self.end_line();
915                }
916                self.line_began = self.read;
917                start = at + 1;
918            }
919            at += 1;
920        }
921        let rest = &piece[start..];
922        self.hold(rest);
923        self.read += u64::try_from(rest.len()).unwrap_or(u64::MAX);
924        ControlFlow::Continue(())
925    }
926}
927
928impl IndexBuilder {
929    /// A builder that has read nothing.
930    #[must_use]
931    pub fn new() -> Self {
932        Self::default()
933    }
934
935    /// A builder that has read nothing and copies every byte it is given to
936    /// a spool file at `path`, created or truncated now, which the index it
937    /// builds reads each layer's toolpath back from.
938    ///
939    /// # Errors
940    ///
941    /// The filesystem's own error when the file cannot be created.
942    pub fn spooling(path: std::path::PathBuf) -> std::io::Result<Self> {
943        let file = std::fs::File::create(&path)?;
944        Ok(Self {
945            spool: Some(Spooling {
946                path,
947                writer: std::io::BufWriter::with_capacity(1 << 16, file),
948                failed: false,
949            }),
950            ..Self::default()
951        })
952    }
953
954    /// A builder reading one layer's bytes from where the reader stood at
955    /// its start, collecting its extrusion moves.
956    fn reading_layer(type_names: Vec<String>, head: Head) -> Self {
957        Self {
958            type_names,
959            labelled_types: true,
960            current_type: head.current_type,
961            at: head.at,
962            e: head.e,
963            axes: head.axes,
964            extruder: head.extruder,
965            collected: Some(Vec::new()),
966            ..Self::default()
967        }
968    }
969
970    /// The index of everything read, the file's last line counting whether or
971    /// not it ended in a newline.
972    #[must_use]
973    pub fn finish(mut self) -> GcodeIndex {
974        if !self.line.is_empty() || self.overlong {
975            self.end_line();
976        }
977        let mut drafts: Vec<Option<ObjectDraft>> = self.objects.into_iter().map(Some).collect();
978        let mut objects = Vec::new();
979        let mut outlines = Vec::new();
980        let mut outline_of = vec![None; drafts.len()];
981        for place in self.object_numbers.into_values() {
982            let Some(draft) = drafts.get_mut(place).and_then(Option::take) else {
983                continue;
984            };
985            let Some([least_x, least_y, most_x, most_y]) = draft.bounds else {
986                continue;
987            };
988            objects.push([
989                whole(tenth(least_x).floor()),
990                whole(tenth(least_y).floor()),
991                whole(tenth(most_x).ceil()),
992                whole(tenth(most_y).ceil()),
993            ]);
994            outline_of[place] = Some(outlines.len());
995            outlines.push(draft.reach.outline().unwrap_or(ObjectOutline {
996                hull_mm: Vec::new(),
997            }));
998        }
999        if !self.labelled_objects {
1000            outlines.extend(self.all.outline());
1001        }
1002        let blocks = self
1003            .blocks
1004            .into_iter()
1005            .map(|(start, place)| (start, outline_of.get(place).copied().flatten()))
1006            .collect();
1007        let spool = self.spool.and_then(|mut spool| {
1008            use std::io::Write as _;
1009            if spool.failed || spool.writer.flush().is_err() {
1010                drop(spool.writer);
1011                let _ = std::fs::remove_file(&spool.path);
1012                return None;
1013            }
1014            Some(spool.path)
1015        });
1016        GcodeIndex {
1017            bytes: self.read,
1018            lines: self.lines,
1019            layers: self.layers,
1020            type_names: self.type_names,
1021            labelled_types: self.labelled_types,
1022            time_left: self.time_left,
1023            flow: self.flow,
1024            fan: self.fan,
1025            objects,
1026            labelled_objects: self.labelled_objects,
1027            outlines,
1028            blocks,
1029            spool,
1030        }
1031    }
1032
1033    /// Hold more of the line being read, up to its bound.
1034    fn hold(&mut self, bytes: &[u8]) {
1035        if self.overlong {
1036            return;
1037        }
1038        if self.line.len() + bytes.len() > LINE_LIMIT {
1039            self.overlong = true;
1040            self.line.clear();
1041            return;
1042        }
1043        self.line.extend_from_slice(bytes);
1044    }
1045
1046    /// Read the line held, which ended at the offset read so far.
1047    fn end_line(&mut self) {
1048        self.lines += 1;
1049        let line = core::mem::take(&mut self.line);
1050        if !self.overlong {
1051            self.read_line(&line);
1052        }
1053        self.overlong = false;
1054        self.line = line;
1055        self.line.clear();
1056    }
1057
1058    /// Read one whole line, without its newline.
1059    fn read_line(&mut self, raw: &[u8]) {
1060        let raw = raw.trim_ascii();
1061        if let Some(comment) = raw.strip_prefix(b";") {
1062            if let Ok(comment) = core::str::from_utf8(comment) {
1063                self.comment(comment.trim_end());
1064            }
1065            return;
1066        }
1067        // A move is nearly every line of a print, so `G0`–`G3` written as a
1068        // slicer writes them are read by their own one pass.
1069        if let [b'G', code @ b'0'..=b'3', b' ', rest @ ..] = raw {
1070            self.motion(u32::from(code - b'0'), &move_of(rest));
1071            return;
1072        }
1073        let held = words(raw);
1074        let mut words = held.as_slice();
1075        // A leading `N<line number>` numbers the line and is no word of it.
1076        if let Some((Word { letter: b'N', .. }, rest)) = words.split_first() {
1077            words = rest;
1078        }
1079        let Some(first) = words.first() else {
1080            return;
1081        };
1082        let code = if held.numbered {
1083            held.second_code
1084        } else {
1085            held.first_code
1086        };
1087        match (char::from(first.letter), code) {
1088            ('G', Some(code @ 0..=3)) => self.motion(code, &Move::of(&words[1..])),
1089            ('G', Some(28)) => self.home(&words[1..]),
1090            ('G', Some(90)) => self.axes = Positioning::Absolute,
1091            ('G', Some(91)) => self.axes = Positioning::Relative,
1092            ('G', Some(92)) => self.declare(&words[1..]),
1093            ('M', Some(82)) => self.extruder = Positioning::Absolute,
1094            ('M', Some(83)) => self.extruder = Positioning::Relative,
1095            ('M', Some(73)) => self.estimate(&words[1..]),
1096            ('M', Some(221)) => self.flow_factor(&words[1..]),
1097            ('M', Some(106)) => self.fan_speed(&words[1..], Fan::Set),
1098            ('M', Some(107)) => self.fan_speed(&words[1..], Fan::Off),
1099            ('M', Some(486)) => self.object(raw, &words[1..]),
1100            _ => {}
1101        }
1102    }
1103
1104    /// A comment line: a layer change, a height, or an extrusion type.
1105    fn comment(&mut self, comment: &str) {
1106        if comment == "LAYER_CHANGE" {
1107            self.layers.push(Layer {
1108                begins: self.line_began,
1109                head: Head {
1110                    at: self.at,
1111                    e: self.e,
1112                    axes: self.axes,
1113                    extruder: self.extruder,
1114                    current_type: self.current_type,
1115                },
1116                at: self.read,
1117                z_mm: None,
1118                types: 0,
1119            });
1120        } else if let Some(z) = comment.strip_prefix("Z:") {
1121            if let Some(layer) = self.layers.last_mut()
1122                && layer.z_mm.is_none()
1123            {
1124                // A height is a place on the Z axis: no lower than the bed and
1125                // no further than any machine reaches.
1126                layer.z_mm = z
1127                    .trim()
1128                    .parse::<f64>()
1129                    .ok()
1130                    .filter(|z| (0.0..=AXIS_LIMIT).contains(z));
1131            }
1132        } else if let Some(name) = comment.strip_prefix("TYPE:") {
1133            let name = name.trim();
1134            self.labelled_types = true;
1135            self.current_type = if name == NOT_THE_PART {
1136                None
1137            } else {
1138                self.intern(name)
1139            };
1140        }
1141    }
1142
1143    /// The bit of the type table one name is, adding it when there is room.
1144    fn intern(&mut self, name: &str) -> Option<usize> {
1145        if let Some(bit) = self.type_names.iter().position(|held| held == name) {
1146            return Some(bit);
1147        }
1148        if self.type_names.len() >= TYPE_LIMIT {
1149            return None;
1150        }
1151        self.type_names.push(name.to_owned());
1152        Some(self.type_names.len() - 1)
1153    }
1154
1155    /// A move: where the head goes, and whether it laid material on the way.
1156    fn motion(&mut self, code: u32, words: &Move) {
1157        // Plain statements rather than iterators and closures: this runs for
1158        // every move of a print.
1159        let start = self.at;
1160        let relative = self.axes == Positioning::Relative;
1161        if let Some(x) = words.x {
1162            self.place(0, x, relative);
1163        }
1164        if let Some(y) = words.y {
1165            self.place(1, y, relative);
1166        }
1167        if let Some(z) = words.z {
1168            self.place(2, z, relative);
1169        }
1170        let mut fed = 0.0;
1171        if let Some(value) = words.e {
1172            if relative || self.extruder == Positioning::Relative {
1173                self.e += value;
1174                fed = value;
1175            } else {
1176                fed = value - self.e;
1177                self.e = value;
1178            }
1179        }
1180        let travel = (self.at[0] - start[0]).hypot(self.at[1] - start[1]);
1181        if fed <= 0.0 || (travel <= TRAVEL_MM && code < 2) {
1182            return;
1183        }
1184        if let (Some(layer), Some(bit)) = (self.layers.last_mut(), self.current_type) {
1185            layer.types |= 1 << bit;
1186        }
1187        let end = self.at;
1188        let turn = match code {
1189            2 => Some(Turn::Clockwise),
1190            3 => Some(Turn::CounterClockwise),
1191            _ => None,
1192        };
1193        let arc = turn.and_then(|turn| arc_of(words, turn, start, end));
1194        if let Some(collected) = self.collected.as_mut() {
1195            let kind = self
1196                .current_type
1197                .and_then(|bit| self.type_names.get(bit))
1198                .map_or(ExtrusionKind::Other, |name| ExtrusionKind::of_type(name));
1199            collect_segments(collected, kind, start, end, arc);
1200            return;
1201        }
1202        let part_of_plan = !(self.labelled_types && self.current_type.is_none());
1203        let reach = if let Some(object) = self.current_object {
1204            let draft = &mut self.objects[object];
1205            grow(&mut draft.bounds, start[0], start[1]);
1206            grow(&mut draft.bounds, end[0], end[1]);
1207            if let Some(turn) = turn {
1208                for [x, y] in arc_extremes(words, turn, start, end) {
1209                    grow(&mut draft.bounds, x, y);
1210                }
1211            }
1212            &mut draft.reach
1213        } else if !self.labelled_objects && part_of_plan {
1214            &mut self.all
1215        } else {
1216            return;
1217        };
1218        // A move continuing the last one starts where that one ended, which
1219        // has been reached already.
1220        if self.reached_last != Some([start[0], start[1]]) {
1221            reach.point(start[0], start[1]);
1222        }
1223        reach.point(end[0], end[1]);
1224        self.reached_last = Some([end[0], end[1]]);
1225        if let Some(arc) = arc {
1226            reach.arc(arc.centre, arc.radius, arc.base, arc.sweep);
1227        }
1228    }
1229
1230    /// Move one axis to a place, or by a distance, when where it lands is
1231    /// within reach: a run of distances each within reach can carry the head
1232    /// past it, and a place beyond it is no place a head can be.
1233    fn place(&mut self, axis: usize, value: f64, relative: bool) {
1234        let landed = if relative {
1235            self.at[axis] + value
1236        } else {
1237            value
1238        };
1239        if landed.abs() <= AXIS_LIMIT {
1240            self.at[axis] = landed;
1241        }
1242    }
1243
1244    /// `G28`: the axes it names, or every axis when it names none, go home.
1245    fn home(&mut self, words: &[Word]) {
1246        let named: Vec<usize> = ['X', 'Y', 'Z']
1247            .into_iter()
1248            .enumerate()
1249            .filter(|(_, letter)| words.iter().any(|word| char::from(word.letter) == *letter))
1250            .map(|(axis, _)| axis)
1251            .collect();
1252        if named.is_empty() {
1253            self.at = [0.0; 3];
1254        } else {
1255            for axis in named {
1256                self.at[axis] = 0.0;
1257            }
1258        }
1259    }
1260
1261    /// `G92`: where the named axes are, without moving them; bare, every axis
1262    /// and the extruder are at zero.
1263    fn declare(&mut self, words: &[Word]) {
1264        if words.is_empty() {
1265            self.at = [0.0; 3];
1266            self.e = 0.0;
1267            return;
1268        }
1269        for (axis, letter) in ['X', 'Y', 'Z'].into_iter().enumerate() {
1270            if let Some(value) = number(words, letter).filter(|value| value.abs() <= AXIS_LIMIT) {
1271                self.at[axis] = value;
1272            }
1273        }
1274        if let Some(value) = number(words, 'E') {
1275            self.e = value;
1276        }
1277    }
1278
1279    /// `M73`: the normal mode's estimate of the minutes left, `P` and `R`.
1280    fn estimate(&mut self, words: &[Word]) {
1281        if number(words, 'P').is_none() {
1282            return;
1283        }
1284        if let Some(minutes) = number(words, 'R').filter(|minutes| *minutes >= 0.0) {
1285            self.time_left.push(Mark {
1286                at: self.read,
1287                value: whole(minutes),
1288            });
1289        }
1290    }
1291
1292    /// `M221 S<percent>`: the flow factor.
1293    fn flow_factor(&mut self, words: &[Word]) {
1294        if let Some(percent) = number(words, 'S').filter(|percent| *percent >= 0.0) {
1295            mark_setting(&mut self.flow, self.read, percent / 100.0);
1296        }
1297    }
1298
1299    /// `M106 S<speed>` or `M107`: the part-cooling fan, in percent.
1300    fn fan_speed(&mut self, words: &[Word], command: Fan) {
1301        if number(words, 'P').is_some_and(|fan| fan != 0.0) {
1302            return;
1303        }
1304        let speed = match command {
1305            Fan::Off => 0.0,
1306            Fan::Set => number(words, 'S').unwrap_or(FAN_FULL),
1307        };
1308        let percent = (speed.clamp(0.0, FAN_FULL) / FAN_FULL * 100.0).round();
1309        mark_setting(&mut self.fan, self.read, percent);
1310    }
1311
1312    /// `M486`: an object starting, stopping, or being named.
1313    fn object(&mut self, raw: &[u8], words: &[Word]) {
1314        // A name labels the file's objects, though none is kept: an object is
1315        // its place on the bed.
1316        if raw
1317            .strip_prefix(b"M486")
1318            .is_some_and(|rest| rest.trim_ascii_start().starts_with(b"A"))
1319        {
1320            self.labelled_objects = true;
1321            return;
1322        }
1323        // An object is a whole number, and `-1` alone stops laying one down;
1324        // any other number names no object and changes nothing.
1325        let Some(number) = number(words, 'S')
1326            .filter(|number| (number - number.round()).abs() < f64::EPSILON && *number >= -1.0)
1327        else {
1328            return;
1329        };
1330        self.labelled_objects = true;
1331        if number < 0.0 {
1332            self.current_object = None;
1333            self.reached_last = None;
1334            return;
1335        }
1336        let id = whole(number);
1337        let place = if let Some(place) = self.object_numbers.get(&id) {
1338            *place
1339        } else if self.objects.len() >= OBJECT_LIMIT {
1340            self.current_object = None;
1341            self.reached_last = None;
1342            return;
1343        } else {
1344            self.objects.push(ObjectDraft::default());
1345            self.object_numbers.insert(id, self.objects.len() - 1);
1346            self.objects.len() - 1
1347        };
1348        self.current_object = Some(place);
1349        self.reached_last = None;
1350        self.blocks.push((self.read, place));
1351    }
1352}
1353
1354/// Record a value a file set, where it set it — every time, the same value
1355/// included, because a command repeating a value still puts it back over a
1356/// change made since.
1357fn mark_setting(marks: &mut Vec<Mark<f64>>, at: u64, value: f64) {
1358    marks.push(Mark { at, value });
1359}
1360
1361/// The whole number nearest a value a file wrote, which every word is
1362/// bounded well inside [`i64`] by.
1363fn whole(value: f64) -> i64 {
1364    format!("{:.0}", value.round()).parse().unwrap_or_default()
1365}
1366
1367/// A length rounded to a tenth of a millimetre before a bed area is widened
1368/// to whole millimetres, so that an arc's extreme computed a hair past a whole
1369/// number does not widen it by a millimetre more.
1370fn tenth(value: f64) -> f64 {
1371    (value * 10.0).round() / 10.0
1372}
1373
1374/// Grow a rectangle to reach a point.
1375fn grow(bounds: &mut Option<[f64; 4]>, x: f64, y: f64) {
1376    *bounds = Some(match *bounds {
1377        None => [x, y, x, y],
1378        Some([least_x, least_y, most_x, most_y]) => {
1379            [least_x.min(x), least_y.min(y), most_x.max(x), most_y.max(y)]
1380        }
1381    });
1382}
1383
1384/// Which way an arc turns: `G2` clockwise, `G3` counter-clockwise.
1385#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1386enum Turn {
1387    /// `G2`.
1388    Clockwise,
1389    /// `G3`.
1390    CounterClockwise,
1391}
1392
1393/// What a part-cooling fan command does: `M106` sets a speed, `M107` turns
1394/// the fan off.
1395#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1396enum Fan {
1397    /// `M106`, at its `S` speed or full.
1398    Set,
1399    /// `M107`.
1400    Off,
1401}
1402
1403/// The points of an arc's circle at which it reaches furthest along X or Y,
1404/// of the part of the circle the arc sweeps: what an arc lays beyond its two
1405/// ends.
1406///
1407/// The centre is the one `I` and `J` name, or for the `R` form the one on the
1408/// side of the chord the direction and the radius's sign choose. `G2` sweeps
1409/// clockwise and `G3` counter-clockwise; an arc ending where it began is the
1410/// whole circle.
1411fn arc_extremes(
1412    words: &Move,
1413    turn: Turn,
1414    start: [f64; 3],
1415    end: [f64; 3],
1416) -> impl Iterator<Item = [f64; 2]> {
1417    let reach = arc_of(words, turn, start, end).map(|arc| {
1418        let ArcGeometry {
1419            centre,
1420            radius,
1421            base,
1422            sweep,
1423            ..
1424        } = arc;
1425        let tau = core::f64::consts::TAU;
1426        (0..4).filter_map(move |quarter| {
1427            let angle = core::f64::consts::FRAC_PI_2 * f64::from(quarter);
1428            ((angle - base).rem_euclid(tau) <= sweep + 1e-9).then(|| {
1429                [
1430                    centre[0] + radius * angle.cos(),
1431                    centre[1] + radius * angle.sin(),
1432                ]
1433            })
1434        })
1435    });
1436    reach.into_iter().flatten()
1437}
1438
1439/// One arc's circle and the part of it swept.
1440#[derive(Debug, Clone, Copy)]
1441struct ArcGeometry {
1442    /// The circle's centre in bed mm, from `I`/`J` or the `R` form.
1443    centre: [f64; 2],
1444    /// The distance from that centre to the move's start, in mm.
1445    radius: f64,
1446    /// The angle the sweep starts at, counter-clockwise: the arc's start for
1447    /// `G3`, its end for `G2`.
1448    base: f64,
1449    /// How far it turns, as a positive angle; a whole turn for an arc ending
1450    /// where it began.
1451    sweep: f64,
1452    /// The direction it is laid in.
1453    turn: Turn,
1454}
1455
1456/// The circle an arc lies on and the part of it swept: the centre `I` and `J`
1457/// name, or for the `R` form the one [`centre_of_radius`] finds. Nothing for
1458/// an `R` arc with no circle.
1459fn arc_of(words: &Move, turn: Turn, start: [f64; 3], end: [f64; 3]) -> Option<ArcGeometry> {
1460    let centre = words.r.map_or_else(
1461        || {
1462            Some([
1463                start[0] + words.i.unwrap_or(0.0),
1464                start[1] + words.j.unwrap_or(0.0),
1465            ])
1466        },
1467        |radius| centre_of_radius(radius, turn, start, end),
1468    )?;
1469    let radius = (start[0] - centre[0]).hypot(start[1] - centre[1]);
1470    let from = (start[1] - centre[1]).atan2(start[0] - centre[0]);
1471    let to = (end[1] - centre[1]).atan2(end[0] - centre[0]);
1472    let tau = core::f64::consts::TAU;
1473    // How far the arc turns, counter-clockwise from `base`, as a positive
1474    // sweep: a clockwise arc is the same sweep taken from its end.
1475    let (base, sweep) = match turn {
1476        Turn::Clockwise => (to, (from - to).rem_euclid(tau)),
1477        Turn::CounterClockwise => (from, (to - from).rem_euclid(tau)),
1478    };
1479    let sweep = if sweep < 1e-9 { tau } else { sweep };
1480    Some(ArcGeometry {
1481        centre,
1482        radius,
1483        base,
1484        sweep,
1485        turn,
1486    })
1487}
1488
1489/// A move's toolpath segments: the move itself, or an arc cut into chords
1490/// of at most [`CHORD_MM`] from its start to its end, in the direction laid.
1491fn collect_segments(
1492    collected: &mut Vec<ToolpathSegment>,
1493    kind: ExtrusionKind,
1494    start: [f64; 3],
1495    end: [f64; 3],
1496    arc: Option<ArcGeometry>,
1497) {
1498    #[expect(
1499        clippy::cast_possible_truncation,
1500        reason = "bed millimetres are far inside f32's range; a toolpath is drawn, not measured"
1501    )]
1502    let at = |x: f64, y: f64| [x as f32, y as f32];
1503    let Some(arc) = arc else {
1504        collected.push(ToolpathSegment {
1505            from_mm: at(start[0], start[1]),
1506            to_mm: at(end[0], end[1]),
1507            kind,
1508        });
1509        return;
1510    };
1511    let length = arc.sweep * arc.radius;
1512    let chords = (length / CHORD_MM).ceil().clamp(1.0, 4096.0);
1513    let (from, step) = match arc.turn {
1514        Turn::CounterClockwise => (arc.base, arc.sweep / chords),
1515        Turn::Clockwise => (arc.base + arc.sweep, -arc.sweep / chords),
1516    };
1517    let mut previous = at(start[0], start[1]);
1518    let mut k = 1.0;
1519    while k < chords {
1520        let angle = from + step * k;
1521        let next = at(
1522            arc.centre[0] + arc.radius * angle.cos(),
1523            arc.centre[1] + arc.radius * angle.sin(),
1524        );
1525        collected.push(ToolpathSegment {
1526            from_mm: previous,
1527            to_mm: next,
1528            kind,
1529        });
1530        previous = next;
1531        k += 1.0;
1532    }
1533    collected.push(ToolpathSegment {
1534        from_mm: previous,
1535        to_mm: at(end[0], end[1]),
1536        kind,
1537    });
1538}
1539
1540/// The centre of an `R`-form arc: on the chord's perpendicular, on the side a
1541/// clockwise or counter-clockwise turn of a short arc puts it, and on the other
1542/// side for a negative radius, which asks for the long way round. Nothing when
1543/// the chord is longer than the circle allows, or the arc ends where it began.
1544fn centre_of_radius(radius: f64, turn: Turn, start: [f64; 3], end: [f64; 3]) -> Option<[f64; 2]> {
1545    let chord = [end[0] - start[0], end[1] - start[1]];
1546    let length = chord[0].hypot(chord[1]);
1547    if length <= TRAVEL_MM || length > 2.0 * radius.abs() {
1548        return None;
1549    }
1550    let rise = (radius * radius - length * length / 4.0).max(0.0).sqrt();
1551    let left = match turn {
1552        Turn::Clockwise => -1.0,
1553        Turn::CounterClockwise => 1.0,
1554    };
1555    let side = left * radius.signum() * rise / length;
1556    Some([
1557        start[0] + chord[0] / 2.0 - chord[1] * side,
1558        start[1] + chord[1] / 2.0 + chord[0] * side,
1559    ])
1560}
1561
1562/// The words of a command, each a letter, the text after it and the number
1563/// that text is when it is one, up to [`WORD_COUNT`] of them: up to the `;`
1564/// a comment starts at or the `*` a checksum does.
1565///
1566/// Each number is read by [`number_at`].
1567fn words(command: &[u8]) -> Words {
1568    let mut found = Words {
1569        held: [Word {
1570            letter: 0,
1571            value: f64::NAN,
1572        }; WORD_COUNT],
1573        len: 0,
1574        first_code: None,
1575        second_code: None,
1576        numbered: false,
1577    };
1578    let length = command.len();
1579    let mut at = 0;
1580    while at < length {
1581        let letter = command[at];
1582        if letter == b';' || letter == b'*' {
1583            break;
1584        }
1585        at += 1;
1586        let upper = match letter {
1587            b'a'..=b'z' => letter - (b'a' - b'A'),
1588            b'A'..=b'Z' => letter,
1589            _ => continue,
1590        };
1591        let start = at;
1592        let (value, next) = number_at(command, at);
1593        at = next;
1594        let text = &command[start..at];
1595        // A command's code is the first word's, or the second's after a
1596        // line number, read as the whole number it is written as.
1597        if found.len == 0 {
1598            found.first_code = whole_number(text);
1599            found.numbered = upper == b'N';
1600        } else if found.len == 1 {
1601            found.second_code = whole_number(text);
1602        }
1603        if found.len < WORD_COUNT {
1604            found.held[found.len] = Word {
1605                letter: upper,
1606                value,
1607            };
1608            found.len += 1;
1609        }
1610    }
1611    found
1612}
1613
1614/// The number a word carries, read from `at` to the next space, letter, `;`
1615/// or `*`, and the offset just past it; a word that is no number is not a
1616/// number.
1617///
1618/// The end is found with a plain loop rather than an iterator adaptor, and the
1619/// number is read by the standard library's own parse, which is compiled
1620/// optimised whatever this crate is built as: this runs for every number of
1621/// every move of a print.
1622fn number_at(line: &[u8], mut at: usize) -> (f64, usize) {
1623    let start = at;
1624    while at < line.len()
1625        && !matches!(line[at], b' ' | b'\t' | b';' | b'*' | b'A'..=b'Z' | b'a'..=b'z')
1626    {
1627        at += 1;
1628    }
1629    (decimal(&line[start..at]).unwrap_or(f64::NAN), at)
1630}
1631
1632/// The words of a move this reader uses, each a number within reach when the
1633/// move carries it: where it goes, what it feeds, and an arc's centre or
1634/// radius.
1635#[derive(Debug, Clone, Copy, Default)]
1636struct Move {
1637    /// `X`.
1638    x: Option<f64>,
1639    /// `Y`.
1640    y: Option<f64>,
1641    /// `Z`.
1642    z: Option<f64>,
1643    /// `E`.
1644    e: Option<f64>,
1645    /// `I`.
1646    i: Option<f64>,
1647    /// `J`.
1648    j: Option<f64>,
1649    /// `R`.
1650    r: Option<f64>,
1651}
1652
1653impl Move {
1654    /// A move's words, from a command read word by word.
1655    fn of(words: &[Word]) -> Self {
1656        Self {
1657            x: number(words, 'X'),
1658            y: number(words, 'Y'),
1659            z: number(words, 'Z'),
1660            e: number(words, 'E'),
1661            i: number(words, 'I'),
1662            j: number(words, 'J'),
1663            r: number(words, 'R'),
1664        }
1665    }
1666}
1667
1668/// A move's words, read in one pass from what follows its `G0`–`G3`: the
1669/// first of each letter it uses, up to the `;` a comment starts at or the `*`
1670/// a checksum does. Every other word — the feedrate above all — is passed
1671/// over unread, which is what keeps this the cheap path through a print.
1672fn move_of(line: &[u8]) -> Move {
1673    let mut found = Move::default();
1674    let length = line.len();
1675    let mut at = 0;
1676    while at < length {
1677        let letter = line[at];
1678        at += 1;
1679        let slot = match letter {
1680            b';' | b'*' => break,
1681            b'X' | b'x' => &mut found.x,
1682            b'Y' | b'y' => &mut found.y,
1683            b'Z' | b'z' => &mut found.z,
1684            b'E' | b'e' => &mut found.e,
1685            b'I' | b'i' => &mut found.i,
1686            b'J' | b'j' => &mut found.j,
1687            b'R' | b'r' => &mut found.r,
1688            b'A'..=b'Z' | b'a'..=b'z' => {
1689                while at < length && !matches!(line[at], b' ' | b'\t' | b';' | b'*') {
1690                    at += 1;
1691                }
1692                continue;
1693            }
1694            _ => continue,
1695        };
1696        let (value, next) = number_at(line, at);
1697        at = next;
1698        if slot.is_none() {
1699            *slot = Some(value).filter(|value| value.is_finite() && value.abs() <= WORD_LIMIT);
1700        }
1701    }
1702    found
1703}
1704
1705/// One word of a command: its letter, upper-cased, and the number it carries,
1706/// not a number when it carries none.
1707#[derive(Debug, Clone, Copy)]
1708struct Word {
1709    /// The letter.
1710    letter: u8,
1711    /// The number, `NaN` when the word's text is none.
1712    value: f64,
1713}
1714
1715/// One command's words, held without allocating.
1716struct Words {
1717    /// The words, the first `len` of them read.
1718    held: [Word; WORD_COUNT],
1719    /// How many were read.
1720    len: usize,
1721    /// The first word's text, as a whole number when it is one.
1722    first_code: Option<u32>,
1723    /// The second word's text, as a whole number when it is one.
1724    second_code: Option<u32>,
1725    /// Whether the first word is a line number.
1726    numbered: bool,
1727}
1728
1729impl Words {
1730    /// The words read.
1731    fn as_slice(&self) -> &[Word] {
1732        &self.held[..self.len]
1733    }
1734}
1735
1736/// The whole number a command's code is, when it is digits alone.
1737fn whole_number(text: &[u8]) -> Option<u32> {
1738    let mut value: u32 = 0;
1739    let mut at = 0;
1740    while at < text.len() {
1741        let byte = text[at];
1742        if !byte.is_ascii_digit() {
1743            return None;
1744        }
1745        value = value.checked_mul(10)?.checked_add(u32::from(byte - b'0'))?;
1746        at += 1;
1747    }
1748    (!text.is_empty()).then_some(value)
1749}
1750
1751/// The number a word's text is, by the standard library's own parse.
1752fn decimal(text: &[u8]) -> Option<f64> {
1753    core::str::from_utf8(text).ok()?.parse::<f64>().ok()
1754}
1755
1756/// The number one word carries, when the command has that word and it is a
1757/// number within reach.
1758fn number(words: &[Word], letter: char) -> Option<f64> {
1759    let mut at = 0;
1760    while at < words.len() {
1761        let Word {
1762            letter: word,
1763            value,
1764        } = words[at];
1765        if char::from(word) == letter {
1766            return Some(value).filter(|value| value.is_finite() && value.abs() <= WORD_LIMIT);
1767        }
1768        at += 1;
1769    }
1770    None
1771}
1772
1773/// Build one file's index from its pieces, in order — what the whole-file
1774/// read does with the pieces it is handed.
1775#[must_use]
1776pub fn index_of(pieces: &[&[u8]]) -> GcodeIndex {
1777    let mut builder = IndexBuilder::new();
1778    for piece in pieces {
1779        let _ = builder.take(piece);
1780    }
1781    builder.finish()
1782}
1783
1784/// One print's index, as the cache holds it.
1785#[derive(Debug, Default)]
1786enum Slot {
1787    /// Nothing is built and nothing is building.
1788    #[default]
1789    Empty,
1790    /// A build is under way, and these are waiting for it.
1791    Building(Vec<Waker>),
1792    /// Built.
1793    Ready(Arc<GcodeIndex>),
1794}
1795
1796/// Every print's index, held for as long as this process runs.
1797#[derive(Debug, Default)]
1798pub struct GcodeIndexes {
1799    /// One slot per print that has been asked for.
1800    slots: Mutex<BTreeMap<PrintId, Slot>>,
1801    /// The frames each print's looks were given, by their capture time, with
1802    /// the file position the job had reached as each was taken: a look's
1803    /// record keeps no job, so a rise since one is measured from this. It is
1804    /// this process's alone, as the indexes are: a restarted one measures
1805    /// from periodic observations until its own looks are old enough.
1806    looked: Mutex<BTreeMap<PrintId, Vec<(Timestamp, i64)>>>,
1807}
1808
1809/// What asking for one print's index answered.
1810#[derive(Debug)]
1811pub enum Claimed<'a> {
1812    /// It is built.
1813    Ready(Arc<GcodeIndex>),
1814    /// Nothing is building it, and this caller is to: it holds the claim.
1815    Build(BuildClaim<'a>),
1816}
1817
1818/// The one caller building a print's index. Dropping it unfinished hands the
1819/// build to whoever asks next, and wakes everyone waiting.
1820#[derive(Debug)]
1821pub struct BuildClaim<'a> {
1822    /// The cache it was claimed from.
1823    indexes: &'a GcodeIndexes,
1824    /// The print it is building for.
1825    print_id: PrintId,
1826    /// Whether it has finished.
1827    done: bool,
1828}
1829
1830impl BuildClaim<'_> {
1831    /// Hand the built index over, waking every caller waiting for it.
1832    #[must_use]
1833    pub fn finish(mut self, index: GcodeIndex) -> Arc<GcodeIndex> {
1834        let index = Arc::new(index);
1835        self.settle(Slot::Ready(Arc::clone(&index)));
1836        self.done = true;
1837        index
1838    }
1839
1840    /// Put the slot into its next state and wake whoever waited.
1841    fn settle(&self, next: Slot) {
1842        let waiting = {
1843            let mut slots = self.indexes.held();
1844            let slot = slots.entry(self.print_id).or_default();
1845            match core::mem::replace(slot, next) {
1846                Slot::Building(waiting) => waiting,
1847                Slot::Empty | Slot::Ready(_) => Vec::new(),
1848            }
1849        };
1850        for waker in waiting {
1851            waker.wake();
1852        }
1853    }
1854}
1855
1856impl Drop for BuildClaim<'_> {
1857    fn drop(&mut self) {
1858        if !self.done {
1859            self.settle(Slot::Empty);
1860        }
1861    }
1862}
1863
1864impl GcodeIndexes {
1865    /// The slots, held for one read or write.
1866    fn held(&self) -> std::sync::MutexGuard<'_, BTreeMap<PrintId, Slot>> {
1867        self.slots.lock().unwrap_or_else(PoisonError::into_inner)
1868    }
1869
1870    /// One print's index when it is built, or the claim to build it, waiting
1871    /// while another caller is building it.
1872    pub const fn claim(&self, print_id: PrintId) -> Claim<'_> {
1873        Claim {
1874            indexes: self,
1875            print_id,
1876        }
1877    }
1878
1879    /// One print's index, when it is built.
1880    #[must_use]
1881    pub fn built(&self, print_id: PrintId) -> Option<Arc<GcodeIndex>> {
1882        match self.held().get(&print_id) {
1883            Some(Slot::Ready(index)) => Some(Arc::clone(index)),
1884            _ => None,
1885        }
1886    }
1887}
1888
1889/// The future [`GcodeIndexes::claim`] answers.
1890#[derive(Debug)]
1891pub struct Claim<'a> {
1892    /// The cache.
1893    indexes: &'a GcodeIndexes,
1894    /// The print.
1895    print_id: PrintId,
1896}
1897
1898impl<'a> Future for Claim<'a> {
1899    type Output = Claimed<'a>;
1900
1901    fn poll(self: Pin<&mut Self>, context: &mut Context<'_>) -> Poll<Self::Output> {
1902        let mut slots = self.indexes.held();
1903        let slot = slots.entry(self.print_id).or_default();
1904        match slot {
1905            Slot::Ready(index) => Poll::Ready(Claimed::Ready(Arc::clone(index))),
1906            Slot::Building(waiting) => {
1907                if !waiting.iter().any(|held| held.will_wake(context.waker())) {
1908                    waiting.push(context.waker().clone());
1909                }
1910                Poll::Pending
1911            }
1912            Slot::Empty => {
1913                *slot = Slot::Building(Vec::new());
1914                Poll::Ready(Claimed::Build(BuildClaim {
1915                    indexes: self.indexes,
1916                    print_id: self.print_id,
1917                    done: false,
1918                }))
1919            }
1920        }
1921    }
1922}
1923
1924/// The most indexes held at once. A print's index is a few tens of kilobytes,
1925/// and a supervisor watches one print at a time; this bounds what a server
1926/// running for months holds of prints long finished.
1927const HELD_INDEXES: usize = 16;
1928
1929impl GcodeIndexes {
1930    /// Remember that a look at one print was given a frame captured at
1931    /// `captured`, with the job at `position`, and forget what no rise can be
1932    /// measured from any more: every look older than the newest one already
1933    /// half an hour old before `now`, and the looks of prints beyond
1934    /// [`HELD_INDEXES`], oldest print first.
1935    pub(crate) fn note_look(
1936        &self,
1937        print_id: PrintId,
1938        captured: Timestamp,
1939        position: i64,
1940        now: Timestamp,
1941    ) {
1942        let mut looked = self.looked.lock().unwrap_or_else(PoisonError::into_inner);
1943        let frames = looked.entry(print_id).or_default();
1944        frames.push((captured, position));
1945        frames.sort_by_key(|(captured, _)| *captured);
1946        if let Ok(until) = now.plus_seconds(-RISE_WINDOW_S) {
1947            let aged = frames.partition_point(|(captured, _)| *captured <= until);
1948            frames.drain(..aged.saturating_sub(1));
1949        }
1950        while looked.len() > HELD_INDEXES {
1951            let Some(oldest) = looked.keys().next().copied() else {
1952                break;
1953            };
1954            let _ = looked.remove(&oldest);
1955        }
1956    }
1957
1958    /// The newest look at one print whose frame was captured no later than
1959    /// `until`: its capture time and the job's position then.
1960    fn newest_look_until(&self, print_id: PrintId, until: Timestamp) -> Option<(Timestamp, i64)> {
1961        let looked = self.looked.lock().unwrap_or_else(PoisonError::into_inner);
1962        looked
1963            .get(&print_id)?
1964            .iter()
1965            .rev()
1966            .find(|(captured, _)| *captured <= until)
1967            .copied()
1968    }
1969
1970    /// Let go of finished indexes beyond [`HELD_INDEXES`], keeping `keep`.
1971    fn trim(&self, keep: PrintId) {
1972        let mut slots = self.held();
1973        let ready: Vec<PrintId> = slots
1974            .iter()
1975            .filter(|(print_id, slot)| **print_id != keep && matches!(slot, Slot::Ready(_)))
1976            .map(|(print_id, _)| *print_id)
1977            .collect();
1978        let over = slots.len().saturating_sub(HELD_INDEXES);
1979        for print_id in ready.into_iter().take(over) {
1980            slots.remove(&print_id);
1981        }
1982    }
1983}
1984
1985impl crate::supervisor::Supervisor {
1986    /// What the slicer planned at the job's current file position, building
1987    /// the print's index first when this supervisor has none for it.
1988    ///
1989    /// Nothing when the print is over, the job is not this print's file, the
1990    /// job reports no position, or the file could not be read — a read that
1991    /// failed builds nothing, so the next one tries again.
1992    ///
1993    /// # Errors
1994    ///
1995    /// The store's own error when the print's actions could not be read, as
1996    /// every other store read of the context answers it.
1997    pub(crate) async fn slicer_plan(
1998        &self,
1999        print: &crate::records::PrintRecord,
2000        job: Option<&printobserver_printer_api::JobSnapshot>,
2001        interventions: &[crate::records::Intervention],
2002    ) -> Result<Option<SlicerPlan>, crate::error::CoreError> {
2003        let Some((position, file)) = job
2004            .and_then(|job| job.file_position_bytes.zip(job.file_name.as_deref()))
2005            .filter(|(_, file)| {
2006                print.ended_at.is_none() && print.file_name.as_deref() == Some(*file)
2007            })
2008        else {
2009            return Ok(None);
2010        };
2011        let Some(index) = self.index_of(print.id, file).await else {
2012            return Ok(None);
2013        };
2014        let (flow, fan) = self
2015            .changes_since(print.id, &index, position, interventions)
2016            .await?;
2017        let mut plan = index.plan_with(position, flow, fan);
2018        plan.rise = self.rise_of(print.id, &index, position).await?;
2019        if plan.rise.is_none() {
2020            plan.unknown.push(PlanFact::Rise);
2021            plan.unknown.sort_unstable();
2022        }
2023        Ok(Some(plan))
2024    }
2025
2026    /// How far the plan has risen since the newest frame at least
2027    /// [`RISE_WINDOW_S`] old that was seen — a periodic observation's, when it
2028    /// carries a position, or a look's — and where the plan had the top then.
2029    async fn rise_of(
2030        &self,
2031        print_id: PrintId,
2032        index: &GcodeIndex,
2033        position: i64,
2034    ) -> Result<Option<Rise>, crate::error::CoreError> {
2035        use printobserver_types::EventPayload as _;
2036
2037        use crate::kinds::PeriodicObservationPayload;
2038
2039        let now = self.clock().now();
2040        let Ok(until) = now.plus_seconds(-RISE_WINDOW_S) else {
2041            return Ok(None);
2042        };
2043        let events = self
2044            .stores()
2045            .events
2046            .history(crate::store::HistoryQuery {
2047                print_id,
2048                kinds: printobserver_types::EventKind::new(PeriodicObservationPayload::KIND)
2049                    .into_iter()
2050                    .collect(),
2051                since: None,
2052                until: Some(until),
2053                limit: Some(1),
2054            })
2055            .await?;
2056        let observed = events.first().and_then(|event| {
2057            let observed = event.payload_as::<PeriodicObservationPayload>()?.ok()?;
2058            let earlier = observed.job?.file_position_bytes?;
2059            Some((
2060                observed.frame_captured_at.unwrap_or(event.received_at),
2061                earlier,
2062            ))
2063        });
2064        let looked = self.gcode_indexes().newest_look_until(print_id, until);
2065        let newest = match (observed, looked) {
2066            (Some(observed), Some(looked)) => Some(if looked.0 > observed.0 {
2067                looked
2068            } else {
2069                observed
2070            }),
2071            (observed, looked) => observed.or(looked),
2072        };
2073        Ok(newest.and_then(|(since, earlier)| {
2074            Some(Rise {
2075                since,
2076                mm: index.height_and_rise_since(earlier, position)?,
2077            })
2078        }))
2079    }
2080
2081    /// One open print's G-code index, built from its file — and spooled —
2082    /// when this supervisor has none for it yet; nothing for a print the
2083    /// store does not hold or could not read, that has ended, names no file,
2084    /// or whose file could not be read.
2085    pub async fn print_gcode_index(&self, print_id: PrintId) -> Option<Arc<GcodeIndex>> {
2086        // A store that cannot be read answers nothing, as a print it does not
2087        // hold does, and its caller asks again at the next read. No test makes
2088        // the store fail here, since every store fake failure lands on the read
2089        // before this one; the same `None` for a print the store does not
2090        // hold is proved by `the_spool_goes_when_the_print_closes_and_strays_are_swept`,
2091        // and the alignment check's asking again by its retried-fetch journey.
2092        let print = self.stores().prints.print(print_id).await.ok()??;
2093        if print.ended_at.is_some() {
2094            return None;
2095        }
2096        self.index_of(print.id, print.file_name.as_deref()?).await
2097    }
2098
2099    /// Delete one print's G-code spool, when there is one.
2100    pub(crate) fn drop_gcode_spool(&self, print_id: PrintId) {
2101        if let Some(directory) = self.config().gcode_spool_dir.as_deref() {
2102            let _ = std::fs::remove_file(crate::toolpath::spool_path(directory, print_id));
2103        }
2104    }
2105
2106    /// Delete every G-code spool of a print that is not open: what a print
2107    /// closed while no supervisor was running left behind.
2108    ///
2109    /// # Errors
2110    ///
2111    /// The store's own error when the open prints could not be read.
2112    pub async fn sweep_gcode_spools(&self) -> Result<(), crate::error::CoreError> {
2113        let Some(directory) = self.config().gcode_spool_dir.clone() else {
2114            return Ok(());
2115        };
2116        let open: Vec<String> = self
2117            .stores()
2118            .prints
2119            .open_prints()
2120            .await?
2121            .iter()
2122            .map(|print| print.id.to_string())
2123            .collect();
2124        // A directory that cannot be listed, an entry that cannot be read and
2125        // a spool that cannot be removed each leave a file behind, which the
2126        // next start's sweep tries again. No test makes the filesystem refuse
2127        // them, since that needs one made to fail beneath a running server;
2128        // what proves the sweep is that it removes exactly the spools of
2129        // closed prints and nothing else, at start and on a close
2130        // (`the_spool_goes_when_the_print_closes_and_strays_are_swept`).
2131        let Ok(entries) = std::fs::read_dir(&directory) else {
2132            return Ok(());
2133        };
2134        for entry in entries.flatten() {
2135            let name = entry.file_name();
2136            // Only a file named for a print is a spool; anything else is left.
2137            let Some(print) = name
2138                .to_str()
2139                .and_then(|name| name.strip_suffix(crate::toolpath::SPOOL_SUFFIX))
2140                .filter(|print| print.parse::<PrintId>().is_ok())
2141            else {
2142                continue;
2143            };
2144            if !open.iter().any(|id| id == print) {
2145                let _ = std::fs::remove_file(entry.path());
2146            }
2147        }
2148        Ok(())
2149    }
2150
2151    /// One print's index, built from its file when there is none yet.
2152    async fn index_of(&self, print_id: PrintId, file: &str) -> Option<Arc<GcodeIndex>> {
2153        // A name no file could carry is no file to read.
2154        let file_name = printobserver_types::FileName::new(file).ok()?;
2155        let claim = match self.gcode_indexes().claim(print_id).await {
2156            Claimed::Ready(index) => return Some(index),
2157            Claimed::Build(claim) => claim,
2158        };
2159        // A spool that cannot be created leaves an index with no toolpaths,
2160        // which is no reason to go without the plan.
2161        let mut builder = self
2162            .config()
2163            .gcode_spool_dir
2164            .as_deref()
2165            .and_then(|directory| {
2166                IndexBuilder::spooling(crate::toolpath::spool_path(directory, print_id)).ok()
2167            })
2168            .unwrap_or_default();
2169        self.read_gcode(file_name.clone(), &mut builder)
2170            .await
2171            .ok()?;
2172        let index = claim.finish(builder.finish());
2173        self.gcode_indexes().trim(print_id);
2174        if let Ok(body) = printobserver_types::EventBody::of(&crate::kinds::GcodeIndexedPayload {
2175            file_name,
2176            bytes: index.bytes(),
2177            layers: u64::try_from(index.layer_count()).unwrap_or(u64::MAX),
2178        }) {
2179            // The index is built whether or not the store takes the record of
2180            // it, and a check goes on without it.
2181            let _ = self.append_system_event(print_id, body).await;
2182        }
2183        Some(index)
2184    }
2185
2186    /// The flow factor and the fan speed the latest change made through this
2187    /// program set, each when it was made after the file last set the same
2188    /// thing and still stands.
2189    ///
2190    /// A change is placed against the file by the position the print had last
2191    /// been read to have reached when it was made, at the file's start when no
2192    /// position had been read yet; a change whose bounded intervention has
2193    /// since expired stands no more.
2194    async fn changes_since(
2195        &self,
2196        print_id: PrintId,
2197        index: &GcodeIndex,
2198        position: i64,
2199        interventions: &[crate::records::Intervention],
2200    ) -> Result<(Option<f64>, Option<f64>), crate::error::CoreError> {
2201        use printobserver_types::EventPayload as _;
2202
2203        use crate::kinds::{ActionExecutedPayload, ActionRequestedPayload};
2204        use crate::records::PrintAction;
2205
2206        let kinds = [ActionRequestedPayload::KIND, ActionExecutedPayload::KIND]
2207            .iter()
2208            .filter_map(|kind| printobserver_types::EventKind::new(*kind).ok())
2209            .collect();
2210        let events = self
2211            .stores()
2212            .events
2213            .history(crate::store::HistoryQuery {
2214                print_id,
2215                kinds,
2216                since: None,
2217                until: None,
2218                limit: Some(crate::store::MAX_HISTORY_LIMIT),
2219            })
2220            .await?;
2221        let requested: BTreeMap<crate::records::ActionId, PrintAction> = events
2222            .iter()
2223            .filter_map(printobserver_types::EventRecord::payload_as::<ActionRequestedPayload>)
2224            .filter_map(Result::ok)
2225            .map(|payload| (payload.action_id, payload.action))
2226            .collect();
2227        let mut flow = None;
2228        let mut fan = None;
2229        // Newest first, so the first change of each kind is the latest.
2230        for executed in events
2231            .iter()
2232            .filter_map(printobserver_types::EventRecord::payload_as::<ActionExecutedPayload>)
2233            .filter_map(Result::ok)
2234        {
2235            let standing = executed
2236                .intervention_id
2237                .is_none_or(|opened| interventions.iter().any(|active| active.id == opened));
2238            // Where in the file the change was made; one made before any
2239            // position was known is placed at the file's start.
2240            let made = executed
2241                .file_position_bytes
2242                .and_then(|made| u64::try_from(made).ok())
2243                .unwrap_or(0);
2244            let after = |set: Option<SetInFile>| set.is_none_or(|set| made >= set.at);
2245            match requested.get(&executed.action_id) {
2246                Some(PrintAction::SetFlowrateFactor { factor, .. }) if flow.is_none() => {
2247                    flow = Some((standing && after(index.flow_at(position))).then_some(*factor));
2248                }
2249                Some(PrintAction::SetFanPercent { percent, .. }) if fan.is_none() => {
2250                    fan = Some((standing && after(index.fan_at(position))).then_some(*percent));
2251                }
2252                _ => {}
2253            }
2254        }
2255        Ok((flow.flatten(), fan.flatten()))
2256    }
2257}
2258
2259#[cfg(test)]
2260mod tests {
2261    use super::{GcodeIndexes, HELD_INDEXES, OVER_AIR, RISE_WINDOW_S, SUPPORTS, WALLS};
2262    use crate::toolpath::ExtrusionKind;
2263
2264    /// The type names the plan's facts single out are the ones the toolpath
2265    /// draws in the same kinds: a wall is drawn as a wall, a support as a
2266    /// support, and what is laid over air as a bridge or an overhang.
2267    #[test]
2268    fn the_plans_type_names_map_to_the_kinds_the_toolpath_draws() {
2269        for name in WALLS {
2270            assert_eq!(ExtrusionKind::of_type(name), ExtrusionKind::Wall, "{name}");
2271        }
2272        for name in SUPPORTS {
2273            assert_eq!(
2274                ExtrusionKind::of_type(name),
2275                ExtrusionKind::Support,
2276                "{name}"
2277            );
2278        }
2279        for name in OVER_AIR {
2280            assert!(
2281                matches!(
2282                    ExtrusionKind::of_type(name),
2283                    ExtrusionKind::Bridge | ExtrusionKind::Overhang
2284                ),
2285                "{name}"
2286            );
2287        }
2288    }
2289    use printobserver_types::{PrintId, Timestamp};
2290
2291    /// An instant some seconds after another.
2292    fn after(start: Timestamp, seconds: i64) -> Timestamp {
2293        start.plus_seconds(seconds).expect("an instant")
2294    }
2295
2296    /// What is remembered of one print's looks, oldest first.
2297    fn held(indexes: &GcodeIndexes, print_id: PrintId) -> Vec<(Timestamp, i64)> {
2298        indexes
2299            .looked
2300            .lock()
2301            .expect("the looks are held")
2302            .get(&print_id)
2303            .cloned()
2304            .unwrap_or_default()
2305    }
2306
2307    /// Of the looks already half an hour old, only the newest is kept: it is
2308    /// the one a rise is measured from until a newer look ages.
2309    #[test]
2310    fn the_newest_aged_look_is_kept_and_every_older_one_let_go() {
2311        let indexes = GcodeIndexes::default();
2312        let print = PrintId::new();
2313        let start = Timestamp::now();
2314        indexes.note_look(print, start, 10, start);
2315        indexes.note_look(print, after(start, 60), 20, after(start, 60));
2316        let now = after(start, 60 + RISE_WINDOW_S + 30);
2317        indexes.note_look(print, now, 30, now);
2318
2319        assert_eq!(
2320            held(&indexes, print),
2321            vec![(after(start, 60), 20), (now, 30)]
2322        );
2323        assert_eq!(
2324            indexes.newest_look_until(print, after(now, -RISE_WINDOW_S)),
2325            Some((after(start, 60), 20))
2326        );
2327        assert_eq!(indexes.newest_look_until(print, after(start, 30)), None);
2328    }
2329
2330    /// Past as many prints as indexes are held, the looks of the oldest print
2331    /// are let go first.
2332    #[test]
2333    fn the_looks_of_prints_beyond_the_held_count_are_let_go_oldest_first() {
2334        let indexes = GcodeIndexes::default();
2335        let now = Timestamp::now();
2336        let mut prints: Vec<PrintId> = (0..=HELD_INDEXES).map(|_| PrintId::new()).collect();
2337        prints.sort_unstable();
2338        for print in &prints {
2339            indexes.note_look(*print, now, 1, now);
2340        }
2341
2342        assert!(held(&indexes, prints[0]).is_empty());
2343        for print in &prints[1..] {
2344            assert_eq!(held(&indexes, *print), vec![(now, 1)]);
2345        }
2346    }
2347}