flm_core/stdlib/features/graphics/convert.rs
1//! Turning an image of one format into another: the converters that a host
2//! or an extension supplies ([`GraphicsConverter`]), the conversion rules set
3//! for an output ([`ConversionRule`]), and the choice of a converter for a
4//! rule ([`choose_converter`]).
5//!
6//! # Converters
7//!
8//! A **converter** ([`GraphicsConverter`]) turns the content of an image of
9//! one format into content of another. It has a **name** (`raster`,
10//! `magick`), says whether it **offers** a pair of formats, and **converts**
11//! content under a rule's options. It is given content and returns content;
12//! the converter decides whether it does the work in the program's own code
13//! or by running another program installed on the machine. Converters are
14//! contributed to the service slot [`CONVERTERS_SLOT`]
15//! (`flm.graphics.converters`), any number of them, kept in the order
16//! contributed; the feature requires none.
17//!
18//! # Conversion rules
19//!
20//! A **conversion rule** ([`ConversionRule`]) says which formats are turned
21//! into which: `from`, one format or a list; `to`, one format; `via`, an
22//! optional list of the names of the converters allowed to perform it; and
23//! `options` ([`ConversionOptions`]), such as the resolution at which a
24//! drawing is turned into pixels. The rules of each output are a render option
25//! of the feature
26//! ([`GraphicsRenderOptions::convert`](super::GraphicsRenderOptions::convert)).
27//! They apply where the output's strategy makes new content from the file
28//! (`copy`, `data-uri` and `content`), and never under `reference`, which
29//! writes the address of the file where it is.
30//!
31//! # Which converter performs a rule
32//!
33//! For an image, the first of the output's rules whose `from` lists the
34//! image's format applies; an image whose format no rule lists is published as
35//! it is. The converters that the rule's `via` lists (every converter, where
36//! `via` is empty) are asked, in the order of precedence of their service slot
37//! (the converters of the feature placed last in the feature order first, each
38//! feature's in the order it contributed them, the host's last), whether they
39//! offer the rule's pair of formats, and the first that does performs the
40//! conversion ([`choose_converter`]). A converter is asked when a rule is applied, not
41//! when the registry is built. Conversions are never chained: a rule whose
42//! pair of formats no allowed converter offers is reported, and the image is
43//! published as it is.
44
45use std::fmt;
46
47use serde::Deserialize;
48
49use crate::progress::Scope;
50
51use super::resolve::ImageFormat;
52
53/// The name of the converters' service slot, `flm.graphics.converters`: it
54/// takes any number of [`GraphicsConverter`]s, which a host or an extension
55/// contributes and the feature never requires. The feature reads them in the
56/// order of precedence
57/// ([`Services::services_by_precedence_named`](crate::core::services::Services::services_by_precedence_named)):
58/// the converters of the feature placed last in the feature order first, each
59/// feature's in the order it contributed them, and the host's last.
60pub const CONVERTERS_SLOT: &str = "flm.graphics.converters";
61
62/// The options of a conversion rule, which the converter that performs the
63/// rule reads. In settings, the rule's `options`, with the keys `dpi` and
64/// `transparent_bg`.
65///
66/// # Examples
67///
68/// ```
69/// use flm_core::stdlib::features::graphics::ConversionOptions;
70///
71/// let options: ConversionOptions = serde_json::from_value(serde_json::json!({ "dpi": 192 })).unwrap();
72/// assert_eq!(options.dpi, Some(192));
73/// assert_eq!(options.transparent_bg, None);
74/// ```
75#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash)]
76#[derive(serde::Deserialize, serde::Serialize, schemars::JsonSchema)]
77#[serde(default, deny_unknown_fields)]
78pub struct ConversionOptions {
79 /// The resolution, in dots per inch, at which a drawing (an SVG or a PDF
80 /// image) is turned into pixels. Where it is not given, the converter
81 /// chooses.
82 #[serde(skip_serializing_if = "Option::is_none")]
83 pub dpi: Option<u32>,
84 /// Whether a drawing turned into pixels keeps a transparent background,
85 /// where the converter can do so. Where it is not given, the converter
86 /// chooses.
87 #[serde(skip_serializing_if = "Option::is_none")]
88 pub transparent_bg: Option<bool>,
89}
90
91impl ConversionOptions {
92 /// Returns the options with nothing given: the converter chooses
93 /// everything.
94 pub fn new() -> ConversionOptions {
95 ConversionOptions::default()
96 }
97
98 /// Builder: sets [`dpi`](ConversionOptions::dpi).
99 pub fn dpi(mut self, dpi: u32) -> ConversionOptions {
100 self.dpi = Some(dpi);
101 self
102 }
103
104 /// Builder: sets [`transparent_bg`](ConversionOptions::transparent_bg).
105 pub fn transparent_bg(mut self, transparent: bool) -> ConversionOptions {
106 self.transparent_bg = Some(transparent);
107 self
108 }
109}
110
111/// One format or a list of formats, as a rule's `from` is written in
112/// settings.
113#[derive(Deserialize, schemars::JsonSchema)]
114#[serde(untagged)]
115enum Formats {
116 /// One format.
117 One(ImageFormat),
118 /// A list of formats.
119 Many(Vec<ImageFormat>),
120}
121
122/// Reads a rule's `from`, written as one format or a list, as a list.
123fn one_or_many<'de, D: serde::Deserializer<'de>>(data: D) -> Result<Vec<ImageFormat>, D::Error> {
124 Ok(match Formats::deserialize(data)? {
125 Formats::One(format) => vec![format],
126 Formats::Many(formats) => formats,
127 })
128}
129
130/// A conversion rule: which formats are turned into which, by which
131/// converters, with which options. See the [module
132/// documentation](self#conversion-rules).
133///
134/// In settings, a rule is written as a map with the keys `from`, `to`, `via`
135/// and `options`; `from` and `to` are required.
136///
137/// # Examples
138///
139/// ```
140/// use flm_core::stdlib::features::graphics::{ConversionRule, ImageFormat};
141///
142/// let rule: ConversionRule = serde_json::from_value(serde_json::json!({
143/// "from": "pdf",
144/// "to": "png",
145/// "options": { "dpi": 192 },
146/// }))
147/// .unwrap();
148/// assert_eq!(rule.from, [ImageFormat::Pdf]);
149/// assert_eq!(rule.to, ImageFormat::Png);
150/// assert!(rule.via.is_empty());
151/// assert_eq!(rule.options.dpi, Some(192));
152/// ```
153#[derive(Debug, Clone, PartialEq, Eq, Hash)]
154#[derive(serde::Deserialize, schemars::JsonSchema)]
155#[serde(deny_unknown_fields)]
156pub struct ConversionRule {
157 /// The formats the rule turns into `to`: one format (`pdf`) or a list
158 /// (`[svg, pdf]`), each one of `png`, `jpeg`, `gif`, `webp`, `svg` and
159 /// `pdf`.
160 #[serde(deserialize_with = "one_or_many")]
161 #[schemars(with = "Formats")]
162 pub from: Vec<ImageFormat>,
163 /// The format the rule turns them into.
164 pub to: ImageFormat,
165 /// The names of the converters allowed to perform the rule, in no
166 /// particular order; where the list is empty (the default), every
167 /// converter is allowed.
168 #[serde(default)]
169 pub via: Vec<String>,
170 /// The options the converter reads, such as the resolution at which a
171 /// drawing is turned into pixels.
172 #[serde(default)]
173 pub options: ConversionOptions,
174}
175
176impl ConversionRule {
177 /// Returns the rule that turns each of the formats `from` into `to`, by
178 /// any converter, with no option given.
179 pub fn new(from: impl IntoIterator<Item = ImageFormat>, to: ImageFormat) -> ConversionRule {
180 ConversionRule {
181 from: from.into_iter().collect(),
182 to,
183 via: Vec::new(),
184 options: ConversionOptions::default(),
185 }
186 }
187
188 /// Builder: adds the converter named `name` to the converters allowed to
189 /// perform the rule.
190 pub fn via(mut self, name: impl Into<String>) -> ConversionRule {
191 self.via.push(name.into());
192 self
193 }
194
195 /// Builder: sets the rule's options.
196 pub fn options(mut self, options: ConversionOptions) -> ConversionRule {
197 self.options = options;
198 self
199 }
200
201 /// Returns whether the rule applies to an image of the format `format`:
202 /// whether its `from` lists the format.
203 pub fn applies_to(&self, format: ImageFormat) -> bool {
204 self.from.contains(&format)
205 }
206}
207
208/// What a converter is asked to do: turn `content`, of the format `from`,
209/// into content of the format `to`, under `options`.
210///
211/// New fields may be added in later versions: a converter reads the fields it
212/// needs, and a request is built with [`new`](ConversionRequest::new).
213#[derive(Debug, Clone, Copy, PartialEq, Eq)]
214#[non_exhaustive]
215pub struct ConversionRequest<'a> {
216 /// The content to convert.
217 pub content: &'a [u8],
218 /// The format of the content.
219 pub from: ImageFormat,
220 /// The format to turn it into.
221 pub to: ImageFormat,
222 /// The rule's options.
223 pub options: &'a ConversionOptions,
224}
225
226impl<'a> ConversionRequest<'a> {
227 /// Returns the request to turn `content`, of the format `from`, into the
228 /// format `to` under `options`.
229 pub fn new(
230 content: &'a [u8],
231 from: ImageFormat,
232 to: ImageFormat,
233 options: &'a ConversionOptions,
234 ) -> ConversionRequest<'a> {
235 ConversionRequest { content, from, to, options }
236 }
237}
238
239/// Why a converter could not convert, in the converter's own words, which the
240/// Error the feature reports shows
241/// ([`ConversionFailed`](super::publish::ConversionFailed)).
242#[derive(Debug, Clone, PartialEq, Eq)]
243pub struct GraphicsConvertError {
244 /// What went wrong, as the converter says it.
245 pub detail: String,
246}
247
248impl GraphicsConvertError {
249 /// Returns the error with the text `detail`.
250 pub fn new(detail: impl Into<String>) -> GraphicsConvertError {
251 GraphicsConvertError { detail: detail.into() }
252 }
253}
254
255impl fmt::Display for GraphicsConvertError {
256 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
257 f.write_str(&self.detail)
258 }
259}
260
261impl std::error::Error for GraphicsConvertError {}
262
263/// A **converter**: a service that turns an image of one format into
264/// another, which a host or an extension contributes to the service slot
265/// [`CONVERTERS_SLOT`]. See the [module documentation](self).
266///
267/// A converter may keep the results it has computed, provided that reusing
268/// one cannot be told from converting again.
269///
270/// # Examples
271///
272/// ```
273/// use std::sync::Arc;
274///
275/// use flm_core::core::registry::RegistryBuilder;
276/// use flm_core::progress::Scope;
277/// use flm_core::stdlib::features::graphics::{
278/// CONVERTERS_SLOT, ConversionRequest, GraphicsConvertError, GraphicsConverter, ImageFormat,
279/// };
280///
281/// /// Turns a GIF into a PNG by keeping its bytes: a stand-in for a real one.
282/// struct GifToPng;
283///
284/// impl GraphicsConverter for GifToPng {
285/// fn name(&self) -> &str {
286/// "gif-to-png"
287/// }
288///
289/// fn offers(&self, from: ImageFormat, to: ImageFormat) -> bool {
290/// from == ImageFormat::Gif && to == ImageFormat::Png
291/// }
292///
293/// fn convert(&self, request: &ConversionRequest<'_>, _progress: &Scope) -> Result<Vec<u8>, GraphicsConvertError> {
294/// Ok(request.content.to_vec())
295/// }
296/// }
297///
298/// let mut builder = RegistryBuilder::new();
299/// builder.contribute_to(CONVERTERS_SLOT, Arc::new(GifToPng) as Arc<dyn GraphicsConverter>);
300/// ```
301pub trait GraphicsConverter: Send + Sync {
302 /// Returns the converter's name, by which a rule's `via` lists it, such as
303 /// `raster`.
304 fn name(&self) -> &str;
305
306 /// Returns whether the converter can turn content of the format `from`
307 /// into the format `to`.
308 fn offers(&self, from: ImageFormat, to: ImageFormat) -> bool;
309
310 /// Returns the content `request.content`, of the format `request.from`,
311 /// turned into the format `request.to` under `request.options`.
312 ///
313 /// `progress` is the scope of the conversion's row on the progress sheet
314 /// of the build, a row of the kind
315 /// [`CONVERT_KIND`](super::CONVERT_KIND) that the publish stage
316 /// declares for this image. A converter that does slow work in steps
317 /// declares its rows under it ([`Scope::child`]), and may ask
318 /// [`cancelled`](Scope::cancelled) between two steps; a converter that
319 /// does the work in one step ignores it. In a build that reports nowhere,
320 /// the scope is [`Scope::none`], whose methods do nothing.
321 ///
322 /// # Errors
323 ///
324 /// A [`GraphicsConvertError`] in the converter's own words when the
325 /// content cannot be read or the conversion fails.
326 fn convert(&self, request: &ConversionRequest<'_>, progress: &Scope) -> Result<Vec<u8>, GraphicsConvertError>;
327}
328
329/// Why no converter can perform a rule, as [`choose_converter`] returns it.
330#[derive(Debug, Clone, PartialEq, Eq)]
331pub enum NoConverter {
332 /// The rule's `via` lists a converter that is not registered: the name
333 /// as written.
334 Unknown(String),
335 /// No converter allowed by the rule offers its pair of formats.
336 NoneOffers,
337}
338
339/// Returns the converter that performs `rule` for an image of the format
340/// `from`: among `converters`, in their order, the first that the rule's
341/// `via` allows (every converter, where `via` is empty) and that offers the
342/// pair `from`, `rule.to`. See the [module
343/// documentation](self#which-converter-performs-a-rule).
344///
345/// # Errors
346///
347/// [`NoConverter::Unknown`] for the first name in the rule's `via` that no
348/// converter of `converters` has, and [`NoConverter::NoneOffers`] where no
349/// allowed converter offers the pair.
350pub fn choose_converter<'c>(
351 rule: &ConversionRule,
352 from: ImageFormat,
353 converters: &[&'c dyn GraphicsConverter],
354) -> Result<&'c dyn GraphicsConverter, NoConverter> {
355 if let Some(unknown) =
356 rule.via.iter().find(|name| !converters.iter().any(|converter| converter.name() == *name))
357 {
358 return Err(NoConverter::Unknown(unknown.clone()));
359 }
360 converters
361 .iter()
362 .copied()
363 .filter(|converter| rule.via.is_empty() || rule.via.iter().any(|name| name == converter.name()))
364 .find(|converter| converter.offers(from, rule.to))
365 .ok_or(NoConverter::NoneOffers)
366}
367
368#[cfg(test)]
369mod tests {
370 use super::*;
371
372 struct Named(&'static str, bool);
373
374 impl GraphicsConverter for Named {
375 fn name(&self) -> &str {
376 self.0
377 }
378 fn offers(&self, _from: ImageFormat, _to: ImageFormat) -> bool {
379 self.1
380 }
381 fn convert(&self, request: &ConversionRequest<'_>, _progress: &Scope) -> Result<Vec<u8>, GraphicsConvertError> {
382 Ok(request.content.to_vec())
383 }
384 }
385
386 #[test]
387 fn the_first_allowed_converter_offering_the_pair_is_chosen() {
388 let (none, first, second) = (Named("none", false), Named("first", true), Named("second", true));
389 let converters: [&dyn GraphicsConverter; 3] = [&none, &first, &second];
390 let rule = ConversionRule::new([ImageFormat::Pdf], ImageFormat::Png);
391 let chosen = |rule: &ConversionRule| {
392 choose_converter(rule, ImageFormat::Pdf, &converters).map(|converter| converter.name().to_string())
393 };
394 assert_eq!(chosen(&rule), Ok(String::from("first")));
395 assert_eq!(chosen(&rule.clone().via("second")), Ok(String::from("second")));
396 assert_eq!(chosen(&rule.clone().via("none")), Err(NoConverter::NoneOffers));
397 assert_eq!(chosen(&rule.clone().via("other")), Err(NoConverter::Unknown(String::from("other"))));
398 }
399
400 #[test]
401 fn a_rule_reads_one_format_or_a_list_and_refuses_several_targets() {
402 let one: ConversionRule =
403 serde_json::from_value(serde_json::json!({ "from": "svg", "to": "pdf" })).unwrap();
404 assert_eq!(one.from, [ImageFormat::Svg]);
405 let many: ConversionRule =
406 serde_json::from_value(serde_json::json!({ "from": ["gif", "webp"], "to": "png", "via": ["raster"] }))
407 .unwrap();
408 assert_eq!(many.from, [ImageFormat::Gif, ImageFormat::Webp]);
409 assert_eq!(many.via, ["raster"]);
410 let several: Result<ConversionRule, _> =
411 serde_json::from_value(serde_json::json!({ "from": "pdf", "to": ["png", "jpeg"] }));
412 assert!(several.is_err());
413 let unknown: Result<ConversionRule, _> =
414 serde_json::from_value(serde_json::json!({ "from": "tiff", "to": "png" }));
415 assert!(unknown.is_err());
416 }
417}