1use std::path::{Path, PathBuf};
15use std::sync::atomic::{AtomicU64, Ordering};
16
17use std::sync::Arc;
18
19use printobserver_core::{CheckImageRequest, CheckImages, GcodeIndex, ImageUse, ShownImage};
20use printobserver_panels::{
21 CameraCalibration, CheckImage, CheckImageInputs, ComposeError, WHOLE_FRAME_HEIGHT,
22 WHOLE_FRAME_WIDTH, compose_check_image, whole_frame,
23};
24use printobserver_types::{PrintId, Timestamp};
25
26use crate::alignment::{AlignmentFailure, Alignments, PreviousCheck, PrintAlignment};
27
28static WRITES: AtomicU64 = AtomicU64::new(0);
31
32pub const CHECK_IMAGES_DIRECTORY: &str = "check-images";
34
35#[derive(Debug, Clone)]
37pub struct WholeFrames {
38 directory: PathBuf,
40}
41
42impl WholeFrames {
43 #[must_use]
45 pub fn under(state_dir: &Path) -> Self {
46 Self {
47 directory: state_dir.join(CHECK_IMAGES_DIRECTORY),
48 }
49 }
50
51 fn destination(&self, frame: &Path) -> PathBuf {
54 let named = |part: Option<&std::ffi::OsStr>| {
55 part.map_or_else(String::new, |part| part.to_string_lossy().into_owned())
56 };
57 let parent = named(frame.parent().and_then(Path::file_name));
58 let file = named(frame.file_name());
59 self.directory.join(format!(
60 "{parent}-{file}-{WHOLE_FRAME_WIDTH}x{WHOLE_FRAME_HEIGHT}.jpg"
61 ))
62 }
63}
64
65impl CheckImages for WholeFrames {
66 fn check_image(&self, _print_id: Option<PrintId>, frame: &Path) -> Result<PathBuf, String> {
67 let destination = self.destination(frame);
68 if destination.is_file() {
69 return Ok(destination);
70 }
71 let bytes = std::fs::read(frame)
72 .map_err(|error| format!("{} is unreadable: {error}", frame.display()))?;
73 let scaled = whole_frame(&bytes).map_err(|error| error.to_string())?;
74 if !scaled.scaled {
75 return Ok(frame.to_path_buf());
76 }
77 write_image(&self.directory, &destination, &scaled.jpeg)?;
78 Ok(destination)
79 }
80}
81
82fn write_image(directory: &Path, destination: &Path, bytes: &[u8]) -> Result<(), String> {
86 std::fs::create_dir_all(directory)
87 .map_err(|error| format!("{} cannot be made: {error}", directory.display()))?;
88 let partial = destination.with_extension(format!(
89 "{}-{}.partial",
90 std::process::id(),
91 WRITES.fetch_add(1, Ordering::Relaxed)
92 ));
93 let written =
94 std::fs::write(&partial, bytes).and_then(|()| std::fs::rename(&partial, destination));
95 written.map_err(|error| {
96 let _ = std::fs::remove_file(&partial);
98 format!("{} cannot be written: {error}", destination.display())
99 })
100}
101
102pub const COMPOSITE_NOTE: &str = "the three-panel check image";
105
106pub const WHOLE_FRAME_NOTE: &str = "the whole camera frame";
108
109#[derive(Debug, Clone, PartialEq)]
111pub enum WholeFrameReason {
112 NoPrint,
115 NoCalibration,
117 NoStream,
120 NoPosition,
123 NoObject,
126 NoLayer,
128 ToolpathUnread(String),
130 AlignmentPending,
132 AlignmentUnavailable,
134 AlignmentFailed(AlignmentFailure),
136 Refused(ComposeError),
138}
139
140impl core::fmt::Display for WholeFrameReason {
141 fn fmt(&self, formatter: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
142 match self {
143 Self::NoPrint => formatter
144 .write_str("no print is named, so there is no planned toolpath to draw on it"),
145 Self::NoCalibration => formatter.write_str("no camera calibration is configured"),
146 Self::NoStream => formatter.write_str(
147 "no camera snapshot address is configured, so the frame's stream is unknown",
148 ),
149 Self::NoPosition => formatter.write_str(
150 "the print's G-code index gives no file position for this check",
151 ),
152 Self::NoObject => formatter.write_str(
153 "the print's G-code names no extruded object laid at this point",
154 ),
155 Self::NoLayer => formatter.write_str("the print's G-code names no layer at this point"),
156 Self::ToolpathUnread(detail) => write!(
157 formatter,
158 "the layer's planned toolpath could not be read from the print's spool: {detail}"
159 ),
160 Self::AlignmentPending => formatter.write_str(
161 "the print's first-layer alignment is pending: its first object layer is not down, or no frame of it has been judged yet",
162 ),
163 Self::AlignmentUnavailable => {
164 formatter.write_str("the print's G-code lays no object to align")
165 }
166 Self::AlignmentFailed(AlignmentFailure::Offset { offset_px }) => write!(
167 formatter,
168 "the print's first-layer alignment failed: the printed first layer lies {offset_px:.1} px from where the calibration projects it"
169 ),
170 Self::AlignmentFailed(AlignmentFailure::Resolution { expected, got }) => write!(
171 formatter,
172 "the print's first-layer alignment failed: the camera's frames are {}x{} and the calibration's {}x{}",
173 got[0], got[1], expected[0], expected[1]
174 ),
175 Self::AlignmentFailed(AlignmentFailure::Stream) => formatter.write_str(
176 "the print's first-layer alignment failed: the camera is not the stream the calibration was fitted on",
177 ),
178 Self::Refused(error) => error.fmt(formatter),
179 }
180 }
181}
182
183#[must_use]
185pub fn whole_frame_note(reason: &WholeFrameReason) -> String {
186 format!(
187 "{WHOLE_FRAME_NOTE}, scaled to fit {WHOLE_FRAME_WIDTH}x{WHOLE_FRAME_HEIGHT} and uncropped, because {reason}"
188 )
189}
190
191#[must_use]
195pub fn composite_note(no_previous: bool) -> String {
196 let previous = if no_previous {
197 "panel 3 empty, no earlier check's frame being at hand"
198 } else {
199 "panel 3 the previous check's frame"
200 };
201 format!(
202 "{COMPOSITE_NOTE}, {}x{}: panel 1 this layer's planned toolpath drawn on the frame, panel 2 a close-up of the part being printed, {previous}",
203 printobserver_panels::compose::PANEL_WIDTH,
204 printobserver_panels::compose::IMAGE_HEIGHT
205 )
206}
207
208#[derive(Debug, Clone, Copy)]
211pub struct PlanAt<'a> {
212 pub index: &'a GcodeIndex,
214 pub file_position_bytes: u64,
216}
217
218pub fn compose_at(
229 plan: PlanAt<'_>,
230 current: (&[u8], Timestamp),
231 previous: Option<(&[u8], Timestamp)>,
232 camera_snapshot_url: &str,
233 calibration: &CameraCalibration,
234) -> Result<CheckImage, WholeFrameReason> {
235 let index = plan.index;
236 let position = plan.file_position_bytes;
237 let active_object = index
238 .object_at(position)
239 .filter(|object| *object < index.object_outlines().len())
240 .ok_or(WholeFrameReason::NoObject)?;
241 let layer = index.layer_at(position).ok_or(WholeFrameReason::NoLayer)?;
242 let print_z_mm = index.layer_z_mm(layer).ok_or(WholeFrameReason::NoLayer)?;
243 let unread =
244 |error: printobserver_core::SpoolError| WholeFrameReason::ToolpathUnread(error.to_string());
245 let toolpath = index.layer_toolpath(layer).map_err(unread)?;
246 let below = if toolpath.carries_object_extrusion() {
247 None
248 } else {
249 index
250 .object_layer_at_or_below(layer)
251 .map(|below| index.layer_toolpath(below))
252 .transpose()
253 .map_err(unread)?
254 };
255 compose_check_image(&CheckImageInputs {
256 current_jpeg: current.0,
257 current_at: current.1,
258 camera_snapshot_url,
259 previous,
260 outlines: index.object_outlines(),
261 active_object,
262 toolpath: &toolpath,
263 object_layer_below: below.as_ref(),
264 print_z_mm,
265 calibration,
266 })
267 .map_err(WholeFrameReason::Refused)
268}
269
270pub struct PanelImages {
273 whole: WholeFrames,
275 alignments: Arc<Alignments>,
277 camera_snapshot_url: Option<String>,
280}
281
282impl core::fmt::Debug for PanelImages {
283 fn fmt(&self, formatter: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
284 formatter
285 .debug_struct("PanelImages")
286 .field("whole", &self.whole)
287 .field("camera_snapshot_url", &self.camera_snapshot_url)
288 .finish_non_exhaustive()
289 }
290}
291
292impl PanelImages {
293 #[must_use]
295 pub fn new(
296 state_dir: &Path,
297 alignments: Arc<Alignments>,
298 camera_snapshot_url: Option<String>,
299 ) -> Self {
300 Self {
301 whole: WholeFrames::under(state_dir),
302 alignments,
303 camera_snapshot_url,
304 }
305 }
306
307 fn whole_frame(&self, frame: &Path, reason: &WholeFrameReason) -> Result<ShownImage, String> {
309 Ok(ShownImage {
310 path: self.whole.check_image(None, frame)?,
311 note: Some(whole_frame_note(reason)),
312 })
313 }
314
315 fn composite(
318 &self,
319 print_id: PrintId,
320 request: &CheckImageRequest<'_>,
321 previous: Option<&PreviousCheck>,
322 ) -> Result<Result<ShownImage, WholeFrameReason>, String> {
323 let Some(calibration) = self.alignments.calibration() else {
324 return Ok(Err(WholeFrameReason::NoCalibration));
325 };
326 let Some(url) = self.camera_snapshot_url.as_deref() else {
327 return Ok(Err(WholeFrameReason::NoStream));
328 };
329 let Some(plan) = &request.plan else {
330 return Ok(Err(WholeFrameReason::NoPosition));
331 };
332 let at = PlanAt {
333 index: &plan.index,
334 file_position_bytes: plan.file_position_bytes,
335 };
336 if at.index.object_at(at.file_position_bytes).is_none()
337 || at.index.object_outlines().is_empty()
338 {
339 return Ok(Err(WholeFrameReason::NoObject));
340 }
341 if at.index.layer_at(at.file_position_bytes).is_none() {
342 return Ok(Err(WholeFrameReason::NoLayer));
343 }
344 match self.alignments.print_alignment(print_id) {
345 PrintAlignment::Passed { .. } => {}
346 PrintAlignment::Pending => return Ok(Err(WholeFrameReason::AlignmentPending)),
347 PrintAlignment::Unavailable => {
348 return Ok(Err(WholeFrameReason::AlignmentUnavailable));
349 }
350 PrintAlignment::Failed { reason } => {
351 return Ok(Err(WholeFrameReason::AlignmentFailed(reason)));
352 }
353 }
354 let current = std::fs::read(request.frame)
355 .map_err(|error| format!("{} is unreadable: {error}", request.frame.display()))?;
356 let earlier = previous.and_then(|check| {
360 std::fs::read(&check.frame)
361 .ok()
362 .filter(|bytes| whole_frame(bytes).is_ok())
363 .map(|bytes| (bytes, check.captured_at))
364 });
365 let composed = match compose_at(
366 at,
367 (¤t, request.captured_at),
368 earlier.as_ref().map(|(bytes, at)| (bytes.as_slice(), *at)),
369 url,
370 calibration,
371 ) {
372 Ok(composed) => composed,
373 Err(WholeFrameReason::Refused(
379 ComposeError::Undecodable { detail } | ComposeError::Encode { detail },
380 )) => return Err(detail),
381 Err(reason) => return Ok(Err(reason)),
382 };
383 let destination = self.composite_destination(request.frame, previous);
384 write_image(&self.whole.directory, &destination, &composed.jpeg)?;
385 Ok(Ok(ShownImage {
386 path: destination,
387 note: Some(composite_note(earlier.is_none())),
388 }))
389 }
390
391 fn composite_destination(&self, frame: &Path, previous: Option<&PreviousCheck>) -> PathBuf {
394 let named = |frame: &Path| {
395 let part = |part: Option<&std::ffi::OsStr>| {
396 part.map_or_else(String::new, |part| part.to_string_lossy().into_owned())
397 };
398 format!(
399 "{}-{}",
400 part(frame.parent().and_then(Path::file_name)),
401 part(frame.file_name())
402 )
403 };
404 let after = previous.map_or_else(|| "first".to_owned(), |check| named(&check.frame));
405 self.whole
406 .directory
407 .join(format!("{}-composite-after-{after}.jpg", named(frame)))
408 }
409}
410
411impl CheckImages for PanelImages {
412 fn check_image(&self, print_id: Option<PrintId>, frame: &Path) -> Result<PathBuf, String> {
413 self.whole.check_image(print_id, frame)
414 }
415
416 fn shown_image(&self, request: &CheckImageRequest<'_>) -> Result<ShownImage, String> {
417 let Some(print_id) = request.print_id else {
418 return self.whole_frame(request.frame, &WholeFrameReason::NoPrint);
419 };
420 let previous = self.alignments.previous_check(print_id);
421 let shown = match self.composite(print_id, request, previous.as_ref())? {
422 Ok(composite) => composite,
423 Err(reason) => self.whole_frame(request.frame, &reason)?,
424 };
425 if request.made_for == ImageUse::Check {
426 self.alignments.record_check(
427 print_id,
428 &PreviousCheck {
429 frame: request.frame.to_path_buf(),
430 captured_at: request.captured_at,
431 },
432 );
433 }
434 Ok(shown)
435 }
436}