1use 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
43static WRITES: AtomicU64 = AtomicU64::new(0);
46
47pub const CHECK_IMAGES_DIRECTORY: &str = "check-images";
49
50#[derive(Debug, Clone)]
52pub struct WholeFrames {
53 directory: PathBuf,
55}
56
57impl WholeFrames {
58 #[must_use]
60 pub fn under(state_dir: &Path) -> Self {
61 Self {
62 directory: state_dir.join(CHECK_IMAGES_DIRECTORY),
63 }
64 }
65
66 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
97fn 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 let _ = std::fs::remove_file(&partial);
113 format!("{} cannot be written: {error}", destination.display())
114 })
115}
116
117pub const COMPOSITE_NOTE: &str = "the three-panel check image";
120
121pub const WHOLE_FRAME_NOTE: &str = "the whole camera frame";
123
124#[derive(Debug, Clone, PartialEq)]
126pub enum WholeFrameReason {
127 NoPrint,
130 NoCalibration,
132 NoStream,
135 NoPosition,
138 NoObject,
141 NoLayer,
143 ToolpathUnread(String),
145 AlignmentPending,
147 AlignmentInconclusive(InconclusiveReason),
150 AlignmentUnavailable,
152 AlignmentFailed(AlignmentFailure),
154 LandmarksNotFound(String),
157 ViewRefitRejected(String),
159 CalibrationStale,
163 FrameMismatch(String),
165 Paused,
168 Refused(ComposeError),
170}
171
172impl WholeFrameReason {
173 #[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
255pub const CALIBRATION_STALE: &str = "the camera has moved since its calibration, so the outline cannot be drawn reliably; recalibrate this camera";
258
259pub const UNSEEN_RISE_BOUND_MM: f64 = 5.0;
266
267#[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
286const CAMERA_HOLDS: &str = "the camera does not shift in regular operation and the drawing already accounts for the bed's travel, so ";
290
291#[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#[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
354fn 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#[derive(Debug, Clone, Copy)]
364pub struct PlanAt<'a> {
365 pub index: &'a GcodeIndex,
367 pub file_position_bytes: u64,
369}
370
371pub 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
426fn 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#[derive(Debug, Clone, Copy)]
470pub struct Shown<'a> {
471 pub frame: &'a Path,
473 pub captured_at: Timestamp,
475 pub made_for: ImageUse,
477 pub plan: Option<&'a PlanPosition>,
479 pub paused: bool,
481}
482
483pub struct PanelImages {
486 whole: WholeFrames,
488 alignments: Arc<Alignments>,
490 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 #[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 #[must_use]
522 pub fn alignment(&self, print_id: PrintId) -> PrintAlignment {
523 self.alignments.print_alignment(print_id)
524 }
525
526 #[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 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 #[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 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 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 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 (¤t, 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 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, ¤t, 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 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 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 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 ¤t,
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 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}