Skip to main content

flm_core/stdlib/features/graphics/
inspect.rs

1//! This module defines the *inspector* of the `graphics` feature
2//! ([`GraphicsInspector`]), a service that reports the type and the size of
3//! image files. It also defines the inspect stage [`INSPECT_STAGE`], which
4//! calls the inspector for each image and writes a record of each image into
5//! the table [`INFO`], along with the error conditions that the inspect stage
6//! reports.
7//!
8//! # The inspector
9//!
10//! The inspector reports whether an image is a *vector image* (a drawing, such
11//! as an SVG or a PDF file) or a *raster image* (a grid of pixels, such as a
12//! PNG or a JPEG file). It also reports the size of the image: the size in
13//! pixels and the resolution of a raster image, and the physical size of the
14//! image, such as `5cm` by `3cm`. The program that embeds FLM can contribute
15//! one inspector to the service slot [`INSPECTOR_SLOT`]
16//! (`flm.graphics.inspector`). The `graphics` feature works without an
17//! inspector, but the size of an image file is then unknown.
18//!
19//! The inspect stage calls [`GraphicsInspector::inspect`] for each image with
20//! a [`GraphicsInspectRequest`]. The request contains the path of the image as
21//! written in the document, and the origin of the source in which the image is
22//! written, from which a relative path is resolved. When a graphics resolver
23//! ([`GraphicsResolver`]) is registered, the inspect stage first calls the
24//! resolver to find and read the file. The request then also contains the file
25//! and its content ([`resolved`](GraphicsInspectRequest::resolved)). Without a
26//! graphics resolver, the inspector must find and read the file itself.
27//!
28//! If the graphics resolver fails to find or to read the file, the inspect
29//! stage reports the error [`ResolveFailed`] and does not call the inspector.
30//! For a path that begins with a scheme, such as `https://example.org/a.png`,
31//! the inspect stage calls neither the resolver nor the inspector
32//! ([`names_scheme`]).
33//!
34//! The inspector returns the *inspected information*
35//! ([`GraphicsInspectedInformation`]), which contains the type and the size of
36//! the image as the file states them, or an error ([`GraphicsInspectError`]).
37//!
38//! The inspector can be called several times for the same image. When content
39//! that contains an image is shown a second time, such as the title of a
40//! section that a reference displays, the inspect stage runs again over this
41//! copy of the content ([synthesized
42//! values](crate::guide::concepts_overview#synthesized-values)). The
43//! diagnostics about the image are then reported again ([reports over content
44//! shown again](crate::guide::rendering#reports-over-content-shown-again)). An
45//! inspector may cache the inspected information that it returned, provided
46//! that a cached result is equal to the result of a new call.
47//!
48//! # The record of an image
49//!
50//! The inspect stage writes one [`GraphicsRecord`] for each image into the
51//! table [`INFO`] (`flm.graphics.info`). The lowering rules of the image
52//! element read this table to compute the size at which the image is shown
53//! ([the size of an image](super#the-size-of-an-image)). The records are keyed
54//! by the address of the image's node. The same path, such as `./a.png`, can
55//! refer to two different files when it is written in sources of different
56//! folders.
57//!
58//! A record contains the path, the origin of the source, the file that the
59//! graphics resolver found, and the inspected information. The inspect stage
60//! keeps every value of the inspected information unchanged, in its own unit,
61//! and fills in what the inspected information of a raster image leaves out:
62//!
63//! - If the inspected information contains no resolution, a resolution of 96
64//!   dots per inch ([`ASSUMED_DPI`]) is assumed, and the warning
65//!   [`AssumedResolution`] is reported.
66//! - If the inspected information contains no physical size, the physical size
67//!   is computed in points from the size in pixels and the resolution. For
68//!   instance, a width of 300 pixels at a resolution of 150 dots per inch
69//!   gives a width of 144 points, that is, 2 inches ([`Length::from_dots`]).
70//!
71//! If the inspector returns an error, the inspect stage reports the error
72//! [`InspectFailed`]. If the inspected information does not meet the
73//! requirements stated in [`GraphicsInspector::inspect`], the inspect stage
74//! reports one of the errors [`NoPixelSize`], [`InspectedSizeNotPhysical`] or
75//! [`InspectedResolutionNotPositive`]. In each of these cases, the record
76//! contains no inspected information, and the size of the image file is
77//! unknown.
78
79use std::collections::BTreeMap;
80use std::fmt;
81
82use techy::core::node::NodeRef;
83use techy::error::{Diagnostic, DiagnosticInfo};
84use techy::serialize::SerialValue;
85
86use crate::core::data::store::StageOut;
87use crate::core::data::table::{ProjectCx, SingletonTable, Table, TableName};
88use crate::core::plan::PlanCx;
89use crate::core::registry::{BuildError, FeatureBuilder};
90use crate::core::run::StageCx;
91use crate::core::stage::{Effect, Needs, Scope, Stage, StageDecl};
92use crate::lang::{Flm, FlmDiagnostic, FlmOrigin, FlmSpan, nowhere};
93use crate::model::addr::NodeAddr;
94use crate::stdlib::backends::pres::{I48F16, Length, LengthUnit};
95use crate::stdlib::features::index::ELEMENT_INDEX;
96use crate::techy::source::SourceOrigin;
97
98use super::resolve::{
99    GraphicsResolveRequest, GraphicsResolver, ImageFile, RESOLVER_SLOT, ResolvedImage, names_scheme,
100};
101use super::{GraphicsImage, INSPECTOR_SLOT, ImagePath, read_path};
102
103/// The name of the inspect stage, `flm.graphics.inspect` ([`InspectStage`]).
104pub const INSPECT_STAGE: &str = "flm.graphics.inspect";
105
106/// The name of the table `flm.graphics.info` ([`GraphicsInfo`]). The table
107/// contains the [`GraphicsRecord`] of each image, keyed by the address of the
108/// image's node. The inspect stage [`INSPECT_STAGE`] writes this table, and
109/// the lowering rules of the image element read it.
110pub const INFO: TableName<GraphicsInfo> = TableName::new("flm.graphics.info");
111
112/// The resolution, in dots per inch, that the inspect stage assumes for a
113/// raster image whose file states no resolution.
114pub const ASSUMED_DPI: i32 = 96;
115
116/// The physical size of an image, given by its width and its height.
117#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
118pub struct Dimensions {
119    /// The width.
120    pub width: Length,
121    /// The height.
122    pub height: Length,
123}
124
125/// The size of a raster image in pixels.
126#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
127pub struct PixelSize {
128    /// The width, in pixels.
129    pub width: u32,
130    /// The height, in pixels.
131    pub height: u32,
132}
133
134/// The *inspected information* that an inspector returns about an image file:
135/// the type of the image and its size, as the file states them.
136///
137/// Every length must be in one of the units `pt`, `mm`, `cm` or `in`. See
138/// [`GraphicsInspector::inspect`] for the other requirements.
139#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
140pub enum GraphicsInspectedInformation {
141    /// A vector image, that is, a drawing, such as an SVG or a PDF file.
142    Vector {
143        /// The physical size of the image, such as the size of the page of a
144        /// PDF file.
145        physical_dimensions: Dimensions,
146    },
147    /// A raster image, that is, a grid of pixels, such as a PNG or a JPEG
148    /// file.
149    Raster {
150        /// The resolution in dots per inch, if the file states one.
151        dpi: Option<I48F16>,
152        /// The size of the image in pixels.
153        size: PixelSize,
154        /// The physical size of the image, if the file states one.
155        physical_dimensions: Option<Dimensions>,
156    },
157}
158
159impl GraphicsInspectedInformation {
160    /// Returns the field `physical_dimensions` of either variant. For a raster
161    /// image, returns `None` if the inspected information contains no physical
162    /// size.
163    pub fn physical_dimensions(&self) -> Option<Dimensions> {
164        match self {
165            GraphicsInspectedInformation::Vector { physical_dimensions } => {
166                Some(*physical_dimensions)
167            }
168            GraphicsInspectedInformation::Raster { physical_dimensions, .. } => {
169                *physical_dimensions
170            }
171        }
172    }
173}
174
175/// The request that the inspect stage passes to the inspector for one image
176/// ([`GraphicsInspector::inspect`]).
177///
178/// Fields may be added to this struct in later versions. Therefore, create a
179/// request with [`new`](GraphicsInspectRequest::new).
180#[derive(Debug, Clone, PartialEq, Eq)]
181#[non_exhaustive]
182pub struct GraphicsInspectRequest {
183    /// The path of the image file, as written in the document.
184    pub path: String,
185    /// The origin of the source in which the image is written. Use its
186    /// canonical path ([`FlmOrigin::canonical_path`]) to resolve a relative
187    /// path. For an image written in the template of a user definition, this
188    /// is the origin of the source in which the call of the definition is
189    /// written.
190    pub origin: FlmOrigin,
191    /// The file that the graphics resolver ([`GraphicsResolver`]) found for
192    /// the path, with its content. `None` if no graphics resolver is
193    /// registered. In this case, the inspector must find and read the file
194    /// itself.
195    pub resolved: Option<ResolvedImage>,
196}
197
198impl GraphicsInspectRequest {
199    /// Returns a request for the path `path`, written in the source with the
200    /// origin `origin`. The request contains no resolved file.
201    pub fn new(path: impl Into<String>, origin: FlmOrigin) -> GraphicsInspectRequest {
202        GraphicsInspectRequest { path: path.into(), origin, resolved: None }
203    }
204
205    /// Sets the file and its content that the graphics resolver found
206    /// ([`resolved`](GraphicsInspectRequest::resolved)), and returns the
207    /// request.
208    pub fn resolved(mut self, resolved: ResolvedImage) -> GraphicsInspectRequest {
209        self.resolved = Some(resolved);
210        self
211    }
212}
213
214/// The error that an inspector returns when it cannot determine the type or
215/// the size of an image file. The inspect stage reports this error as the
216/// error [`InspectFailed`].
217#[derive(Debug, Clone, PartialEq, Eq)]
218pub struct GraphicsInspectError {
219    /// The reason for the failure, such as `no such file`. The message of
220    /// [`InspectFailed`] contains this text after a colon, as in
221    /// `Failed to inspect image file ‘plot.pdf’: no such file`. Therefore,
222    /// begin the text with a lowercase letter, and end it without a period.
223    pub detail: String,
224}
225
226impl GraphicsInspectError {
227    /// Returns the error with the text `detail`.
228    pub fn new(detail: impl Into<String>) -> GraphicsInspectError {
229        GraphicsInspectError { detail: detail.into() }
230    }
231}
232
233impl fmt::Display for GraphicsInspectError {
234    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
235        f.write_str(&self.detail)
236    }
237}
238
239impl std::error::Error for GraphicsInspectError {}
240
241/// An *inspector* is a service that reports the type and the size of image
242/// files. The program that embeds FLM can contribute one inspector to the
243/// service slot [`INSPECTOR_SLOT`]. The inspect stage [`INSPECT_STAGE`] then
244/// calls [`inspect`](GraphicsInspector::inspect) for each image of the
245/// document. See the [module documentation](self) for the requests that the
246/// inspector receives and for the use of the information that it returns.
247///
248/// # Examples
249///
250/// ```
251/// use std::sync::Arc;
252///
253/// use flm_core::core::registry::RegistryBuilder;
254/// use flm_core::stdlib::backends::pres::{Length, LengthUnit};
255/// use flm_core::stdlib::features::graphics::{
256///     Dimensions, GraphicsInspectError, GraphicsInspectRequest, GraphicsInspectedInformation,
257///     GraphicsInspector, INSPECTOR_SLOT,
258/// };
259///
260/// /// Every image is a vector picture three inches wide and two high.
261/// struct Fixed;
262///
263/// impl GraphicsInspector for Fixed {
264///     fn inspect(
265///         &self,
266///         _request: &GraphicsInspectRequest,
267///     ) -> Result<GraphicsInspectedInformation, GraphicsInspectError> {
268///         let inches = |amount: i32| Length::new(amount.into(), LengthUnit::Inches);
269///         Ok(GraphicsInspectedInformation::Vector {
270///             physical_dimensions: Dimensions { width: inches(3), height: inches(2) },
271///         })
272///     }
273/// }
274///
275/// let mut builder = RegistryBuilder::new();
276/// builder.contribute_to(INSPECTOR_SLOT, Arc::new(Fixed) as Arc<dyn GraphicsInspector>);
277/// ```
278pub trait GraphicsInspector: Send + Sync {
279    /// Returns the type and the size of the image file that `request` refers
280    /// to, as the file states them.
281    ///
282    /// If the file of a raster image states no resolution or no physical
283    /// size, set the corresponding field to `None`. The inspect stage then
284    /// assumes a resolution and computes the physical size ([the record of an
285    /// image](self#the-record-of-an-image)).
286    ///
287    /// The returned inspected information must meet three requirements:
288    ///
289    /// - Every length is in one of the units `pt`, `mm`, `cm` or `in`.
290    /// - The width and the height in pixels of a raster image are greater
291    ///   than zero.
292    /// - The resolution of a raster image, if given, is greater than zero.
293    ///
294    /// If one of these requirements is not met, the inspect stage reports the
295    /// error [`InspectedSizeNotPhysical`], [`NoPixelSize`] or
296    /// [`InspectedResolutionNotPositive`], and ignores the inspected
297    /// information.
298    ///
299    /// # Errors
300    ///
301    /// Returns a [`GraphicsInspectError`] if the inspector cannot determine
302    /// the type and the size of the file, for instance if the file does not
303    /// exist, cannot be read, or has a format that the inspector does not
304    /// support. The inspect stage reports this error as the error
305    /// [`InspectFailed`].
306    fn inspect(
307        &self,
308        request: &GraphicsInspectRequest,
309    ) -> Result<GraphicsInspectedInformation, GraphicsInspectError>;
310}
311
312/// A `GraphicsRecord` contains what the inspect stage found out about one
313/// image: its path, the origin of its source, the file that the graphics
314/// resolver found, and the inspected information. The table [`INFO`] contains
315/// the record of each image. See [the record of an
316/// image](self#the-record-of-an-image).
317#[derive(Debug, Clone, PartialEq, Eq)]
318pub struct GraphicsRecord {
319    /// The path of the image file, as written in the document.
320    pub path: String,
321    /// The origin of the source in which the image is written, as passed to
322    /// the graphics resolver and to the inspector
323    /// ([`GraphicsInspectRequest::origin`]).
324    pub origin: FlmOrigin,
325    /// The file that the graphics resolver found, without its content.
326    /// `None` if no graphics resolver is registered, if the resolver failed to
327    /// find the file, or if the path begins with a scheme.
328    pub file: Option<ImageFile>,
329    /// The inspected information, with the resolution and the physical size
330    /// that the inspect stage filled in. `None` in the following cases:
331    ///
332    /// - No inspector is registered.
333    /// - The inspector was not called, because the graphics resolver failed or
334    ///   because the path begins with a scheme.
335    /// - The inspector returned an error.
336    /// - The inspected information does not meet the requirements of
337    ///   [`GraphicsInspector::inspect`].
338    pub inspected: Option<GraphicsInspectedInformation>,
339}
340
341/// The content of the table [`INFO`]: the [`GraphicsRecord`] of each image,
342/// keyed by the address of the image's node.
343#[derive(Debug, Clone, Default, PartialEq, Eq)]
344pub struct GraphicsInfo {
345    records: BTreeMap<NodeAddr, GraphicsRecord>,
346}
347
348impl GraphicsInfo {
349    /// Returns the record of the image whose node has the address `addr`, or
350    /// `None` if the table contains no record for this address.
351    pub fn get(&self, addr: NodeAddr) -> Option<&GraphicsRecord> {
352        self.records.get(&addr)
353    }
354
355    /// Returns every record, in node-address order.
356    pub fn iter(&self) -> impl Iterator<Item = (NodeAddr, &GraphicsRecord)> + '_ {
357        self.records.iter().map(|(addr, record)| (*addr, record))
358    }
359
360    /// Returns the number of records.
361    pub fn len(&self) -> usize {
362        self.records.len()
363    }
364
365    /// Returns `true` if the table contains no record.
366    pub fn is_empty(&self) -> bool {
367        self.records.is_empty()
368    }
369}
370
371/// Returns `length` as a serialized string, such as `5cm`.
372fn length_value(length: &Length) -> SerialValue {
373    SerialValue::Str(length.to_string())
374}
375
376/// Returns `dimensions` as a serialized map with the keys `width` and
377/// `height`.
378fn dimensions_value(dimensions: &Dimensions) -> SerialValue {
379    SerialValue::Map(vec![
380        (String::from("width"), length_value(&dimensions.width)),
381        (String::from("height"), length_value(&dimensions.height)),
382    ])
383}
384
385/// Returns the inspected information `answer` as a serialized map. The key
386/// `kind` has the value `vector` or `raster`. The other keys are the fields of
387/// the variant, except a field whose value is `None`.
388fn answer_value(answer: &GraphicsInspectedInformation) -> SerialValue {
389    match answer {
390        GraphicsInspectedInformation::Vector { physical_dimensions } => SerialValue::Map(vec![
391            (String::from("kind"), SerialValue::Str(String::from("vector"))),
392            (String::from("physical_dimensions"), dimensions_value(physical_dimensions)),
393        ]),
394        GraphicsInspectedInformation::Raster { dpi, size, physical_dimensions } => {
395            let mut entries = vec![
396                (String::from("kind"), SerialValue::Str(String::from("raster"))),
397                (
398                    String::from("size"),
399                    SerialValue::Map(vec![
400                        (String::from("width"), SerialValue::Str(size.width.to_string())),
401                        (String::from("height"), SerialValue::Str(size.height.to_string())),
402                    ]),
403                ),
404            ];
405            if let Some(dpi) = dpi {
406                entries.push((
407                    String::from("dpi"),
408                    SerialValue::Str(dpi.to_string()),
409                ));
410            }
411            if let Some(dimensions) = physical_dimensions {
412                entries.push((String::from("physical_dimensions"), dimensions_value(dimensions)));
413            }
414            SerialValue::Map(entries)
415        }
416    }
417}
418
419impl Table for GraphicsInfo {
420    fn absorb(&mut self, piece: GraphicsInfo) {
421        self.records.extend(piece.records);
422    }
423
424    /// Returns the records as a list of maps, in the order of the node
425    /// addresses. Each map has the keys `node` and `path`. It also has the
426    /// key `origin` if the origin has a label, and the keys `file` and
427    /// `inspected` if the record contains a value for them.
428    fn project(&self, cx: &dyn ProjectCx) -> SerialValue {
429        SerialValue::List(
430            self.records
431                .iter()
432                .map(|(addr, record)| {
433                    let mut entries = vec![
434                        (String::from("node"), cx.node_ref(*addr)),
435                        (String::from("path"), SerialValue::Str(record.path.clone())),
436                    ];
437                    if let Some(label) = record.origin.label() {
438                        entries.push((String::from("origin"), SerialValue::Str(label.into_owned())));
439                    }
440                    if let Some(file) = &record.file {
441                        entries.push((
442                            String::from("file"),
443                            SerialValue::Map(vec![
444                                (String::from("identity"), SerialValue::Str(file.identity.clone())),
445                                (String::from("media_type"), SerialValue::Str(file.media_type.clone())),
446                                (String::from("address"), SerialValue::Str(file.address.clone())),
447                            ]),
448                        ));
449                    }
450                    if let Some(answer) = &record.inspected {
451                        entries.push((String::from("inspected"), answer_value(answer)));
452                    }
453                    SerialValue::Map(entries)
454                })
455                .collect(),
456        )
457    }
458}
459
460impl SingletonTable for GraphicsInfo {
461    const NAME: &'static str = "flm.graphics.info";
462}
463
464/// The warning that is reported when a raster image file does not state its
465/// resolution (id `flm.graphics.assumed-resolution`).
466///
467/// Reported by the inspect stage [`INSPECT_STAGE`] when the inspected
468/// information of a raster image contains no resolution. The inspect stage
469/// then assumes a resolution of 96 dots per inch ([`ASSUMED_DPI`]). If the
470/// file states no physical size either, the size of the image is computed
471/// from its size in pixels at this resolution.
472#[derive(Debug, Clone, PartialEq, Eq, DiagnosticInfo)]
473#[diagnostic(
474    id = "flm.graphics.assumed-resolution",
475    message = "Missing resolution in image file ‘{path}’"
476)]
477pub struct AssumedResolution {
478    /// The path of the image file, as written in the document.
479    pub path: String,
480}
481
482/// The error that is reported when the inspector fails to determine the type
483/// or the size of an image file (id `flm.graphics.inspect-failed`).
484///
485/// The message contains the reason that the inspector returned
486/// ([`GraphicsInspectError`]). Reported by the inspect stage
487/// [`INSPECT_STAGE`]. The image is then written with the size given in its
488/// options `width` and `height`. If neither option is given, the image is
489/// written without a size.
490#[derive(Debug, Clone, PartialEq, Eq, DiagnosticInfo)]
491#[diagnostic(
492    id = "flm.graphics.inspect-failed",
493    message = "Failed to inspect image file ‘{path}’: {detail}"
494)]
495pub struct InspectFailed {
496    /// The path of the image file, as written in the document.
497    pub path: String,
498    /// The reason that the inspector returned
499    /// ([`GraphicsInspectError::detail`]).
500    pub detail: String,
501}
502
503/// The error that is reported when the graphics resolver fails to find or to
504/// read the file of an image (id `flm.graphics.resolve-failed`).
505///
506/// The message contains the reason that the graphics resolver returned
507/// ([`GraphicsResolveError`](super::GraphicsResolveError)). Two stages report
508/// this error:
509///
510/// - The inspect stage [`INSPECT_STAGE`] reports it when the resolver fails to
511///   find the file, or fails to read the content that the inspector needs. The
512///   image is then written with the size given in its options `width` and
513///   `height`. If neither option is given, the image is written without a
514///   size.
515/// - The publish stage of an output ([`PublishStage`](super::PublishStage))
516///   reports it when the resolver fails to read the file under the strategy
517///   `copy`, `data-uri` or `content`.
518///
519/// If the resolver fails to find the file, every output refers to the image by
520/// its path as written. If a publish stage fails to read the file, its output
521/// refers to the image by the address of the file that the resolver returned.
522#[derive(Debug, Clone, PartialEq, Eq, DiagnosticInfo)]
523#[diagnostic(
524    id = "flm.graphics.resolve-failed",
525    message = "Failed to read image file ‘{path}’: {detail}"
526)]
527pub struct ResolveFailed {
528    /// The path of the image file, as written in the document.
529    pub path: String,
530    /// The reason that the graphics resolver returned
531    /// ([`GraphicsResolveError::detail`](super::GraphicsResolveError::detail)).
532    pub detail: String,
533}
534
535/// The error that is reported when the inspector returns a width or a height
536/// of zero pixels for a raster image (id `flm.graphics.no-pixel-size`).
537///
538/// Reported by the inspect stage [`INSPECT_STAGE`], which then ignores the
539/// inspected information of the image. The image is written with the size
540/// given in its options `width` and `height`. If neither option is given, the
541/// image is written without a size.
542#[derive(Debug, Clone, PartialEq, Eq, DiagnosticInfo)]
543#[diagnostic(
544    id = "flm.graphics.no-pixel-size",
545    message = "Invalid size of image file ‘{path}’: the width and the height in \
546               pixels must be greater than zero"
547)]
548pub struct NoPixelSize {
549    /// The path of the image file, as written in the document.
550    pub path: String,
551}
552
553/// The error that is reported when the inspector returns a size of an image
554/// in the unit `em` or `tab` (id `flm.graphics.inspected-size-not-physical`).
555///
556/// An inspector must give every length in one of the units `pt`, `mm`, `cm`
557/// or `in`, which have a fixed size. A document cannot cause this error: it
558/// is caused by a faulty inspector.
559///
560/// Reported by the inspect stage [`INSPECT_STAGE`], which then ignores the
561/// inspected information of the image. The image is written with the size
562/// given in its options `width` and `height`. If neither option is given, the
563/// image is written without a size.
564#[derive(Debug, Clone, PartialEq, Eq, DiagnosticInfo)]
565#[diagnostic(
566    id = "flm.graphics.inspected-size-not-physical",
567    message = "Invalid unit ‘{unit}’ in the size reported by the inspector for image file \
568               ‘{path}’: sizes must be given in ‘pt’, ‘mm’, ‘cm’ or ‘in’"
569)]
570pub struct InspectedSizeNotPhysical {
571    /// The path of the image file, as written in the document.
572    pub path: String,
573    /// The unit of the size, `em` or `tab`.
574    pub unit: String,
575}
576
577/// The error that is reported when the inspector returns a resolution of zero
578/// or less for a raster image (id
579/// `flm.graphics.inspected-resolution-not-positive`).
580///
581/// Reported by the inspect stage [`INSPECT_STAGE`], which then ignores the
582/// inspected information of the image. The image is written with the size
583/// given in its options `width` and `height`. If neither option is given, the
584/// image is written without a size.
585#[derive(Debug, Clone, PartialEq, Eq, DiagnosticInfo)]
586#[diagnostic(
587    id = "flm.graphics.inspected-resolution-not-positive",
588    message = "Invalid resolution in image file ‘{path}’: the resolution must be \
589               greater than zero"
590)]
591pub struct InspectedResolutionNotPositive {
592    /// The path of the image file, as written in the document.
593    pub path: String,
594}
595
596/// The error that is reported when a stage of the [`graphics`](super) feature
597/// fails because of an error in the program (id `flm.graphics.stage-failed`).
598///
599/// A document cannot cause this error. The inspect stage and the publish
600/// stages report it when they cannot access a table or the render options
601/// listed in their declarations. This means that the plan does not match the
602/// declarations of the stage. Reported at no position in the document. The
603/// stage then stops, and the tables that it has not written yet are absent.
604#[derive(Debug, Clone, PartialEq, Eq, DiagnosticInfo)]
605#[diagnostic(id = "flm.graphics.stage-failed", message = "Stage ‘{stage}’ failed: {detail}")]
606pub struct StageFailed {
607    /// The name of the stage.
608    pub stage: String,
609    /// The message of the error that the stage received when it accessed a
610    /// table or the render options.
611    pub detail: String,
612}
613
614/// Pushes the error [`StageFailed`] of the stage `stage` to `out`, with the
615/// text `detail`, at no position in the document.
616pub(super) fn stage_failed(out: &mut StageOut<'_>, stage: &str, detail: impl ToString) {
617    out.diags.push(Diagnostic::error(
618        StageFailed { stage: stage.to_string(), detail: detail.to_string() },
619        nowhere(FlmOrigin::none()),
620    ));
621}
622
623/// Returns the origin that the graphics resolver and the inspector receive for
624/// the image at `span`.
625///
626/// This is the origin of the first source that has a canonical path, starting
627/// from the source of `span` and following each expansion back to the place
628/// where it was triggered. For an image written in the template of a user
629/// definition, this is the source in which the call of the definition is
630/// written. If no source on this chain has a canonical path, returns the
631/// origin of the source of `span`.
632// A source that the expansion of a user definition produces has no file of its
633// own, so the host is given the file in which the author wrote the use site.
634fn request_origin(span: &FlmSpan) -> FlmOrigin {
635    let own = span.source().origin().clone();
636    let mut span = span.clone();
637    loop {
638        if span.source().origin().canonical_path().is_some() {
639            return span.source().origin().clone();
640        }
641        let Some(triggered) = span.source().provenance().triggered_at().cloned() else {
642            return own;
643        };
644        span = triggered;
645    }
646}
647
648/// The reason why the inspect stage ignores the inspected information of an
649/// image. Each variant corresponds to one error condition.
650enum Refusal {
651    /// A raster image with a width or a height of zero pixels
652    /// ([`NoPixelSize`]).
653    NoPixelSize,
654    /// A size in a unit that has no fixed size, `em` or `tab`
655    /// ([`InspectedSizeNotPhysical`]).
656    NotPhysical(LengthUnit),
657    /// A resolution of zero or less ([`InspectedResolutionNotPositive`]).
658    ResolutionNotPositive,
659}
660
661/// Returns the unit of the width of `dimensions` if this unit has no fixed
662/// size, else the unit of the height if this unit has no fixed size, else
663/// `None`.
664fn non_physical(dimensions: &Dimensions) -> Option<LengthUnit> {
665    [dimensions.width.unit, dimensions.height.unit].into_iter().find(|unit| !unit.is_physical())
666}
667
668/// Checks the inspected information `answer` and fills in what it leaves out,
669/// as described in [the record of an image](self#the-record-of-an-image).
670///
671/// Returns the completed inspected information, and `true` if the resolution
672/// [`ASSUMED_DPI`] was assumed. If a physical size computed from the size in
673/// pixels is too large to represent, the completed inspected information
674/// contains no physical size. Returns the reason for ignoring `answer` if it
675/// does not meet the requirements of [`GraphicsInspector::inspect`].
676fn complete(
677    answer: GraphicsInspectedInformation,
678) -> Result<(GraphicsInspectedInformation, bool), Refusal> {
679    match answer {
680        GraphicsInspectedInformation::Vector { physical_dimensions } => {
681            if let Some(unit) = non_physical(&physical_dimensions) {
682                return Err(Refusal::NotPhysical(unit));
683            }
684            Ok((answer, false))
685        }
686        GraphicsInspectedInformation::Raster { dpi, size, physical_dimensions } => {
687            if size.width == 0 || size.height == 0 {
688                return Err(Refusal::NoPixelSize);
689            }
690            if let Some(unit) = physical_dimensions.as_ref().and_then(non_physical) {
691                return Err(Refusal::NotPhysical(unit));
692            }
693            if dpi.is_some_and(|dpi| dpi <= I48F16::ZERO) {
694                return Err(Refusal::ResolutionNotPositive);
695            }
696            let assumed = dpi.is_none();
697            let dpi = dpi.unwrap_or(I48F16::from_num(ASSUMED_DPI));
698            let physical_dimensions = match physical_dimensions {
699                Some(stated) => Some(stated),
700                // A size too large to hold is left out rather than wrapped.
701                None => Length::from_dots(u64::from(size.width), dpi)
702                    .and_then(|width| {
703                        Length::from_dots(u64::from(size.height), dpi)
704                            .map(|height| Dimensions { width, height })
705                    })
706                    .ok(),
707            };
708            Ok((
709                GraphicsInspectedInformation::Raster { dpi: Some(dpi), size, physical_dimensions },
710                assumed,
711            ))
712        }
713    }
714}
715
716/// The services that the inspect stage calls: the graphics resolver and the
717/// inspector registered in the registry. A field is `None` if no service was
718/// contributed to its service slot.
719struct Services<'r> {
720    resolver: Option<&'r dyn GraphicsResolver>,
721    inspector: Option<&'r dyn GraphicsInspector>,
722}
723
724/// Returns the record of the image `node` with the path `path`. Calls the
725/// graphics resolver and the inspector of `services`, if they are registered,
726/// and pushes the resulting diagnostics to `diags`.
727fn record_of(
728    node: &NodeRef<'_, Flm>,
729    path: String,
730    services: &Services<'_>,
731    diags: &mut Vec<FlmDiagnostic>,
732) -> GraphicsRecord {
733    let origin = request_origin(node.span());
734    let mut record = GraphicsRecord { path, origin, file: None, inspected: None };
735    if names_scheme(&record.path) {
736        return record;
737    }
738    let span = node.span().clone();
739    let mut request = GraphicsInspectRequest::new(record.path.clone(), record.origin.clone());
740    if let Some(resolver) = services.resolver {
741        let asked = GraphicsResolveRequest::new(record.path.clone(), record.origin.clone());
742        let file = match resolver.resolve(&asked) {
743            Ok(file) => file,
744            Err(error) => {
745                let failed = ResolveFailed { path: record.path.clone(), detail: error.detail };
746                diags.push(Diagnostic::error(failed, span));
747                return record;
748            }
749        };
750        record.file = Some(file.clone());
751        if services.inspector.is_none() {
752            return record;
753        }
754        match resolver.read(&file) {
755            Ok(content) => request = request.resolved(ResolvedImage { file, content: content.into() }),
756            Err(error) => {
757                let failed = ResolveFailed { path: record.path.clone(), detail: error.detail };
758                diags.push(Diagnostic::error(failed, span));
759                return record;
760            }
761        }
762    }
763    let Some(inspector) = services.inspector else { return record };
764    let path = record.path.clone();
765    match inspector.inspect(&request).map_err(|error| error.detail) {
766        Err(detail) => diags.push(Diagnostic::error(InspectFailed { path, detail }, span)),
767        Ok(answer) => match complete(answer) {
768            Ok((completed, assumed)) => {
769                if assumed {
770                    diags.push(Diagnostic::warning(AssumedResolution { path }, span));
771                }
772                record.inspected = Some(completed);
773            }
774            Err(Refusal::NoPixelSize) => {
775                diags.push(Diagnostic::error(NoPixelSize { path }, span));
776            }
777            Err(Refusal::NotPhysical(unit)) => diags.push(Diagnostic::error(
778                InspectedSizeNotPhysical { path, unit: unit.to_string() },
779                span,
780            )),
781            Err(Refusal::ResolutionNotPositive) => {
782                diags.push(Diagnostic::error(InspectedResolutionNotPositive { path }, span));
783            }
784        },
785    }
786    record
787}
788
789/// The inspect stage of the `graphics` feature, registered under the name
790/// [`INSPECT_STAGE`].
791///
792/// For each image, the stage calls the graphics resolver and the inspector, if
793/// they are registered, and writes the [`GraphicsRecord`] of the image into
794/// the table [`INFO`]. The stage finds the images in the element index
795/// ([`ElementIndex`](crate::stdlib::features::index::ElementIndex), table
796/// [`ELEMENT_INDEX`]). It runs once for each tree, including each copy of
797/// content that is shown a second time. See the [module documentation](self).
798#[derive(Debug, Default, Clone, Copy)]
799pub struct InspectStage;
800
801impl Stage for InspectStage {
802    fn decl(&self) -> StageDecl {
803        // Once per tree, so that value catch-up, which re-runs only per-tree
804        // stages, re-enters it and an image a value shows is inspected too; an
805        // image needs nothing outside the tree it stands in.
806        StageDecl::new(INSPECT_STAGE, Effect::Compute, Scope::PerTree).writes(INFO).docs(
807            "Calls the graphics resolver and the inspector, if they are registered, for each \
808             image, and writes the record of each image to `flm.graphics.info`. Reports each \
809             image file that cannot be found, read or inspected, and each raster image file \
810             that does not state its resolution.",
811        )
812    }
813
814    fn needs(&self, _cx: &PlanCx<'_>) -> Needs {
815        Needs::new().reads(ELEMENT_INDEX)
816    }
817
818    fn run(&self, cx: &StageCx<'_>, out: &mut StageOut<'_>) {
819        let (Some(id), Some(tree)) = (cx.tree_id(), cx.my_tree()) else { return };
820        let index = match cx.get(ELEMENT_INDEX) {
821            Ok(Some(index)) => index,
822            Ok(None) => return,
823            Err(error) => return stage_failed(out, INSPECT_STAGE, error),
824        };
825        let registered = cx.registry().services();
826        let services = Services {
827            resolver: registered.service_named::<dyn GraphicsResolver>(RESOLVER_SLOT),
828            inspector: registered.service_named::<dyn GraphicsInspector>(INSPECTOR_SLOT),
829        };
830        let mut info = GraphicsInfo::default();
831        let mut diags = Vec::new();
832        for (addr, node, _) in index.values_of::<GraphicsImage>(id, &tree) {
833            // A path holding a template's placeholder is read where each use
834            // site is lowered; a path that is not characters, or is empty, is
835            // reported by the rules, which show no image for it.
836            let Ok(ImagePath::Read(path)) = read_path(&node) else { continue };
837            let record = record_of(&node, path, &services, &mut diags);
838            info.records.insert(addr, record);
839        }
840        for diagnostic in diags {
841            out.diags.push(diagnostic);
842        }
843        match out.table(INFO) {
844            Ok(table) => *table = info,
845            Err(error) => stage_failed(out, INSPECT_STAGE, error),
846        }
847    }
848}
849
850/// Declares the table [`INFO`] and the inspect stage.
851pub(super) fn register(b: &mut FeatureBuilder<'_>) -> Result<(), BuildError> {
852    b.table(INFO, "The record of each image, keyed by the address of the image's node: the path, \
853                   the file that the graphics resolver found, and the type and the size of the \
854                   image that the inspector returned.")?;
855    b.stage(std::sync::Arc::new(InspectStage))
856}
857
858#[cfg(test)]
859mod tests {
860    use super::*;
861
862    fn length(text: &str) -> Length {
863        Length::parse(text).expect("a length")
864    }
865
866    #[test]
867    fn a_raster_answer_is_completed_and_nothing_stated_changes() {
868        let size = PixelSize { width: 300, height: 150 };
869        let bare = GraphicsInspectedInformation::Raster { dpi: None, size, physical_dimensions: None };
870        let Ok((completed, assumed)) = complete(bare) else { panic!("completed") };
871        assert!(assumed);
872        assert_eq!(
873            completed,
874            GraphicsInspectedInformation::Raster {
875                dpi: Some(I48F16::from_num(96)),
876                size,
877                physical_dimensions: Some(Dimensions {
878                    width: length("225pt"),
879                    height: length("112.5pt")
880                }),
881            }
882        );
883        let stated = Dimensions { width: length("3cm"), height: length("1.5cm") };
884        let full = GraphicsInspectedInformation::Raster {
885            dpi: Some(I48F16::from_num(300)),
886            size,
887            physical_dimensions: Some(stated),
888        };
889        assert_eq!(complete(full).ok(), Some((full, false)));
890    }
891
892    #[test]
893    fn an_answer_that_cannot_be_recorded_is_refused() {
894        let size = PixelSize { width: 0, height: 10 };
895        let zero = GraphicsInspectedInformation::Raster { dpi: None, size, physical_dimensions: None };
896        assert!(matches!(complete(zero), Err(Refusal::NoPixelSize)));
897        let ems = Dimensions { width: length("2em"), height: length("1in") };
898        let vector = GraphicsInspectedInformation::Vector { physical_dimensions: ems };
899        assert!(matches!(complete(vector), Err(Refusal::NotPhysical(LengthUnit::Ems))));
900        let flat = GraphicsInspectedInformation::Raster {
901            dpi: Some(I48F16::ZERO),
902            size: PixelSize { width: 1, height: 1 },
903            physical_dimensions: None,
904        };
905        assert!(matches!(complete(flat), Err(Refusal::ResolutionNotPositive)));
906    }
907}