Skip to main content

flm_core/stdlib/features/graphics/
mod.rs

1//! This module defines the `graphics` feature ([`Graphics`]), which provides
2//! the command `\includegraphics[options]{path}`. The command inserts an
3//! *image*, that is, an external picture file, into the document. For
4//! instance, `\includegraphics[alt=A plot, width=5cm]{figures/plot.png}`
5//! inserts the picture of the file `figures/plot.png`, 5cm wide, with the
6//! alternative text `A plot`. A path can also be an address, such as
7//! `https://example.org/a.svg`.
8//!
9//! The library never opens a file itself. The program that embeds FLM can
10//! contribute *services* that find, measure and convert image files, as
11//! described below; the `flm` program contributes them with its feature
12//! `graphics-files`. Without these services, every output refers to an image
13//! by its path as written.
14//!
15//! The language guide describes the command for authors
16//! ([Graphics](crate::guide::language_syntax#graphics)). The rendering guide
17//! shows what each output writes ([images and how an output reaches
18//! them](crate::guide::rendering#images-and-how-an-output-reaches-them)).
19//!
20//! # Where the command can be written
21//!
22//! `\includegraphics` is declared in the [scoped
23//! package](crate::guide::concepts_overview#scoped-packages)
24//! [`INCLUDEGRAPHICS_PACKAGE`] (`flm.graphics.includegraphics`). The command
25//! is therefore available only in the bodies and arguments whose declarations
26//! refer to this package. Elsewhere, it is an unknown command. With the
27//! `floats` feature, the float types `figure` and `table` refer to this
28//! package, so that an image can be written as the content of a figure:
29//!
30//! ```text
31//! \begin{figure}
32//!   \includegraphics{figures/plot.png}
33//!   \caption{A plot of the data.}
34//! \end{figure}
35//! ```
36//!
37//! With the configuration [`GraphicsConfig::global`], `\includegraphics` is
38//! also declared as an ordinary command, which can be written wherever text
39//! can be written.
40//!
41//! An image is a block when it is a direct child of the body of a float, as in
42//! the figure above. Everywhere else, an image is inline content, like a word
43//! of the text around it ([`GraphicsImage`]).
44//!
45//! # The options and the path
46//!
47//! The optional argument contains key-value pairs: the alternative text `alt`,
48//! and the size `width` and `height`. The module [`options`](mod@options)
49//! reads the options and defines the diagnostics that are reported for them.
50//! An invalid option is reported as an error and ignored, and the image is
51//! written as usual.
52//!
53//! The mandatory argument contains the path of the image file as raw text, up
54//! to the matching `}`. The characters `%`, `#`, `~`, `\` and nested braces are
55//! part of the path. The path is read when the image is lowered. Therefore, a
56//! placeholder in the path of a user definition's template is replaced by the
57//! characters of the corresponding argument of the call. For instance, if the
58//! template of `\fig` is `\includegraphics{figs/#1.png}`, the call `\fig{plot}`
59//! inserts the image `figs/plot.png`. A path that is not plain text is
60//! reported as the error [`PathNotCharacters`], and an empty path as the error
61//! [`EmptyPath`]. In both cases, no image is written.
62//!
63//! # The size of an image
64//!
65//! The size at which an image is shown is computed when the image is lowered
66//! ([`shown_size`]):
67//!
68//! - When both `width` and `height` are given, the image has this size.
69//! - When only one of them is given, the other dimension is computed from the
70//!   size of the image file, so that the image keeps its proportions. If the
71//!   size of the file is not known, only the given dimension is set.
72//! - When neither is given, the image has the size of the image file.
73//!
74//! The size of the image file is known when an inspector, one of the services
75//! described below, has reported it. The size is then multiplied by the
76//! *magnification* of the output: one factor for raster images and another
77//! for vector images ([`GraphicsRenderOptions::magnification`]). Both factors
78//! are 1 by default. When no size is known, the warning [`UnknownSize`] is
79//! reported, and the image is written without a size.
80//!
81//! # Services for image files
82//!
83//! A *service* is a value that a feature, or the program that embeds FLM,
84//! contributes to a *service slot* declared in another feature
85//! ([`core::services`](crate::core::services)). The `graphics` feature
86//! declares three service slots, for the work that needs access to files or to
87//! installed programs. None of these services is required.
88//!
89//! - The *graphics resolver* ([`GraphicsResolver`], slot [`RESOLVER_SLOT`], at
90//!   most one) finds the file that a path refers to, and reads its content
91//!   ([`resolve`](mod@resolve)).
92//! - The *inspector* ([`GraphicsInspector`], slot [`INSPECTOR_SLOT`], at most
93//!   one) reports the type and the size of an image file
94//!   ([`inspect`](mod@inspect)).
95//! - The *converters* ([`GraphicsConverter`], slot [`CONVERTERS_SLOT`], any
96//!   number) convert image files from one format into another, for instance
97//!   from PDF to PNG ([`convert`](mod@convert)).
98//!
99//! # Stages and lowering rules
100//!
101//! The feature registers two kinds of stages, which call the services:
102//!
103//! - The inspect stage [`INSPECT_STAGE`] (`flm.graphics.inspect`) calls the
104//!   graphics resolver and the inspector for each image. It writes the results
105//!   into the table [`INFO`] (`flm.graphics.info`), keyed by the address of the
106//!   image's node.
107//! - The publish stage `flm.graphics.publish.<backend>` ([`PublishStage`]) is
108//!   registered for each of the backends `text`, `html`, `latex-recomposed`
109//!   and `latex-rendered`. It computes the address at which the output of the
110//!   backend refers to each image, and writes this address into the table
111//!   `flm.graphics.published.<backend>` ([`published_table`]). The address
112//!   depends on the *strategy* that the render options set for the output: the
113//!   address of the file where it is (`reference`, the default), the address
114//!   of a copy of the file that is made part of the output (`copy`), or a
115//!   `data:` address that contains the content of the file (`data-uri`). Under
116//!   the strategy `content`, the stage also writes the content of each image
117//!   file into the table `flm.graphics.content.<backend>` ([`content_table`]),
118//!   for an output that renders images itself. See the modules
119//!   [`strategy`](mod@strategy) and [`publish`](mod@publish). A stage of the
120//!   program that embeds FLM can write the published table in place of this
121//!   stage ([a publish stage of your
122//!   own](publish#a-publish-stage-of-your-own)).
123//!
124//! On the progress sheet of a build ([`crate::progress`]), the inspect stage
125//! declares no row of its own: the run counts its trees. A call of a publish
126//! stage that converts images declares a row of the kind [`IMAGES_KIND`]
127//! (`flm.graphics.images`), counted in the images it converts, and under it a
128//! row of the kind [`CONVERT_KIND`] (`flm.graphics.convert`, "Converting
129//! graphics") for each conversion, whose scope the converter receives.
130//!
131//! The lowering rules of the image element read these tables:
132//!
133//! - On the backends `text`, `html` and `latex-rendered`, the rule
134//!   [`image_rule`] lowers an image to a
135//!   [`flm.pres.image`](crate::stdlib::backends::pres::IMAGE) node. For
136//!   instance, the plain-text output prints this node as
137//!   `[image: <alternative text or address>]`, and the HTML output writes it
138//!   as an `<img>` element.
139//! - On the backend `latex-recomposed`, the rule
140//!   [`LATEX_RULE`](latex::LATEX_RULE) writes the LaTeX hook
141//!   `\flmIncludeGraphics[<keys>]{<path>}` ([`latex`](mod@latex)).
142//!
143//! The stages and the rules of each backend are registered with a peer
144//! declaration of the backend ([`PeerName`](crate::core::registry::PeerName)).
145//! A registry without one of these backends therefore still builds.
146//!
147//! # Settings
148//!
149//! The configuration [`GraphicsConfig`] is the value from which the feature is
150//! constructed, and is fixed when the registry is built. The render options
151//! [`GraphicsRenderOptions`] are set for each render request. For each output,
152//! they contain the strategy (`strategy`), the conversion rules (`convert`,
153//! [`ConversionRule`]) and the magnification (`magnification`,
154//! [`Magnification`]). See [settings, options and
155//! configuration](crate::guide::concepts_overview#settings-options-and-configuration).
156//!
157//! # Images in floats
158//!
159//! The feature contributes the content handler `includegraphics` to the
160//! `floats` feature ([`handler`](mod@handler)). A float type that lists this
161//! handler, as `figure` and `table` do by default, accepts a body that
162//! contains exactly one image besides its caption and labels.
163//!
164//! In a registry without the `floats` feature, this contribution is dropped
165//! with a note. To use images without floats, set [`GraphicsConfig::global`].
166//!
167//! [`shown_size`]: crate::stdlib::features::graphics::rules::shown_size
168
169pub mod convert;
170pub mod handler;
171pub mod inspect;
172pub mod latex;
173pub mod options;
174pub mod publish;
175pub mod resolve;
176pub mod rules;
177pub mod strategy;
178
179use std::sync::Arc;
180
181use techy::core::node::NodeRef;
182use techy::error::DiagnosticInfo;
183
184use crate::core::settings::SettingsDecl;
185use crate::model::options::Bind;
186use crate::core::lowering::chars_at_lowering;
187use crate::core::registry::{BuildError, FeatureBuilder, FeatureInfo, FlmFeature};
188use crate::core::services::Arity;
189use crate::lang::mint::{ArgDef, ArgStdKind, ElementDef, ScopedPackageDef, SyntaxDef};
190use crate::lang::Flm;
191use crate::model::aspects::{ApartFromText, BlockRole, BlockRoleAspect, ContentRef};
192use crate::model::element::{ElementSpec, element_of};
193use crate::model::names::{FeatureName, Name};
194use crate::stdlib::backends::lowering::rules::owning_callable;
195use crate::stdlib::backends::{html, text};
196use crate::stdlib::features::floats::{CONTENT_SLOT, FLOAT, FloatContentHandler};
197
198pub use convert::{
199    CONVERTERS_SLOT, ConversionOptions, ConversionRequest, ConversionRule, GraphicsConvertError,
200    GraphicsConverter, NoConverter, choose_converter,
201};
202pub use handler::IncludeGraphicsContent;
203pub use inspect::{
204    Dimensions, GraphicsInfo, GraphicsInspectError, GraphicsInspectRequest,
205    GraphicsInspectedInformation, GraphicsInspector, GraphicsRecord, PixelSize,
206};
207pub use publish::{
208    CONVERT_KIND, GraphicsContent, GraphicsPublished, IMAGES_KIND, ImageContent, OutputImages,
209    PublishStage, PublishedImage, content_table, output_images, published_table,
210};
211pub use resolve::{
212    GraphicsResolveError, GraphicsResolveRequest, GraphicsResolver, ImageFile, ImageFormat,
213    RESOLVER_SLOT, ResolvedImage, names_scheme,
214};
215pub use strategy::{Factor, FactorError, GraphicsRenderOptions, Magnification, Strategy};
216pub use rules::{ImageRule, UnknownSize, image_rule};
217
218/// The name under which the [`Graphics`] feature is registered: `graphics`.
219pub const FEATURE: &str = "graphics";
220
221/// Returns the declaration of the settings of the `graphics` feature. The fields of the
222/// configuration [`GraphicsConfig`] and of the render options [`GraphicsRenderOptions`] are the
223/// settings keys.
224///
225/// The values of the keys `strategy`, `convert` and `magnification` are maps from the name of an
226/// output to the value for this output. These keys are merged entry by entry
227/// ([`SettingsDecl::merge_entries`]), and have no default entries. Therefore, when a host
228/// combines several sources of settings, a source that sets the entry of one output leaves the
229/// entries of the other outputs unchanged.
230fn settings() -> SettingsDecl {
231    SettingsDecl::new(FEATURE)
232        .config::<GraphicsConfig>(
233            "Whether `\\includegraphics` can be written wherever text can be written (`global`). \
234            When `global` is false, which is the default, the command is available only in the \
235            bodies of the float types that allow it, such as `figure` and `table`. This \
236            configuration is fixed when the registry is built; it cannot vary per document or \
237            per render.",
238        )
239        .options::<GraphicsRenderOptions>(
240            Bind::Render,
241            "The image settings of each output, set per render request. Each key maps the name \
242            of an output to the value for this output. `strategy` selects how the output refers \
243            to its images: `reference` (the default) refers to the file where it is, `copy` \
244            makes a copy of the file part of the output, `data-uri` writes the content of the \
245            file into a `data:` address, and `content` passes the content of the file to an \
246            output that renders images itself. `convert` lists the conversion rules that the \
247            output applies to image files under the strategies `copy`, `data-uri` and \
248            `content`. `magnification` contains the factors by which the output multiplies the \
249            size of raster images and of vector images (`raster` and `vector`, 1 by default).",
250        )
251        .merge_entries("strategy", || Ok(serde_json::Value::Object(serde_json::Map::new())))
252        .remove_false("strategy")
253        .merge_entries("convert", || Ok(serde_json::Value::Object(serde_json::Map::new())))
254        .remove_false("convert")
255        .merge_entries("magnification", || Ok(serde_json::Value::Object(serde_json::Map::new())))
256        .remove_false("magnification")
257}
258
259/// The name of the element of `\includegraphics`: `flm.graphics.image`. The
260/// data of its element value is [`GraphicsImage`].
261pub const IMAGE_ELEMENT: &str = "flm.graphics.image";
262
263/// The name of the scoped package that contains the declaration of
264/// `\includegraphics`: `flm.graphics.includegraphics`.
265///
266/// `\includegraphics` is available in the bodies and arguments whose
267/// declarations refer to this package. For instance, a float type refers to
268/// the package by listing it in
269/// [`FloatType::scoped_packages`](crate::stdlib::features::floats::FloatType::scoped_packages),
270/// as the types `figure` and `table` do. The package is declared under every
271/// configuration of the feature, also when [`GraphicsConfig::global`] makes
272/// `\includegraphics` an ordinary command.
273pub const INCLUDEGRAPHICS_PACKAGE: &str = "flm.graphics.includegraphics";
274
275/// The name of the command, without the backslash, `includegraphics`.
276pub const COMMAND: &str = "includegraphics";
277
278/// The name of the optional argument of `\includegraphics`: `options`. The
279/// argument contains the options of the image as key-value pairs (see the
280/// module [`options`](mod@options)).
281pub const OPTIONS_ARG: &str = "options";
282
283/// The name of the mandatory argument of `\includegraphics`: `path`. The
284/// argument contains the path of the image file as raw text, up to the
285/// matching `}`.
286pub const PATH_ARG: &str = "path";
287
288/// The name of the argument role `flm.graphics.path`, which marks an argument
289/// that contains the path of an image file. The path argument [`PATH_ARG`] of
290/// `\includegraphics` has this role
291/// ([`ArgDef::role`](crate::lang::mint::ArgDef::role)).
292pub const PATH_ARG_ROLE: &str = "flm.graphics.path";
293
294/// The name of the service slot of the inspector: `flm.graphics.inspector`.
295/// A feature or the program that embeds FLM can contribute at most one
296/// [`GraphicsInspector`] to this slot ([`Arity::Single`]). The `graphics`
297/// feature works without an inspector. See the module [`inspect`](mod@inspect).
298pub const INSPECTOR_SLOT: &str = "flm.graphics.inspector";
299
300pub use inspect::{INFO, INSPECT_STAGE};
301
302/// The configuration of the `graphics` feature, which selects where
303/// `\includegraphics` can be written.
304///
305/// By default (`global` is `false`), `\includegraphics` is available only in
306/// the bodies whose declarations refer to the scoped package
307/// [`flm.graphics.includegraphics`](INCLUDEGRAPHICS_PACKAGE), for instance the
308/// body of a `figure` when the `floats` feature is registered. When `global`
309/// is `true`, `\includegraphics` is also an ordinary command, which can be
310/// written wherever text can be written.
311///
312/// The configuration is the value from which the feature is constructed. It
313/// is fixed when the registry is built, and cannot vary per document or per
314/// render ([settings, options and
315/// configuration](crate::guide::concepts_overview#settings-options-and-configuration)).
316/// The configuration changes which commands exist in the language, so
317/// [`digest_bytes`](GraphicsConfig::digest_bytes) is an input of the registry
318/// digest. To configure the feature among the standard features, use
319/// [`StdlibConfig::graphics`](crate::stdlib::StdlibConfig::graphics).
320///
321/// # Examples
322///
323/// ```
324/// use flm_core::stdlib::features::graphics::GraphicsConfig;
325///
326/// assert!(!GraphicsConfig::new().global);
327/// assert!(GraphicsConfig::new().global(true).global);
328/// ```
329#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash, serde::Deserialize)]
330#[derive(schemars::JsonSchema)]
331#[serde(default, deny_unknown_fields)]
332pub struct GraphicsConfig {
333    /// Whether `\includegraphics` can be written wherever text can be written.
334    /// When `false` (the default), the command is available only in the
335    /// bodies that refer to its scoped package
336    /// [`flm.graphics.includegraphics`](INCLUDEGRAPHICS_PACKAGE), such as the
337    /// bodies of the float types `figure` and `table`.
338    pub global: bool,
339}
340
341impl GraphicsConfig {
342    /// Returns the default configuration, in which `global` is `false`.
343    pub fn new() -> GraphicsConfig {
344        GraphicsConfig::default()
345    }
346
347    /// Sets [`global`](GraphicsConfig::global) and returns the configuration.
348    pub fn global(mut self, global: bool) -> GraphicsConfig {
349        self.global = global;
350        self
351    }
352
353    /// Returns the bytes that represent this configuration in the registry
354    /// digest: one byte, `1` when `global` is `true` and `0` otherwise.
355    pub fn digest_bytes(&self) -> Vec<u8> {
356        // Taken apart by name, so a field added and not written here fails
357        // to compile.
358        let GraphicsConfig { global } = self;
359        vec![u8::from(*global)]
360    }
361}
362
363/// The data of the element value of `\includegraphics` ([`IMAGE_ELEMENT`]).
364///
365/// This type implements the two aspects of the element. An aspect is a piece
366/// of behavior attached to an element ([elements and
367/// aspects](crate::guide::concepts_overview#elements-and-aspects)).
368///
369/// - [`BlockRoleAspect`]: an image is a block when it is a direct child of
370///   the body of a float, and inline content everywhere else.
371/// - [`ApartFromText`]: the options and the path of an image are not part of
372///   the text in which the image is written.
373#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]
374pub struct GraphicsImage;
375
376/// An image is a block when it is a direct child of the body of a float, that
377/// is, of a node of the element [`FLOAT`] (`flm.floats.float`) of the `floats`
378/// feature, whatever its float type. Everywhere else, an image is inline
379/// content, for instance in a sentence, in the title of a heading, in a
380/// caption, or in a paragraph of the body of a float. Without the `floats`
381/// feature, every image is inline content.
382impl BlockRoleAspect for GraphicsImage {
383    fn block_role(&self, node: &NodeRef<'_, Flm>) -> BlockRole {
384        let in_float_body = owning_callable(node).is_some_and(|owner| {
385            element_of(&owner).name.as_str() == FLOAT
386                && owner.body().is_some_and(|body| body.iter().any(|child| child.id() == node.id()))
387        });
388        if in_float_body { BlockRole::Block } else { BlockRole::DEFAULT }
389    }
390}
391
392/// Returns the options argument [`OPTIONS_ARG`] and the path argument
393/// [`PATH_ARG`]: neither is part of the text in which the image is written.
394/// For instance, the identifier of a heading whose title contains an image is
395/// computed from the other words of the title. The alternative text is part
396/// of the options argument, and is therefore left out as well.
397impl ApartFromText for GraphicsImage {
398    fn apart_from_text(&self, _node: &NodeRef<'_, Flm>) -> Vec<ContentRef> {
399        vec![
400            ContentRef::ArgumentNamed(OPTIONS_ARG.to_string()),
401            ContentRef::ArgumentNamed(PATH_ARG.to_string()),
402        ]
403    }
404}
405
406/// The error that is reported when the path of `\includegraphics` is not
407/// plain text (`flm.graphics.path-not-characters`).
408///
409/// The path that an author writes in `\includegraphics{path}` is always plain
410/// text, because the argument is read as raw text. Other content gets into
411/// the path through a user definition whose template places one of its
412/// arguments in the path. A call of such a definition must pass plain text in
413/// this argument, that is, characters only. For instance, if the template of
414/// `\fig` is `\includegraphics{figs/#1.png}`, the call can be `\fig{plot}`.
415///
416/// Reported by the lowering rule of `\includegraphics` when it is invoked.
417/// The `\includegraphics` command then expands to nothing.
418#[derive(Debug, Clone, PartialEq, Eq, DiagnosticInfo)]
419#[diagnostic(
420    id = "flm.graphics.path-not-characters",
421    message = "Invalid path in ‘\\includegraphics’: the path must be plain text"
422)]
423pub struct PathNotCharacters;
424
425/// The error that is reported when the path of `\includegraphics` is empty
426/// (`flm.graphics.empty-path`).
427///
428/// The path must contain at least one character, as in
429/// `\includegraphics{figures/plot.png}`.
430///
431/// Reported by the lowering rule of `\includegraphics` when it is invoked.
432/// The `\includegraphics` command then expands to nothing.
433#[derive(Debug, Clone, PartialEq, Eq, DiagnosticInfo)]
434#[diagnostic(id = "flm.graphics.empty-path", message = "Missing path in ‘\\includegraphics’")]
435pub struct EmptyPath;
436
437/// The path of an image, as returned by [`read_path`].
438pub(crate) enum ImagePath {
439    /// The path as written, which contains at least one character.
440    Read(String),
441    /// The path is empty.
442    Empty,
443    /// The path contains content other than characters, such as a command.
444    NotCharacters,
445}
446
447/// Reads the path of the image `node` with [`chars_at_lowering`]. A path
448/// argument that is missing after a parse error is read as an empty path.
449///
450/// # Errors
451///
452/// Returns
453/// [`LowerError::PlaceholderCharacters`](crate::core::lowering::LowerError::PlaceholderCharacters)
454/// when the path contains a placeholder of a user definition's template. This
455/// happens only when a template is lowered without being expanded, such as
456/// the template of a user definition that the recomposed LaTeX keeps as a
457/// LaTeX definition.
458pub(crate) fn read_path(
459    node: &NodeRef<'_, Flm>,
460) -> Result<ImagePath, crate::core::lowering::LowerError> {
461    let Ok(Some(content)) = node.argument_content_nodes_named(PATH_ARG) else {
462        return Ok(ImagePath::Empty);
463    };
464    Ok(match chars_at_lowering(content.iter())? {
465        Ok(text) if text.is_empty() => ImagePath::Empty,
466        Ok(text) => ImagePath::Read(text),
467        Err(_) => ImagePath::NotCharacters,
468    })
469}
470
471/// Returns the element value of [`IMAGE_ELEMENT`]. Its data is
472/// [`GraphicsImage`], which also implements the two aspects of the element,
473/// [`BlockRoleAspect`] and [`ApartFromText`]. The declaration of
474/// `\includegraphics` in the scoped package and the ordinary declaration under
475/// [`GraphicsConfig::global`] share this element value.
476fn image_spec() -> Arc<ElementSpec> {
477    Arc::new(
478        ElementSpec::new(IMAGE_ELEMENT)
479            .docs("An image, inserted with `\\includegraphics[options]{path}`.")
480            .with::<dyn BlockRoleAspect>(Arc::new(GraphicsImage))
481            .with::<dyn ApartFromText>(Arc::new(GraphicsImage))
482            .with_value(Arc::new(GraphicsImage)),
483    )
484}
485
486/// Returns the declarations of the two arguments of `\includegraphics`, in
487/// order: the optional argument [`OPTIONS_ARG`], which contains key-value
488/// pairs, and the mandatory argument [`PATH_ARG`], which contains the path as
489/// raw text up to the matching `}`.
490pub fn arguments() -> Vec<ArgDef> {
491    vec![
492        ArgDef::named(OPTIONS_ARG, ArgStdKind::KeyVals).docs(
493            "The options of the image, as key-value pairs, as in `alt=A plot, width=5cm`. The \
494             keys are `alt` for the alternative text, and `width` and `height` for the size.",
495        ),
496        ArgDef::named(PATH_ARG, ArgStdKind::Verbatim { delimiters: Some(('{', '}')) })
497            .docs(
498                "The path of the image file, as in `figures/plot.png`. The path is raw text up to \
499                 the matching `}`: the characters `%`, `#`, `\\`, `~` and nested braces are part \
500                 of the path.",
501            )
502            .role(PATH_ARG_ROLE),
503    ]
504}
505
506/// Returns a declaration of `\includegraphics` in text mode, owned by the
507/// feature `owner`, with the element value `spec`.
508fn command_def(owner: &FeatureName, spec: &Arc<ElementSpec>) -> ElementDef {
509    ElementDef::new(owner.clone(), [COMMAND], SyntaxDef::Macro { args: arguments() }, Arc::clone(spec))
510        .docs("Inserts the image whose file is at `path`.")
511}
512
513/// Returns the scoped package [`INCLUDEGRAPHICS_PACKAGE`], owned by the
514/// feature `owner`. The package contains a declaration of `\includegraphics`
515/// with the element value `spec`.
516fn includegraphics_package(owner: &FeatureName, spec: &Arc<ElementSpec>) -> ScopedPackageDef {
517    ScopedPackageDef {
518        owner: owner.clone(),
519        name: Name::from(INCLUDEGRAPHICS_PACKAGE),
520        elements: vec![command_def(owner, spec)],
521        docs: String::from(
522            "Provides `\\includegraphics[options]{path}` in the bodies that refer to this \
523             package, such as the bodies of the float types `figure` and `table`.",
524        ),
525    }
526}
527
528/// The `graphics` feature, which provides the command `\includegraphics` for
529/// images. See the [module documentation](self).
530///
531/// The feature registers the element of `\includegraphics` with its scoped
532/// package [`INCLUDEGRAPHICS_PACKAGE`], the three service slots for image
533/// files, the inspect stage, one publish stage for each backend, and the
534/// lowering rules of images. Construct the feature with [`Graphics::new`], or
535/// use [`feature`] for the default configuration.
536#[derive(Debug, Default, Clone, Copy)]
537pub struct Graphics {
538    config: GraphicsConfig,
539}
540
541impl Graphics {
542    /// Returns the feature constructed from the configuration `config`. The
543    /// configuration stays fixed in the registry that the feature is built
544    /// into.
545    pub fn new(config: GraphicsConfig) -> Graphics {
546        Graphics { config }
547    }
548
549    /// Returns the configuration this feature was constructed with.
550    pub fn config(&self) -> &GraphicsConfig {
551        &self.config
552    }
553}
554
555/// The backends for which the feature registers a publish stage: `text`,
556/// `html`, `latex-recomposed` and `latex-rendered`. Each of these backends
557/// also has a lowering rule for images: [`image_rule`] on `text`, `html` and
558/// `latex-rendered`, and [`latex::LATEX_RULE`] on `latex-recomposed`.
559const BACKENDS: [&str; 4] = [
560    text::BACKEND,
561    html::BACKEND,
562    crate::stdlib::backends::latex_recomposed::BACKEND,
563    crate::stdlib::backends::latex_rendered::BACKEND,
564];
565
566impl FlmFeature for Graphics {
567    fn info(&self) -> FeatureInfo {
568        FeatureInfo::new(FEATURE, "Graphics").docs(
569            "Images, inserted with `\\includegraphics[options]{path}`. By default, the command \
570             is available in the bodies of the float types that allow it, such as `figure` and \
571             `table`. With the configuration `global`, it can be written wherever text can be \
572             written. The program can provide services that find, inspect and convert image \
573             files. The render options select how each output refers to its images, for \
574             instance by the path of the file or with a copy of the file. On the plain-text, \
575             HTML and rendered LaTeX outputs, an image is lowered to `flm.pres.image`; on the \
576             recomposed LaTeX, it is written as the LaTeX hook `\\flmIncludeGraphics`.",
577        )
578    }
579
580    fn settings(&self) -> Option<SettingsDecl> {
581        Some(settings())
582    }
583
584    fn register(&self, b: &mut FeatureBuilder<'_>) -> Result<(), BuildError> {
585        let owner: FeatureName = b.feature().clone();
586        b.argument_role(PATH_ARG_ROLE, "The path of an image file.")?;
587        let spec = image_spec();
588        b.scoped_package(includegraphics_package(&owner, &spec))?;
589        b.element_type_text(
590            IMAGE_ELEMENT,
591            "An image, given by the path of an image file, with an optional alternative text and \
592             an optional size.",
593        )?;
594        if self.config.global {
595            // The same element, as an ordinary command: which declaration
596            // answers inside a body naming the package is immaterial.
597            b.element(command_def(&owner, &spec))?;
598        }
599        // Where the floats feature is absent, nobody declares the slot and
600        // the contribution is dropped with a Note.
601        b.peer_slot::<dyn FloatContentHandler>(CONTENT_SLOT, Arc::new(IncludeGraphicsContent))?;
602        b.service_slot::<dyn GraphicsResolver>(
603            RESOLVER_SLOT,
604            Arity::Single,
605            "the graphics resolver, which finds the file that the path of an image refers to and \
606             reads the content of this file",
607        )?;
608        b.service_slot::<dyn GraphicsInspector>(
609            INSPECTOR_SLOT,
610            Arity::Single,
611            "the inspector, which reports the type of an image file (vector or raster image), its \
612             size in pixels, its resolution and its physical size",
613        )?;
614        b.service_slot::<dyn GraphicsConverter>(
615            CONVERTERS_SLOT,
616            Arity::OrderedMany,
617            "the converters, which convert an image file from one format into another; for a \
618             conversion rule, the first converter in the order of contribution that can perform \
619             the rule is used",
620        )?;
621        inspect::register(b)?;
622        for backend in BACKENDS {
623            publish::register(b, backend)?;
624        }
625        for backend in [text::BACKEND, html::BACKEND, crate::stdlib::backends::latex_rendered::BACKEND] {
626            b.peer_backend(backend, "a backend on which the image rule is the default")?;
627            b.lowering_rule(image_rule(backend))?;
628        }
629        latex::register(b)?;
630        b.digest_input(&self.config.digest_bytes())?;
631        Ok(())
632    }
633}
634
635/// Returns the [`Graphics`] feature with the default configuration, ready to
636/// be listed in a package entry.
637///
638/// Use `Arc::new(Graphics::new(config))` to list the feature with a
639/// [`GraphicsConfig`] of your own.
640pub fn feature() -> Arc<dyn FlmFeature> {
641    Arc::new(Graphics::default())
642}
643
644#[cfg(test)]
645mod tests {
646    use super::*;
647
648    #[test]
649    fn the_command_takes_key_values_then_a_braced_verbatim_path() {
650        let args = arguments();
651        assert_eq!(args.len(), 2);
652        assert_eq!(args[0].name.as_deref(), Some(OPTIONS_ARG));
653        assert_eq!(args[0].kind.identity(), ArgDef::new(ArgStdKind::KeyVals).kind.identity());
654        assert_eq!(args[1].name.as_deref(), Some(PATH_ARG));
655        let braced = ArgDef::new(ArgStdKind::Verbatim { delimiters: Some(('{', '}')) });
656        assert_eq!(args[1].kind.identity(), braced.kind.identity());
657    }
658
659    #[test]
660    fn the_configuration_digests_its_one_switch() {
661        assert_eq!(GraphicsConfig::new().digest_bytes(), [0]);
662        assert_eq!(GraphicsConfig::new().global(true).digest_bytes(), [1]);
663    }
664}