use std::sync::Arc;
use techy::core::node::NodeRef;
use techy::error::{Diagnostic, DiagnosticInfo};
use crate::core::lowering::{
DefaultMark, Lower, LowerCx, LowerError, Lowerer, Lowering, LoweringDecl, LoweringRule,
};
use crate::lang::Flm;
use crate::model::names::ElementName;
use crate::model::aspects::{BlockRole, block_role_of};
use crate::stdlib::backends::pres::{self, ImageDisplay, ImagePayload, Length};
use super::inspect::{GraphicsInspectedInformation, GraphicsRecord, INFO};
use super::options::{ImageOptions, image_options, report};
use super::publish::{PublishedImage, published_table};
use super::strategy::{GraphicsRenderOptions, Magnification};
use super::{EmptyPath, IMAGE_ELEMENT, ImagePath, PathNotCharacters, read_path};
pub fn rule_name(backend: &str) -> String {
format!("{IMAGE_ELEMENT}.lower.{backend}")
}
pub fn shown_size(
options: &ImageOptions,
record: Option<&GraphicsRecord>,
magnification: &Magnification,
) -> (Option<Length>, Option<Length>) {
let inspected = record.and_then(|record| record.inspected.as_ref());
let factor = match inspected {
Some(GraphicsInspectedInformation::Raster { .. }) => magnification.raster,
Some(GraphicsInspectedInformation::Vector { .. }) | None => magnification.vector,
};
let (width, height) = match (
options.width,
options.height,
inspected.and_then(GraphicsInspectedInformation::physical_dimensions),
) {
(Some(width), Some(height), _) => (Some(width), Some(height)),
(Some(width), None, Some(size)) => {
(Some(width), size.height.scaled(&width, &size.width, width.unit).ok())
}
(None, Some(height), Some(size)) => {
(size.width.scaled(&height, &size.height, height.unit).ok(), Some(height))
}
(None, None, Some(size)) => (Some(size.width), Some(size.height)),
(width, height, None) => (width, height),
};
let magnify = |length: Option<Length>| length.and_then(|length| length.times(factor.value()).ok());
(magnify(width), magnify(height))
}
#[derive(Debug, Clone, PartialEq, Eq, DiagnosticInfo)]
#[diagnostic(
id = "flm.graphics.unknown-size",
message = "Unknown size of image ‘{path}’; set its size with ‘width=…’ \
or ‘height=…’"
)]
pub struct UnknownSize {
pub path: String,
}
pub(crate) struct Image<'r> {
pub(crate) options: ImageOptions,
pub(crate) published: &'r PublishedImage,
pub(crate) size: (Option<Length>, Option<Length>),
}
pub(crate) fn read_image<'r>(
node: &NodeRef<'_, Flm>,
backend: &str,
lw: &'r mut dyn Lowerer,
) -> Result<Option<Image<'r>>, LowerError> {
let path = match read_path(node)? {
ImagePath::Read(path) => path,
ImagePath::NotCharacters => {
lw.diagnose(Diagnostic::error(PathNotCharacters, node.span().clone()));
return Ok(None);
}
ImagePath::Empty => {
lw.diagnose(Diagnostic::error(EmptyPath, node.span().clone()));
return Ok(None);
}
};
let options = image_options(node)?;
report(node, lw)?;
let addr = lw.addr();
let size = {
let record = lw.get(INFO)?.and_then(|info| info.get(addr));
let magnification = lw.option::<GraphicsRenderOptions>()?.magnification_for(backend);
shown_size(&options, record, &magnification)
};
if size == (None, None) {
lw.diagnose(Diagnostic::warning(UnknownSize { path }, node.span().clone()));
}
let lw: &'r dyn Lowerer = lw;
let published = lw
.get(&published_table(backend))?
.and_then(|table| table.get(addr))
.ok_or_else(|| {
LowerError::structure(format!(
"missing entry for the image in table ‘{}’",
published_table(backend).name()
))
})?;
Ok(Some(Image { options, published, size }))
}
#[derive(Debug, Clone)]
pub struct ImageRule {
backend: String,
}
impl ImageRule {
pub fn new(backend: impl Into<String>) -> ImageRule {
ImageRule { backend: backend.into() }
}
}
impl Lower for ImageRule {
fn lower(
&self,
node: NodeRef<'_, Flm>,
cx: &mut LowerCx<'_>,
lw: &mut dyn Lowerer,
) -> Result<Lowering, LowerError> {
let payload = {
let Some(image) = read_image(&node, &self.backend, lw)? else {
return Ok(Lowering::Emit(Vec::new()));
};
let (width, height) = image.size;
ImagePayload {
src: image.published.src.clone(),
display: image_display(&node),
alt: image.options.alt,
width,
height,
srcset: image.published.srcset.clone(),
anchor: None,
}
};
let image = lw.pres_with(cx, &ElementName::from(pres::IMAGE), payload, Vec::new())?;
Ok(Lowering::Emit(vec![image]))
}
}
fn image_display(node: &NodeRef<'_, Flm>) -> ImageDisplay {
if block_role_of(node) == BlockRole::Block { ImageDisplay::Block } else { ImageDisplay::Inline }
}
pub fn image_rule(backend: &str) -> LoweringRule {
LoweringRule::new(
rule_name(backend),
IMAGE_ELEMENT,
LoweringDecl::new()
.reads(INFO)
.reads(published_table(backend))
.option::<GraphicsRenderOptions>()
.produces(pres::IMAGE),
Arc::new(ImageRule::new(backend)),
DefaultMark::OnBackends(vec![backend.into()]),
)
.docs(
"Lowers an image to a `flm.pres.image` node. The node contains the address at which the \
output refers to the image, whether the image is a block or inline content, the \
alternative text, and the size at which the image is shown. The size is computed from \
`width`, `height` and the size of the image file, and is multiplied by the \
magnification of the output.",
)
}
#[cfg(test)]
mod tests {
use super::*;
use crate::lang::FlmOrigin;
use crate::stdlib::backends::pres::I48F16;
use crate::stdlib::features::graphics::{
Dimensions, Factor, GraphicsInspectedInformation, PixelSize,
};
fn length(text: &str) -> Length {
Length::parse(text).expect("a length")
}
fn record(width: &str, height: &str) -> GraphicsRecord {
GraphicsRecord {
file: None,
path: String::from("a.svg"),
origin: FlmOrigin::none(),
inspected: Some(GraphicsInspectedInformation::Vector {
physical_dimensions: Dimensions { width: length(width), height: length(height) },
}),
}
}
#[test]
fn one_dimension_given_scales_the_other_in_its_unit() {
let one = Magnification::default();
let inspected = record("340pt", "170pt");
let width = ImageOptions { width: Some(length("5cm")), ..ImageOptions::default() };
assert_eq!(shown_size(&width, Some(&inspected), &one), (Some(length("5cm")), Some(length("2.5cm"))));
let height = ImageOptions { height: Some(length("2.5cm")), ..ImageOptions::default() };
assert_eq!(shown_size(&height, Some(&inspected), &one), (Some(length("5cm")), Some(length("2.5cm"))));
let both = ImageOptions {
width: Some(length("1in")),
height: Some(length("3in")),
..ImageOptions::default()
};
assert_eq!(shown_size(&both, Some(&inspected), &one), (Some(length("1in")), Some(length("3in"))));
assert_eq!(
shown_size(&ImageOptions::default(), Some(&inspected), &one),
(Some(length("340pt")), Some(length("170pt")))
);
}
#[test]
fn with_nothing_inspected_the_given_dimension_stands_alone() {
let one = Magnification::default();
let width = ImageOptions { width: Some(length("5cm")), ..ImageOptions::default() };
assert_eq!(shown_size(&width, None, &one), (Some(length("5cm")), None));
assert_eq!(shown_size(&ImageOptions::default(), None, &one), (None, None));
let flat = record("0pt", "10pt");
assert_eq!(shown_size(&width, Some(&flat), &one), (Some(length("5cm")), None));
}
fn magnification(raster: f64, vector: f64) -> Magnification {
Magnification {
raster: Factor::try_from(raster).expect("a factor"),
vector: Factor::try_from(vector).expect("a factor"),
}
}
fn raster(physical: Option<(&str, &str)>) -> GraphicsRecord {
GraphicsRecord {
file: None,
path: String::from("a.png"),
origin: FlmOrigin::none(),
inspected: Some(GraphicsInspectedInformation::Raster {
dpi: Some(I48F16::from_num(72)),
size: PixelSize { width: 200, height: 100 },
physical_dimensions: physical.map(|(width, height)| Dimensions {
width: length(width),
height: length(height),
}),
}),
}
}
#[test]
fn a_raster_image_takes_the_raster_factor_and_a_vector_image_the_vector_factor() {
let factors = magnification(1.5, 2.0);
let none = ImageOptions::default();
assert_eq!(
shown_size(&none, Some(&raster(Some(("200pt", "100pt")))), &factors),
(Some(length("300pt")), Some(length("150pt")))
);
assert_eq!(
shown_size(&none, Some(&record("200pt", "100pt")), &factors),
(Some(length("400pt")), Some(length("200pt")))
);
}
#[test]
fn the_given_dimensions_are_magnified_too() {
let factors = magnification(1.5, 2.0);
let both = ImageOptions {
width: Some(length("2cm")),
height: Some(length("1in")),
..ImageOptions::default()
};
assert_eq!(
shown_size(&both, Some(&raster(None)), &factors),
(Some(length("3cm")), Some(length("1.5in")))
);
let width = ImageOptions { width: Some(length("5cm")), ..ImageOptions::default() };
assert_eq!(
shown_size(&width, Some(&record("340pt", "170pt")), &factors),
(Some(length("10cm")), Some(length("5cm")))
);
}
#[test]
fn an_image_of_unknown_type_takes_the_vector_factor() {
let factors = magnification(1.5, 2.0);
let width = ImageOptions { width: Some(length("5cm")), ..ImageOptions::default() };
assert_eq!(shown_size(&width, None, &factors), (Some(length("10cm")), None));
let mut uninspected = record("1pt", "1pt");
uninspected.inspected = None;
assert_eq!(shown_size(&width, Some(&uninspected), &factors), (Some(length("10cm")), None));
assert_eq!(shown_size(&ImageOptions::default(), None, &factors), (None, None));
}
#[test]
fn the_default_magnification_keeps_every_size() {
let one = Magnification::default();
let none = ImageOptions::default();
assert_eq!(
shown_size(&none, Some(&raster(Some(("7.25pt", "3mm")))), &one),
(Some(length("7.25pt")), Some(length("3mm")))
);
}
}