use std::path::{Path, PathBuf};
use std::sync::Arc;
use printobserver_printer_api::JobSnapshot;
use printobserver_types::{EventRecord, ImageRef, PrintId, Timestamp};
use crate::gcode_index::GcodeIndex;
use crate::records::PrintRecord;
use crate::supervisor::Supervisor;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ImageUse {
Check,
Look,
}
#[derive(Debug, Clone)]
pub struct PlanPosition {
pub index: Arc<GcodeIndex>,
pub file_position_bytes: u64,
}
#[derive(Debug, Clone)]
pub struct CheckImageRequest<'a> {
pub print_id: Option<PrintId>,
pub frame: &'a Path,
pub captured_at: Timestamp,
pub made_for: ImageUse,
pub plan: Option<PlanPosition>,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ShownImage {
pub path: PathBuf,
pub note: Option<String>,
}
pub trait CheckImages: Send + Sync {
fn check_image(&self, print_id: Option<PrintId>, frame: &Path) -> Result<PathBuf, String>;
fn shown_image(&self, request: &CheckImageRequest<'_>) -> Result<ShownImage, String> {
self.check_image(request.print_id, request.frame)
.map(|path| ShownImage { path, note: None })
}
}
pub(crate) fn captured_at_of(event: &EventRecord, known: Option<Timestamp>) -> Timestamp {
known
.or_else(|| {
event
.body
.payload
.get("frame_captured_at")
.cloned()
.and_then(|value| printobserver_types::serde_json::from_value(value).ok())
})
.unwrap_or(event.received_at)
}
impl Supervisor {
pub fn install_check_images(&self, images: std::sync::Arc<dyn CheckImages>) -> bool {
self.check_images.set(images).is_ok()
}
pub(crate) async fn plan_position(
&self,
print: &PrintRecord,
job: Option<&JobSnapshot>,
) -> Option<PlanPosition> {
let job = job?;
if job.file_name.is_none() || job.file_name != print.file_name {
return None;
}
let file_position_bytes = u64::try_from(job.file_position_bytes?).ok()?;
let index = self.print_gcode_index(print.id).await?;
Some(PlanPosition {
index,
file_position_bytes,
})
}
pub(crate) async fn shown_image_of(
&self,
image: &ImageRef,
print_id: Option<PrintId>,
captured_at: Timestamp,
made_for: ImageUse,
plan: Option<PlanPosition>,
) -> Option<ShownImage> {
let stored = self.image_path(image).await?;
let Some(images) = self.check_images.get() else {
return Some(ShownImage {
path: stored,
note: None,
});
};
let request = CheckImageRequest {
print_id,
frame: &stored,
captured_at,
made_for,
plan,
};
Some(
images
.shown_image(&request)
.unwrap_or_else(|error| ShownImage {
note: Some(format!(
"the frame as the camera took it, because its check image could not be made: {error}"
)),
path: stored.clone(),
}),
)
}
}