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