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