printobserver_core/check_image.rs
1//! The image a check is shown, chosen in one place.
2//!
3//! A frame is stored at the size the camera took it, and the operator's own
4//! image read serves exactly that. What a supervision turn is shown — the
5//! image attached to its prompt and the image a look answers — is whatever the
6//! installed [`CheckImages`] makes of the stored frame, because every call of a
7//! turn re-sends the images it holds. With none installed, a check is shown the
8//! stored frame itself.
9//!
10//! What makes the image is told what it is for — a check, or a look — and
11//! where the print stood in its own G-code when the check began, so that it can
12//! draw that plan on the frame; it answers the image and one line saying what
13//! that image is, which the turn's prompt carries.
14
15use std::path::{Path, PathBuf};
16use std::sync::Arc;
17
18use printobserver_printer_api::JobSnapshot;
19use printobserver_types::{EventRecord, ImageRef, PrintId, Timestamp};
20
21use crate::gcode_index::GcodeIndex;
22use crate::records::PrintRecord;
23use crate::supervisor::Supervisor;
24
25/// What a check's image is asked for.
26#[derive(Debug, Clone, Copy, PartialEq, Eq)]
27pub enum ImageUse {
28 /// The image attached to a supervision turn's prompt: the print's next
29 /// check is shown this one's frame as the previous.
30 Check,
31 /// The image a look answers, which moves no check along.
32 Look,
33}
34
35/// Where a print stood in its own G-code: the index of its file, and the
36/// job's file position in it.
37#[derive(Debug, Clone)]
38pub struct PlanPosition {
39 /// The print's G-code index.
40 pub index: Arc<GcodeIndex>,
41 /// The job's file position, in bytes.
42 pub file_position_bytes: u64,
43}
44
45/// One request for a check's image of a stored frame.
46#[derive(Debug, Clone)]
47pub struct CheckImageRequest<'a> {
48 /// The print the image is of; none for a look at the printer.
49 pub print_id: Option<PrintId>,
50 /// Where the stored frame is.
51 pub frame: &'a Path,
52 /// When the frame was captured.
53 pub captured_at: Timestamp,
54 /// What the image is for.
55 pub made_for: ImageUse,
56 /// Where the print stood in its G-code, when its job is its own file and
57 /// reported a position the index was read for.
58 pub plan: Option<PlanPosition>,
59}
60
61/// A check's image, and the line saying what it is.
62#[derive(Debug, Clone, PartialEq, Eq)]
63pub struct ShownImage {
64 /// The image's path.
65 pub path: PathBuf,
66 /// What the image is, and why it is that one, in one line; none when what
67 /// made it says nothing.
68 pub note: Option<String>,
69 /// Whether it is the three-panel image, drawn from the print's plan,
70 /// rather than a frame as the camera took it or scaled whole.
71 pub composite: bool,
72}
73
74/// What makes a check's image of one stored frame.
75pub trait CheckImages: Send + Sync {
76 /// The path of the image a check of `print_id` — or a look at the printer,
77 /// when it names none — is shown of the frame stored at `frame`, or why
78 /// none could be made.
79 ///
80 /// # Errors
81 ///
82 /// Answers why the image could not be made: the frame unreadable, or the
83 /// image unwritable.
84 fn check_image(&self, print_id: Option<PrintId>, frame: &Path) -> Result<PathBuf, String>;
85
86 /// The image one request is shown and the line saying what it is: by
87 /// default [`check_image`](Self::check_image)'s, saying nothing.
88 ///
89 /// # Errors
90 ///
91 /// As [`check_image`](Self::check_image)'s.
92 fn shown_image(&self, request: &CheckImageRequest<'_>) -> Result<ShownImage, String> {
93 self.check_image(request.print_id, request.frame)
94 .map(|path| ShownImage {
95 path,
96 note: None,
97 composite: false,
98 })
99 }
100
101 /// Whether a check of `print_id` would be shown the three-panel image of a
102 /// frame from the server's own camera: by default, never.
103 fn composes(&self, print_id: PrintId) -> bool {
104 let _ = print_id;
105 false
106 }
107}
108
109/// When an event's frame was captured: what the arrival knew, else what its
110/// payload says, else when the event was received.
111pub(crate) fn captured_at_of(event: &EventRecord, known: Option<Timestamp>) -> Timestamp {
112 known
113 .or_else(|| {
114 event
115 .body
116 .payload
117 .get("frame_captured_at")
118 .cloned()
119 .and_then(|value| printobserver_types::serde_json::from_value(value).ok())
120 })
121 .unwrap_or(event.received_at)
122}
123
124impl Supervisor {
125 /// Install what makes every check's image. The first installation stands;
126 /// answers whether this one did.
127 pub fn install_check_images(&self, images: std::sync::Arc<dyn CheckImages>) -> bool {
128 self.check_images.set(images).is_ok()
129 }
130
131 /// Where a print stood in its own G-code by a job read: nothing when the
132 /// job runs another file, reported no position, or the file has no index.
133 pub(crate) async fn plan_position(
134 &self,
135 print: &PrintRecord,
136 job: Option<&JobSnapshot>,
137 ) -> Option<PlanPosition> {
138 let job = job?;
139 if job.file_name.is_none() || job.file_name != print.file_name {
140 return None;
141 }
142 let file_position_bytes = u64::try_from(job.file_position_bytes?).ok()?;
143 let index = self.print_gcode_index(print.id).await?;
144 Some(PlanPosition {
145 index,
146 file_position_bytes,
147 })
148 }
149
150 /// The image a check is shown of one stored frame, and the line saying
151 /// what it is: the stored frame itself when nothing that makes one is
152 /// installed, or when what is installed could not make it, which is a
153 /// check shown more than it needs rather than a check shown nothing.
154 pub(crate) async fn shown_image_of(
155 &self,
156 image: &ImageRef,
157 print_id: Option<PrintId>,
158 captured_at: Timestamp,
159 made_for: ImageUse,
160 plan: Option<PlanPosition>,
161 ) -> Option<ShownImage> {
162 let stored = self.image_path(image).await?;
163 let Some(images) = self.check_images.get() else {
164 return Some(ShownImage {
165 path: stored,
166 note: None,
167 composite: false,
168 });
169 };
170 let request = CheckImageRequest {
171 print_id,
172 frame: &stored,
173 captured_at,
174 made_for,
175 plan,
176 };
177 Some(
178 images
179 .shown_image(&request)
180 .unwrap_or_else(|error| ShownImage {
181 note: Some(format!(
182 "the frame as the camera took it, because its check image could not be made: {error}"
183 )),
184 path: stored.clone(),
185 composite: false,
186 }),
187 )
188 }
189}