use std::path::{Path, PathBuf};
use std::sync::atomic::{AtomicU64, Ordering};
use std::sync::Arc;
use printobserver_core::check_image::PlanPosition;
use printobserver_core::{CheckImageRequest, CheckImages, GcodeIndex, ImageUse, ShownImage};
use printobserver_panels::growth::MIN_RISE_MM;
use printobserver_panels::{
CameraCalibration, CheckImage, CheckImageInputs, ComposeError, GrowthInputs, SheetEdgesInputs,
WHOLE_FRAME_HEIGHT, WHOLE_FRAME_WIDTH, compose_check_image, measure_growth, sheet_edges,
whole_frame,
};
use printobserver_types::{PrintId, Timestamp};
use printobserver_panels::{InconclusiveReason, ViewCorrection, ViewOutcome};
use printobserver_supervisor_api::{ImageFallback, WholeFrameReasonCode};
use crate::alignment::{
AlignmentFailure, AlignmentJudging, Alignments, CheckedFrame, Judged, Judging, LastCheckImage,
PreviousCheck, PrintAlignment, failure_sentence,
};
static WRITES: AtomicU64 = AtomicU64::new(0);
pub const CHECK_IMAGES_DIRECTORY: &str = "check-images";
#[derive(Debug, Clone)]
pub struct WholeFrames {
directory: PathBuf,
}
impl WholeFrames {
#[must_use]
pub fn under(state_dir: &Path) -> Self {
Self {
directory: state_dir.join(CHECK_IMAGES_DIRECTORY),
}
}
fn destination(&self, frame: &Path) -> PathBuf {
let named = |part: Option<&std::ffi::OsStr>| {
part.map_or_else(String::new, |part| part.to_string_lossy().into_owned())
};
let parent = named(frame.parent().and_then(Path::file_name));
let file = named(frame.file_name());
self.directory.join(format!(
"{parent}-{file}-{WHOLE_FRAME_WIDTH}x{WHOLE_FRAME_HEIGHT}.jpg"
))
}
}
impl WholeFrames {
fn sheet_edges_destination(&self, frame: &Path) -> PathBuf {
let scaled = self.destination(frame);
let stem = scaled
.file_stem()
.map_or_else(String::new, |stem| stem.to_string_lossy().into_owned());
self.directory.join(format!("{stem}-sheet-edges.jpg"))
}
}
impl CheckImages for WholeFrames {
fn check_image(&self, _print_id: Option<PrintId>, frame: &Path) -> Result<PathBuf, String> {
let destination = self.destination(frame);
if destination.is_file() {
return Ok(destination);
}
let bytes = std::fs::read(frame)
.map_err(|error| format!("{} is unreadable: {error}", frame.display()))?;
let scaled = whole_frame(&bytes).map_err(|error| error.to_string())?;
if !scaled.scaled {
return Ok(frame.to_path_buf());
}
write_image(&self.directory, &destination, &scaled.jpeg)?;
Ok(destination)
}
}
fn write_image(directory: &Path, destination: &Path, bytes: &[u8]) -> Result<(), String> {
std::fs::create_dir_all(directory)
.map_err(|error| format!("{} cannot be made: {error}", directory.display()))?;
let partial = destination.with_extension(format!(
"{}-{}.partial",
std::process::id(),
WRITES.fetch_add(1, Ordering::Relaxed)
));
let written =
std::fs::write(&partial, bytes).and_then(|()| std::fs::rename(&partial, destination));
written.map_err(|error| {
let _ = std::fs::remove_file(&partial);
format!("{} cannot be written: {error}", destination.display())
})
}
pub const COMPOSITE_NOTE: &str = "the three-panel check image";
pub const WHOLE_FRAME_NOTE: &str = "the whole camera frame";
#[derive(Debug, Clone, PartialEq)]
pub enum WholeFrameReason {
NoPrint,
NoCalibration,
NoStream,
NoPosition,
NoObject,
NoLayer,
ToolpathUnread(String),
AlignmentPending,
AlignmentInconclusive(InconclusiveReason),
AlignmentUnavailable,
AlignmentFailed(AlignmentFailure),
LandmarksNotFound(String),
ViewRefitRejected(String),
CalibrationStale,
FrameMismatch(String),
Paused,
Refused(ComposeError),
}
impl WholeFrameReason {
#[must_use]
pub const fn code(&self) -> WholeFrameReasonCode {
match self {
Self::NoPrint => WholeFrameReasonCode::NoPrint,
Self::NoCalibration => WholeFrameReasonCode::NoCalibration,
Self::NoStream => WholeFrameReasonCode::NoStream,
Self::NoPosition => WholeFrameReasonCode::NoPosition,
Self::NoObject => WholeFrameReasonCode::NoObject,
Self::NoLayer => WholeFrameReasonCode::NoLayer,
Self::ToolpathUnread(_) => WholeFrameReasonCode::ToolpathUnread,
Self::AlignmentPending => WholeFrameReasonCode::AlignmentPending,
Self::AlignmentInconclusive(_) => WholeFrameReasonCode::AlignmentInconclusive,
Self::AlignmentUnavailable => WholeFrameReasonCode::AlignmentUnavailable,
Self::AlignmentFailed(_) => WholeFrameReasonCode::AlignmentFailed,
Self::LandmarksNotFound(_) | Self::Refused(ComposeError::DriftUnverified) => {
WholeFrameReasonCode::LandmarksNotFound
}
Self::ViewRefitRejected(_) | Self::Refused(ComposeError::CameraMoved { .. }) => {
WholeFrameReasonCode::ViewRefitRejected
}
Self::FrameMismatch(_) | Self::Refused(ComposeError::FrameMismatch { .. }) => {
WholeFrameReasonCode::FrameMismatch
}
Self::CalibrationStale => WholeFrameReasonCode::CalibrationStale,
Self::Paused => WholeFrameReasonCode::Paused,
Self::Refused(_) => WholeFrameReasonCode::Refused,
}
}
}
impl core::fmt::Display for WholeFrameReason {
fn fmt(&self, formatter: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
match self {
Self::NoPrint => formatter
.write_str("no print is named, so there is no planned toolpath to draw on it"),
Self::NoCalibration => formatter.write_str("no camera calibration is configured"),
Self::NoStream => formatter.write_str(
"no camera snapshot address is configured, so the frame's stream is unknown",
),
Self::NoPosition => formatter.write_str(
"the print's G-code index gives no file position for this check",
),
Self::NoObject => formatter.write_str(
"the print's G-code names no extruded object laid at this point",
),
Self::NoLayer => formatter.write_str("the print's G-code names no layer at this point"),
Self::ToolpathUnread(detail) => write!(
formatter,
"the layer's planned toolpath could not be read from the print's spool: {detail}"
),
Self::AlignmentPending => formatter.write_str(
"the print's first-layer alignment is pending: its first object layer is not down, or no frame of it has been judged yet",
),
Self::AlignmentInconclusive(why) => write!(
formatter,
"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",
match why {
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",
InconclusiveReason::NotClearlyFound => "the printed first layer was not clearly found",
}
),
Self::AlignmentUnavailable => {
formatter.write_str("the print's G-code lays no object to align")
}
Self::AlignmentFailed(failure) => write!(
formatter,
"the print's first-layer alignment failed: {}",
failure_sentence(failure)
),
Self::LandmarksNotFound(reason) | Self::ViewRefitRejected(reason) | Self::FrameMismatch(reason) => {
formatter.write_str(reason)
}
Self::CalibrationStale => formatter.write_str(CALIBRATION_STALE),
Self::Paused => formatter.write_str(
"the printer reports the print paused, so its bed may stand off the plan's height and nothing is drawn",
),
Self::Refused(error) => error.fmt(formatter),
}
}
}
pub const CALIBRATION_STALE: &str = "the camera has moved since its calibration, so the outline cannot be drawn reliably; recalibrate this camera";
pub const UNSEEN_RISE_BOUND_MM: f64 = 5.0;
#[must_use]
pub fn whole_frame_note(reason: &WholeFrameReason) -> String {
let bound = match reason {
WholeFrameReason::CalibrationStale | WholeFrameReason::AlignmentInconclusive(_) => format!(
"; 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"
),
_ => String::new(),
};
format!(
"{WHOLE_FRAME_NOTE}, scaled to fit {WHOLE_FRAME_WIDTH}x{WHOLE_FRAME_HEIGHT} and uncropped, because {reason}{bound}"
)
}
pub const NO_SHEET_CLAUSE: &str =
"; no sheet was found in it, so no close-up of the sheet's edges is shown";
#[must_use]
pub fn sheet_edges_note(reason: &WholeFrameReason) -> String {
format!(
"{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"
)
}
const CAMERA_HOLDS: &str = "the camera holds still and the drawing follows the bed, so ";
#[must_use]
pub fn composite_note(
made_for: ImageUse,
current_at: Timestamp,
previous_at: Option<Timestamp>,
) -> String {
let (current, previous, moved) = match (made_for, previous_at) {
(ImageUse::Look, at) => (
"this layer's planned toolpath drawn on the frame".to_owned(),
if at.is_none() {
"panel 3 empty, no earlier frame at hand".to_owned()
} else {
"panel 3 the previous check's frame".to_owned()
},
String::new(),
),
(ImageUse::Check, None) => (
format!(
"this check's frame, captured {current_at}, with this layer's planned toolpath drawn"
),
"panel 3 empty, no earlier frame at hand".to_owned(),
format!(
"; {CAMERA_HOLDS}a part off its drawn walls in panel 1 has moved unless strongly shown otherwise; no later frame undoes that"
),
),
(ImageUse::Check, Some(at)) => (
format!(
"this check's frame, captured {current_at}, with this layer's planned toolpath drawn"
),
format!("panel 3 the last check's frame, captured {at}"),
format!(
"; {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"
),
),
};
format!(
"{COMPOSITE_NOTE}, {}x{}: panel 1 {current}, panel 2 a close-up of the part, {previous}{moved}",
printobserver_panels::compose::PANEL_WIDTH,
printobserver_panels::compose::IMAGE_HEIGHT
)
}
#[must_use]
pub fn not_grown_note(since: Timestamp, rise_mm: f64) -> String {
format!(
"; 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"
)
}
fn plan_z(plan: &PlanPosition) -> Option<f64> {
plan.index
.layer_at(plan.file_position_bytes)
.and_then(|layer| plan.index.layer_z_mm(layer))
}
#[derive(Debug, Clone, Copy)]
pub struct PlanAt<'a> {
pub index: &'a GcodeIndex,
pub file_position_bytes: u64,
}
pub fn compose_at(
plan: PlanAt<'_>,
current: (&[u8], Timestamp),
previous: Option<(&[u8], Timestamp)>,
camera_snapshot_url: &str,
calibration: &CameraCalibration,
correction: Option<&ViewCorrection>,
) -> Result<CheckImage, WholeFrameReason> {
let index = plan.index;
let position = plan.file_position_bytes;
let active_object = index
.object_at(position)
.filter(|object| *object < index.object_outlines().len())
.ok_or(WholeFrameReason::NoObject)?;
let layer = index.layer_at(position).ok_or(WholeFrameReason::NoLayer)?;
let print_z_mm = index.layer_z_mm(layer).ok_or(WholeFrameReason::NoLayer)?;
let unread =
|error: printobserver_core::SpoolError| WholeFrameReason::ToolpathUnread(error.to_string());
let toolpath = index.layer_toolpath(layer).map_err(unread)?;
let below = if toolpath.carries_object_extrusion() {
None
} else {
index
.object_layer_at_or_below(layer)
.map(|below| index.layer_toolpath(below))
.transpose()
.map_err(unread)?
};
let facts = index.layer_facts(position, &toolpath);
let head_trail_mm = index
.planned_heads_before(position, printobserver_panels::occlusion::QUEUED_MOVES)
.ok()
.flatten()
.map(|heads| heads.trail)
.unwrap_or_default();
compose_check_image(&CheckImageInputs {
current_jpeg: current.0,
current_at: current.1,
camera_snapshot_url,
previous,
outlines: index.object_outlines(),
active_object,
toolpath: &toolpath,
object_layer_below: below.as_ref(),
print_z_mm,
calibration,
correction,
file_position_bytes: Some(position),
facts: facts.as_ref(),
head_trail_mm: &head_trail_mm,
reported_head_mm: None,
})
.map_err(WholeFrameReason::Refused)
}
#[must_use]
pub fn panel_one_clause(text: &[String]) -> String {
if text.is_empty() {
return String::new();
}
format!("; panel 1: {}", text.join("; "))
}
fn refusal_of(judged: &Judged) -> Result<(), WholeFrameReason> {
if let Some(reason) = &judged.rejected {
return Err(WholeFrameReason::ViewRefitRejected(reason.clone()));
}
if judged.camera_check.is_some() {
return refusal_under_check(judged);
}
match &judged.alignment {
PrintAlignment::Passed { .. } => {}
PrintAlignment::Pending => {
return Err(judged.inconclusive.map_or(
WholeFrameReason::AlignmentPending,
WholeFrameReason::AlignmentInconclusive,
));
}
PrintAlignment::Unavailable => return Err(WholeFrameReason::AlignmentUnavailable),
PrintAlignment::Failed { reason } => {
return Err(WholeFrameReason::AlignmentFailed(reason.clone()));
}
}
if let Some(reason) = &judged.mismatch {
return Err(WholeFrameReason::FrameMismatch(reason.clone()));
}
let said = |reason: &Option<String>| reason.clone().unwrap_or_default();
match &judged.view {
Some((ViewOutcome::LandmarksNotFound, reason)) => {
Err(WholeFrameReason::LandmarksNotFound(said(reason)))
}
Some((ViewOutcome::ViewRefitRejected, reason)) => {
Err(WholeFrameReason::ViewRefitRejected(said(reason)))
}
Some((ViewOutcome::FrameMismatch, reason)) => {
Err(WholeFrameReason::FrameMismatch(said(reason)))
}
Some((ViewOutcome::Refit, _)) => Err(WholeFrameReason::CalibrationStale),
Some((ViewOutcome::Unshifted, _)) | None => Ok(()),
}
}
fn refusal_under_check(judged: &Judged) -> Result<(), WholeFrameReason> {
if let Some(reason) = &judged.mismatch {
return Err(WholeFrameReason::FrameMismatch(reason.clone()));
}
let said = |reason: &Option<String>| reason.clone().unwrap_or_default();
match &judged.view {
Some((ViewOutcome::LandmarksNotFound, reason)) => {
Err(WholeFrameReason::LandmarksNotFound(said(reason)))
}
Some((ViewOutcome::ViewRefitRejected, reason)) => {
Err(WholeFrameReason::ViewRefitRejected(said(reason)))
}
Some((ViewOutcome::FrameMismatch, reason)) => {
Err(WholeFrameReason::FrameMismatch(said(reason)))
}
Some((ViewOutcome::Refit | ViewOutcome::Unshifted, _)) | None => Ok(()),
}
}
#[derive(Debug, Clone, Copy)]
pub struct Shown<'a> {
pub frame: &'a Path,
pub captured_at: Timestamp,
pub made_for: ImageUse,
pub plan: Option<&'a PlanPosition>,
pub paused: bool,
}
pub struct PanelImages {
whole: WholeFrames,
alignments: Arc<Alignments>,
camera_snapshot_url: Option<String>,
}
impl core::fmt::Debug for PanelImages {
fn fmt(&self, formatter: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
formatter
.debug_struct("PanelImages")
.field("whole", &self.whole)
.field("camera_snapshot_url", &self.camera_snapshot_url)
.finish_non_exhaustive()
}
}
impl PanelImages {
#[must_use]
pub fn new(
state_dir: &Path,
alignments: Arc<Alignments>,
camera_snapshot_url: Option<String>,
) -> Self {
Self {
whole: WholeFrames::under(state_dir),
alignments,
camera_snapshot_url,
}
}
#[must_use]
pub fn calibration(&self) -> Option<&CameraCalibration> {
self.alignments.calibration()
}
pub fn write_camera_check_image(
&self,
camera_check: printobserver_core::CameraCheckId,
jpeg: &[u8],
) -> Result<PathBuf, String> {
let destination = self
.whole
.directory
.join(format!("camera-check-{camera_check}.jpg"));
write_image(&self.whole.directory, &destination, jpeg)?;
Ok(destination)
}
#[must_use]
pub fn alignment(&self, print_id: PrintId) -> PrintAlignment {
self.alignments.print_alignment(print_id)
}
#[must_use]
pub fn last_check_image(&self, print_id: PrintId) -> Option<LastCheckImage> {
self.alignments.last_check_image(print_id)
}
fn whole_frame(&self, frame: &Path, reason: &WholeFrameReason) -> Result<ShownImage, String> {
Ok(ShownImage {
fallback: Some(ImageFallback {
code: reason.code(),
message: reason.to_string(),
}),
..ShownImage::plain(
self.whole.check_image(None, frame)?,
Some(whole_frame_note(reason)),
)
})
}
fn printer_look(&self, frame: &Path, own_camera: bool) -> Result<ShownImage, String> {
let reason = WholeFrameReason::NoPrint;
let destination = self.whole.sheet_edges_destination(frame);
if !destination.is_file() {
let bytes = std::fs::read(frame)
.map_err(|error| format!("{} is unreadable: {error}", frame.display()))?;
let calibration = if own_camera {
self.alignments
.calibration()
.zip(self.camera_snapshot_url.as_deref())
} else {
None
};
let made = sheet_edges(&SheetEdgesInputs {
frame_jpeg: &bytes,
calibration,
});
match made {
Ok(Some(edges)) => write_image(&self.whole.directory, &destination, &edges.jpeg)?,
Ok(None) => {
let mut shown = self.whole_frame(frame, &reason)?;
shown.note = shown.note.map(|note| format!("{note}{NO_SHEET_CLAUSE}"));
return Ok(shown);
}
Err(error) => return Err(error.to_string()),
}
}
Ok(ShownImage {
fallback: Some(ImageFallback {
code: reason.code(),
message: reason.to_string(),
}),
..ShownImage::plain(destination, Some(sheet_edges_note(&reason)))
})
}
pub fn adopt_camera_check(
&self,
print_id: PrintId,
record: Option<&printobserver_types::EventRecord>,
) {
if let Some(record) = record {
self.alignments.adopt_camera_check(print_id, record);
}
}
#[must_use]
pub fn judge_frame(
&self,
print_id: PrintId,
frame: &[u8],
frame_sha256: &str,
plan: Option<&PlanPosition>,
alignment: AlignmentJudging,
) -> Option<Judged> {
self.alignments.calibration()?;
let url = self.camera_snapshot_url.as_deref()?;
Some(self.alignments.judge(
print_id,
&Judging {
frame_jpeg: frame,
frame_sha256,
camera_snapshot_url: url,
plan,
alignment,
},
))
}
pub fn image_of(
&self,
print_id: PrintId,
shown: &Shown<'_>,
judged: Option<&Judged>,
) -> Result<ShownImage, String> {
let previous = self.alignments.previous_check(print_id);
match self.chosen(print_id, shown, judged, previous.as_ref())? {
Ok(composite) => Ok(composite),
Err(reason) => self.whole_frame(shown.frame, &reason),
}
}
fn chosen(
&self,
print_id: PrintId,
shown: &Shown<'_>,
judged: Option<&Judged>,
previous: Option<&PreviousCheck>,
) -> Result<Result<ShownImage, WholeFrameReason>, String> {
let Some(calibration) = self.alignments.calibration() else {
return Ok(Err(WholeFrameReason::NoCalibration));
};
let Some(url) = self.camera_snapshot_url.as_deref() else {
return Ok(Err(WholeFrameReason::NoStream));
};
if shown.paused {
return Ok(Err(WholeFrameReason::Paused));
}
let Some(judged) = judged else {
return Ok(Err(WholeFrameReason::AlignmentPending));
};
if let Some(detail) = &judged.unreadable {
return Err(detail.clone());
}
let Some(plan) = shown.plan else {
return Ok(Err(WholeFrameReason::NoPosition));
};
let at = PlanAt {
index: &plan.index,
file_position_bytes: plan.file_position_bytes,
};
if at.index.object_at(at.file_position_bytes).is_none()
|| at.index.object_outlines().is_empty()
{
return Ok(Err(WholeFrameReason::NoObject));
}
if at.index.layer_at(at.file_position_bytes).is_none() {
return Ok(Err(WholeFrameReason::NoLayer));
}
if let Err(reason) = refusal_of(judged) {
return Ok(Err(reason));
}
let current = std::fs::read(shown.frame)
.map_err(|error| format!("{} is unreadable: {error}", shown.frame.display()))?;
let earlier = previous.and_then(|check| {
std::fs::read(&check.frame)
.ok()
.filter(|bytes| whole_frame(bytes).is_ok())
.map(|bytes| (bytes, check.captured_at))
});
let composed = match compose_at(
at,
(¤t, shown.captured_at),
earlier.as_ref().map(|(bytes, at)| (bytes.as_slice(), *at)),
url,
calibration,
judged.correction.as_ref(),
) {
Ok(composed) => composed,
Err(WholeFrameReason::Refused(
ComposeError::Undecodable { detail } | ComposeError::Encode { detail },
)) => return Err(detail),
Err(reason) => return Ok(Err(reason)),
};
let destination = self.composite_destination(shown.frame, previous);
write_image(&self.whole.directory, &destination, &composed.jpeg)?;
let mut note = composite_note(
shown.made_for,
shown.captured_at,
earlier.as_ref().map(|(_, at)| *at),
);
note.push_str(&panel_one_clause(&composed.text));
if shown.made_for == ImageUse::Check
&& let Some(clause) = self.growth_clause(print_id, plan, ¤t, url, calibration)
{
note.push_str(&clause);
}
Ok(Ok(ShownImage {
composite: true,
..ShownImage::plain(destination, Some(note))
}))
}
fn growth_clause(
&self,
print_id: PrintId,
plan: &PlanPosition,
current: &[u8],
url: &str,
calibration: &CameraCalibration,
) -> Option<String> {
let layer = plan.index.layer_at(plan.file_position_bytes)?;
let print_z_mm = plan.index.layer_z_mm(layer)?;
let reference = self
.alignments
.growth_reference(print_id, print_z_mm, MIN_RISE_MM)?;
let earlier = std::fs::read(&reference.frame).ok()?;
let toolpath = plan.index.layer_toolpath(layer).ok()?;
let measured = measure_growth(&GrowthInputs {
earlier_jpeg: &earlier,
earlier_print_z_mm: reference.print_z_mm,
current_jpeg: current,
current_print_z_mm: print_z_mm,
camera_snapshot_url: url,
toolpath: &toolpath,
calibration,
})
.ok()??;
let not_grown = measured.not_grown();
eprintln!(
"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: {}",
reference.print_z_mm,
reference.captured_at,
measured.carried,
measured.held,
measured.carried_share * 100.0,
measured.samples,
measured.separation_px,
if not_grown { "not grown" } else { "no verdict" }
);
not_grown.then(|| not_grown_note(reference.captured_at, print_z_mm - reference.print_z_mm))
}
fn composite_destination(&self, frame: &Path, previous: Option<&PreviousCheck>) -> PathBuf {
let named = |frame: &Path| {
let part = |part: Option<&std::ffi::OsStr>| {
part.map_or_else(String::new, |part| part.to_string_lossy().into_owned())
};
format!(
"{}-{}",
part(frame.parent().and_then(Path::file_name)),
part(frame.file_name())
)
};
let after = previous.map_or_else(|| "first".to_owned(), |check| named(&check.frame));
self.whole
.directory
.join(format!("{}-composite-after-{after}.jpg", named(frame)))
}
}
impl CheckImages for PanelImages {
fn check_image(&self, print_id: Option<PrintId>, frame: &Path) -> Result<PathBuf, String> {
self.whole.check_image(print_id, frame)
}
fn restart_growth(&self, print_id: PrintId) {
self.alignments.restart_growth(print_id);
}
fn composes(&self, print_id: PrintId) -> bool {
self.alignments.calibration().is_some()
&& self.camera_snapshot_url.is_some()
&& (self.alignments.started_under_a_camera_check(print_id)
|| matches!(
self.alignments.print_alignment(print_id),
PrintAlignment::Passed { .. }
))
}
fn shown_image(&self, request: &CheckImageRequest<'_>) -> Result<ShownImage, String> {
let Some(print_id) = request.print_id else {
return self.printer_look(request.frame, request.own_camera);
};
if let Some(record) = &request.camera_check {
self.alignments.adopt_camera_check(print_id, record);
}
let judged = if request.paused {
None
} else {
let alignment = if request.made_for == ImageUse::Check && request.own_camera {
AlignmentJudging::WhilePending
} else {
AlignmentJudging::Never
};
match std::fs::read(request.frame) {
Ok(current) => self.judge_frame(
print_id,
¤t,
request.frame_sha256,
request.plan.as_ref(),
alignment,
),
Err(error) => {
return Err(format!(
"{} is unreadable: {error}",
request.frame.display()
));
}
}
};
let shown = Shown {
frame: request.frame,
captured_at: request.captured_at,
made_for: request.made_for,
plan: request.plan.as_ref(),
paused: request.paused,
};
let mut image = self.image_of(print_id, &shown, judged.as_ref())?;
image.records = judged.map(|judged| judged.records).unwrap_or_default();
if request.made_for == ImageUse::Check && request.own_camera {
self.alignments.record_check(
print_id,
&PreviousCheck {
frame: request.frame.to_path_buf(),
captured_at: request.captured_at,
},
);
if let Some(print_z_mm) = request.plan.as_ref().and_then(plan_z) {
self.alignments.record_checked_frame(
print_id,
CheckedFrame {
frame: request.frame.to_path_buf(),
captured_at: request.captured_at,
print_z_mm,
},
MIN_RISE_MM,
);
}
}
if request.made_for == ImageUse::Check {
image.records.extend(self.alignments.note_check_image(
print_id,
LastCheckImage {
at: request.captured_at,
kind: image.kind(),
fallback: image.fallback.clone(),
},
request.frame_sha256,
));
}
Ok(image)
}
}