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 if judged.camera_check.is_some() {
437 return refusal_under_check(judged);
438 }
439 match &judged.alignment {
440 PrintAlignment::Passed { .. } => {}
441 PrintAlignment::Pending => {
442 return Err(judged.inconclusive.map_or(
443 WholeFrameReason::AlignmentPending,
444 WholeFrameReason::AlignmentInconclusive,
445 ));
446 }
447 PrintAlignment::Unavailable => return Err(WholeFrameReason::AlignmentUnavailable),
448 PrintAlignment::Failed { reason } => {
449 return Err(WholeFrameReason::AlignmentFailed(reason.clone()));
450 }
451 }
452 if let Some(reason) = &judged.mismatch {
453 return Err(WholeFrameReason::FrameMismatch(reason.clone()));
454 }
455 let said = |reason: &Option<String>| reason.clone().unwrap_or_default();
456 match &judged.view {
457 Some((ViewOutcome::LandmarksNotFound, reason)) => {
458 Err(WholeFrameReason::LandmarksNotFound(said(reason)))
459 }
460 Some((ViewOutcome::ViewRefitRejected, reason)) => {
461 Err(WholeFrameReason::ViewRefitRejected(said(reason)))
462 }
463 Some((ViewOutcome::FrameMismatch, reason)) => {
464 Err(WholeFrameReason::FrameMismatch(said(reason)))
465 }
466 Some((ViewOutcome::Refit, _)) => Err(WholeFrameReason::CalibrationStale),
467 Some((ViewOutcome::Unshifted, _)) | None => Ok(()),
468 }
469}
470
471fn refusal_under_check(judged: &Judged) -> Result<(), WholeFrameReason> {
478 if let Some(reason) = &judged.mismatch {
479 return Err(WholeFrameReason::FrameMismatch(reason.clone()));
480 }
481 let said = |reason: &Option<String>| reason.clone().unwrap_or_default();
482 match &judged.view {
483 Some((ViewOutcome::LandmarksNotFound, reason)) => {
484 Err(WholeFrameReason::LandmarksNotFound(said(reason)))
485 }
486 Some((ViewOutcome::ViewRefitRejected, reason)) => {
487 Err(WholeFrameReason::ViewRefitRejected(said(reason)))
488 }
489 Some((ViewOutcome::FrameMismatch, reason)) => {
490 Err(WholeFrameReason::FrameMismatch(said(reason)))
491 }
492 Some((ViewOutcome::Refit | ViewOutcome::Unshifted, _)) | None => Ok(()),
493 }
494}
495
496#[derive(Debug, Clone, Copy)]
498pub struct Shown<'a> {
499 pub frame: &'a Path,
501 pub captured_at: Timestamp,
503 pub made_for: ImageUse,
505 pub plan: Option<&'a PlanPosition>,
507 pub paused: bool,
509}
510
511pub struct PanelImages {
514 whole: WholeFrames,
516 alignments: Arc<Alignments>,
518 camera_snapshot_url: Option<String>,
521}
522
523impl core::fmt::Debug for PanelImages {
524 fn fmt(&self, formatter: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
525 formatter
526 .debug_struct("PanelImages")
527 .field("whole", &self.whole)
528 .field("camera_snapshot_url", &self.camera_snapshot_url)
529 .finish_non_exhaustive()
530 }
531}
532
533impl PanelImages {
534 #[must_use]
536 pub fn new(
537 state_dir: &Path,
538 alignments: Arc<Alignments>,
539 camera_snapshot_url: Option<String>,
540 ) -> Self {
541 Self {
542 whole: WholeFrames::under(state_dir),
543 alignments,
544 camera_snapshot_url,
545 }
546 }
547
548 #[must_use]
550 pub fn calibration(&self) -> Option<&CameraCalibration> {
551 self.alignments.calibration()
552 }
553
554 pub fn write_camera_check_image(
561 &self,
562 camera_check: printobserver_core::CameraCheckId,
563 jpeg: &[u8],
564 ) -> Result<PathBuf, String> {
565 let destination = self
566 .whole
567 .directory
568 .join(format!("camera-check-{camera_check}.jpg"));
569 write_image(&self.whole.directory, &destination, jpeg)?;
570 Ok(destination)
571 }
572
573 #[must_use]
575 pub fn alignment(&self, print_id: PrintId) -> PrintAlignment {
576 self.alignments.print_alignment(print_id)
577 }
578
579 #[must_use]
581 pub fn last_check_image(&self, print_id: PrintId) -> Option<LastCheckImage> {
582 self.alignments.last_check_image(print_id)
583 }
584
585 fn whole_frame(&self, frame: &Path, reason: &WholeFrameReason) -> Result<ShownImage, String> {
587 Ok(ShownImage {
588 fallback: Some(ImageFallback {
589 code: reason.code(),
590 message: reason.to_string(),
591 }),
592 ..ShownImage::plain(
593 self.whole.check_image(None, frame)?,
594 Some(whole_frame_note(reason)),
595 )
596 })
597 }
598
599 pub fn adopt_camera_check(
602 &self,
603 print_id: PrintId,
604 record: Option<&printobserver_types::EventRecord>,
605 ) {
606 if let Some(record) = record {
607 self.alignments.adopt_camera_check(print_id, record);
608 }
609 }
610
611 #[must_use]
616 pub fn judge_frame(
617 &self,
618 print_id: PrintId,
619 frame: &[u8],
620 frame_sha256: &str,
621 plan: Option<&PlanPosition>,
622 alignment: AlignmentJudging,
623 ) -> Option<Judged> {
624 self.alignments.calibration()?;
625 let url = self.camera_snapshot_url.as_deref()?;
626 Some(self.alignments.judge(
627 print_id,
628 &Judging {
629 frame_jpeg: frame,
630 frame_sha256,
631 camera_snapshot_url: url,
632 plan,
633 alignment,
634 },
635 ))
636 }
637
638 pub fn image_of(
647 &self,
648 print_id: PrintId,
649 shown: &Shown<'_>,
650 judged: Option<&Judged>,
651 ) -> Result<ShownImage, String> {
652 let previous = self.alignments.previous_check(print_id);
653 match self.chosen(print_id, shown, judged, previous.as_ref())? {
654 Ok(composite) => Ok(composite),
655 Err(reason) => self.whole_frame(shown.frame, &reason),
656 }
657 }
658
659 fn chosen(
662 &self,
663 print_id: PrintId,
664 shown: &Shown<'_>,
665 judged: Option<&Judged>,
666 previous: Option<&PreviousCheck>,
667 ) -> Result<Result<ShownImage, WholeFrameReason>, String> {
668 let Some(calibration) = self.alignments.calibration() else {
669 return Ok(Err(WholeFrameReason::NoCalibration));
670 };
671 let Some(url) = self.camera_snapshot_url.as_deref() else {
672 return Ok(Err(WholeFrameReason::NoStream));
673 };
674 if shown.paused {
675 return Ok(Err(WholeFrameReason::Paused));
676 }
677 let Some(judged) = judged else {
678 return Ok(Err(WholeFrameReason::AlignmentPending));
679 };
680 if let Some(detail) = &judged.unreadable {
681 return Err(detail.clone());
682 }
683 let Some(plan) = shown.plan else {
684 return Ok(Err(WholeFrameReason::NoPosition));
685 };
686 let at = PlanAt {
687 index: &plan.index,
688 file_position_bytes: plan.file_position_bytes,
689 };
690 if at.index.object_at(at.file_position_bytes).is_none()
691 || at.index.object_outlines().is_empty()
692 {
693 return Ok(Err(WholeFrameReason::NoObject));
694 }
695 if at.index.layer_at(at.file_position_bytes).is_none() {
696 return Ok(Err(WholeFrameReason::NoLayer));
697 }
698 if let Err(reason) = refusal_of(judged) {
699 return Ok(Err(reason));
700 }
701 let current = std::fs::read(shown.frame)
702 .map_err(|error| format!("{} is unreadable: {error}", shown.frame.display()))?;
703 let earlier = previous.and_then(|check| {
707 std::fs::read(&check.frame)
708 .ok()
709 .filter(|bytes| whole_frame(bytes).is_ok())
710 .map(|bytes| (bytes, check.captured_at))
711 });
712 let composed = match compose_at(
713 at,
714 (¤t, shown.captured_at),
715 earlier.as_ref().map(|(bytes, at)| (bytes.as_slice(), *at)),
716 url,
717 calibration,
718 judged.correction.as_ref(),
719 ) {
720 Ok(composed) => composed,
721 Err(WholeFrameReason::Refused(
727 ComposeError::Undecodable { detail } | ComposeError::Encode { detail },
728 )) => return Err(detail),
729 Err(reason) => return Ok(Err(reason)),
730 };
731 let destination = self.composite_destination(shown.frame, previous);
732 write_image(&self.whole.directory, &destination, &composed.jpeg)?;
733 let mut note = composite_note(
734 shown.made_for,
735 shown.captured_at,
736 earlier.as_ref().map(|(_, at)| *at),
737 );
738 if shown.made_for == ImageUse::Check
739 && let Some(clause) = self.growth_clause(print_id, plan, ¤t, url, calibration)
740 {
741 note.push_str(&clause);
742 }
743 Ok(Ok(ShownImage {
744 composite: true,
745 ..ShownImage::plain(destination, Some(note))
746 }))
747 }
748
749 fn growth_clause(
756 &self,
757 print_id: PrintId,
758 plan: &PlanPosition,
759 current: &[u8],
760 url: &str,
761 calibration: &CameraCalibration,
762 ) -> Option<String> {
763 let layer = plan.index.layer_at(plan.file_position_bytes)?;
764 let print_z_mm = plan.index.layer_z_mm(layer)?;
765 let reference = self
766 .alignments
767 .growth_reference(print_id, print_z_mm, MIN_RISE_MM)?;
768 let earlier = std::fs::read(&reference.frame).ok()?;
769 let toolpath = plan.index.layer_toolpath(layer).ok()?;
770 let measured = measure_growth(&GrowthInputs {
771 earlier_jpeg: &earlier,
772 earlier_print_z_mm: reference.print_z_mm,
773 current_jpeg: current,
774 current_print_z_mm: print_z_mm,
775 camera_snapshot_url: url,
776 toolpath: &toolpath,
777 calibration,
778 })
779 .ok()??;
780 let not_grown = measured.not_grown();
781 eprintln!(
782 "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: {}",
783 reference.print_z_mm,
784 reference.captured_at,
785 measured.carried,
786 measured.held,
787 measured.carried_share * 100.0,
788 measured.samples,
789 measured.separation_px,
790 if not_grown { "not grown" } else { "no verdict" }
791 );
792 not_grown.then(|| not_grown_note(reference.captured_at, print_z_mm - reference.print_z_mm))
793 }
794
795 fn composite_destination(&self, frame: &Path, previous: Option<&PreviousCheck>) -> PathBuf {
798 let named = |frame: &Path| {
799 let part = |part: Option<&std::ffi::OsStr>| {
800 part.map_or_else(String::new, |part| part.to_string_lossy().into_owned())
801 };
802 format!(
803 "{}-{}",
804 part(frame.parent().and_then(Path::file_name)),
805 part(frame.file_name())
806 )
807 };
808 let after = previous.map_or_else(|| "first".to_owned(), |check| named(&check.frame));
809 self.whole
810 .directory
811 .join(format!("{}-composite-after-{after}.jpg", named(frame)))
812 }
813}
814
815impl CheckImages for PanelImages {
816 fn check_image(&self, print_id: Option<PrintId>, frame: &Path) -> Result<PathBuf, String> {
817 self.whole.check_image(print_id, frame)
818 }
819
820 fn restart_growth(&self, print_id: PrintId) {
821 self.alignments.restart_growth(print_id);
822 }
823
824 fn composes(&self, print_id: PrintId) -> bool {
825 self.alignments.calibration().is_some()
826 && self.camera_snapshot_url.is_some()
827 && (self.alignments.started_under_a_camera_check(print_id)
828 || matches!(
829 self.alignments.print_alignment(print_id),
830 PrintAlignment::Passed { .. }
831 ))
832 }
833
834 fn shown_image(&self, request: &CheckImageRequest<'_>) -> Result<ShownImage, String> {
835 let Some(print_id) = request.print_id else {
836 return self.whole_frame(request.frame, &WholeFrameReason::NoPrint);
837 };
838 if let Some(record) = &request.camera_check {
839 self.alignments.adopt_camera_check(print_id, record);
840 }
841 let judged = if request.paused {
844 None
845 } else {
846 let alignment = if request.made_for == ImageUse::Check && request.own_camera {
847 AlignmentJudging::WhilePending
848 } else {
849 AlignmentJudging::Never
850 };
851 match std::fs::read(request.frame) {
852 Ok(current) => self.judge_frame(
853 print_id,
854 ¤t,
855 request.frame_sha256,
856 request.plan.as_ref(),
857 alignment,
858 ),
859 Err(error) => {
860 return Err(format!(
861 "{} is unreadable: {error}",
862 request.frame.display()
863 ));
864 }
865 }
866 };
867 let shown = Shown {
868 frame: request.frame,
869 captured_at: request.captured_at,
870 made_for: request.made_for,
871 plan: request.plan.as_ref(),
872 paused: request.paused,
873 };
874 let mut image = self.image_of(print_id, &shown, judged.as_ref())?;
875 image.records = judged.map(|judged| judged.records).unwrap_or_default();
876 if request.made_for == ImageUse::Check && request.own_camera {
881 self.alignments.record_check(
882 print_id,
883 &PreviousCheck {
884 frame: request.frame.to_path_buf(),
885 captured_at: request.captured_at,
886 },
887 );
888 if let Some(print_z_mm) = request.plan.as_ref().and_then(plan_z) {
889 self.alignments.record_checked_frame(
890 print_id,
891 CheckedFrame {
892 frame: request.frame.to_path_buf(),
893 captured_at: request.captured_at,
894 print_z_mm,
895 },
896 MIN_RISE_MM,
897 );
898 }
899 }
900 if request.made_for == ImageUse::Check {
901 image.records.extend(self.alignments.note_check_image(
902 print_id,
903 LastCheckImage {
904 at: request.captured_at,
905 kind: image.kind(),
906 fallback: image.fallback.clone(),
907 },
908 request.frame_sha256,
909 ));
910 }
911 Ok(image)
912 }
913}