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