Skip to main content

flm_core/stdlib/features/graphics/
publish.rs

1//! This module defines the publish stages of the `graphics` feature
2//! ([`PublishStage`]), along with the tables that these stages write and the
3//! error conditions that they report. A publish stage computes the address at
4//! which an output refers to each image.
5//!
6//! The *published address* of an image is the address that an output writes
7//! to refer to the image, for instance in the `src` attribute of an HTML
8//! `<img>` element. The `graphics` feature registers one publish stage for
9//! each of the backends `text`, `html`, `latex-recomposed` and
10//! `latex-rendered`, named `flm.graphics.publish.<backend>`
11//! ([`publish_stage_name`]). The stage writes a [`PublishedImage`] for each
12//! image into the *published table* of the backend,
13//! `flm.graphics.published.<backend>` ([`published_table`]), keyed by the
14//! address of the image's node. The lowering rule of images on this backend
15//! reads the published table. Since each backend has its own published table,
16//! the outputs of one document can refer to the same image in different ways.
17//!
18//! # Strategies
19//!
20//! The published address depends on the *strategy* that the render options
21//! set for the output ([`GraphicsRenderOptions::strategy`], [`Strategy`]). The
22//! render options select the strategy by the name of the output, which is the
23//! name of its backend. There are four strategies:
24//!
25//! - `reference` (the default): The address is the address of the file that
26//!   the graphics resolver returned ([`ImageFile::address`]), or the path as
27//!   written in the document if no graphics resolver found the file. The file
28//!   is not read.
29//! - `copy`: The stage reads the file, converts its content if a conversion
30//!   rule applies, and adds a copy of the file to the output. The address is
31//!   the path of the copy (see [copies of image
32//!   files](self#copies-of-image-files)). The plain-text output `text` cannot
33//!   use this strategy.
34//! - `data-uri`: The stage reads the file, converts its content if a
35//!   conversion rule applies, and writes the content into the address itself,
36//!   as in `data:image/png;base64,iVBORw0…`. Only the `html` output can use
37//!   this strategy.
38//! - `content`: The address is the same as under `reference`. The stage also
39//!   reads the file, converts its content if a conversion rule applies, and
40//!   writes the content into the *content table* of the backend,
41//!   `flm.graphics.content.<backend>` ([`content_table`]). This strategy is
42//!   meant for an output that renders images itself, for instance by drawing
43//!   each image with characters on a terminal. A stage of this output reads
44//!   the content table. Every output can use this strategy.
45//!
46//! The stage reads files through the graphics resolver ([`GraphicsResolver`]),
47//! a service that the program which embeds FLM can contribute. A path that
48//! begins with a scheme, such as `https://example.org/a.png`, is written
49//! unchanged under every strategy, and is never read ([`names_scheme`]).
50//!
51//! If the strategy `copy`, `data-uri` or `content` cannot be carried out for an
52//! image, an error is reported at the image. The output then refers to the
53//! image as under `reference`, and the content table contains no entry for the
54//! image. This happens in the following cases:
55//!
56//! - The output cannot use the strategy ([`CopyInOneFile`],
57//!   [`DataUriNotShown`]).
58//! - No graphics resolver is registered ([`NeedsResolver`]).
59//! - The graphics resolver fails to find or to read the file
60//!   ([`ResolveFailed`]).
61//! - The strategy is `copy`, and no artifact namer is registered
62//!   ([`NeedsNamer`]).
63//!
64//! # Conversion
65//!
66//! Under the strategies `copy`, `data-uri` and `content`, the stage applies the
67//! first conversion rule of the output whose `from` lists the format of the
68//! file ([`GraphicsRenderOptions::convert`]). The converter that performs the
69//! rule is selected by [`choose_converter`]. The copy, the `data:` address or
70//! the entry of the content table then has the format `to` of the rule. If the
71//! conversion cannot be carried out, an error is reported at the image
72//! ([`UnknownConverter`], [`NoConverterOffers`], [`ConversionFailed`]), and the
73//! stage uses the content of the file unconverted. See the module
74//! [`convert`](super::convert).
75//!
76//! # Copies of image files
77//!
78//! Under the strategy `copy`, the stage writes each copy as an artifact into
79//! the artifact table of the output, `flm.output.<backend>.artifacts`
80//! ([`OutputImages::artifacts`]). An *artifact* is one file of an output, held
81//! in memory ([`Artifact`]). The final stage of the output adds these
82//! artifacts to the artifact set of the output ([`ArtifactSet`]).
83//!
84//! The identity of a copy has the form `graphics:<stem>-<digest>`, as in
85//! `graphics:plot-3fa9c2d1`. The stem is the file name without its extension.
86//! The digest consists of eight hexadecimal digits, computed from the content
87//! of the file, the format of the copy and the options of the conversion rule.
88//! The identity therefore depends only on the file and on its conversion. An
89//! image file that appears several times in a document has a single copy.
90//!
91//! The address of a copy is the path, relative to the output, that the
92//! artifact namer ([`ArtifactNamer`]) returns for the identity and the file
93//! extension of the copy. The artifact namer is a service that the program
94//! which embeds FLM contributes to the service slot [`NAMER_SLOT`]. The file
95//! extension is the short name of the format of the copy, such as `png`
96//! ([`ImageFormat::name`]). A copy in a format that [`ImageFormat`] does not
97//! list has no file extension.
98//!
99//! # Synthesized values
100//!
101//! A publish stage runs once for each tree, including the trees of
102//! [synthesized values](crate::guide::concepts_overview#synthesized-values),
103//! such as the title of a section that a reference displays again. In a
104//! synthesized value, an image has the same published address as in the
105//! document. Under the strategy `content`, the image also has its own entry
106//! in the content table. Copies are written only by the runs over the trees of
107//! the document.
108//!
109//! The output does not contain a copy of an image that appears only in a
110//! synthesized value, and in no tree of the document. The output nevertheless
111//! refers to such an image by the address of its copy.
112//!
113//! # A publish stage of your own
114//!
115//! The program that embeds FLM can register a stage of its own that writes
116//! the published table of a backend, for instance to give each image
117//! alternative sources ([`PublishedImage::srcset`]). The stage declares that
118//! it writes [`published_table`] of the backend ([`StageDecl::writes`]). The
119//! standard publish stage of the backend writes the same table, so the plan
120//! of the build must prefer one of the two stages
121//! ([`Overrides::prefer`](crate::core::plan::Overrides::prefer),
122//! [`PlanRequest::prefer`](crate::core::plan::PlanRequest::prefer)). Without
123//! a preference, the plan cannot be built
124//! ([`PlanError::Contested`](crate::core::plan::PlanError::Contested)). The
125//! preferred stage runs, and the other one does not run on this backend.
126//!
127//! Declare the stage per tree ([`Scope::PerTree`]). For each image of its
128//! tree, the stage writes one entry, keyed by the address of the image's node
129//! ([`GraphicsPublished::insert`]). The stage can list the images with
130//! [`ElementIndex::values_of`](crate::stdlib::features::index::ElementIndex::values_of)
131//! for [`GraphicsImage`] in the table [`ELEMENT_INDEX`], and read the path of
132//! each image from its record in the table [`INFO`] ([`GraphicsRecord::path`]).
133//! The lowering of an image that has no entry in the table fails.
134//!
135//! When the standard publish stage of a backend does not run, the strategy
136//! and the conversion rules of the output have no effect on this backend.
137//! The content table of the backend and the copies of image files then exist
138//! only if your stage writes them ([`GraphicsContent::insert`],
139//! [`OutputImages::artifacts`]), and your stage declares that it writes them.
140//! A stage that writes copies writes them only from its runs over the trees
141//! of the document, whose identifier is not that of a synthesized value
142//! ([`TreeId::is_value`](crate::model::addr::TreeId::is_value)), as the
143//! standard publish stage does.
144
145use std::collections::BTreeMap;
146use std::hash::Hash;
147use std::sync::Arc;
148
149use base64::Engine as _;
150use techy::core::node::NodeRef;
151use techy::error::{Diagnostic, DiagnosticInfo};
152use techy::serialize::SerialValue;
153
154use crate::core::artifact::{Artifact, ArtifactId, ArtifactNamer, ArtifactRef, ArtifactSet, NamingScope, digest_name};
155use crate::core::data::store::StageOut;
156use crate::core::data::table::{ProjectCx, Table, TableHandle, TableName};
157use crate::core::plan::PlanCx;
158use crate::core::registry::{BuildError, FeatureBuilder};
159use crate::core::run::StageCx;
160use crate::core::stage::{Effect, Needs, Scope, Stage, StageDecl};
161use crate::lang::{Flm, FlmDiagnostic, FlmSpan};
162use crate::model::addr::NodeAddr;
163use crate::model::digest::Fnv1a64;
164use crate::model::names::StageName;
165use crate::progress::{self, Counted, Kind, Unit};
166use crate::stdlib::backends::lowering::NAMER_SLOT;
167use crate::stdlib::backends::pres::SrcsetCandidate;
168use crate::stdlib::backends::{html, latex_recomposed, latex_rendered};
169use crate::stdlib::features::index::ELEMENT_INDEX;
170
171use super::convert::{
172    CONVERTERS_SLOT, ConversionOptions, ConversionRequest, ConversionRule, GraphicsConverter,
173    NoConverter, choose_converter,
174};
175use super::inspect::{GraphicsInfo, GraphicsRecord, INFO, ResolveFailed, stage_failed};
176use super::resolve::{GraphicsResolver, ImageFile, ImageFormat, RESOLVER_SLOT, names_scheme, stem_of};
177use super::strategy::{GraphicsRenderOptions, Strategy};
178use super::{FEATURE, GraphicsImage, ImagePath, read_path};
179
180/// A `PublishedImage` contains the published address of one image, which the
181/// lowering rule of images on a backend writes to refer to the image. See the
182/// [module documentation](self).
183#[derive(Debug, Clone, Default, PartialEq, Eq)]
184pub struct PublishedImage {
185    /// The published address of the image, as the stage that writes the
186    /// published table chose it. The standard publish stage chooses it by the
187    /// strategy of the output.
188    pub src: String,
189    /// Alternative sources of the image, each with its descriptor, as in the
190    /// `srcset` attribute of an HTML `<img>` element. The standard publish
191    /// stage writes no alternative source; a [publish stage of your
192    /// own](self#a-publish-stage-of-your-own) can. The lowering rule of images
193    /// copies them into the `flm.pres.image` node, and the HTML output writes
194    /// them as the `srcset` attribute.
195    pub srcset: Vec<SrcsetCandidate>,
196}
197
198/// The value of the published table of a backend,
199/// `flm.graphics.published.<backend>` ([`published_table`]).
200///
201/// The table contains one [`PublishedImage`] for each image of the document,
202/// keyed by the address of the image's node. The standard publish stage of the
203/// backend writes the table, or a stage that the plan prefers in its place
204/// (see [a publish stage of your own](self#a-publish-stage-of-your-own)).
205#[derive(Debug, Clone, Default, PartialEq, Eq)]
206pub struct GraphicsPublished {
207    images: BTreeMap<NodeAddr, PublishedImage>,
208}
209
210impl GraphicsPublished {
211    /// Returns the published image at the node address `addr`, or `None` if
212    /// no image was published at this address.
213    pub fn get(&self, addr: NodeAddr) -> Option<&PublishedImage> {
214        self.images.get(&addr)
215    }
216
217    /// Returns every published image, in node-address order.
218    pub fn iter(&self) -> impl Iterator<Item = (NodeAddr, &PublishedImage)> + '_ {
219        self.images.iter().map(|(addr, image)| (*addr, image))
220    }
221
222    /// Returns the number of published images.
223    pub fn len(&self) -> usize {
224        self.images.len()
225    }
226
227    /// Returns whether no image was published.
228    pub fn is_empty(&self) -> bool {
229        self.images.is_empty()
230    }
231
232    /// Records `image` as the published image of the node at the address
233    /// `addr`. An image already recorded for `addr` is replaced, as
234    /// [`Table::absorb`] replaces it between the pieces of the table.
235    pub fn insert(&mut self, addr: NodeAddr, image: PublishedImage) {
236        self.images.insert(addr, image);
237    }
238}
239
240impl Table for GraphicsPublished {
241    fn absorb(&mut self, piece: GraphicsPublished) {
242        self.images.extend(piece.images);
243    }
244
245    /// Returns the list of published images, in the order of their node
246    /// addresses. Each entry is a map with the keys `node` and `src`, and also
247    /// `srcset` if the image has alternative sources.
248    fn project(&self, cx: &dyn ProjectCx) -> SerialValue {
249        SerialValue::List(
250            self.images
251                .iter()
252                .map(|(addr, image)| {
253                    let mut entries = vec![
254                        (String::from("node"), cx.node_ref(*addr)),
255                        (String::from("src"), SerialValue::Str(image.src.clone())),
256                    ];
257                    if !image.srcset.is_empty() {
258                        entries.push((
259                            String::from("srcset"),
260                            SerialValue::List(
261                                image
262                                    .srcset
263                                    .iter()
264                                    .map(|candidate| {
265                                        SerialValue::Str(format!(
266                                            "{} {}",
267                                            candidate.src, candidate.descriptor
268                                        ))
269                                    })
270                                    .collect(),
271                            ),
272                        ));
273                    }
274                    SerialValue::Map(entries)
275                })
276                .collect(),
277        )
278    }
279}
280
281/// Returns the handle of the published table of `backend`,
282/// `flm.graphics.published.<backend>`. The standard publish stage of the
283/// backend writes this table, or a stage that the plan prefers in its place
284/// ([a publish stage of your own](self#a-publish-stage-of-your-own)). The
285/// lowering rule of images on the backend reads it.
286pub fn published_table(backend: &str) -> TableHandle<GraphicsPublished> {
287    TableHandle::new(format!("flm.graphics.published.{backend}"))
288}
289
290/// An `ImageContent` contains the content of one image file, as the standard
291/// publish stage writes it into the content table under the strategy
292/// `content`, or a stage that the plan prefers in its place (see [a publish
293/// stage of your own](self#a-publish-stage-of-your-own)). An
294/// output that renders images itself reads this content. See the [module
295/// documentation](self).
296#[derive(Debug, Clone, Default, PartialEq, Eq)]
297pub struct ImageContent {
298    /// The published address of the image. As the standard publish stage
299    /// writes it, this is the same as under the strategy `reference`.
300    pub src: String,
301    /// The media type of the content, such as `image/png`. If a conversion
302    /// rule converted the content, this is the media type of the format `to`
303    /// of the rule.
304    pub media_type: String,
305    /// The content of the image file, or the result of its conversion.
306    pub content: Vec<u8>,
307}
308
309/// The value of the content table of a backend,
310/// `flm.graphics.content.<backend>` ([`content_table`]).
311///
312/// Under the strategy `content`, the standard publish stage writes one
313/// [`ImageContent`] into the table for each image whose file it read, keyed by
314/// the address of the image's node. Under the other strategies, the table is
315/// empty. A stage that the plan prefers in place of the standard one decides
316/// what the table contains (see [a publish stage of your
317/// own](self#a-publish-stage-of-your-own)).
318#[derive(Debug, Clone, Default, PartialEq, Eq)]
319pub struct GraphicsContent {
320    images: BTreeMap<NodeAddr, ImageContent>,
321}
322
323impl GraphicsContent {
324    /// Returns the content of the image at the node address `addr`, or `None`
325    /// if the table contains no entry for this address.
326    pub fn get(&self, addr: NodeAddr) -> Option<&ImageContent> {
327        self.images.get(&addr)
328    }
329
330    /// Returns the content of every image with its node address, in the order
331    /// of the node addresses.
332    pub fn iter(&self) -> impl Iterator<Item = (NodeAddr, &ImageContent)> + '_ {
333        self.images.iter().map(|(addr, image)| (*addr, image))
334    }
335
336    /// Returns the number of entries in the table.
337    pub fn len(&self) -> usize {
338        self.images.len()
339    }
340
341    /// Returns whether the table contains no entry.
342    pub fn is_empty(&self) -> bool {
343        self.images.is_empty()
344    }
345
346    /// Records `image` as the content of the image of the node at the address
347    /// `addr`. An entry already recorded for `addr` is replaced, as
348    /// [`Table::absorb`] replaces it between the pieces of the table.
349    pub fn insert(&mut self, addr: NodeAddr, image: ImageContent) {
350        self.images.insert(addr, image);
351    }
352}
353
354impl Table for GraphicsContent {
355    fn absorb(&mut self, piece: GraphicsContent) {
356        self.images.extend(piece.images);
357    }
358
359    /// Returns the list of entries, in the order of their node addresses. Each
360    /// entry is a map with the keys `node`, `src`, `media_type` and `content`.
361    ///
362    /// The value of `content` is `{ text }` if the bytes are valid UTF-8 text,
363    /// and `{ base64 }` otherwise, with the bytes encoded in base64 (standard
364    /// alphabet, with padding). An extension receives the content of an
365    /// artifact in the same form.
366    fn project(&self, cx: &dyn ProjectCx) -> SerialValue {
367        SerialValue::List(
368            self.images
369                .iter()
370                .map(|(addr, image)| {
371                    SerialValue::Map(vec![
372                        (String::from("node"), cx.node_ref(*addr)),
373                        (String::from("src"), SerialValue::Str(image.src.clone())),
374                        (String::from("media_type"), SerialValue::Str(image.media_type.clone())),
375                        (String::from("content"), content_value(&image.content)),
376                    ])
377                })
378                .collect(),
379        )
380    }
381}
382
383/// Returns `bytes` as `{ text }` if they are valid UTF-8 text, and as
384/// `{ base64 }` otherwise.
385fn content_value(bytes: &[u8]) -> SerialValue {
386    let entry = match std::str::from_utf8(bytes) {
387        Ok(text) => (String::from("text"), SerialValue::Str(text.to_string())),
388        Err(_) => {
389            (String::from("base64"), SerialValue::Str(base64::engine::general_purpose::STANDARD.encode(bytes)))
390        }
391    };
392    SerialValue::Map(vec![entry])
393}
394
395/// Returns the handle of the content table of `backend`,
396/// `flm.graphics.content.<backend>`. Under the strategy `content`, the standard
397/// publish stage of the backend writes the content of each image file into
398/// this table; a stage that the plan prefers in its place writes the table
399/// only if it declares so ([a publish stage of your
400/// own](self#a-publish-stage-of-your-own)). A stage of an output that renders images itself reads the table.
401pub fn content_table(backend: &str) -> TableHandle<GraphicsContent> {
402    TableHandle::new(format!("flm.graphics.content.{backend}"))
403}
404
405/// Returns the name of the publish stage of `backend`,
406/// `flm.graphics.publish.<backend>`.
407pub fn publish_stage_name(backend: &str) -> StageName {
408    StageName::from(format!("flm.graphics.publish.{backend}"))
409}
410
411/// The kind of the row, `flm.graphics.images`, that a call of a publish stage
412/// declares on the progress sheet of the build for the images of its tree
413/// that it converts ([`crate::progress`]).
414///
415/// The row is counted in items: its total is the number of images of the tree
416/// to which a conversion rule applies, as far as the records of the inspect
417/// stage tell, and it advances as each of them is published. It is labeled
418/// with the name of the tree's source file, where the tree has one. A call
419/// that converts no image declares no row; an image that is only copied is
420/// not counted. The row has no title: a display shows the conversions under
421/// it ([`CONVERT_KIND`]).
422pub const IMAGES_KIND: Kind = Kind::new("flm.graphics.images");
423
424/// The kind of the row, `flm.graphics.convert`, with the title "Converting
425/// graphics", that a publish stage declares on the progress sheet of the
426/// build for each conversion of an image, under its row [`IMAGES_KIND`]
427/// ([`crate::progress`]).
428///
429/// The row is labeled with the path of the image as written in the
430/// document. It runs while the converter converts, and the converter receives
431/// its scope ([`GraphicsConverter::convert`]). It ends as finished when the
432/// converter returns the converted content, and as failed when the converter
433/// fails.
434pub const CONVERT_KIND: Kind = Kind::titled("flm.graphics.convert", "Converting graphics");
435
436/// An `OutputImages` describes whether the output of one backend can contain
437/// copies of image files, and whether it can use `data:` addresses. This
438/// determines whether the output can use the strategies `copy` and
439/// `data-uri`. [`output_images`] returns this value for a backend.
440#[derive(Debug, Clone, Copy)]
441pub struct OutputImages {
442    /// The artifact table of the output, `flm.output.<backend>.artifacts`,
443    /// into which the publish stage writes the copies of image files under
444    /// the strategy `copy`. `None` if the output consists of a single file,
445    /// such as the plain-text output; such an output cannot use the strategy
446    /// `copy`.
447    pub artifacts: Option<TableName<ArtifactSet>>,
448    /// Whether the output can refer to an image by an address that begins
449    /// with `data:`, as the strategy `data-uri` writes it. An HTML page can,
450    /// as in `<img src="data:…">`.
451    pub data_address: bool,
452}
453
454/// Returns whether the output of `backend` can contain copies of image files
455/// and use `data:` addresses ([`OutputImages`]).
456///
457/// - The `html` output can contain copies and use `data:` addresses.
458/// - The `latex-recomposed` and `latex-rendered` outputs can contain copies.
459/// - The `text` output, and the output of every other backend, can do
460///   neither.
461pub fn output_images(backend: &str) -> OutputImages {
462    match backend {
463        html::BACKEND => OutputImages { artifacts: Some(html::ARTIFACTS), data_address: true },
464        latex_recomposed::BACKEND => {
465            OutputImages { artifacts: Some(latex_recomposed::ARTIFACTS), data_address: false }
466        }
467        latex_rendered::BACKEND => {
468            OutputImages { artifacts: Some(latex_rendered::ARTIFACTS), data_address: false }
469        }
470        _ => OutputImages { artifacts: None, data_address: false },
471    }
472}
473
474/// The error that is reported when the strategy of an output requires reading
475/// an image file, and no graphics resolver is registered (id
476/// `flm.graphics.needs-resolver`).
477///
478/// The strategies `copy`, `data-uri` and `content` read the content of each
479/// image file through the graphics resolver ([`GraphicsResolver`]). The program
480/// that embeds FLM can contribute a graphics resolver to the service slot
481/// [`RESOLVER_SLOT`].
482///
483/// Reported by the publish stage of the output ([`PublishStage`]) for each
484/// image. The output then refers to the image by its path as written in the
485/// document. Under the strategy `content`, the content table contains no entry
486/// for the image.
487#[derive(Debug, Clone, PartialEq, Eq, DiagnosticInfo)]
488#[diagnostic(
489    id = "flm.graphics.needs-resolver",
490    message = "Unsupported strategy ‘{strategy}’ for output ‘{output}’ (image file ‘{path}’): \
491               reading image files is not available"
492)]
493pub struct NeedsResolver {
494    /// The name of the output, which is the name of its backend.
495    pub output: String,
496    /// The path of the image file, as written in the document.
497    pub path: String,
498    /// The name of the strategy: `copy`, `data-uri` or `content`.
499    pub strategy: String,
500}
501
502/// The error that is reported when the strategy of an output is `copy`, and no
503/// artifact namer is registered (id `flm.graphics.needs-namer`).
504///
505/// The address of a copy of an image file is the path that the artifact namer
506/// ([`ArtifactNamer`]) returns for the copy. The program that embeds FLM can
507/// contribute an artifact namer to the service slot [`NAMER_SLOT`].
508///
509/// Reported by the publish stage of the output ([`PublishStage`]) for each
510/// image whose file the graphics resolver found. The output then refers to the
511/// image by the address of the file that the graphics resolver returned, and
512/// contains no copy of the file.
513#[derive(Debug, Clone, PartialEq, Eq, DiagnosticInfo)]
514#[diagnostic(
515    id = "flm.graphics.needs-namer",
516    message = "Unsupported strategy ‘copy’ for output ‘{output}’ (image file ‘{path}’): \
517               choosing file names for copies is not available"
518)]
519pub struct NeedsNamer {
520    /// The name of the output, which is the name of its backend.
521    pub output: String,
522    /// The path of the image file, as written in the document.
523    pub path: String,
524}
525
526/// The error that is reported when the strategy `copy` is set for an output
527/// that consists of a single file (id `flm.graphics.copy-in-one-file`).
528///
529/// The strategy `copy` adds a copy of each image file to the output. It
530/// requires an output that can contain several files, such as the `html`
531/// output. The plain-text output `text` consists of a single file
532/// ([`OutputImages::artifacts`]).
533///
534/// Reported by the publish stage of the output ([`PublishStage`]) for each
535/// image. The output then refers to the image as under the strategy
536/// `reference`: by the address of the file that the graphics resolver
537/// returned, or by its path as written in the document if no graphics resolver
538/// found the file.
539#[derive(Debug, Clone, PartialEq, Eq, DiagnosticInfo)]
540#[diagnostic(
541    id = "flm.graphics.copy-in-one-file",
542    message = "Unsupported strategy ‘copy’ for output ‘{output}’ (image file ‘{path}’): \
543               this output is a single file"
544)]
545pub struct CopyInOneFile {
546    /// The name of the output, which is the name of its backend.
547    pub output: String,
548    /// The path of the image file, as written in the document.
549    pub path: String,
550}
551
552/// The error that is reported when the strategy `data-uri` is set for an
553/// output that cannot use `data:` addresses (id
554/// `flm.graphics.data-uri-not-shown`).
555///
556/// The strategy `data-uri` writes the content of each image file into the
557/// address of the image, as in `<img src="data:image/png;base64,iVBORw0…">`.
558/// Only the `html` output can use such addresses
559/// ([`OutputImages::data_address`]).
560///
561/// Reported by the publish stage of the output ([`PublishStage`]) for each
562/// image. The output then refers to the image as under the strategy
563/// `reference`: by the address of the file that the graphics resolver
564/// returned, or by its path as written in the document if no graphics resolver
565/// found the file.
566#[derive(Debug, Clone, PartialEq, Eq, DiagnosticInfo)]
567#[diagnostic(
568    id = "flm.graphics.data-uri-not-shown",
569    message = "Unsupported strategy ‘data-uri’ for output ‘{output}’ (image file ‘{path}’): \
570               this output cannot use ‘data:’ addresses"
571)]
572pub struct DataUriNotShown {
573    /// The name of the output, which is the name of its backend.
574    pub output: String,
575    /// The path of the image file, as written in the document.
576    pub path: String,
577}
578
579/// The error that is reported when the conversion rule that applies to an
580/// image lists a converter that is not registered (id
581/// `flm.graphics.unknown-converter`).
582///
583/// The `via` of a conversion rule lists the names of the converters that may
584/// perform the rule ([`ConversionRule::via`]), as in `via: [raster]`. Each of
585/// these names must be the name of a converter registered in the service slot
586/// [`CONVERTERS_SLOT`] ([`GraphicsConverter::name`]).
587///
588/// Reported by the publish stage of the output ([`PublishStage`]) for each
589/// image to which the rule applies. The image is then published with the
590/// unconverted content of its file, as if no conversion rule applied.
591#[derive(Debug, Clone, PartialEq, Eq, DiagnosticInfo)]
592#[diagnostic(
593    id = "flm.graphics.unknown-converter",
594    message = "Unknown converter ‘{converter}’ in ‘via’ of the conversion rule from ‘{from}’ \
595               to ‘{to}’ for output ‘{output}’"
596)]
597pub struct UnknownConverter {
598    /// The name of the output, which is the name of its backend.
599    pub output: String,
600    /// The short name of the format of the image file, such as `pdf`.
601    pub from: String,
602    /// The short name of the format `to` of the conversion rule, such as
603    /// `png`.
604    pub to: String,
605    /// The name of the converter, as listed in the `via` of the rule.
606    pub converter: String,
607}
608
609/// The error that is reported when none of the converters allowed by a
610/// conversion rule can convert an image file into the format `to` of the rule
611/// (id `flm.graphics.no-converter`).
612///
613/// The converters allowed by a conversion rule are the converters that its
614/// `via` lists, or every registered converter if `via` is empty. One of these
615/// converters must offer the conversion from the format of the image file into
616/// the format `to` of the rule ([`GraphicsConverter::offers`]). The publish
617/// stage does not chain conversions: a single converter must perform the whole
618/// conversion.
619///
620/// Reported by the publish stage of the output ([`PublishStage`]) for each
621/// image to which the rule applies. The image is then published with the
622/// unconverted content of its file, as if no conversion rule applied.
623#[derive(Debug, Clone, PartialEq, Eq, DiagnosticInfo)]
624#[diagnostic(
625    id = "flm.graphics.no-converter",
626    message = "No converter available to convert image file ‘{path}’ from ‘{from}’ to ‘{to}’ \
627               (conversion rule for output ‘{output}’)"
628)]
629pub struct NoConverterOffers {
630    /// The name of the output, which is the name of its backend.
631    pub output: String,
632    /// The path of the image file, as written in the document.
633    pub path: String,
634    /// The short name of the format of the image file, such as `pdf`.
635    pub from: String,
636    /// The short name of the format `to` of the conversion rule, such as
637    /// `png`.
638    pub to: String,
639}
640
641/// The error that is reported when a converter fails to convert an image file
642/// (id `flm.graphics.conversion-failed`).
643///
644/// The message contains the reason that the converter returned
645/// ([`GraphicsConvertError`](super::GraphicsConvertError)). Reported by the
646/// publish stage of the output ([`PublishStage`]). The image is then published
647/// with the unconverted content of its file, as if no conversion rule applied.
648#[derive(Debug, Clone, PartialEq, Eq, DiagnosticInfo)]
649#[diagnostic(
650    id = "flm.graphics.conversion-failed",
651    message = "Failed to convert image file ‘{path}’ from ‘{from}’ to ‘{to}’ with converter \
652               ‘{converter}’: {detail}"
653)]
654pub struct ConversionFailed {
655    /// The path of the image file, as written in the document.
656    pub path: String,
657    /// The short name of the format of the image file, such as `pdf`.
658    pub from: String,
659    /// The short name of the format `to` of the conversion rule, such as
660    /// `png`.
661    pub to: String,
662    /// The name of the converter ([`GraphicsConverter::name`]).
663    pub converter: String,
664    /// The reason that the converter returned
665    /// ([`GraphicsConvertError::detail`](super::GraphicsConvertError::detail)).
666    pub detail: String,
667}
668
669/// The settings and services that a publish stage reads once for each run,
670/// and uses for every image of the tree.
671struct Publishing<'r> {
672    /// The name of the output, which is the name of the backend.
673    output: &'r str,
674    strategy: Strategy,
675    rules: &'r [ConversionRule],
676    resolver: Option<&'r dyn GraphicsResolver>,
677    converters: Vec<&'r dyn GraphicsConverter>,
678    namer: Option<&'r dyn ArtifactNamer>,
679    /// The outputs of the command, which the artifact namer receives with
680    /// each copy.
681    scope: &'r NamingScope,
682    /// Whether the output can contain copies and use `data:` addresses.
683    holds: OutputImages,
684}
685
686/// The content with which an image is published: the content of the file, or
687/// the result of its conversion.
688struct Content {
689    bytes: Vec<u8>,
690    media_type: String,
691    /// The options of the conversion rule that converted the content, or
692    /// `None` if the content is unconverted.
693    options: Option<ConversionOptions>,
694}
695
696/// The result of publishing one image: the published address, and the copy or
697/// the content that the strategy produces.
698struct Publication {
699    /// The published address.
700    src: String,
701    /// The copy of the image file, under the strategy `copy`.
702    copy: Option<Artifact>,
703    /// The content to write into the content table, under the strategy
704    /// `content`.
705    content: Option<Content>,
706}
707
708impl Publication {
709    /// Returns the publication of an image at the address `src`, with no copy
710    /// and no content.
711    fn at(src: String) -> Publication {
712        Publication { src, copy: None, content: None }
713    }
714}
715
716/// Why the stage does not read the file of an image, which is then published
717/// at its reference.
718enum Unread {
719    /// Nothing to report: the path names a scheme, the strategy needs no
720    /// content, or the graphics resolver did not find the file, which was
721    /// reported where the record was made.
722    Quietly,
723    /// The strategy is `copy`, and the output is a single file.
724    CopyInOneFile,
725    /// The strategy is `data-uri`, and the output cannot show such an address.
726    DataUriNotShown,
727    /// No graphics resolver is registered.
728    NeedsResolver,
729    /// The strategy is `copy`, and no artifact namer is registered.
730    NeedsNamer,
731}
732
733impl<'r> Publishing<'r> {
734    /// Returns the graphics resolver and the file through which the stage
735    /// reads the content of an image, or why it does not read it. `path` is
736    /// the path of the image as written in the document, and `file` the file
737    /// that the graphics resolver found for it.
738    fn readable<'f>(
739        &self,
740        path: &str,
741        file: Option<&'f ImageFile>,
742    ) -> Result<(&'r dyn GraphicsResolver, &'f ImageFile), Unread> {
743        if names_scheme(path) || !self.strategy.needs_content() {
744            return Err(Unread::Quietly);
745        }
746        match self.strategy {
747            Strategy::Copy if self.holds.artifacts.is_none() => return Err(Unread::CopyInOneFile),
748            Strategy::DataUri if !self.holds.data_address => return Err(Unread::DataUriNotShown),
749            _ => {}
750        }
751        let resolver = self.resolver.ok_or(Unread::NeedsResolver)?;
752        let file = file.ok_or(Unread::Quietly)?;
753        if self.strategy == Strategy::Copy && self.namer.is_none() {
754            return Err(Unread::NeedsNamer);
755        }
756        Ok((resolver, file))
757    }
758
759    /// Pushes to `diags` the error, if any, that says why the stage does not
760    /// read the file of the image at `path`, written at `span`.
761    fn report_unread(&self, unread: Unread, path: &str, span: &FlmSpan, diags: &mut Vec<FlmDiagnostic>) {
762        if matches!(unread, Unread::Quietly) {
763            return;
764        }
765        let (output, path, span) = (self.output.to_string(), path.to_string(), span.clone());
766        match unread {
767            Unread::Quietly => {}
768            Unread::CopyInOneFile => diags.push(Diagnostic::error(CopyInOneFile { output, path }, span)),
769            Unread::DataUriNotShown => diags.push(Diagnostic::error(DataUriNotShown { output, path }, span)),
770            Unread::NeedsResolver => {
771                let strategy = self.strategy.name().to_string();
772                diags.push(Diagnostic::error(NeedsResolver { output, path, strategy }, span));
773            }
774            Unread::NeedsNamer => diags.push(Diagnostic::error(NeedsNamer { output, path }, span)),
775        }
776    }
777
778    /// Returns the format of `file` and the first conversion rule of the
779    /// output that applies to it, or `None` if the format is not known or no
780    /// rule applies.
781    fn rule_for(&self, file: &ImageFile) -> Option<(ImageFormat, &'r ConversionRule)> {
782        let from = file.format()?;
783        self.rules.iter().find(|rule| rule.applies_to(from)).map(|rule| (from, rule))
784    }
785
786    /// Returns whether a conversion rule applies to the image at `path`, whose
787    /// record in the table [`INFO`] is `record`: whether the stage reads its
788    /// file and a rule applies to the file's format. Reads no file.
789    fn converts(&self, path: &str, record: Option<&GraphicsRecord>) -> bool {
790        let file = record.and_then(|record| record.file.as_ref());
791        self.readable(path, file).is_ok_and(|(_, file)| self.rule_for(file).is_some())
792    }
793
794    /// Publishes the image `node` under the strategy of the output, and
795    /// returns the result. `path` is the path of the image as written in the
796    /// document, and `record` is the record of the image in the table
797    /// [`INFO`]. A conversion is reported on the progress sheet as a row under
798    /// `images`. Pushes the errors to `diags`.
799    fn publish(
800        &self,
801        node: &NodeRef<'_, Flm>,
802        path: &str,
803        record: Option<&GraphicsRecord>,
804        images: &Counted,
805        diags: &mut Vec<FlmDiagnostic>,
806    ) -> Publication {
807        let file = record.and_then(|record| record.file.as_ref());
808        let reference = file.map_or_else(|| path.to_string(), |file| file.address.clone());
809        let (resolver, file) = match self.readable(path, file) {
810            Ok(readable) => readable,
811            Err(unread) => {
812                self.report_unread(unread, path, node.span(), diags);
813                return Publication::at(reference);
814            }
815        };
816        let original = match resolver.read(file) {
817            Ok(bytes) => bytes,
818            Err(failed) => {
819                let failed = ResolveFailed { path: path.to_string(), detail: failed.detail };
820                diags.push(Diagnostic::error(failed, node.span().clone()));
821                return Publication::at(reference);
822            }
823        };
824        let content = self.convert(node, path, file, &original, images, diags);
825        match self.strategy {
826            Strategy::Reference => Publication::at(reference),
827            Strategy::Content => Publication { src: reference, copy: None, content: Some(content) },
828            Strategy::DataUri => {
829                let encoded = base64::engine::general_purpose::STANDARD.encode(&content.bytes);
830                Publication::at(format!("data:{};base64,{encoded}", content.media_type))
831            }
832            Strategy::Copy => {
833                let Some(namer) = self.namer else { return Publication::at(reference) };
834                let id = ArtifactId::new(FEATURE, copy_name(path, &original, &content));
835                let extension = ImageFormat::from_media_type(&content.media_type).map(ImageFormat::name);
836                let artifact = ArtifactRef {
837                    id: &id,
838                    entry: false,
839                    media_type: &content.media_type,
840                    extension,
841                    output: None,
842                    folder: false,
843                };
844                let address = namer.url_of(&artifact, self.scope);
845                let mut copy = Artifact::bytes(id, content.media_type, content.bytes);
846                copy.extension = extension.map(String::from);
847                Publication { src: address.as_str().to_string(), copy: Some(copy), content: None }
848            }
849        }
850    }
851
852    /// Returns the content `original` of `file`, converted by the first
853    /// conversion rule of the output that applies to the format of the file.
854    ///
855    /// Returns the content unconverted if no rule applies, or if the
856    /// conversion cannot be carried out. In the second case, pushes the error
857    /// to `diags`. The conversion is a row of the kind [`CONVERT_KIND`] under
858    /// `images`, whose scope the converter receives.
859    fn convert(
860        &self,
861        node: &NodeRef<'_, Flm>,
862        path: &str,
863        file: &ImageFile,
864        original: &[u8],
865        images: &Counted,
866        diags: &mut Vec<FlmDiagnostic>,
867    ) -> Content {
868        let unconverted = || Content {
869            bytes: original.to_vec(),
870            media_type: file.media_type.clone(),
871            options: None,
872        };
873        let Some((from, rule)) = self.rule_for(file) else { return unconverted() };
874        let span = node.span().clone();
875        let (from_name, to_name) = (from.name().to_string(), rule.to.name().to_string());
876        let converter = match choose_converter(rule, from, &self.converters) {
877            Ok(converter) => converter,
878            Err(NoConverter::Unknown(converter)) => {
879                let output = self.output.to_string();
880                let unknown = UnknownConverter { output, from: from_name, to: to_name, converter };
881                diags.push(Diagnostic::error(unknown, span));
882                return unconverted();
883            }
884            Err(NoConverter::NoneOffers) => {
885                let none = NoConverterOffers {
886                    output: self.output.to_string(),
887                    path: path.to_string(),
888                    from: from_name,
889                    to: to_name,
890                };
891                diags.push(Diagnostic::error(none, span));
892                return unconverted();
893            }
894        };
895        let request = ConversionRequest::new(original, from, rule.to, &rule.options);
896        // A conversion that fails ends its row as failed, when the row is
897        // dropped.
898        let row = images.scope().child(&CONVERT_KIND, Some(path)).start();
899        match converter.convert(&request, &row.scope()) {
900            Ok(bytes) => {
901                row.finish();
902                Content { bytes, media_type: rule.to.media_type().to_string(), options: Some(rule.options) }
903            }
904            Err(failed) => {
905                let failed = ConversionFailed {
906                    path: path.to_string(),
907                    from: from_name,
908                    to: to_name,
909                    converter: converter.name().to_string(),
910                    detail: failed.detail,
911                };
912                diags.push(Diagnostic::error(failed, span));
913                unconverted()
914            }
915        }
916    }
917}
918
919/// Returns the name of the copy of an image file. `path` is the path of the
920/// file as written in the document, `original` is the content of the file,
921/// and `content` is the content of the copy.
922///
923/// The name consists of the stem of the file and eight hexadecimal digits of a
924/// digest. The digest is computed from `original`, the media type of
925/// `content` and the options of the conversion rule that produced `content`.
926/// See the [module documentation](self#copies-of-image-files).
927fn copy_name(path: &str, original: &[u8], content: &Content) -> String {
928    // The name is computed from the file and its conversion alone, with no
929    // counter, so that a file shown twice, in one tree or two, on one thread or
930    // several, is one copy.
931    let mut digest = Fnv1a64::new();
932    digest.write_bytes(original);
933    digest.write_str(&content.media_type);
934    content.options.hash(&mut digest);
935    digest_name(&stem_of(path), &digest)
936}
937
938/// The publish stage of one backend, named `flm.graphics.publish.<backend>`.
939/// See the [module documentation](self).
940///
941/// For each image of a tree, the stage computes the published address under
942/// the strategy that the render options set for the output of the backend
943/// ([`GraphicsRenderOptions`]). The stage writes the published addresses into
944/// the published table of the backend ([`published_table`]). Under the
945/// strategy `content`, it also writes the content of each image file into the
946/// content table of the backend ([`content_table`]). Under the strategy
947/// `copy`, it writes the copies of the image files into the artifact table of
948/// the output ([`OutputImages::artifacts`]). The stage reads the records that
949/// the inspect stage writes into the table [`INFO`].
950///
951/// On the progress sheet of the build, a call that converts images declares a
952/// row of the kind [`IMAGES_KIND`], and under it a row of the kind
953/// [`CONVERT_KIND`] for each conversion. Between two conversions, the call
954/// asks whether the build was cancelled, and returns when it was.
955///
956/// The `graphics` feature registers a publish stage for each of the backends
957/// `text`, `html`, `latex-recomposed` and `latex-rendered`. To use the
958/// lowering rule [`image_rule`](super::image_rule) on a backend of your own,
959/// register a publish stage for this backend with [`PublishStage::new`].
960/// Also declare the published table of the backend (a [`GraphicsPublished`])
961/// and its content table (a [`GraphicsContent`]), for instance with
962/// [`FeatureBuilder::table_named`]. The output of such a backend cannot
963/// contain copies or use `data:` addresses ([`output_images`]), so it can use
964/// only the strategies `reference` and `content`.
965///
966/// A stage of your own can write the published table in place of this stage
967/// (see [a publish stage of your own](self#a-publish-stage-of-your-own)).
968#[derive(Debug, Clone)]
969pub struct PublishStage {
970    backend: String,
971}
972
973impl PublishStage {
974    /// Returns the publish stage of `backend`.
975    pub fn new(backend: impl Into<String>) -> PublishStage {
976        PublishStage { backend: backend.into() }
977    }
978}
979
980impl Stage for PublishStage {
981    fn decl(&self) -> StageDecl {
982        let decl = StageDecl::new(publish_stage_name(&self.backend), Effect::Compute, Scope::PerTree)
983            .writes(published_table(&self.backend))
984            .writes(content_table(&self.backend));
985        let decl = match output_images(&self.backend).artifacts {
986            Some(table) => decl.writes(table),
987            None => decl,
988        };
989        let backend = &self.backend;
990        let copies = match output_images(backend).artifacts {
991            Some(table) => format!(
992                " Under the strategy `copy`, writes the copies of the image files into `{}`.",
993                table.name()
994            ),
995            None => String::new(),
996        };
997        decl.docs(format!(
998            "Writes the address at which the `{backend}` output refers to each image into \
999             `flm.graphics.published.{backend}`, according to the strategy set for this output. \
1000             Under the strategy `content`, writes the content of each image file into \
1001             `flm.graphics.content.{backend}`.{copies} Reports an error for each image whose \
1002             strategy or conversion cannot be carried out."
1003        ))
1004    }
1005
1006    fn needs(&self, _cx: &PlanCx<'_>) -> Needs {
1007        Needs::new().reads(ELEMENT_INDEX).reads(INFO).option::<GraphicsRenderOptions>()
1008    }
1009
1010    fn run(&self, cx: &StageCx<'_>, out: &mut StageOut<'_>) {
1011        let (Some(id), Some(tree)) = (cx.tree_id(), cx.my_tree()) else { return };
1012        let stage = publish_stage_name(&self.backend);
1013        let index = match cx.get(ELEMENT_INDEX) {
1014            Ok(Some(index)) => index,
1015            Ok(None) => return,
1016            Err(error) => return stage_failed(out, stage.as_str(), error),
1017        };
1018        let info: Option<&GraphicsInfo> = match cx.get(INFO) {
1019            Ok(info) => info,
1020            Err(error) => return stage_failed(out, stage.as_str(), error),
1021        };
1022        let options = match cx.option::<GraphicsRenderOptions>() {
1023            Ok(options) => options,
1024            Err(error) => return stage_failed(out, stage.as_str(), error),
1025        };
1026        let services = cx.registry().services();
1027        let scope = NamingScope::of(cx.registry(), cx.plan().demands());
1028        let publishing = Publishing {
1029            output: &self.backend,
1030            strategy: options.strategy_for(&self.backend),
1031            rules: options.rules_for(&self.backend),
1032            resolver: services.service_named::<dyn GraphicsResolver>(RESOLVER_SLOT),
1033            converters: services.services_by_precedence_named::<dyn GraphicsConverter>(CONVERTERS_SLOT).collect(),
1034            namer: services.service_named::<dyn ArtifactNamer>(NAMER_SLOT),
1035            scope: &scope,
1036            holds: output_images(&self.backend),
1037        };
1038        // As the inspect stage: a path whose characters are not known here is
1039        // the rules' to handle.
1040        let images: Vec<_> = index
1041            .values_of::<GraphicsImage>(id, &tree)
1042            .filter_map(|(addr, node, _)| match read_path(&node) {
1043                Ok(ImagePath::Read(path)) => {
1044                    let record = info.and_then(|info| info.get(addr));
1045                    let converts = publishing.converts(&path, record);
1046                    Some((addr, node, path, record, converts))
1047                }
1048                _ => None,
1049            })
1050            .collect();
1051        let total = images.iter().filter(|(.., converts)| *converts).count() as u64;
1052        // A call with nothing to convert declares no row.
1053        let no_row = progress::Scope::none();
1054        let parent = if total == 0 { &no_row } else { cx.progress() };
1055        let label = cx.fragment(id).and_then(|fragment| fragment.source().origin().canonical_path());
1056        let converting = parent.child(&IMAGES_KIND, label).start_counted(Unit::Items, total);
1057        let mut published = GraphicsPublished::default();
1058        let mut contents = GraphicsContent::default();
1059        let mut copies = ArtifactSet::new();
1060        let mut diags = Vec::new();
1061        let mut first = true;
1062        for (addr, node, path, record, converts) in images {
1063            if converts {
1064                // What a cancelled step produced is discarded whole.
1065                if !first && cx.progress().cancelled() {
1066                    return;
1067                }
1068                first = false;
1069            }
1070            let Publication { src, copy, content } =
1071                publishing.publish(&node, &path, record, &converting, &mut diags);
1072            if converts {
1073                converting.advance(1);
1074            }
1075            if let Some(content) = content {
1076                let image = ImageContent { src: src.clone(), media_type: content.media_type, content: content.bytes };
1077                contents.insert(addr, image);
1078            }
1079            if let Some(copy) = copy {
1080                // A set is refused only a second entry, and a copy is no
1081                // entry; two copies under one identity are combined by
1082                // `absorb`, which keeps the first.
1083                let mut one = ArtifactSet::new();
1084                one.insert(copy)
1085                    .expect("a new artifact set accepts one artifact that is not an entry artifact");
1086                copies.absorb(one);
1087            }
1088            published.insert(addr, PublishedImage { src, srcset: Vec::new() });
1089        }
1090        converting.finish();
1091        for diagnostic in diags {
1092            out.diags.push(diagnostic);
1093        }
1094        match out.table(&published_table(&self.backend)) {
1095            Ok(table) => *table = published,
1096            Err(error) => return stage_failed(out, stage.as_str(), error),
1097        }
1098        // A row is no file of the output: a value's rows are written as a
1099        // tree's are.
1100        match out.table(&content_table(&self.backend)) {
1101            Ok(table) => *table = contents,
1102            Err(error) => return stage_failed(out, stage.as_str(), error),
1103        }
1104        // A value states no fact about the document: its images' copies are
1105        // the document's own trees'.
1106        if let (Some(table), false) = (publishing.holds.artifacts, id.is_value()) {
1107            match out.table(table) {
1108                Ok(written) => *written = copies,
1109                Err(error) => stage_failed(out, stage.as_str(), error),
1110            }
1111        }
1112    }
1113}
1114
1115/// Declares the published table, the content table and the publish stage of
1116/// `backend`.
1117///
1118/// The backend is declared as a peer, so that a registry without the backend
1119/// still builds. If the output of the backend can contain copies, the artifact
1120/// table of the output is also declared as a peer table, since the backend
1121/// declares this table. In a registry without the backend, this peer table is
1122/// unresolved, and the publish stage, which writes the table, is not
1123/// registered.
1124pub(super) fn register(b: &mut FeatureBuilder<'_>, backend: &str) -> Result<(), BuildError> {
1125    b.peer_backend(
1126        backend,
1127        format!(
1128            "the `{backend}` backend, for which the publish stage computes the address of each image"
1129        ),
1130    )?;
1131    b.table_named::<GraphicsPublished>(
1132        published_table(backend).name().clone(),
1133        format!(
1134            "The address at which the `{backend}` output refers to each image, keyed by the \
1135             address of the image's node."
1136        ),
1137    )?;
1138    b.table_named::<GraphicsContent>(
1139        content_table(backend).name().clone(),
1140        format!(
1141            "The content of each image file under the strategy `content`, for a stage of the \
1142             `{backend}` output that renders images itself, keyed by the address of the image's \
1143             node. Empty under the other strategies."
1144        ),
1145    )?;
1146    if let Some(table) = output_images(backend).artifacts {
1147        b.peer_table::<ArtifactSet>(
1148            table.name(),
1149            format!(
1150                "the artifact table of the `{backend}` output, into which the publish stage writes \
1151                 the copies of image files"
1152            ),
1153        )?;
1154    }
1155    b.stage(Arc::new(PublishStage::new(backend)))
1156}