Skip to main content

printobserver_server/
check_images.rs

1//! The image every check is shown, made of the frame the camera gave.
2//!
3//! The one place that chooses it ([`PanelImages`]). A check of a print is shown
4//! `printobserver-panels`' three-panel check image when that image can be
5//! trusted: a calibration is configured, the print's G-code index names the
6//! object being laid and the layer at the check's file position, the print's
7//! first-layer alignment `Passed`, and the frame passes the composer's
8//! resolution, stream and drift checks. Every other check, and every look at
9//! the printer, is shown the whole frame scaled to [`WHOLE_FRAME_WIDTH`] by
10//! [`WHOLE_FRAME_HEIGHT`] and never cropped ([`WholeFrames`]). Either way the
11//! image is written under `<state_dir>/check-images/` while the stored frame
12//! keeps the camera's size, and one line says which image it is and why.
13//!
14//! A check shown the three-panel image is also measured against the newest
15//! earlier check's frame at least [`MIN_RISE_MM`] below it in the plan
16//! ([`measure_growth`]). When the parts this layer lays sit where that frame
17//! had them, carried down with the bed, the line says so
18//! ([`not_grown_note`]): a stall shows as a few pixels between a drawn line
19//! and a part's top, which the eye misreads, and the measurement does not.
20
21use std::path::{Path, PathBuf};
22use std::sync::atomic::{AtomicU64, Ordering};
23
24use std::sync::Arc;
25
26use printobserver_core::check_image::PlanPosition;
27use printobserver_core::{CheckImageRequest, CheckImages, GcodeIndex, ImageUse, ShownImage};
28use printobserver_panels::growth::MIN_RISE_MM;
29use printobserver_panels::{
30    CameraCalibration, CheckImage, CheckImageInputs, ComposeError, GrowthInputs, SheetEdgesInputs,
31    WHOLE_FRAME_HEIGHT, WHOLE_FRAME_WIDTH, compose_check_image, measure_growth, sheet_edges,
32    whole_frame,
33};
34use printobserver_types::{PrintId, Timestamp};
35
36use printobserver_panels::{InconclusiveReason, ViewCorrection, ViewOutcome};
37use printobserver_supervisor_api::{ImageFallback, WholeFrameReasonCode};
38
39use crate::alignment::{
40    AlignmentFailure, AlignmentJudging, Alignments, CheckedFrame, Judged, Judging, LastCheckImage,
41    PreviousCheck, PrintAlignment, failure_sentence,
42};
43
44/// How many scaled frames this process has begun writing, which names each
45/// write's partial file apart from any other's.
46static WRITES: AtomicU64 = AtomicU64::new(0);
47
48/// The directory under the state directory check images are written in.
49pub const CHECK_IMAGES_DIRECTORY: &str = "check-images";
50
51/// Every check shown the whole frame, scaled.
52#[derive(Debug, Clone)]
53pub struct WholeFrames {
54    /// Where the scaled frames are written.
55    directory: PathBuf,
56}
57
58impl WholeFrames {
59    /// Write scaled frames under one state directory.
60    #[must_use]
61    pub fn under(state_dir: &Path) -> Self {
62        Self {
63            directory: state_dir.join(CHECK_IMAGES_DIRECTORY),
64        }
65    }
66
67    /// Where the scaled copy of one stored frame is written: named for the
68    /// stored frame's own directory and file, which name it uniquely.
69    fn destination(&self, frame: &Path) -> PathBuf {
70        let named = |part: Option<&std::ffi::OsStr>| {
71            part.map_or_else(String::new, |part| part.to_string_lossy().into_owned())
72        };
73        let parent = named(frame.parent().and_then(Path::file_name));
74        let file = named(frame.file_name());
75        self.directory.join(format!(
76            "{parent}-{file}-{WHOLE_FRAME_WIDTH}x{WHOLE_FRAME_HEIGHT}.jpg"
77        ))
78    }
79}
80
81impl WholeFrames {
82    /// Where the image of one stored frame with its sheet's edges is written.
83    fn sheet_edges_destination(&self, frame: &Path) -> PathBuf {
84        let scaled = self.destination(frame);
85        let stem = scaled
86            .file_stem()
87            .map_or_else(String::new, |stem| stem.to_string_lossy().into_owned());
88        self.directory.join(format!("{stem}-sheet-edges.jpg"))
89    }
90}
91
92impl CheckImages for WholeFrames {
93    fn check_image(&self, _print_id: Option<PrintId>, frame: &Path) -> Result<PathBuf, String> {
94        let destination = self.destination(frame);
95        if destination.is_file() {
96            return Ok(destination);
97        }
98        let bytes = std::fs::read(frame)
99            .map_err(|error| format!("{} is unreadable: {error}", frame.display()))?;
100        let scaled = whole_frame(&bytes).map_err(|error| error.to_string())?;
101        if !scaled.scaled {
102            return Ok(frame.to_path_buf());
103        }
104        write_image(&self.directory, &destination, &scaled.jpeg)?;
105        Ok(destination)
106    }
107}
108
109/// Write one check image — a scaled frame or a three-panel image — under
110/// `directory` at `destination`, beside its name first
111/// and moved onto it, so a reader never opens a half-written image.
112fn write_image(directory: &Path, destination: &Path, bytes: &[u8]) -> Result<(), String> {
113    std::fs::create_dir_all(directory)
114        .map_err(|error| format!("{} cannot be made: {error}", directory.display()))?;
115    let partial = destination.with_extension(format!(
116        "{}-{}.partial",
117        std::process::id(),
118        WRITES.fetch_add(1, Ordering::Relaxed)
119    ));
120    let written =
121        std::fs::write(&partial, bytes).and_then(|()| std::fs::rename(&partial, destination));
122    written.map_err(|error| {
123        // Whatever was written is no image a reader may open.
124        let _ = std::fs::remove_file(&partial);
125        format!("{} cannot be written: {error}", destination.display())
126    })
127}
128
129/// The first words of every line saying a check was shown the three-panel
130/// image, which the real-print suite's record reads the image's kind from.
131pub const COMPOSITE_NOTE: &str = "the three-panel check image";
132
133/// The first words of every line saying a check was shown the whole frame.
134pub const WHOLE_FRAME_NOTE: &str = "the whole camera frame";
135
136/// Why a check is shown the whole frame rather than the three-panel image.
137#[derive(Debug, Clone, PartialEq)]
138pub enum WholeFrameReason {
139    /// No print is named: a look at the printer, before, between or after
140    /// prints, a start's bed check among them.
141    NoPrint,
142    /// No camera calibration is configured.
143    NoCalibration,
144    /// No camera snapshot address is configured, so the frame's stream is
145    /// unknown.
146    NoStream,
147    /// The job is not the print's file, reported no position, or its file has
148    /// no index.
149    NoPosition,
150    /// The print's G-code names no extruded object, or none laid yet, at the
151    /// check's file position.
152    NoObject,
153    /// It names no layer there.
154    NoLayer,
155    /// The layer's planned toolpath could not be read from the print's spool.
156    ToolpathUnread(String),
157    /// The print's first-layer alignment is not decided yet.
158    AlignmentPending,
159    /// The frame the print's first-layer alignment was last judged on could
160    /// not tell where the layer lies; a later check's is judged again.
161    AlignmentInconclusive(InconclusiveReason),
162    /// The print's G-code lays no object to align.
163    AlignmentUnavailable,
164    /// The print's first-layer alignment failed.
165    AlignmentFailed(AlignmentFailure),
166    /// Fewer than two landmarks are found, so whether the camera shifted is
167    /// unknown.
168    LandmarksNotFound(String),
169    /// The camera moved since the print's correction was taken.
170    ViewRefitRejected(String),
171    /// The landmarks show the camera has moved since its calibration, so the
172    /// plan cannot be drawn reliably on its frames, whatever correction a pass
173    /// took: a translation cannot repair a camera that has turned.
174    CalibrationStale,
175    /// The frame is not the calibration's size or stream.
176    FrameMismatch(String),
177    /// The printer reports the print paused, its bed moved off the plan's
178    /// height.
179    Paused,
180    /// The composer refused this frame.
181    Refused(ComposeError),
182}
183
184impl WholeFrameReason {
185    /// The reason as a code.
186    #[must_use]
187    pub const fn code(&self) -> WholeFrameReasonCode {
188        match self {
189            Self::NoPrint => WholeFrameReasonCode::NoPrint,
190            Self::NoCalibration => WholeFrameReasonCode::NoCalibration,
191            Self::NoStream => WholeFrameReasonCode::NoStream,
192            Self::NoPosition => WholeFrameReasonCode::NoPosition,
193            Self::NoObject => WholeFrameReasonCode::NoObject,
194            Self::NoLayer => WholeFrameReasonCode::NoLayer,
195            Self::ToolpathUnread(_) => WholeFrameReasonCode::ToolpathUnread,
196            Self::AlignmentPending => WholeFrameReasonCode::AlignmentPending,
197            Self::AlignmentInconclusive(_) => WholeFrameReasonCode::AlignmentInconclusive,
198            Self::AlignmentUnavailable => WholeFrameReasonCode::AlignmentUnavailable,
199            Self::AlignmentFailed(_) => WholeFrameReasonCode::AlignmentFailed,
200            Self::LandmarksNotFound(_) | Self::Refused(ComposeError::DriftUnverified) => {
201                WholeFrameReasonCode::LandmarksNotFound
202            }
203            Self::ViewRefitRejected(_) | Self::Refused(ComposeError::CameraMoved { .. }) => {
204                WholeFrameReasonCode::ViewRefitRejected
205            }
206            Self::FrameMismatch(_) | Self::Refused(ComposeError::FrameMismatch { .. }) => {
207                WholeFrameReasonCode::FrameMismatch
208            }
209            Self::CalibrationStale => WholeFrameReasonCode::CalibrationStale,
210            Self::Paused => WholeFrameReasonCode::Paused,
211            Self::Refused(_) => WholeFrameReasonCode::Refused,
212        }
213    }
214}
215
216impl core::fmt::Display for WholeFrameReason {
217    fn fmt(&self, formatter: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
218        match self {
219            Self::NoPrint => formatter
220                .write_str("no print is named, so there is no planned toolpath to draw on it"),
221            Self::NoCalibration => formatter.write_str("no camera calibration is configured"),
222            Self::NoStream => formatter.write_str(
223                "no camera snapshot address is configured, so the frame's stream is unknown",
224            ),
225            Self::NoPosition => formatter.write_str(
226                "the print's G-code index gives no file position for this check",
227            ),
228            Self::NoObject => formatter.write_str(
229                "the print's G-code names no extruded object laid at this point",
230            ),
231            Self::NoLayer => formatter.write_str("the print's G-code names no layer at this point"),
232            Self::ToolpathUnread(detail) => write!(
233                formatter,
234                "the layer's planned toolpath could not be read from the print's spool: {detail}"
235            ),
236            Self::AlignmentPending => formatter.write_str(
237                "the print's first-layer alignment is pending: its first object layer is not down, or no frame of it has been judged yet",
238            ),
239            Self::AlignmentInconclusive(why) => write!(
240                formatter,
241                "the print's first-layer alignment is inconclusive on the frame judged last: {}, so a later check's frame is judged again; this is no evidence of a defect",
242                match why {
243                    InconclusiveReason::Covered => "the toolhead covers the part, which sits hidden under the head on this frame: bare sheet beside the head alone is no sign the part is gone, but a part seen moved, loose or in spaghetti is",
244                    InconclusiveReason::NotClearlyFound => "the printed first layer was not clearly found",
245                }
246            ),
247            Self::AlignmentUnavailable => {
248                formatter.write_str("the print's G-code lays no object to align")
249            }
250            Self::AlignmentFailed(failure) => write!(
251                formatter,
252                "the print's first-layer alignment failed: {}",
253                failure_sentence(failure)
254            ),
255            Self::LandmarksNotFound(reason) | Self::ViewRefitRejected(reason) | Self::FrameMismatch(reason) => {
256                formatter.write_str(reason)
257            }
258            Self::CalibrationStale => formatter.write_str(CALIBRATION_STALE),
259            Self::Paused => formatter.write_str(
260                "the printer reports the print paused, so its bed may stand off the plan's height and nothing is drawn",
261            ),
262            Self::Refused(error) => error.fmt(formatter),
263        }
264    }
265}
266
267/// Why a check of a camera that has moved since its calibration is shown the
268/// whole frame.
269pub const CALIBRATION_STALE: &str = "the camera has moved since its calibration, so the outline cannot be drawn reliably; recalibrate this camera";
270
271/// How far the plan may rise, in millimetres, past a frame a check is compared
272/// against before a part not plainly higher on a whole frame shown for the
273/// camera's own sake is grounds to pause. On the two-colour print's stale
274/// camera, the box's rise of 1.8 and 4.0 mm was read by eye as none, and the
275/// healthy print paused; a part that stops growing for longer than this still
276/// is.
277pub const UNSEEN_RISE_BOUND_MM: f64 = 5.0;
278
279/// The line saying a check was shown the whole frame, and why.
280///
281/// A whole frame shown because the camera moved since its calibration, or
282/// because the first layer was not clearly found, carries the bound
283/// [`UNSEEN_RISE_BOUND_MM`] on judging a rise by eye; every other whole frame
284/// keeps the skill's own rule.
285#[must_use]
286pub fn whole_frame_note(reason: &WholeFrameReason) -> String {
287    let bound = match reason {
288        WholeFrameReason::CalibrationStale | WholeFrameReason::AlignmentInconclusive(_) => format!(
289            "; on this frame a part that is not plainly higher is no grounds to pause on its own until the plan's rise since the frame it is compared against exceeds {UNSEEN_RISE_BOUND_MM:.0} mm"
290        ),
291        _ => String::new(),
292    };
293    format!(
294        "{WHOLE_FRAME_NOTE}, scaled to fit {WHOLE_FRAME_WIDTH}x{WHOLE_FRAME_HEIGHT} and uncropped, because {reason}{bound}"
295    )
296}
297
298/// What the line of a look at the printer adds when the frame shows no sheet
299/// to cut a close-up of its edges from.
300pub const NO_SHEET_CLAUSE: &str =
301    "; no sheet was found in it, so no close-up of the sheet's edges is shown";
302
303/// The line saying a look at the printer was shown the whole frame over a
304/// close-up of the sheet's edges and clips. It begins as every whole frame's
305/// line does, because panel 1 is that frame, scaled the same way.
306#[must_use]
307pub fn sheet_edges_note(reason: &WholeFrameReason) -> String {
308    format!(
309        "{WHOLE_FRAME_NOTE}, scaled to fit {WHOLE_FRAME_WIDTH}x{WHOLE_FRAME_HEIGHT} and uncropped, because {reason}, as panel 1; panel 2 under it is a close-up of the sheet's edges and clips at twice that scale, cut from the full frame, each edge unrolled into a strip named by the way it faces, outside up and sheet down"
310    )
311}
312
313/// What a check's note says of the drawing before it says what a part off it
314/// means: an agent shown a part off its walls otherwise explains the
315/// difference as the camera or the bed having shifted in view.
316const CAMERA_HOLDS: &str = "the camera holds still and the drawing follows the bed, so ";
317
318/// The line saying a check or a look was shown the three-panel image of the
319/// frame captured at `current_at`, beside the frame `previous_at` names: panel
320/// 3 empty when no earlier check's frame is at hand — the print's first check,
321/// or one whose earlier frame is gone from the store.
322///
323/// A check's names which frame each panel is and when each was captured, and
324/// says what the skill says: the camera holds still and the drawing follows
325/// the bed, so a part off it has moved unless strongly shown otherwise, and no
326/// later frame undoes it. A turn handed a check's image decides on it, with no look to
327/// stall on, so this is what it decides from. A look's says only what each
328/// panel is.
329#[must_use]
330pub fn composite_note(
331    made_for: ImageUse,
332    current_at: Timestamp,
333    previous_at: Option<Timestamp>,
334) -> String {
335    let (current, previous, moved) = match (made_for, previous_at) {
336        (ImageUse::Look, at) => (
337            "this layer's planned toolpath drawn on the frame".to_owned(),
338            if at.is_none() {
339                "panel 3 empty, no earlier frame at hand".to_owned()
340            } else {
341                "panel 3 the previous check's frame".to_owned()
342            },
343            String::new(),
344        ),
345        (ImageUse::Check, None) => (
346            format!(
347                "this check's frame, captured {current_at}, with this layer's planned toolpath drawn"
348            ),
349            "panel 3 empty, no earlier frame at hand".to_owned(),
350            format!(
351                "; {CAMERA_HOLDS}a part off its drawn walls in panel 1 has moved unless strongly shown otherwise; no later frame undoes that"
352            ),
353        ),
354        (ImageUse::Check, Some(at)) => (
355            format!(
356                "this check's frame, captured {current_at}, with this layer's planned toolpath drawn"
357            ),
358            format!("panel 3 the last check's frame, captured {at}"),
359            format!(
360                "; {CAMERA_HOLDS}a part off its drawn walls in panel 1, or moved since panel 3, has moved unless strongly shown otherwise; no later frame undoes that"
361            ),
362        ),
363    };
364    format!(
365        "{COMPOSITE_NOTE}, {}x{}: panel 1 {current}, panel 2 a close-up of the part, {previous}{moved}",
366        printobserver_panels::compose::PANEL_WIDTH,
367        printobserver_panels::compose::IMAGE_HEIGHT
368    )
369}
370
371/// What a check's line adds when the measurement finds the parts this layer
372/// lays have not grown since the frame captured at `since`, `rise_mm` lower in
373/// the plan: the skill's own words for it, `not risen as planned`.
374#[must_use]
375pub fn not_grown_note(since: Timestamp, rise_mm: f64) -> String {
376    format!(
377        "; measured against the check frame captured {since}, {rise_mm:.1} mm lower in the plan: the parts this layer lays have not risen as planned, sitting where that frame had them, carried down with the bed, so nothing has been laid on them since"
378    )
379}
380
381/// The print's height in its plan at a check's position.
382fn plan_z(plan: &PlanPosition) -> Option<f64> {
383    plan.index
384        .layer_at(plan.file_position_bytes)
385        .and_then(|layer| plan.index.layer_z_mm(layer))
386}
387
388/// What a check image is composed from, beyond the frames: the print's plan at
389/// one file position.
390#[derive(Debug, Clone, Copy)]
391pub struct PlanAt<'a> {
392    /// The print's G-code index, its toolpaths read from its spool.
393    pub index: &'a GcodeIndex,
394    /// The check's file position.
395    pub file_position_bytes: u64,
396}
397
398/// Compose the three-panel check image of one frame at one file position, as
399/// every check of a print whose alignment passed is shown it, through the
400/// print's correction when one is given: the active
401/// object at that position, the layer there — and, when that layer lays
402/// supports alone, the nearest object layer below it — over the frame, with
403/// `previous` as panel 3.
404///
405/// # Errors
406///
407/// [`WholeFrameReason`] naming what the index lacks at that position, or the
408/// composer's own refusal.
409pub fn compose_at(
410    plan: PlanAt<'_>,
411    current: (&[u8], Timestamp),
412    previous: Option<(&[u8], Timestamp)>,
413    camera_snapshot_url: &str,
414    calibration: &CameraCalibration,
415    correction: Option<&ViewCorrection>,
416) -> Result<CheckImage, WholeFrameReason> {
417    let index = plan.index;
418    let position = plan.file_position_bytes;
419    let active_object = index
420        .object_at(position)
421        .filter(|object| *object < index.object_outlines().len())
422        .ok_or(WholeFrameReason::NoObject)?;
423    let layer = index.layer_at(position).ok_or(WholeFrameReason::NoLayer)?;
424    let print_z_mm = index.layer_z_mm(layer).ok_or(WholeFrameReason::NoLayer)?;
425    let unread =
426        |error: printobserver_core::SpoolError| WholeFrameReason::ToolpathUnread(error.to_string());
427    let toolpath = index.layer_toolpath(layer).map_err(unread)?;
428    let below = if toolpath.carries_object_extrusion() {
429        None
430    } else {
431        index
432            .object_layer_at_or_below(layer)
433            .map(|below| index.layer_toolpath(below))
434            .transpose()
435            .map_err(unread)?
436    };
437    let facts = index.layer_facts(position, &toolpath);
438    // Where the plan has had the nozzle over the moves the printer may still
439    // hold: a spool that cannot be read for it leaves the head unplaced, which
440    // the text says, rather than the check without its image.
441    let head_trail_mm = index
442        .planned_heads_before(position, printobserver_panels::occlusion::QUEUED_MOVES)
443        .ok()
444        .flatten()
445        .map(|heads| heads.trail)
446        .unwrap_or_default();
447    compose_check_image(&CheckImageInputs {
448        current_jpeg: current.0,
449        current_at: current.1,
450        camera_snapshot_url,
451        previous,
452        outlines: index.object_outlines(),
453        active_object,
454        toolpath: &toolpath,
455        object_layer_below: below.as_ref(),
456        print_z_mm,
457        calibration,
458        correction,
459        file_position_bytes: Some(position),
460        facts: facts.as_ref(),
461        head_trail_mm: &head_trail_mm,
462        // The printer reports no head position while it prints: the watch's
463        // own reads are of an idle printer, and the firmware answers a
464        // position query with where its queue ends, not where the head is.
465        reported_head_mm: None,
466    })
467    .map_err(WholeFrameReason::Refused)
468}
469
470/// What a check's line adds of panel 1: the lines the turn is told of its
471/// drawing, which the image itself carries no text of.
472#[must_use]
473pub fn panel_one_clause(text: &[String]) -> String {
474    if text.is_empty() {
475        return String::new();
476    }
477    format!("; panel 1: {}", text.join("; "))
478}
479
480/// Why a judged frame of a print whose plan places it may not be drawn on.
481///
482/// A frame whose landmarks have moved from the calibration is drawn on not at
483/// all, though they agree with the correction in force: on the first shifted
484/// print the projection stood 1 to 31 px off the part, growing with height and
485/// toward the back, which no translation removes.
486fn refusal_of(judged: &Judged) -> Result<(), WholeFrameReason> {
487    if let Some(reason) = &judged.rejected {
488        return Err(WholeFrameReason::ViewRefitRejected(reason.clone()));
489    }
490    if judged.camera_check.is_some() {
491        return refusal_under_check(judged);
492    }
493    match &judged.alignment {
494        PrintAlignment::Passed { .. } => {}
495        PrintAlignment::Pending => {
496            return Err(judged.inconclusive.map_or(
497                WholeFrameReason::AlignmentPending,
498                WholeFrameReason::AlignmentInconclusive,
499            ));
500        }
501        PrintAlignment::Unavailable => return Err(WholeFrameReason::AlignmentUnavailable),
502        PrintAlignment::Failed { reason } => {
503            return Err(WholeFrameReason::AlignmentFailed(reason.clone()));
504        }
505    }
506    if let Some(reason) = &judged.mismatch {
507        return Err(WholeFrameReason::FrameMismatch(reason.clone()));
508    }
509    let said = |reason: &Option<String>| reason.clone().unwrap_or_default();
510    match &judged.view {
511        Some((ViewOutcome::LandmarksNotFound, reason)) => {
512            Err(WholeFrameReason::LandmarksNotFound(said(reason)))
513        }
514        Some((ViewOutcome::ViewRefitRejected, reason)) => {
515            Err(WholeFrameReason::ViewRefitRejected(said(reason)))
516        }
517        Some((ViewOutcome::FrameMismatch, reason)) => {
518            Err(WholeFrameReason::FrameMismatch(said(reason)))
519        }
520        Some((ViewOutcome::Refit, _)) => Err(WholeFrameReason::CalibrationStale),
521        Some((ViewOutcome::Unshifted, _)) | None => Ok(()),
522    }
523}
524
525/// Why a frame of a print started under a camera check may not be drawn on:
526/// only a frame that is not the calibration's, or whose landmarks the check's
527/// reference no longer finds, or finds moved again beyond it. Its first-layer
528/// verdict, whatever it is, is no reason: the check already placed the
529/// projection, and a first-layer search scores a toolhead over a small part as
530/// readily as the part.
531fn refusal_under_check(judged: &Judged) -> Result<(), WholeFrameReason> {
532    if let Some(reason) = &judged.mismatch {
533        return Err(WholeFrameReason::FrameMismatch(reason.clone()));
534    }
535    let said = |reason: &Option<String>| reason.clone().unwrap_or_default();
536    match &judged.view {
537        Some((ViewOutcome::LandmarksNotFound, reason)) => {
538            Err(WholeFrameReason::LandmarksNotFound(said(reason)))
539        }
540        Some((ViewOutcome::ViewRefitRejected, reason)) => {
541            Err(WholeFrameReason::ViewRefitRejected(said(reason)))
542        }
543        Some((ViewOutcome::FrameMismatch, reason)) => {
544            Err(WholeFrameReason::FrameMismatch(said(reason)))
545        }
546        Some((ViewOutcome::Refit | ViewOutcome::Unshifted, _)) | None => Ok(()),
547    }
548}
549
550/// One judged frame whose image is chosen.
551#[derive(Debug, Clone, Copy)]
552pub struct Shown<'a> {
553    /// Where the stored frame is.
554    pub frame: &'a Path,
555    /// When it was captured.
556    pub captured_at: Timestamp,
557    /// What the image is for.
558    pub made_for: ImageUse,
559    /// Where the print stood in its plan.
560    pub plan: Option<&'a PlanPosition>,
561    /// Whether the printer reported the print paused.
562    pub paused: bool,
563}
564
565/// Every check's image, the three-panel one where it can be trusted and the
566/// whole frame otherwise, each with the line saying which and why.
567pub struct PanelImages {
568    /// The whole frames, and where every image is written.
569    whole: WholeFrames,
570    /// Each print's alignment verdict and last check, and the calibration.
571    alignments: Arc<Alignments>,
572    /// The configured camera's snapshot address: the stream every frame of a
573    /// print is of, an alert's included, which the camera's own feed relays.
574    camera_snapshot_url: Option<String>,
575}
576
577impl core::fmt::Debug for PanelImages {
578    fn fmt(&self, formatter: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
579        formatter
580            .debug_struct("PanelImages")
581            .field("whole", &self.whole)
582            .field("camera_snapshot_url", &self.camera_snapshot_url)
583            .finish_non_exhaustive()
584    }
585}
586
587impl PanelImages {
588    /// The images of one state directory's frames.
589    #[must_use]
590    pub fn new(
591        state_dir: &Path,
592        alignments: Arc<Alignments>,
593        camera_snapshot_url: Option<String>,
594    ) -> Self {
595        Self {
596            whole: WholeFrames::under(state_dir),
597            alignments,
598            camera_snapshot_url,
599        }
600    }
601
602    /// The camera calibration in force, when one is configured.
603    #[must_use]
604    pub fn calibration(&self) -> Option<&CameraCalibration> {
605        self.alignments.calibration()
606    }
607
608    /// Write the frame a camera check drew its fit on beside every check
609    /// image, named for the check, and answer where it is.
610    ///
611    /// # Errors
612    ///
613    /// Why it could not be written.
614    pub fn write_camera_check_image(
615        &self,
616        camera_check: printobserver_core::CameraCheckId,
617        jpeg: &[u8],
618    ) -> Result<PathBuf, String> {
619        let destination = self
620            .whole
621            .directory
622            .join(format!("camera-check-{camera_check}.jpg"));
623        write_image(&self.whole.directory, &destination, jpeg)?;
624        Ok(destination)
625    }
626
627    /// One print's first-layer alignment as it stands.
628    #[must_use]
629    pub fn alignment(&self, print_id: PrintId) -> PrintAlignment {
630        self.alignments.print_alignment(print_id)
631    }
632
633    /// The image one print's last check was shown; nothing before its first.
634    #[must_use]
635    pub fn last_check_image(&self, print_id: PrintId) -> Option<LastCheckImage> {
636        self.alignments.last_check_image(print_id)
637    }
638
639    /// The whole frame, with the line saying why.
640    fn whole_frame(&self, frame: &Path, reason: &WholeFrameReason) -> Result<ShownImage, String> {
641        Ok(ShownImage {
642            fallback: Some(ImageFallback {
643                code: reason.code(),
644                message: reason.to_string(),
645            }),
646            ..ShownImage::plain(
647                self.whole.check_image(None, frame)?,
648                Some(whole_frame_note(reason)),
649            )
650        })
651    }
652
653    /// The image of a frame no print is named for — a look at the printer,
654    /// before, between or after prints, a start's bed check among them: the
655    /// whole frame over a close-up of the sheet's edges and clips
656    /// ([`sheet_edges`]), with the line saying so; or, where no sheet is
657    /// located in the frame, the whole frame alone, its line saying why there
658    /// is no close-up. Either way the reason it is the whole frame is
659    /// [`WholeFrameReason::NoPrint`].
660    ///
661    /// The sheet is located through the configured calibration only for the
662    /// camera's own frame, which alone its calibration can fit.
663    fn printer_look(&self, frame: &Path, own_camera: bool) -> Result<ShownImage, String> {
664        let reason = WholeFrameReason::NoPrint;
665        let destination = self.whole.sheet_edges_destination(frame);
666        if !destination.is_file() {
667            let bytes = std::fs::read(frame)
668                .map_err(|error| format!("{} is unreadable: {error}", frame.display()))?;
669            let calibration = if own_camera {
670                self.alignments
671                    .calibration()
672                    .zip(self.camera_snapshot_url.as_deref())
673            } else {
674                None
675            };
676            let made = sheet_edges(&SheetEdgesInputs {
677                frame_jpeg: &bytes,
678                calibration,
679            });
680            match made {
681                Ok(Some(edges)) => write_image(&self.whole.directory, &destination, &edges.jpeg)?,
682                Ok(None) => {
683                    let mut shown = self.whole_frame(frame, &reason)?;
684                    shown.note = shown.note.map(|note| format!("{note}{NO_SHEET_CLAUSE}"));
685                    return Ok(shown);
686                }
687                // The frame was judged whole by the vision port before it was
688                // stored, so neither refusal is reached by a frame the camera
689                // gave; one that is is shown as any image that cannot be made.
690                Err(error) => return Err(error.to_string()),
691            }
692        }
693        Ok(ShownImage {
694            fallback: Some(ImageFallback {
695                code: reason.code(),
696                message: reason.to_string(),
697            }),
698            ..ShownImage::plain(destination, Some(sheet_edges_note(&reason)))
699        })
700    }
701
702    /// Keep the camera check a print started under, from its record, so its
703    /// checks are drawn through it from now on.
704    pub fn adopt_camera_check(
705        &self,
706        print_id: PrintId,
707        record: Option<&printobserver_types::EventRecord>,
708    ) {
709        if let Some(record) = record {
710            self.alignments.adopt_camera_check(print_id, record);
711        }
712    }
713
714    /// Judge one frame of a print — its view, and its first-layer alignment
715    /// as `alignment` asks — keeping what that decides. Nothing when no
716    /// calibration or no camera stream is configured, which leaves nothing to
717    /// judge a frame against.
718    #[must_use]
719    pub fn judge_frame(
720        &self,
721        print_id: PrintId,
722        frame: &[u8],
723        frame_sha256: &str,
724        plan: Option<&PlanPosition>,
725        alignment: AlignmentJudging,
726    ) -> Option<Judged> {
727        self.alignments.calibration()?;
728        let url = self.camera_snapshot_url.as_deref()?;
729        Some(self.alignments.judge(
730            print_id,
731            &Judging {
732                frame_jpeg: frame,
733                frame_sha256,
734                camera_snapshot_url: url,
735                plan,
736                alignment,
737            },
738        ))
739    }
740
741    /// The image one frame of a print is shown once it has been judged: the
742    /// three-panel image where the judgement allows it, and the whole frame
743    /// with the reason otherwise.
744    ///
745    /// # Errors
746    ///
747    /// Why no image could be made at all: the frame unreadable, or the image
748    /// unwritable.
749    pub fn image_of(
750        &self,
751        print_id: PrintId,
752        shown: &Shown<'_>,
753        judged: Option<&Judged>,
754    ) -> Result<ShownImage, String> {
755        let previous = self.alignments.previous_check(print_id);
756        match self.chosen(print_id, shown, judged, previous.as_ref())? {
757            Ok(composite) => Ok(composite),
758            Err(reason) => self.whole_frame(shown.frame, &reason),
759        }
760    }
761
762    /// The three-panel image of one judged frame of a print, or why it is
763    /// shown the whole frame instead.
764    fn chosen(
765        &self,
766        print_id: PrintId,
767        shown: &Shown<'_>,
768        judged: Option<&Judged>,
769        previous: Option<&PreviousCheck>,
770    ) -> Result<Result<ShownImage, WholeFrameReason>, String> {
771        let Some(calibration) = self.alignments.calibration() else {
772            return Ok(Err(WholeFrameReason::NoCalibration));
773        };
774        let Some(url) = self.camera_snapshot_url.as_deref() else {
775            return Ok(Err(WholeFrameReason::NoStream));
776        };
777        if shown.paused {
778            return Ok(Err(WholeFrameReason::Paused));
779        }
780        let Some(judged) = judged else {
781            return Ok(Err(WholeFrameReason::AlignmentPending));
782        };
783        if let Some(detail) = &judged.unreadable {
784            return Err(detail.clone());
785        }
786        let Some(plan) = shown.plan else {
787            return Ok(Err(WholeFrameReason::NoPosition));
788        };
789        let at = PlanAt {
790            index: &plan.index,
791            file_position_bytes: plan.file_position_bytes,
792        };
793        if at.index.object_at(at.file_position_bytes).is_none()
794            || at.index.object_outlines().is_empty()
795        {
796            return Ok(Err(WholeFrameReason::NoObject));
797        }
798        if at.index.layer_at(at.file_position_bytes).is_none() {
799            return Ok(Err(WholeFrameReason::NoLayer));
800        }
801        if let Err(reason) = refusal_of(judged) {
802            return Ok(Err(reason));
803        }
804        let current = std::fs::read(shown.frame)
805            .map_err(|error| format!("{} is unreadable: {error}", shown.frame.display()))?;
806        // A previous frame gone from the store, or one that no longer decodes,
807        // is one the panel cannot show, which leaves panel 3 empty rather than
808        // the check without an image.
809        let earlier = previous.and_then(|check| {
810            std::fs::read(&check.frame)
811                .ok()
812                .filter(|bytes| whole_frame(bytes).is_ok())
813                .map(|bytes| (bytes, check.captured_at))
814        });
815        let composed = match compose_at(
816            at,
817            (&current, shown.captured_at),
818            earlier.as_ref().map(|(bytes, at)| (bytes.as_slice(), *at)),
819            url,
820            calibration,
821            judged.correction.as_ref(),
822        ) {
823            Ok(composed) => composed,
824            // The current frame was judged whole by the vision port before it
825            // was stored, and the previous one was decoded above, so neither
826            // refusal is reached by a frame the camera gave; one that is is a
827            // check shown the stored frame, as any check image that cannot be
828            // made is, which `a check image that cannot be written` proves.
829            Err(WholeFrameReason::Refused(
830                ComposeError::Undecodable { detail } | ComposeError::Encode { detail },
831            )) => return Err(detail),
832            Err(reason) => return Ok(Err(reason)),
833        };
834        let destination = self.composite_destination(shown.frame, previous);
835        write_image(&self.whole.directory, &destination, &composed.jpeg)?;
836        let mut note = composite_note(
837            shown.made_for,
838            shown.captured_at,
839            earlier.as_ref().map(|(_, at)| *at),
840        );
841        note.push_str(&panel_one_clause(&composed.text));
842        if shown.made_for == ImageUse::Check
843            && let Some(clause) = self.growth_clause(print_id, plan, &current, url, calibration)
844        {
845            note.push_str(&clause);
846        }
847        Ok(Ok(ShownImage {
848            composite: true,
849            ..ShownImage::plain(destination, Some(note))
850        }))
851    }
852
853    /// What a check's line adds of whether the parts grew: the
854    /// [`not_grown_note`] when the measurement against the newest earlier
855    /// check's frame at least [`MIN_RISE_MM`] below finds they did not, and
856    /// nothing otherwise — no such frame, one gone from the store, a layer
857    /// laying supports alone, or a measurement that found growth or could not
858    /// tell. Each measurement made is said on the log.
859    fn growth_clause(
860        &self,
861        print_id: PrintId,
862        plan: &PlanPosition,
863        current: &[u8],
864        url: &str,
865        calibration: &CameraCalibration,
866    ) -> Option<String> {
867        let layer = plan.index.layer_at(plan.file_position_bytes)?;
868        let print_z_mm = plan.index.layer_z_mm(layer)?;
869        let reference = self
870            .alignments
871            .growth_reference(print_id, print_z_mm, MIN_RISE_MM)?;
872        let earlier = std::fs::read(&reference.frame).ok()?;
873        let toolpath = plan.index.layer_toolpath(layer).ok()?;
874        let measured = measure_growth(&GrowthInputs {
875            earlier_jpeg: &earlier,
876            earlier_print_z_mm: reference.print_z_mm,
877            current_jpeg: current,
878            current_print_z_mm: print_z_mm,
879            camera_snapshot_url: url,
880            toolpath: &toolpath,
881            calibration,
882        })
883        .ok()??;
884        let not_grown = measured.not_grown();
885        eprintln!(
886            "printobserver: print {print_id}: growth from Z {:.1} ({}) to Z {print_z_mm:.1}: carried {:.2}, held {:.2}, {:.0}% carried over {} samples {:.1} px apart: {}",
887            reference.print_z_mm,
888            reference.captured_at,
889            measured.carried,
890            measured.held,
891            measured.carried_share * 100.0,
892            measured.samples,
893            measured.separation_px,
894            if not_grown { "not grown" } else { "no verdict" }
895        );
896        not_grown.then(|| not_grown_note(reference.captured_at, print_z_mm - reference.print_z_mm))
897    }
898
899    /// Where the three-panel image of one stored frame, after one previous
900    /// check, is written: named for both, which name it uniquely.
901    fn composite_destination(&self, frame: &Path, previous: Option<&PreviousCheck>) -> PathBuf {
902        let named = |frame: &Path| {
903            let part = |part: Option<&std::ffi::OsStr>| {
904                part.map_or_else(String::new, |part| part.to_string_lossy().into_owned())
905            };
906            format!(
907                "{}-{}",
908                part(frame.parent().and_then(Path::file_name)),
909                part(frame.file_name())
910            )
911        };
912        let after = previous.map_or_else(|| "first".to_owned(), |check| named(&check.frame));
913        self.whole
914            .directory
915            .join(format!("{}-composite-after-{after}.jpg", named(frame)))
916    }
917}
918
919impl CheckImages for PanelImages {
920    fn check_image(&self, print_id: Option<PrintId>, frame: &Path) -> Result<PathBuf, String> {
921        self.whole.check_image(print_id, frame)
922    }
923
924    fn restart_growth(&self, print_id: PrintId) {
925        self.alignments.restart_growth(print_id);
926    }
927
928    fn composes(&self, print_id: PrintId) -> bool {
929        self.alignments.calibration().is_some()
930            && self.camera_snapshot_url.is_some()
931            && (self.alignments.started_under_a_camera_check(print_id)
932                || matches!(
933                    self.alignments.print_alignment(print_id),
934                    PrintAlignment::Passed { .. }
935                ))
936    }
937
938    fn shown_image(&self, request: &CheckImageRequest<'_>) -> Result<ShownImage, String> {
939        let Some(print_id) = request.print_id else {
940            return self.printer_look(request.frame, request.own_camera);
941        };
942        if let Some(record) = &request.camera_check {
943            self.alignments.adopt_camera_check(print_id, record);
944        }
945        // A check taken while the printer reports the print paused is not
946        // judged: its bed is lowered off the plan's height.
947        let judged = if request.paused {
948            None
949        } else {
950            let alignment = if request.made_for == ImageUse::Check && request.own_camera {
951                AlignmentJudging::WhilePending
952            } else {
953                AlignmentJudging::Never
954            };
955            match std::fs::read(request.frame) {
956                Ok(current) => self.judge_frame(
957                    print_id,
958                    &current,
959                    request.frame_sha256,
960                    request.plan.as_ref(),
961                    alignment,
962                ),
963                Err(error) => {
964                    return Err(format!(
965                        "{} is unreadable: {error}",
966                        request.frame.display()
967                    ));
968                }
969            }
970        };
971        let shown = Shown {
972            frame: request.frame,
973            captured_at: request.captured_at,
974            made_for: request.made_for,
975            plan: request.plan.as_ref(),
976            paused: request.paused,
977        };
978        let mut image = self.image_of(print_id, &shown, judged.as_ref())?;
979        image.records = judged.map(|judged| judged.records).unwrap_or_default();
980        // Only the camera's own frame is a later check's panel 3 or the
981        // reference its growth is measured from: a detector's picture need be
982        // neither the calibration's size nor its stream, and the composer
983        // refuses a previous frame of another size than the current one.
984        if request.made_for == ImageUse::Check && request.own_camera {
985            self.alignments.record_check(
986                print_id,
987                &PreviousCheck {
988                    frame: request.frame.to_path_buf(),
989                    captured_at: request.captured_at,
990                },
991            );
992            if let Some(print_z_mm) = request.plan.as_ref().and_then(plan_z) {
993                self.alignments.record_checked_frame(
994                    print_id,
995                    CheckedFrame {
996                        frame: request.frame.to_path_buf(),
997                        captured_at: request.captured_at,
998                        print_z_mm,
999                    },
1000                    MIN_RISE_MM,
1001                );
1002            }
1003        }
1004        if request.made_for == ImageUse::Check {
1005            image.records.extend(self.alignments.note_check_image(
1006                print_id,
1007                LastCheckImage {
1008                    at: request.captured_at,
1009                    kind: image.kind(),
1010                    fallback: image.fallback.clone(),
1011                },
1012                request.frame_sha256,
1013            ));
1014        }
1015        Ok(image)
1016    }
1017}