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