Skip to main content

printobserver_core/
gcode_index.rs

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