use std::collections::BTreeMap;
use std::fmt;
use techy::core::node::NodeRef;
use techy::error::{Diagnostic, DiagnosticInfo};
use techy::serialize::SerialValue;
use crate::core::data::store::StageOut;
use crate::core::data::table::{ProjectCx, SingletonTable, Table, TableName};
use crate::core::plan::PlanCx;
use crate::core::registry::{BuildError, FeatureBuilder};
use crate::core::run::StageCx;
use crate::core::stage::{Effect, Needs, Scope, Stage, StageDecl};
use crate::lang::{Flm, FlmDiagnostic, FlmOrigin, FlmSpan, nowhere};
use crate::model::addr::NodeAddr;
use crate::stdlib::backends::pres::{I48F16, Length, LengthUnit};
use crate::stdlib::features::index::ELEMENT_INDEX;
use crate::techy::source::SourceOrigin;
use super::resolve::{
GraphicsResolveRequest, GraphicsResolver, ImageFile, RESOLVER_SLOT, ResolvedImage, names_scheme,
};
use super::{GraphicsImage, INSPECTOR_SLOT, ImagePath, read_path};
pub const INSPECT_STAGE: &str = "flm.graphics.inspect";
pub const INFO: TableName<GraphicsInfo> = TableName::new("flm.graphics.info");
pub const ASSUMED_DPI: i32 = 96;
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct Dimensions {
pub width: Length,
pub height: Length,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct PixelSize {
pub width: u32,
pub height: u32,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum GraphicsInspectedInformation {
Vector {
physical_dimensions: Dimensions,
},
Raster {
dpi: Option<I48F16>,
size: PixelSize,
physical_dimensions: Option<Dimensions>,
},
}
impl GraphicsInspectedInformation {
pub fn physical_dimensions(&self) -> Option<Dimensions> {
match self {
GraphicsInspectedInformation::Vector { physical_dimensions } => {
Some(*physical_dimensions)
}
GraphicsInspectedInformation::Raster { physical_dimensions, .. } => {
*physical_dimensions
}
}
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub struct GraphicsInspectRequest {
pub path: String,
pub origin: FlmOrigin,
pub resolved: Option<ResolvedImage>,
}
impl GraphicsInspectRequest {
pub fn new(path: impl Into<String>, origin: FlmOrigin) -> GraphicsInspectRequest {
GraphicsInspectRequest { path: path.into(), origin, resolved: None }
}
pub fn resolved(mut self, resolved: ResolvedImage) -> GraphicsInspectRequest {
self.resolved = Some(resolved);
self
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct GraphicsInspectError {
pub detail: String,
}
impl GraphicsInspectError {
pub fn new(detail: impl Into<String>) -> GraphicsInspectError {
GraphicsInspectError { detail: detail.into() }
}
}
impl fmt::Display for GraphicsInspectError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(&self.detail)
}
}
impl std::error::Error for GraphicsInspectError {}
pub trait GraphicsInspector: Send + Sync {
fn inspect(
&self,
request: &GraphicsInspectRequest,
) -> Result<GraphicsInspectedInformation, GraphicsInspectError>;
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct GraphicsRecord {
pub path: String,
pub origin: FlmOrigin,
pub file: Option<ImageFile>,
pub inspected: Option<GraphicsInspectedInformation>,
}
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct GraphicsInfo {
records: BTreeMap<NodeAddr, GraphicsRecord>,
}
impl GraphicsInfo {
pub fn get(&self, addr: NodeAddr) -> Option<&GraphicsRecord> {
self.records.get(&addr)
}
pub fn iter(&self) -> impl Iterator<Item = (NodeAddr, &GraphicsRecord)> + '_ {
self.records.iter().map(|(addr, record)| (*addr, record))
}
pub fn len(&self) -> usize {
self.records.len()
}
pub fn is_empty(&self) -> bool {
self.records.is_empty()
}
}
fn length_value(length: &Length) -> SerialValue {
SerialValue::Str(length.to_string())
}
fn dimensions_value(dimensions: &Dimensions) -> SerialValue {
SerialValue::Map(vec![
(String::from("width"), length_value(&dimensions.width)),
(String::from("height"), length_value(&dimensions.height)),
])
}
fn answer_value(answer: &GraphicsInspectedInformation) -> SerialValue {
match answer {
GraphicsInspectedInformation::Vector { physical_dimensions } => SerialValue::Map(vec![
(String::from("kind"), SerialValue::Str(String::from("vector"))),
(String::from("physical_dimensions"), dimensions_value(physical_dimensions)),
]),
GraphicsInspectedInformation::Raster { dpi, size, physical_dimensions } => {
let mut entries = vec![
(String::from("kind"), SerialValue::Str(String::from("raster"))),
(
String::from("size"),
SerialValue::Map(vec![
(String::from("width"), SerialValue::Str(size.width.to_string())),
(String::from("height"), SerialValue::Str(size.height.to_string())),
]),
),
];
if let Some(dpi) = dpi {
entries.push((
String::from("dpi"),
SerialValue::Str(dpi.to_string()),
));
}
if let Some(dimensions) = physical_dimensions {
entries.push((String::from("physical_dimensions"), dimensions_value(dimensions)));
}
SerialValue::Map(entries)
}
}
}
impl Table for GraphicsInfo {
fn absorb(&mut self, piece: GraphicsInfo) {
self.records.extend(piece.records);
}
fn project(&self, cx: &dyn ProjectCx) -> SerialValue {
SerialValue::List(
self.records
.iter()
.map(|(addr, record)| {
let mut entries = vec![
(String::from("node"), cx.node_ref(*addr)),
(String::from("path"), SerialValue::Str(record.path.clone())),
];
if let Some(label) = record.origin.label() {
entries.push((String::from("origin"), SerialValue::Str(label.into_owned())));
}
if let Some(file) = &record.file {
entries.push((
String::from("file"),
SerialValue::Map(vec![
(String::from("identity"), SerialValue::Str(file.identity.clone())),
(String::from("media_type"), SerialValue::Str(file.media_type.clone())),
(String::from("address"), SerialValue::Str(file.address.clone())),
]),
));
}
if let Some(answer) = &record.inspected {
entries.push((String::from("inspected"), answer_value(answer)));
}
SerialValue::Map(entries)
})
.collect(),
)
}
}
impl SingletonTable for GraphicsInfo {
const NAME: &'static str = "flm.graphics.info";
}
#[derive(Debug, Clone, PartialEq, Eq, DiagnosticInfo)]
#[diagnostic(
id = "flm.graphics.assumed-resolution",
message = "Missing resolution in image file ‘{path}’"
)]
pub struct AssumedResolution {
pub path: String,
}
#[derive(Debug, Clone, PartialEq, Eq, DiagnosticInfo)]
#[diagnostic(
id = "flm.graphics.inspect-failed",
message = "Failed to inspect image file ‘{path}’: {detail}"
)]
pub struct InspectFailed {
pub path: String,
pub detail: String,
}
#[derive(Debug, Clone, PartialEq, Eq, DiagnosticInfo)]
#[diagnostic(
id = "flm.graphics.resolve-failed",
message = "Failed to read image file ‘{path}’: {detail}"
)]
pub struct ResolveFailed {
pub path: String,
pub detail: String,
}
#[derive(Debug, Clone, PartialEq, Eq, DiagnosticInfo)]
#[diagnostic(
id = "flm.graphics.no-pixel-size",
message = "Invalid size of image file ‘{path}’: the width and the height in \
pixels must be greater than zero"
)]
pub struct NoPixelSize {
pub path: String,
}
#[derive(Debug, Clone, PartialEq, Eq, DiagnosticInfo)]
#[diagnostic(
id = "flm.graphics.inspected-size-not-physical",
message = "Invalid unit ‘{unit}’ in the size reported by the inspector for image file \
‘{path}’: sizes must be given in ‘pt’, ‘mm’, ‘cm’ or ‘in’"
)]
pub struct InspectedSizeNotPhysical {
pub path: String,
pub unit: String,
}
#[derive(Debug, Clone, PartialEq, Eq, DiagnosticInfo)]
#[diagnostic(
id = "flm.graphics.inspected-resolution-not-positive",
message = "Invalid resolution in image file ‘{path}’: the resolution must be \
greater than zero"
)]
pub struct InspectedResolutionNotPositive {
pub path: String,
}
#[derive(Debug, Clone, PartialEq, Eq, DiagnosticInfo)]
#[diagnostic(id = "flm.graphics.stage-failed", message = "Stage ‘{stage}’ failed: {detail}")]
pub struct StageFailed {
pub stage: String,
pub detail: String,
}
pub(super) fn stage_failed(out: &mut StageOut<'_>, stage: &str, detail: impl ToString) {
out.diags.push(Diagnostic::error(
StageFailed { stage: stage.to_string(), detail: detail.to_string() },
nowhere(FlmOrigin::none()),
));
}
fn request_origin(span: &FlmSpan) -> FlmOrigin {
let own = span.source().origin().clone();
let mut span = span.clone();
loop {
if span.source().origin().canonical_path().is_some() {
return span.source().origin().clone();
}
let Some(triggered) = span.source().provenance().triggered_at().cloned() else {
return own;
};
span = triggered;
}
}
enum Refusal {
NoPixelSize,
NotPhysical(LengthUnit),
ResolutionNotPositive,
}
fn non_physical(dimensions: &Dimensions) -> Option<LengthUnit> {
[dimensions.width.unit, dimensions.height.unit].into_iter().find(|unit| !unit.is_physical())
}
fn complete(
answer: GraphicsInspectedInformation,
) -> Result<(GraphicsInspectedInformation, bool), Refusal> {
match answer {
GraphicsInspectedInformation::Vector { physical_dimensions } => {
if let Some(unit) = non_physical(&physical_dimensions) {
return Err(Refusal::NotPhysical(unit));
}
Ok((answer, false))
}
GraphicsInspectedInformation::Raster { dpi, size, physical_dimensions } => {
if size.width == 0 || size.height == 0 {
return Err(Refusal::NoPixelSize);
}
if let Some(unit) = physical_dimensions.as_ref().and_then(non_physical) {
return Err(Refusal::NotPhysical(unit));
}
if dpi.is_some_and(|dpi| dpi <= I48F16::ZERO) {
return Err(Refusal::ResolutionNotPositive);
}
let assumed = dpi.is_none();
let dpi = dpi.unwrap_or(I48F16::from_num(ASSUMED_DPI));
let physical_dimensions = match physical_dimensions {
Some(stated) => Some(stated),
None => Length::from_dots(u64::from(size.width), dpi)
.and_then(|width| {
Length::from_dots(u64::from(size.height), dpi)
.map(|height| Dimensions { width, height })
})
.ok(),
};
Ok((
GraphicsInspectedInformation::Raster { dpi: Some(dpi), size, physical_dimensions },
assumed,
))
}
}
}
struct Services<'r> {
resolver: Option<&'r dyn GraphicsResolver>,
inspector: Option<&'r dyn GraphicsInspector>,
}
fn record_of(
node: &NodeRef<'_, Flm>,
path: String,
services: &Services<'_>,
diags: &mut Vec<FlmDiagnostic>,
) -> GraphicsRecord {
let origin = request_origin(node.span());
let mut record = GraphicsRecord { path, origin, file: None, inspected: None };
if names_scheme(&record.path) {
return record;
}
let span = node.span().clone();
let mut request = GraphicsInspectRequest::new(record.path.clone(), record.origin.clone());
if let Some(resolver) = services.resolver {
let asked = GraphicsResolveRequest::new(record.path.clone(), record.origin.clone());
let file = match resolver.resolve(&asked) {
Ok(file) => file,
Err(error) => {
let failed = ResolveFailed { path: record.path.clone(), detail: error.detail };
diags.push(Diagnostic::error(failed, span));
return record;
}
};
record.file = Some(file.clone());
if services.inspector.is_none() {
return record;
}
match resolver.read(&file) {
Ok(content) => request = request.resolved(ResolvedImage { file, content: content.into() }),
Err(error) => {
let failed = ResolveFailed { path: record.path.clone(), detail: error.detail };
diags.push(Diagnostic::error(failed, span));
return record;
}
}
}
let Some(inspector) = services.inspector else { return record };
let path = record.path.clone();
match inspector.inspect(&request).map_err(|error| error.detail) {
Err(detail) => diags.push(Diagnostic::error(InspectFailed { path, detail }, span)),
Ok(answer) => match complete(answer) {
Ok((completed, assumed)) => {
if assumed {
diags.push(Diagnostic::warning(AssumedResolution { path }, span));
}
record.inspected = Some(completed);
}
Err(Refusal::NoPixelSize) => {
diags.push(Diagnostic::error(NoPixelSize { path }, span));
}
Err(Refusal::NotPhysical(unit)) => diags.push(Diagnostic::error(
InspectedSizeNotPhysical { path, unit: unit.to_string() },
span,
)),
Err(Refusal::ResolutionNotPositive) => {
diags.push(Diagnostic::error(InspectedResolutionNotPositive { path }, span));
}
},
}
record
}
#[derive(Debug, Default, Clone, Copy)]
pub struct InspectStage;
impl Stage for InspectStage {
fn decl(&self) -> StageDecl {
StageDecl::new(INSPECT_STAGE, Effect::Compute, Scope::PerTree).writes(INFO).docs(
"Calls the graphics resolver and the inspector, if they are registered, for each \
image, and writes the record of each image to `flm.graphics.info`. Reports each \
image file that cannot be found, read or inspected, and each raster image file \
that does not state its resolution.",
)
}
fn needs(&self, _cx: &PlanCx<'_>) -> Needs {
Needs::new().reads(ELEMENT_INDEX)
}
fn run(&self, cx: &StageCx<'_>, out: &mut StageOut<'_>) {
let (Some(id), Some(tree)) = (cx.tree_id(), cx.my_tree()) else { return };
let index = match cx.get(ELEMENT_INDEX) {
Ok(Some(index)) => index,
Ok(None) => return,
Err(error) => return stage_failed(out, INSPECT_STAGE, error),
};
let registered = cx.registry().services();
let services = Services {
resolver: registered.service_named::<dyn GraphicsResolver>(RESOLVER_SLOT),
inspector: registered.service_named::<dyn GraphicsInspector>(INSPECTOR_SLOT),
};
let mut info = GraphicsInfo::default();
let mut diags = Vec::new();
for (addr, node, _) in index.values_of::<GraphicsImage>(id, &tree) {
let Ok(ImagePath::Read(path)) = read_path(&node) else { continue };
let record = record_of(&node, path, &services, &mut diags);
info.records.insert(addr, record);
}
for diagnostic in diags {
out.diags.push(diagnostic);
}
match out.table(INFO) {
Ok(table) => *table = info,
Err(error) => stage_failed(out, INSPECT_STAGE, error),
}
}
}
pub(super) fn register(b: &mut FeatureBuilder<'_>) -> Result<(), BuildError> {
b.table(INFO, "The record of each image, keyed by the address of the image's node: the path, \
the file that the graphics resolver found, and the type and the size of the \
image that the inspector returned.")?;
b.stage(std::sync::Arc::new(InspectStage))
}
#[cfg(test)]
mod tests {
use super::*;
fn length(text: &str) -> Length {
Length::parse(text).expect("a length")
}
#[test]
fn a_raster_answer_is_completed_and_nothing_stated_changes() {
let size = PixelSize { width: 300, height: 150 };
let bare = GraphicsInspectedInformation::Raster { dpi: None, size, physical_dimensions: None };
let Ok((completed, assumed)) = complete(bare) else { panic!("completed") };
assert!(assumed);
assert_eq!(
completed,
GraphicsInspectedInformation::Raster {
dpi: Some(I48F16::from_num(96)),
size,
physical_dimensions: Some(Dimensions {
width: length("225pt"),
height: length("112.5pt")
}),
}
);
let stated = Dimensions { width: length("3cm"), height: length("1.5cm") };
let full = GraphicsInspectedInformation::Raster {
dpi: Some(I48F16::from_num(300)),
size,
physical_dimensions: Some(stated),
};
assert_eq!(complete(full).ok(), Some((full, false)));
}
#[test]
fn an_answer_that_cannot_be_recorded_is_refused() {
let size = PixelSize { width: 0, height: 10 };
let zero = GraphicsInspectedInformation::Raster { dpi: None, size, physical_dimensions: None };
assert!(matches!(complete(zero), Err(Refusal::NoPixelSize)));
let ems = Dimensions { width: length("2em"), height: length("1in") };
let vector = GraphicsInspectedInformation::Vector { physical_dimensions: ems };
assert!(matches!(complete(vector), Err(Refusal::NotPhysical(LengthUnit::Ems))));
let flat = GraphicsInspectedInformation::Raster {
dpi: Some(I48F16::ZERO),
size: PixelSize { width: 1, height: 1 },
physical_dimensions: None,
};
assert!(matches!(complete(flat), Err(Refusal::ResolutionNotPositive)));
}
}