Skip to main content

flm_core/stdlib/features/graphics/
strategy.rs

1//! How each output publishes its images: the strategies ([`Strategy`]), and
2//! the render options ([`GraphicsRenderOptions`]) that choose, per output, a
3//! strategy, the conversion rules and the magnification of images
4//! ([`Magnification`]).
5//!
6//! **Publishing** an image is deciding the address an output writes to reach
7//! it. A **strategy** says how the address is decided:
8//!
9//! | strategy | the address | what the output holds |
10//! |---|---|---|
11//! | `reference` | the address of the file where it is | the entry artifact alone |
12//! | `copy` | the address of a copy of the file, made part of the output | the entry artifact and one copy per file |
13//! | `data-uri` | the file's content, in an address beginning with `data:` | the entry artifact alone |
14//! | `content` | the address of the file where it is, as under `reference` | the entry artifact alone; the file's content is a row of a table |
15//!
16//! The entry artifact is the artifact that represents an output as a whole,
17//! such as the HTML page ([`ArtifactSet`](crate::core::artifact::ArtifactSet)).
18//! The strategy `content` is for an output that renders images itself from
19//! their content, such as a picture drawn with characters: the publish stage
20//! writes each image's content into a table that the output's own stages read
21//! ([`content_table`](super::content_table)), and the output holds no copy.
22//! Not every output can use every strategy: `copy` needs an output that can
23//! hold several files (not the plain-text output), and `data-uri` an output
24//! that can show such an address (the HTML page only). A strategy set for an
25//! output that cannot use it is reported at each image, which is then
26//! published by `reference` ([`OutputImages`](super::OutputImages)).
27//!
28//! The strategy and the conversion rules are chosen per output, by the
29//! output's name. An output that the render options do not list keeps
30//! `reference` and no conversion rule, so a caller that sets nothing, or a
31//! host that supplies no graphics resolver, gets every image's path written
32//! as the author wrote it. The publish stages ([`publish`](super::publish))
33//! carry the strategies out.
34//!
35//! The **magnification** of an output multiplies the size every image is
36//! shown at on that output, by one factor for raster images and one for vector
37//! images ([`Magnification`]); the image rules apply it where they decide an
38//! image's size ([`shown_size`](super::rules::shown_size)).
39
40use std::borrow::Cow;
41use std::collections::BTreeMap;
42use std::fmt;
43
44use crate::stdlib::backends::pres::I48F16;
45
46use super::convert::ConversionRule;
47
48/// How an output publishes its images: one of the four strategies. In
49/// settings, written `reference`, `copy`, `data-uri` or `content`. See the
50/// [module documentation](self).
51#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash)]
52#[derive(serde::Deserialize, serde::Serialize, schemars::JsonSchema)]
53#[serde(rename_all = "kebab-case")]
54pub enum Strategy {
55    /// The address of the file where it is: the graphics resolver's address
56    /// where a resolver found the file, else the path as written. Nothing is
57    /// read, copied or converted. The default.
58    #[default]
59    Reference,
60    /// A copy of the file, converted where a conversion rule says so, is made
61    /// part of the output, and the address is the copy's, as the host's
62    /// artifact namer gives it. Needs a graphics resolver to read the file, an
63    /// artifact namer, and an output that can hold several files (not the
64    /// plain-text output).
65    Copy,
66    /// The file's content, converted where a conversion rule says so, is
67    /// written into the address itself, `data:<media type>;base64,<content>`,
68    /// so that the output needs no other file. Needs a graphics resolver to
69    /// read the file, and an output that can show such an address (the HTML
70    /// page only).
71    DataUri,
72    /// The address of the file where it is, as under `reference`, and the
73    /// file's content, converted where a conversion rule says so, written as
74    /// a row of the table `flm.graphics.content.<backend>`
75    /// ([`content_table`](super::content_table)), for an output that renders
76    /// images itself from their content. The output holds no copy. Needs a
77    /// graphics resolver to read the file.
78    Content,
79}
80
81impl Strategy {
82    /// Returns whether the strategy makes new content from the file (`copy`,
83    /// `data-uri` and `content`): such a strategy needs the file's content,
84    /// and the conversion rules apply to it.
85    pub fn needs_content(self) -> bool {
86        !matches!(self, Strategy::Reference)
87    }
88
89    /// Returns the strategy's name, as settings write it: `reference`,
90    /// `copy`, `data-uri` or `content`.
91    pub fn name(self) -> &'static str {
92        match self {
93            Strategy::Reference => "reference",
94            Strategy::Copy => "copy",
95            Strategy::DataUri => "data-uri",
96            Strategy::Content => "content",
97        }
98    }
99}
100
101/// The render options of the `graphics` feature: for each output, how its
102/// images are published, which conversion rules apply, and by how much its
103/// images are magnified.
104///
105/// An option type is a plain Rust struct a feature declares once; its values
106/// are set on a document or on a render request
107/// ([`crate::model::options`]). This one is set on the render request. Each
108/// field is a map from an output's name (`html`, `latex-recomposed`, `text`)
109/// to that output's value; an output that a map does not list takes the
110/// default. When a host combines several sources of settings, a source that
111/// writes one output's entry leaves the other outputs' entries as the
112/// lower-ranked sources wrote them. The publish stage of a backend reads the
113/// entries of the output of the backend's name: each standard backend makes
114/// one output, named after the backend.
115///
116/// # Examples
117///
118/// ```
119/// use flm_core::stdlib::features::graphics::{GraphicsRenderOptions, ImageFormat, Strategy};
120///
121/// let options: GraphicsRenderOptions = serde_json::from_value(serde_json::json!({
122///     "strategy": { "html": "data-uri", "latex-recomposed": "copy", "text": "content" },
123///     "convert": { "html": [ { "from": "pdf", "to": "png", "options": { "dpi": 192 } } ] },
124///     "magnification": { "html": { "raster": 1.5, "vector": 1.25 } },
125/// }))
126/// .unwrap();
127/// assert_eq!(options.strategy_for("html"), Strategy::DataUri);
128/// assert_eq!(options.strategy_for("text"), Strategy::Content);
129/// assert_eq!(options.strategy_for("latex-rendered"), Strategy::Reference);
130/// assert_eq!(options.rules_for("html")[0].to, ImageFormat::Png);
131/// assert!(options.rules_for("latex-recomposed").is_empty());
132/// assert_eq!(options.magnification_for("html").raster.value().to_string(), "1.5");
133/// assert_eq!(options.magnification_for("text").vector.value().to_string(), "1");
134/// ```
135#[derive(Debug, Clone, Default, PartialEq, Eq, Hash)]
136#[derive(serde::Deserialize, schemars::JsonSchema)]
137#[serde(default, deny_unknown_fields)]
138pub struct GraphicsRenderOptions {
139    /// How each output publishes its images, by the output's name:
140    /// `reference` (the address of the file where it is, the default), `copy`
141    /// (a copy of the file beside the output), `data-uri` (the file's content
142    /// written into the address) or `content` (the address of the file where
143    /// it is, and the file's content kept for an output that renders images
144    /// itself). `copy`, `data-uri` and `content` need a way to read image
145    /// files, which the program must supply.
146    pub strategy: BTreeMap<String, Strategy>,
147    /// The conversion rules of each output, by the output's name, applied
148    /// under `copy`, `data-uri` and `content` and never under `reference`.
149    /// Each rule has `from` (a format or a list of formats among `png`,
150    /// `jpeg`, `gif`, `webp`, `svg`, `pdf`), `to` (one format), `via` (the
151    /// names of the converters allowed; any converter where empty) and
152    /// `options` (`dpi`, `transparent_bg`). For each image, the first rule
153    /// whose `from` lists the image's format applies. No rule by default.
154    pub convert: BTreeMap<String, Vec<ConversionRule>>,
155    /// The magnification of each output, by the output's name: `raster` and
156    /// `vector`, each a number greater than zero (1 where not given), by
157    /// which every dimension of a raster or a vector image shown on that
158    /// output is multiplied, including the `width` and `height` the author
159    /// gave. An image whose type is not known uses `vector`. No
160    /// magnification by default.
161    pub magnification: BTreeMap<String, Magnification>,
162}
163
164impl GraphicsRenderOptions {
165    /// Returns the strategy of the output `output`: its entry, else
166    /// `reference`.
167    pub fn strategy_for(&self, output: &str) -> Strategy {
168        self.strategy.get(output).copied().unwrap_or_default()
169    }
170
171    /// Returns the conversion rules of the output `output`: its entry, else
172    /// none.
173    pub fn rules_for(&self, output: &str) -> &[ConversionRule] {
174        self.convert.get(output).map(Vec::as_slice).unwrap_or_default()
175    }
176
177    /// Returns the magnification of the output `output`: its entry, else a
178    /// factor of 1 for both types of images.
179    pub fn magnification_for(&self, output: &str) -> Magnification {
180        self.magnification.get(output).copied().unwrap_or_default()
181    }
182}
183
184/// The magnification of one output: the factor by which the size of each
185/// image shown on it is multiplied, one for raster images (a grid of pixels,
186/// such as a PNG or JPEG file) and one for vector images (a drawing, such as
187/// an SVG or PDF file). In settings, `{raster: 1.5, vector: 1.25}`; a factor
188/// not given is 1.
189///
190/// The two factors let an output show images at another size relative to its
191/// text than the other outputs do, such as larger on a web page than in a
192/// printed document. See [`GraphicsRenderOptions::magnification`].
193#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash)]
194#[derive(serde::Deserialize, schemars::JsonSchema)]
195#[serde(default, deny_unknown_fields)]
196pub struct Magnification {
197    /// The factor of a raster image.
198    pub raster: Factor,
199    /// The factor of a vector image, and of an image whose type is not known.
200    pub vector: Factor,
201}
202
203/// A magnification factor: an exact number greater than zero, 1 by default.
204///
205/// The factor is held exactly, as the fixed-point number with sixteen
206/// fractional bits that a length's amount is ([`I48F16`]), so that render
207/// options holding it compare equal and hash alike (an option value is part of
208/// what identifies a plan) and an image's size is computed identically on
209/// every platform. In settings it is written as a number, which is rounded to
210/// the nearest 1/65536 when it is read: `1.5` and `1.25` are held exactly, and
211/// `1.1` as the nearest multiple of 1/65536.
212#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
213#[derive(serde::Deserialize)]
214#[serde(try_from = "f64")]
215pub struct Factor(I48F16);
216
217impl Factor {
218    /// The factor 1, which leaves a size as it is.
219    pub const ONE: Factor = Factor(I48F16::ONE);
220
221    /// Returns the factor `value`, or `None` where `value` is not greater than
222    /// zero.
223    pub fn new(value: I48F16) -> Option<Factor> {
224        (value > I48F16::ZERO).then_some(Factor(value))
225    }
226
227    /// Returns the factor's value.
228    pub fn value(self) -> I48F16 {
229        self.0
230    }
231}
232
233impl Default for Factor {
234    fn default() -> Factor {
235        Factor::ONE
236    }
237}
238
239impl TryFrom<f64> for Factor {
240    type Error = FactorError;
241
242    fn try_from(value: f64) -> Result<Factor, FactorError> {
243        if value.is_nan() || value <= 0.0 {
244            return Err(FactorError::NotPositive(value));
245        }
246        I48F16::checked_from_num(value)
247            .and_then(Factor::new)
248            .ok_or(FactorError::OutOfRange(value))
249    }
250}
251
252/// Why a number is not a magnification [`Factor`].
253#[derive(Debug, Clone, Copy, PartialEq)]
254pub enum FactorError {
255    /// The number is zero or negative.
256    NotPositive(f64),
257    /// The number is too small to differ from zero once rounded to the
258    /// nearest 1/65536, or too large to hold.
259    OutOfRange(f64),
260}
261
262impl fmt::Display for FactorError {
263    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
264        match self {
265            FactorError::NotPositive(value) => {
266                write!(f, "a magnification factor must be greater than zero, not `{value}`")
267            }
268            FactorError::OutOfRange(value) => write!(
269                f,
270                "a magnification factor must lie between 1/65536 and 2^47, not `{value}`"
271            ),
272        }
273    }
274}
275
276impl std::error::Error for FactorError {}
277
278impl schemars::JsonSchema for Factor {
279    fn schema_name() -> Cow<'static, str> {
280        Cow::Borrowed("Factor")
281    }
282
283    fn inline_schema() -> bool {
284        true
285    }
286
287    fn json_schema(_generator: &mut schemars::SchemaGenerator) -> schemars::Schema {
288        schemars::json_schema!({
289            "type": "number",
290            "exclusiveMinimum": 0,
291            "default": 1,
292            "description": "A magnification factor, greater than zero.",
293        })
294    }
295}
296
297#[cfg(test)]
298mod tests {
299    use super::{Factor, FactorError, GraphicsRenderOptions, I48F16, Magnification, Strategy};
300
301    #[test]
302    fn a_magnification_defaults_to_one_per_output_and_per_type() {
303        let options: GraphicsRenderOptions = serde_json::from_value(serde_json::json!({
304            "magnification": { "html": { "raster": 1.5 } },
305        }))
306        .expect("the settings read");
307        let html = options.magnification_for("html");
308        assert_eq!(html.raster.value(), I48F16::from_num(1.5));
309        assert_eq!(html.vector, Factor::ONE);
310        assert_eq!(options.magnification_for("text"), Magnification::default());
311        assert_eq!(Magnification::default().raster, Factor::ONE);
312    }
313
314    #[test]
315    fn a_factor_is_greater_than_zero() {
316        assert_eq!(Factor::try_from(0.0), Err(FactorError::NotPositive(0.0)));
317        assert_eq!(Factor::try_from(-2.0), Err(FactorError::NotPositive(-2.0)));
318        assert_eq!(Factor::try_from(1e-9), Err(FactorError::OutOfRange(1e-9)));
319        assert_eq!(Factor::try_from(1e20), Err(FactorError::OutOfRange(1e20)));
320        assert!(Factor::try_from(f64::NAN).is_err());
321        assert_eq!(Factor::try_from(1.25).map(Factor::value), Ok(I48F16::from_num(1.25)));
322        let refused = serde_json::from_value::<GraphicsRenderOptions>(serde_json::json!({
323            "magnification": { "html": { "vector": 0 } },
324        }));
325        assert!(refused.is_err());
326    }
327
328    #[test]
329    fn each_strategy_s_name_reads_back_as_the_same_strategy() {
330        for strategy in [Strategy::Reference, Strategy::Copy, Strategy::DataUri, Strategy::Content] {
331            let read: Strategy = serde_json::from_value(serde_json::Value::from(strategy.name()))
332                .expect("the name is the settings' spelling");
333            assert_eq!(read, strategy);
334        }
335    }
336}