flm_core/stdlib/features/graphics/options.rs
1//! This module reads the options of an image, which are written in the
2//! optional argument of `\includegraphics[options]{path}`. It also defines
3//! the diagnostic conditions that are reported for these options.
4//!
5//! The options are key-value pairs separated by commas, as in
6//! `\includegraphics[alt=A plot, width=5cm]{plot.png}`. A value that contains
7//! a comma is written in braces, as in `alt={A plot, before and after}`. Three
8//! keys are valid:
9//!
10//! - `alt` ([`ALT_KEY`]): the alternative text of the image, which must be
11//! plain text.
12//! - `width` ([`WIDTH_KEY`]) and `height` ([`HEIGHT_KEY`]): the size of the
13//! image. The value is a length greater than zero, in one of the units `pt`,
14//! `mm`, `cm` or `in`, as in `5cm` ([`Length`] describes the units).
15//!
16//! [`image_options`] returns the options of an image, and [`report`] reports
17//! the errors and warnings for these options. Each lowering rule of
18//! `\includegraphics` (element [`IMAGE_ELEMENT`](super::IMAGE_ELEMENT)) calls
19//! both functions when it lowers an image: the rule
20//! [`image_rule`](super::image_rule) on the plain-text, HTML and
21//! `latex-rendered` backends, and the rule
22//! [`LATEX_RULE`](super::latex::LATEX_RULE) on the `latex-recomposed`
23//! backend.
24//!
25//! An invalid option is reported as an error and ignored, and the image is
26//! otherwise written as usual. Each `width` or `height` that is used is
27//! reported with the warning [`Resized`]. The diagnostics are reported each
28//! time the image is lowered. An image is lowered again for each copy of it
29//! in an output, for instance in the title of a heading that a `\ref` expands
30//! to, and its diagnostics are then reported again. The `check` workflow
31//! ([`CHECK_WORKFLOW`](crate::stdlib::CHECK_WORKFLOW)) lowers nothing, and
32//! therefore does not report them.
33
34use std::collections::BTreeSet;
35
36use techy::core::node::NodeRef;
37use techy::error::{Diagnostic, DiagnosticInfo};
38use techy::extract::parse_keyval_drop_annotations;
39
40use crate::core::lowering::{LowerError, Lowerer, chars_at_lowering};
41use crate::lang::Flm;
42use crate::lang::text::{is_space, plain_text_of};
43use crate::stdlib::backends::pres::{I48F16, Length};
44
45use super::OPTIONS_ARG;
46
47/// The key of the alternative text, `alt`.
48pub const ALT_KEY: &str = "alt";
49
50/// The key of the width, `width`.
51pub const WIDTH_KEY: &str = "width";
52
53/// The key of the height, `height`.
54pub const HEIGHT_KEY: &str = "height";
55
56/// The keys that are valid in the options of `\includegraphics`: `alt`,
57/// `width` and `height`.
58pub const KEYS: [&str; 3] = [ALT_KEY, WIDTH_KEY, HEIGHT_KEY];
59
60/// The options of an image, as returned by [`image_options`].
61///
62/// A field is `None` when its key is not written in the options, or when the
63/// option is invalid. [`report`] reports the errors for the invalid options.
64#[derive(Debug, Clone, Default, PartialEq, Eq)]
65pub struct ImageOptions {
66 /// The alternative text: the value of `alt`, with the whitespace at both
67 /// ends removed.
68 pub alt: Option<String>,
69 /// The width of the image: the value of `width`, a length greater than
70 /// zero in one of the units `pt`, `mm`, `cm` or `in`.
71 pub width: Option<Length>,
72 /// The height of the image: the value of `height`, a length greater than
73 /// zero in one of the units `pt`, `mm`, `cm` or `in`.
74 pub height: Option<Length>,
75}
76
77/// A finding of [`read`] in the options of an image: an invalid option, or a
78/// `width` or `height` that is used. [`report`] reports one diagnostic for
79/// each finding.
80#[derive(Debug, Clone, PartialEq, Eq)]
81enum Finding {
82 /// The optional argument is not a list of key-value pairs with
83 /// plain-text keys.
84 Unreadable,
85 /// A value written with no key before its `=`.
86 NoKey,
87 /// A key that is not one of [`KEYS`].
88 Unknown(String),
89 /// A key written a second time.
90 Repeated(String),
91 /// A key written without `=` and a value.
92 NoValue(String),
93 /// An `alt=` value that is not plain text.
94 AltNotText,
95 /// A `width=` or `height=` value that is not a length.
96 NotALength { key: String, value: String },
97 /// A `width=` or `height=` length in a unit with no fixed size.
98 NotPhysical { key: String, unit: String },
99 /// A `width=` or `height=` length that is zero or negative.
100 NotPositive { key: String, value: String },
101 /// A `width=` or `height=` that takes effect.
102 Resized(String),
103}
104
105/// Error raised when a key in the options of `\includegraphics` is not plain
106/// text (id `flm.graphics.unreadable-options`).
107///
108/// Each key must be plain text, as in
109/// `\includegraphics[alt=A plot, width=5cm]{plot.png}`. An option written
110/// without `=` consists of its key alone.
111///
112/// Reported by the lowering rule of `\includegraphics` when it is invoked.
113/// The whole optional argument is ignored, and the image is written as if it
114/// had no options.
115#[derive(Debug, Clone, PartialEq, Eq, DiagnosticInfo)]
116#[diagnostic(
117 id = "flm.graphics.unreadable-options",
118 message = "Invalid key in the options of ‘\\includegraphics’: keys must be plain text"
119)]
120pub struct UnreadableOptions;
121
122/// Error raised when an option of `\includegraphics` has a value but no key
123/// (id `flm.graphics.missing-key`).
124///
125/// An option consists of a key, `=` and a value, as in `width=5cm`.
126///
127/// Reported by the lowering rule of `\includegraphics` when it is invoked.
128/// The value is ignored.
129#[derive(Debug, Clone, PartialEq, Eq, DiagnosticInfo)]
130#[diagnostic(
131 id = "flm.graphics.missing-key",
132 message = "Missing key before ‘=’ in the options of ‘\\includegraphics’"
133)]
134pub struct MissingKey;
135
136/// Error raised when the options of `\includegraphics` contain an unknown key
137/// (id `flm.graphics.unknown-key`).
138///
139/// The valid keys are `alt`, `width` and `height` ([`KEYS`]).
140///
141/// Reported by the lowering rule of `\includegraphics` when it is invoked.
142/// The key and its value are ignored.
143#[derive(Debug, Clone, PartialEq, Eq, DiagnosticInfo)]
144#[diagnostic(
145 id = "flm.graphics.unknown-key",
146 message = "Invalid key ‘{key}’ in the options of ‘\\includegraphics’: \
147 valid keys are ‘alt’, ‘width’ and ‘height’"
148)]
149pub struct UnknownKey {
150 /// The key as written.
151 pub key: String,
152}
153
154/// Error raised when a key is written more than once in the options of
155/// `\includegraphics` (id `flm.graphics.repeated-key`).
156///
157/// Reported by the lowering rule of `\includegraphics` when it is invoked,
158/// once for each repetition of the key. Only the first occurrence of the key
159/// is read. Each later occurrence is ignored, even when the first occurrence
160/// is itself reported as an error.
161#[derive(Debug, Clone, PartialEq, Eq, DiagnosticInfo)]
162#[diagnostic(
163 id = "flm.graphics.repeated-key",
164 message = "Duplicate key ‘{key}’ in the options of ‘\\includegraphics’"
165)]
166pub struct RepeatedKey {
167 /// The key as written.
168 pub key: String,
169}
170
171/// Error raised when a key in the options of `\includegraphics` is written
172/// without `=` (id `flm.graphics.missing-value`).
173///
174/// Each key must be followed by `=` and its value, as in `alt=A plot`.
175///
176/// Reported by the lowering rule of `\includegraphics` when it is invoked.
177/// The key is ignored.
178#[derive(Debug, Clone, PartialEq, Eq, DiagnosticInfo)]
179#[diagnostic(
180 id = "flm.graphics.missing-value",
181 message = "Missing value for key ‘{key}’ of ‘\\includegraphics’: use the syntax ‘{key}=…’"
182)]
183pub struct MissingValue {
184 /// The key as written.
185 pub key: String,
186}
187
188/// Error raised when the value of `alt` in the options of `\includegraphics`
189/// is not plain text (id `flm.graphics.alt-not-text`).
190///
191/// The alternative text must be plain text, that is, text without commands
192/// or math, as in `alt=A plot` or `alt={A plot, before and after}`.
193///
194/// Reported by the lowering rule of `\includegraphics` when it is invoked.
195/// The image is otherwise written as usual, without alternative text.
196#[derive(Debug, Clone, PartialEq, Eq, DiagnosticInfo)]
197#[diagnostic(
198 id = "flm.graphics.alt-not-text",
199 message = "The ‘alt’ text of an image must be plain text, without formulas or commands"
200)]
201pub struct AltNotText;
202
203/// Error raised when the value of `width` or `height` in the options of
204/// `\includegraphics` is not a length (id `flm.graphics.not-a-length`).
205///
206/// A length is a decimal number followed directly by a unit, as in `5cm`,
207/// `2.5in` or `144pt`. The valid units are `pt`, `mm`, `cm` and `in`
208/// ([`Length`] describes them). A length in the unit `em` or `tab` is
209/// reported as [`RelativeUnit`].
210///
211/// Reported by the lowering rule of `\includegraphics` when it is invoked.
212/// The key is ignored, and the size of the image is determined as if the key
213/// were not written.
214#[derive(Debug, Clone, PartialEq, Eq, DiagnosticInfo)]
215#[diagnostic(
216 id = "flm.graphics.not-a-length",
217 message = "Invalid length ‘{value}’ for key ‘{key}’ of ‘\\includegraphics’: a length must be \
218 a number followed directly by a unit, as in ‘5cm’ (supported units: ‘pt’, ‘mm’, \
219 ‘cm’ and ‘in’)"
220)]
221pub struct NotALength {
222 /// The key, `width` or `height`.
223 pub key: String,
224 /// The value as written, trimmed. When the value contains commands, this
225 /// is its plain text ([`plain_text_of`]).
226 pub value: String,
227}
228
229/// Error raised when the value of `width` or `height` in the options of
230/// `\includegraphics` is a length in the unit `em` or `tab` (id
231/// `flm.graphics.relative-unit`).
232///
233/// The size of an image must be given in a unit of fixed size, `pt`, `mm`,
234/// `cm` or `in`, as in `width=5cm`. The units `em` and `tab` have no fixed
235/// size: an em depends on the font, and each backend sets the width of a tab.
236///
237/// Reported by the lowering rule of `\includegraphics` when it is invoked.
238/// The key is ignored, and the size of the image is determined as if the key
239/// were not written.
240#[derive(Debug, Clone, PartialEq, Eq, DiagnosticInfo)]
241#[diagnostic(
242 id = "flm.graphics.relative-unit",
243 message = "Unsupported unit ‘{unit}’ for key ‘{key}’ of ‘\\includegraphics’ (supported units: \
244 ‘pt’, ‘mm’, ‘cm’ and ‘in’)"
245)]
246pub struct RelativeUnit {
247 /// The key, `width` or `height`.
248 pub key: String,
249 /// The unit as written, `em` or `tab`.
250 pub unit: String,
251}
252
253/// Error raised when the value of `width` or `height` in the options of
254/// `\includegraphics` is zero or negative (id `flm.graphics.not-positive`).
255///
256/// Reported by the lowering rule of `\includegraphics` when it is invoked.
257/// The key is ignored, and the size of the image is determined as if the key
258/// were not written.
259#[derive(Debug, Clone, PartialEq, Eq, DiagnosticInfo)]
260#[diagnostic(
261 id = "flm.graphics.not-positive",
262 message = "Invalid length ‘{value}’ for key ‘{key}’ of ‘\\includegraphics’: the length must be \
263 greater than zero"
264)]
265pub struct NotPositive {
266 /// The key, `width` or `height`.
267 pub key: String,
268 /// The length, as written and trimmed.
269 pub value: String,
270}
271
272/// The warning that is reported when the size of an image is set with the key
273/// `width` or `height` of `\includegraphics` (id `flm.graphics.resized`).
274///
275/// An image file that is prepared at the size at which the image is
276/// displayed, with a resolution suited to that size, looks better than an
277/// image file that is resized in the output.
278///
279/// Reported by the lowering rule of `\includegraphics` when it is invoked,
280/// once for each `width` and each `height` that is used. The image is written
281/// at the given size.
282#[derive(Debug, Clone, PartialEq, Eq, DiagnosticInfo)]
283#[diagnostic(
284 id = "flm.graphics.resized",
285 message = "Image resized with key ‘{key}’ of ‘\\includegraphics’: \
286 for the best quality, prepare the image file at the displayed size"
287)]
288pub struct Resized {
289 /// The key, `width` or `height`.
290 pub key: String,
291}
292
293/// Returns the options of the image `node`, a node of `\includegraphics`.
294///
295/// The result contains only the valid options (see [`ImageOptions`]). This
296/// function reports no diagnostic; call [`report`] to report the errors and
297/// warnings for the options.
298///
299/// # Errors
300///
301/// Returns [`LowerError::PlaceholderCharacters`] when the value of `alt`,
302/// `width` or `height` contains a placeholder of a user definition's
303/// template, such as `#1`. This happens only when the template is lowered
304/// without being expanded (see [`LowerError::PlaceholderCharacters`]).
305pub fn image_options(node: &NodeRef<'_, Flm>) -> Result<ImageOptions, LowerError> {
306 Ok(read(node)?.0)
307}
308
309/// Reports the errors and warnings for the options of the image `node`
310/// through `lw`.
311///
312/// One error is reported for each invalid option, and one [`Resized`] warning
313/// for each `width` and each `height` that is used, in the order in which
314/// the options are written. Each diagnostic is located at `node`.
315///
316/// # Errors
317///
318/// Returns [`LowerError::PlaceholderCharacters`] in the same cases as
319/// [`image_options`].
320pub fn report(node: &NodeRef<'_, Flm>, lw: &mut dyn Lowerer) -> Result<(), LowerError> {
321 let (_, findings) = read(node)?;
322 for finding in findings {
323 let span = node.span().clone();
324 lw.diagnose(match finding {
325 Finding::Unreadable => Diagnostic::error(UnreadableOptions, span),
326 Finding::NoKey => Diagnostic::error(MissingKey, span),
327 Finding::Unknown(key) => Diagnostic::error(UnknownKey { key }, span),
328 Finding::Repeated(key) => Diagnostic::error(RepeatedKey { key }, span),
329 Finding::NoValue(key) => Diagnostic::error(MissingValue { key }, span),
330 Finding::AltNotText => Diagnostic::error(AltNotText, span),
331 Finding::NotALength { key, value } => {
332 Diagnostic::error(NotALength { key, value }, span)
333 }
334 Finding::NotPhysical { key, unit } => {
335 Diagnostic::error(RelativeUnit { key, unit }, span)
336 }
337 Finding::NotPositive { key, value } => {
338 Diagnostic::error(NotPositive { key, value }, span)
339 }
340 Finding::Resized(key) => Diagnostic::warning(Resized { key }, span),
341 });
342 }
343 Ok(())
344}
345
346/// Reads the options of the image `node`. Returns the valid options, and the
347/// findings in the order in which the options are written.
348fn read(node: &NodeRef<'_, Flm>) -> Result<(ImageOptions, Vec<Finding>), LowerError> {
349 let mut options = ImageOptions::default();
350 let mut findings = Vec::new();
351 let Ok(Some(content)) = node.argument_content_nodes_named(OPTIONS_ARG) else {
352 return Ok((options, findings));
353 };
354 let Ok(keyvals) = parse_keyval_drop_annotations(content) else {
355 findings.push(Finding::Unreadable);
356 return Ok((options, findings));
357 };
358 let mut seen: BTreeSet<&str> = BTreeSet::new();
359 for entry in keyvals.iter() {
360 let key = entry.key();
361 if key.is_empty() {
362 // An empty entry, as between the commas of `[a=1,,b=2]`, says
363 // nothing; a value with no key is refused.
364 if entry.value_content().is_some() {
365 findings.push(Finding::NoKey);
366 }
367 continue;
368 }
369 if !KEYS.contains(&key) {
370 findings.push(Finding::Unknown(key.to_string()));
371 continue;
372 }
373 if !seen.insert(key) {
374 findings.push(Finding::Repeated(key.to_string()));
375 continue;
376 }
377 let Some(value) = entry.value_content() else {
378 findings.push(Finding::NoValue(key.to_string()));
379 continue;
380 };
381 let text = chars_at_lowering(value.iter())?.map(|text| text.trim_matches(is_space).to_string());
382 if key == ALT_KEY {
383 match text {
384 Ok(text) => options.alt = Some(text),
385 Err(_) => findings.push(Finding::AltNotText),
386 }
387 continue;
388 }
389 let written = match text {
390 Ok(text) => text,
391 Err(_) => plain_text_of(value.iter()).trim_matches(is_space).to_string(),
392 };
393 match dimension(key, &written) {
394 Ok(length) => {
395 // A Warning for a dimension taken, none for one refused: a
396 // refused dimension resizes nothing, and its Error says why.
397 if key == WIDTH_KEY {
398 options.width = Some(length);
399 } else {
400 options.height = Some(length);
401 }
402 findings.push(Finding::Resized(key.to_string()));
403 }
404 Err(finding) => findings.push(finding),
405 }
406 }
407 Ok((options, findings))
408}
409
410/// Parses `written`, the value of the key `key` (`width` or `height`), as a
411/// length. Returns the finding for the error when the value is not a length,
412/// when its unit is `em` or `tab`, or when it is not greater than zero.
413fn dimension(key: &str, written: &str) -> Result<Length, Finding> {
414 let length = Length::parse(written).map_err(|_| Finding::NotALength {
415 key: key.to_string(),
416 value: written.to_string(),
417 })?;
418 if !length.unit.is_physical() {
419 return Err(Finding::NotPhysical { key: key.to_string(), unit: length.unit.to_string() });
420 }
421 if length.amount <= I48F16::ZERO {
422 return Err(Finding::NotPositive { key: key.to_string(), value: written.to_string() });
423 }
424 Ok(length)
425}
426
427#[cfg(test)]
428mod tests {
429 use super::*;
430
431 #[test]
432 fn a_dimension_is_a_positive_physical_length() {
433 assert_eq!(dimension("width", "5cm"), Ok(Length::parse("5cm").unwrap()));
434 assert_eq!(dimension("width", ".5in"), Ok(Length::parse("0.5in").unwrap()));
435 for text in ["300px", "0.5\\linewidth", "50%", "10bp", "", "5"] {
436 assert!(matches!(dimension("width", text), Err(Finding::NotALength { .. })), "{text}");
437 }
438 assert!(matches!(dimension("width", "1.5em"), Err(Finding::NotPhysical { .. })));
439 assert!(matches!(dimension("height", "2tab"), Err(Finding::NotPhysical { .. })));
440 assert!(matches!(dimension("width", "0cm"), Err(Finding::NotPositive { .. })));
441 assert!(matches!(dimension("width", "-1pt"), Err(Finding::NotPositive { .. })));
442 }
443}