flm_core/stdlib/features/graphics/rules.rs
1//! This module defines the lowering rule [`image_rule`] of the `graphics`
2//! feature, along with what every lowering rule of the image element shares:
3//! the computation of the size at which an image is shown ([`shown_size`]),
4//! and the warning [`UnknownSize`], which is reported when this size is
5//! unknown.
6//!
7//! The rule [`image_rule`] lowers an image, that is, a node of the element
8//! [`IMAGE_ELEMENT`] of `\includegraphics`, to a
9//! [`flm.pres.image`](crate::stdlib::backends::pres::IMAGE) node. The
10//! `graphics` feature registers this rule for the backends `text`, `html` and
11//! `latex-rendered`. On the backend `latex-recomposed`, the rule
12//! [`LATEX_RULE`](super::latex::LATEX_RULE) writes an image as a LaTeX hook
13//! ([`latex`](mod@super::latex)).
14//!
15//! The payload of the `flm.pres.image` node ([`ImagePayload`]) contains the
16//! following values:
17//!
18//! - `src`: the *published address* of the image, that is, the address at
19//! which the output refers to the image. The publish stage of the backend
20//! computes this address according to the strategy set for the output
21//! ([`publish`](mod@super::publish)), unless a [publish stage of your
22//! own](super::publish#a-publish-stage-of-your-own) writes the published
23//! table in its place.
24//! - `display`: whether the image is a block or inline content. An image is a
25//! block when it is a direct child of the body of a float, and inline
26//! content everywhere else ([`GraphicsImage`](super::GraphicsImage)).
27//! - `alt`: the alternative text, given with the option `alt`.
28//! - `width` and `height`: the size at which the image is shown
29//! ([`shown_size`]).
30//!
31//! Each backend writes this node in its own way. For instance, the plain-text
32//! output prints `\includegraphics[alt=A plot]{plot.png}` as
33//! `[image: A plot]`, and the HTML output writes an `<img>` element. The
34//! rendering guide describes the output of each backend: [images in plain
35//! text](crate::guide::rendering#images), [images in
36//! HTML](crate::guide::rendering#images-in-html), and [images in the rendered
37//! LaTeX](crate::guide::rendering#images-in-the-rendered-latex).
38
39use std::sync::Arc;
40
41use techy::core::node::NodeRef;
42use techy::error::{Diagnostic, DiagnosticInfo};
43
44use crate::core::lowering::{
45 DefaultMark, Lower, LowerCx, LowerError, Lowerer, Lowering, LoweringDecl, LoweringRule,
46};
47use crate::lang::Flm;
48use crate::model::names::ElementName;
49use crate::model::aspects::{BlockRole, block_role_of};
50use crate::stdlib::backends::pres::{self, ImageDisplay, ImagePayload, Length};
51
52use super::inspect::{GraphicsInspectedInformation, GraphicsRecord, INFO};
53use super::options::{ImageOptions, image_options, report};
54use super::publish::{PublishedImage, published_table};
55use super::strategy::{GraphicsRenderOptions, Magnification};
56use super::{EmptyPath, IMAGE_ELEMENT, ImagePath, PathNotCharacters, read_path};
57
58/// Returns the name of the lowering rule [`image_rule`] for `backend`:
59/// `flm.graphics.image.lower.<backend>`.
60pub fn rule_name(backend: &str) -> String {
61 format!("{IMAGE_ELEMENT}.lower.{backend}")
62}
63
64/// Returns the width and the height at which an image is shown on an output.
65/// A dimension is `None` when it is not set.
66///
67/// `options` contains the valid options of the image, `record` is the record
68/// that the inspect stage wrote for the image into the table [`INFO`], and
69/// `magnification` is the magnification of the output
70/// ([`GraphicsRenderOptions::magnification`]). The size is first computed from
71/// the options and from the physical size of the image file:
72///
73/// - When both `width` and `height` are given, the image has this size.
74/// - When only one of them is given, the other dimension is computed from the
75/// physical size of the image file, so that the image keeps its
76/// proportions. The computed dimension has the unit of the given one
77/// ([`Length::scaled`]). For instance, with `width=5cm`, an image file of
78/// 340pt by 170pt gets a height of 2.5cm.
79/// - When neither is given, the image has the physical size of the image file.
80///
81/// The physical size of the image file is known only when `record` contains
82/// inspected information ([`GraphicsRecord::inspected`]). Otherwise, only the
83/// given dimensions are set. A computed dimension is also left unset when it
84/// cannot be computed, because a dimension of the image file is zero or the
85/// result is too large to be represented as a [`Length`].
86///
87/// Each dimension, including a given one, is then multiplied by a factor of
88/// `magnification` ([`Length::times`]): the factor `raster` for a raster
89/// image, and the factor `vector` for a vector image or for an image without
90/// inspected information. A dimension that becomes too large to be
91/// represented is left unset.
92///
93/// Every lowering rule of the image element computes the size with this
94/// function. A lowering rule of your own can call it to show images at the
95/// same size.
96pub fn shown_size(
97 options: &ImageOptions,
98 record: Option<&GraphicsRecord>,
99 magnification: &Magnification,
100) -> (Option<Length>, Option<Length>) {
101 let inspected = record.and_then(|record| record.inspected.as_ref());
102 let factor = match inspected {
103 Some(GraphicsInspectedInformation::Raster { .. }) => magnification.raster,
104 Some(GraphicsInspectedInformation::Vector { .. }) | None => magnification.vector,
105 };
106 let (width, height) = match (
107 options.width,
108 options.height,
109 inspected.and_then(GraphicsInspectedInformation::physical_dimensions),
110 ) {
111 (Some(width), Some(height), _) => (Some(width), Some(height)),
112 (Some(width), None, Some(size)) => {
113 (Some(width), size.height.scaled(&width, &size.width, width.unit).ok())
114 }
115 (None, Some(height), Some(size)) => {
116 (size.width.scaled(&height, &size.height, height.unit).ok(), Some(height))
117 }
118 (None, None, Some(size)) => (Some(size.width), Some(size.height)),
119 (width, height, None) => (width, height),
120 };
121 // One computation for every backend, the factor keyed by output: the
122 // magnification is applied once, where the size is decided, and not
123 // repeated in each backend, where the copies could drift apart.
124 let magnify = |length: Option<Length>| length.and_then(|length| length.times(factor.value()).ok());
125 (magnify(width), magnify(height))
126}
127
128/// The warning that is reported when the size of an image is unknown
129/// (`flm.graphics.unknown-size`).
130///
131/// The size of an image is unknown when neither `width` nor `height` is given
132/// and the size of the image file is not known. The size of the image file is
133/// not known in the following cases:
134///
135/// - The program that embeds FLM contributes no inspector
136/// ([`GraphicsInspector`](super::GraphicsInspector)), the service that
137/// reports the size of image files.
138/// - The image file cannot be found or inspected.
139/// - The path is an address that begins with a scheme, such as
140/// `https://example.org/a.svg`. Such an address is never inspected.
141///
142/// The size of such an image can be given with `width` or `height`, as in
143/// `\includegraphics[width=5cm]{https://example.org/a.svg}`.
144///
145/// Reported by the lowering rule of `\includegraphics` when it is invoked.
146/// The image is then written without a size.
147#[derive(Debug, Clone, PartialEq, Eq, DiagnosticInfo)]
148#[diagnostic(
149 id = "flm.graphics.unknown-size",
150 message = "Unknown size of image ‘{path}’; set its size with ‘width=…’ \
151 or ‘height=…’"
152)]
153pub struct UnknownSize {
154 /// The path, as written.
155 pub path: String,
156}
157
158/// The values that every lowering rule of the image element needs to write an
159/// image. [`read_image`] returns these values.
160pub(crate) struct Image<'r> {
161 /// The valid options of the image.
162 pub(crate) options: ImageOptions,
163 /// The entry of the image in the published table of the backend, which
164 /// contains the published address of the image.
165 pub(crate) published: &'r PublishedImage,
166 /// The width and the height at which the image is shown ([`shown_size`]).
167 pub(crate) size: (Option<Length>, Option<Length>),
168}
169
170/// Reads the image `node` for the lowering rule of `backend`, and reports the
171/// diagnostics of the image. Returns the values that the rule needs to write
172/// the image, or `None` when the path of the image is invalid.
173///
174/// The function performs the following steps:
175///
176/// 1. It reads the path of the image ([`read_path`]). When the path is not
177/// plain text, it reports the error [`PathNotCharacters`] and returns
178/// `None`. When the path is empty, it reports the error [`EmptyPath`] and
179/// returns `None`. The rule then writes nothing for the image.
180/// 2. It reads the options ([`image_options`]), and reports their errors and
181/// warnings ([`report`]).
182/// 3. It computes the size of the image with [`shown_size`], from the record
183/// of the image in the table [`INFO`] and from the magnification of the
184/// output of `backend` ([`GraphicsRenderOptions::magnification_for`]). When
185/// neither the width nor the height is set, it reports the warning
186/// [`UnknownSize`].
187/// 4. It looks up the entry of the image in the published table of `backend`
188/// ([`published_table`]).
189///
190/// The calling rule must declare that it reads the table [`INFO`], the
191/// published table of `backend`, and the option type
192/// [`GraphicsRenderOptions`].
193///
194/// # Errors
195///
196/// - [`LowerError::PlaceholderCharacters`] when the path or the value of an
197/// option contains a placeholder of a user definition's template. This
198/// happens only when the template is lowered without being expanded.
199/// - [`LowerError::Access`] or [`LowerError::Option`] when the calling rule
200/// did not declare one of the reads above.
201/// - [`LowerError::Structure`] when the published table of `backend` has no
202/// entry for the image. This does not happen when the standard publish stage
203/// of `backend` ran before the lowering; it happens when a stage that writes
204/// the published table in its place writes no entry for the image.
205pub(crate) fn read_image<'r>(
206 node: &NodeRef<'_, Flm>,
207 backend: &str,
208 lw: &'r mut dyn Lowerer,
209) -> Result<Option<Image<'r>>, LowerError> {
210 let path = match read_path(node)? {
211 ImagePath::Read(path) => path,
212 ImagePath::NotCharacters => {
213 lw.diagnose(Diagnostic::error(PathNotCharacters, node.span().clone()));
214 return Ok(None);
215 }
216 ImagePath::Empty => {
217 lw.diagnose(Diagnostic::error(EmptyPath, node.span().clone()));
218 return Ok(None);
219 }
220 };
221 let options = image_options(node)?;
222 report(node, lw)?;
223 let addr = lw.addr();
224 let size = {
225 let record = lw.get(INFO)?.and_then(|info| info.get(addr));
226 let magnification = lw.option::<GraphicsRenderOptions>()?.magnification_for(backend);
227 shown_size(&options, record, &magnification)
228 };
229 if size == (None, None) {
230 lw.diagnose(Diagnostic::warning(UnknownSize { path }, node.span().clone()));
231 }
232 let lw: &'r dyn Lowerer = lw;
233 let published = lw
234 .get(&published_table(backend))?
235 .and_then(|table| table.get(addr))
236 .ok_or_else(|| {
237 LowerError::structure(format!(
238 "missing entry for the image in table ‘{}’",
239 published_table(backend).name()
240 ))
241 })?;
242 Ok(Some(Image { options, published, size }))
243}
244
245/// The implementation of the lowering rule [`image_rule`] for one backend. It
246/// lowers each image to a
247/// [`flm.pres.image`](crate::stdlib::backends::pres::IMAGE) node, as the
248/// [module documentation](self) describes.
249#[derive(Debug, Clone)]
250pub struct ImageRule {
251 backend: String,
252}
253
254impl ImageRule {
255 /// Returns the implementation for `backend`. It reads the published table
256 /// and the magnification of `backend`.
257 pub fn new(backend: impl Into<String>) -> ImageRule {
258 ImageRule { backend: backend.into() }
259 }
260}
261
262impl Lower for ImageRule {
263 fn lower(
264 &self,
265 node: NodeRef<'_, Flm>,
266 cx: &mut LowerCx<'_>,
267 lw: &mut dyn Lowerer,
268 ) -> Result<Lowering, LowerError> {
269 let payload = {
270 let Some(image) = read_image(&node, &self.backend, lw)? else {
271 return Ok(Lowering::Emit(Vec::new()));
272 };
273 let (width, height) = image.size;
274 ImagePayload {
275 src: image.published.src.clone(),
276 display: image_display(&node),
277 alt: image.options.alt,
278 width,
279 height,
280 srcset: image.published.srcset.clone(),
281 anchor: None,
282 }
283 };
284 let image = lw.pres_with(cx, &ElementName::from(pres::IMAGE), payload, Vec::new())?;
285 Ok(Lowering::Emit(vec![image]))
286 }
287}
288
289/// Returns whether the image `node` is shown as a block or inline, according
290/// to its block role ([`block_role_of`]). An image is a block when it is a
291/// direct child of the body of a float ([`GraphicsImage`](super::GraphicsImage)).
292fn image_display(node: &NodeRef<'_, Flm>) -> ImageDisplay {
293 if block_role_of(node) == BlockRole::Block { ImageDisplay::Block } else { ImageDisplay::Inline }
294}
295
296/// Returns the lowering rule `flm.graphics.image.lower.<backend>`
297/// ([`rule_name`]), which lowers each image to a
298/// [`flm.pres.image`](crate::stdlib::backends::pres::IMAGE) node on
299/// `backend`, as the [module documentation](self) describes.
300///
301/// The rule is the default rule for images on `backend`, and is never chosen
302/// on another backend ([`DefaultMark::OnBackends`]). The rule reads the table
303/// [`INFO`], the published table of `backend` ([`published_table`]) and the
304/// render options [`GraphicsRenderOptions`].
305///
306/// The `graphics` feature registers this rule for the backends `text`, `html`
307/// and `latex-rendered`. You can register it for a backend of your own that
308/// writes `flm.pres.image` nodes. This backend then also needs a publish
309/// stage, which writes the published table of the backend
310/// ([`PublishStage`](super::PublishStage)), or a [publish stage of your
311/// own](super::publish#a-publish-stage-of-your-own).
312pub fn image_rule(backend: &str) -> LoweringRule {
313 LoweringRule::new(
314 rule_name(backend),
315 IMAGE_ELEMENT,
316 LoweringDecl::new()
317 .reads(INFO)
318 .reads(published_table(backend))
319 .option::<GraphicsRenderOptions>()
320 .produces(pres::IMAGE),
321 Arc::new(ImageRule::new(backend)),
322 DefaultMark::OnBackends(vec![backend.into()]),
323 )
324 .docs(
325 "Lowers an image to a `flm.pres.image` node. The node contains the address at which the \
326 output refers to the image, whether the image is a block or inline content, the \
327 alternative text, and the size at which the image is shown. The size is computed from \
328 `width`, `height` and the size of the image file, and is multiplied by the \
329 magnification of the output.",
330 )
331}
332
333#[cfg(test)]
334mod tests {
335 use super::*;
336 use crate::lang::FlmOrigin;
337 use crate::stdlib::backends::pres::I48F16;
338 use crate::stdlib::features::graphics::{
339 Dimensions, Factor, GraphicsInspectedInformation, PixelSize,
340 };
341
342 fn length(text: &str) -> Length {
343 Length::parse(text).expect("a length")
344 }
345
346 fn record(width: &str, height: &str) -> GraphicsRecord {
347 GraphicsRecord {
348 file: None,
349 path: String::from("a.svg"),
350 origin: FlmOrigin::none(),
351 inspected: Some(GraphicsInspectedInformation::Vector {
352 physical_dimensions: Dimensions { width: length(width), height: length(height) },
353 }),
354 }
355 }
356
357 #[test]
358 fn one_dimension_given_scales_the_other_in_its_unit() {
359 let one = Magnification::default();
360 let inspected = record("340pt", "170pt");
361 let width = ImageOptions { width: Some(length("5cm")), ..ImageOptions::default() };
362 assert_eq!(shown_size(&width, Some(&inspected), &one), (Some(length("5cm")), Some(length("2.5cm"))));
363 let height = ImageOptions { height: Some(length("2.5cm")), ..ImageOptions::default() };
364 assert_eq!(shown_size(&height, Some(&inspected), &one), (Some(length("5cm")), Some(length("2.5cm"))));
365 let both = ImageOptions {
366 width: Some(length("1in")),
367 height: Some(length("3in")),
368 ..ImageOptions::default()
369 };
370 assert_eq!(shown_size(&both, Some(&inspected), &one), (Some(length("1in")), Some(length("3in"))));
371 assert_eq!(
372 shown_size(&ImageOptions::default(), Some(&inspected), &one),
373 (Some(length("340pt")), Some(length("170pt")))
374 );
375 }
376
377 #[test]
378 fn with_nothing_inspected_the_given_dimension_stands_alone() {
379 let one = Magnification::default();
380 let width = ImageOptions { width: Some(length("5cm")), ..ImageOptions::default() };
381 assert_eq!(shown_size(&width, None, &one), (Some(length("5cm")), None));
382 assert_eq!(shown_size(&ImageOptions::default(), None, &one), (None, None));
383 let flat = record("0pt", "10pt");
384 assert_eq!(shown_size(&width, Some(&flat), &one), (Some(length("5cm")), None));
385 }
386
387 fn magnification(raster: f64, vector: f64) -> Magnification {
388 Magnification {
389 raster: Factor::try_from(raster).expect("a factor"),
390 vector: Factor::try_from(vector).expect("a factor"),
391 }
392 }
393
394 fn raster(physical: Option<(&str, &str)>) -> GraphicsRecord {
395 GraphicsRecord {
396 file: None,
397 path: String::from("a.png"),
398 origin: FlmOrigin::none(),
399 inspected: Some(GraphicsInspectedInformation::Raster {
400 dpi: Some(I48F16::from_num(72)),
401 size: PixelSize { width: 200, height: 100 },
402 physical_dimensions: physical.map(|(width, height)| Dimensions {
403 width: length(width),
404 height: length(height),
405 }),
406 }),
407 }
408 }
409
410 #[test]
411 fn a_raster_image_takes_the_raster_factor_and_a_vector_image_the_vector_factor() {
412 let factors = magnification(1.5, 2.0);
413 let none = ImageOptions::default();
414 assert_eq!(
415 shown_size(&none, Some(&raster(Some(("200pt", "100pt")))), &factors),
416 (Some(length("300pt")), Some(length("150pt")))
417 );
418 assert_eq!(
419 shown_size(&none, Some(&record("200pt", "100pt")), &factors),
420 (Some(length("400pt")), Some(length("200pt")))
421 );
422 }
423
424 #[test]
425 fn the_given_dimensions_are_magnified_too() {
426 let factors = magnification(1.5, 2.0);
427 let both = ImageOptions {
428 width: Some(length("2cm")),
429 height: Some(length("1in")),
430 ..ImageOptions::default()
431 };
432 assert_eq!(
433 shown_size(&both, Some(&raster(None)), &factors),
434 (Some(length("3cm")), Some(length("1.5in")))
435 );
436 // One given, the other scaled from the inspected size, then both
437 // magnified.
438 let width = ImageOptions { width: Some(length("5cm")), ..ImageOptions::default() };
439 assert_eq!(
440 shown_size(&width, Some(&record("340pt", "170pt")), &factors),
441 (Some(length("10cm")), Some(length("5cm")))
442 );
443 }
444
445 #[test]
446 fn an_image_of_unknown_type_takes_the_vector_factor() {
447 let factors = magnification(1.5, 2.0);
448 let width = ImageOptions { width: Some(length("5cm")), ..ImageOptions::default() };
449 assert_eq!(shown_size(&width, None, &factors), (Some(length("10cm")), None));
450 let mut uninspected = record("1pt", "1pt");
451 uninspected.inspected = None;
452 assert_eq!(shown_size(&width, Some(&uninspected), &factors), (Some(length("10cm")), None));
453 assert_eq!(shown_size(&ImageOptions::default(), None, &factors), (None, None));
454 }
455
456 #[test]
457 fn the_default_magnification_keeps_every_size() {
458 let one = Magnification::default();
459 let none = ImageOptions::default();
460 assert_eq!(
461 shown_size(&none, Some(&raster(Some(("7.25pt", "3mm")))), &one),
462 (Some(length("7.25pt")), Some(length("3mm")))
463 );
464 }
465}