flm_core/stdlib/features/graphics/resolve.rs
1//! Finding and reading the file of an image: the graphics resolver that a
2//! host supplies ([`GraphicsResolver`]), what it returns ([`ImageFile`],
3//! [`ResolvedImage`]), and the formats of image files ([`ImageFormat`]).
4//!
5//! # The graphics resolver
6//!
7//! The graphics resolver ([`GraphicsResolver`]) is the service that finds the
8//! file an image's path refers to and reads its content. A host that can read
9//! image files contributes one to the service slot [`RESOLVER_SLOT`]
10//! (`flm.graphics.resolver`, one value at most) when it builds its registry;
11//! the feature never requires one. The library itself opens no file. The
12//! converters ([`GraphicsConverter`](super::GraphicsConverter)) are given
13//! content and open nothing. The inspector
14//! ([`GraphicsInspector`](super::GraphicsInspector)) is given the file's
15//! content where a graphics resolver is registered and has read it; otherwise
16//! it receives only the path and the origin
17//! ([`GraphicsInspectRequest`](super::GraphicsInspectRequest)) and finds the
18//! file itself.
19//!
20//! The feature asks the resolver in two steps:
21//!
22//! 1. [`resolve`](GraphicsResolver::resolve) returns, for the path as written
23//! and the origin of the source the image is written in, an [`ImageFile`]:
24//! the file's **identity** in the host's own form (two images that refer to
25//! one file have the same identity), its **format** as a media type, and
26//! the **address** an output writes to reach the file where it is. The
27//! inspect stage asks it for every image.
28//! 2. [`read`](GraphicsResolver::read) returns the file's content. Only a
29//! stage that needs the content asks for it: the inspect stage where an
30//! inspector is registered to measure the content, and the publish stage
31//! where the strategy copies the file or writes it into the page.
32//!
33//! When the resolver returns an error, the stage that asked reports it
34//! ([`ResolveFailed`](super::inspect::ResolveFailed)), and the image is
35//! published by the strategy `reference`: at the path as written where the
36//! file was not found.
37//!
38//! # A path that begins with a scheme
39//!
40//! A path that begins with a scheme, such as `https://example.org/a.png` or
41//! `data:image/png;base64,…`, is not a file: it is never given to the resolver
42//! or the inspector, and every output writes it as written, regardless of the
43//! strategy ([`names_scheme`]).
44
45use std::borrow::Cow;
46use std::fmt;
47use std::sync::Arc;
48
49use crate::core::artifact::name_safe;
50use crate::lang::FlmOrigin;
51
52/// The name of the graphics resolver's service slot, `flm.graphics.resolver`:
53/// it takes one [`GraphicsResolver`] at most, which a host contributes and
54/// the feature never requires.
55pub const RESOLVER_SLOT: &str = "flm.graphics.resolver";
56
57/// The format of an image file that a conversion rule can list: one of the
58/// six kinds of image the library knows by name.
59///
60/// A file of another kind is still published, under its own media type, but
61/// no conversion rule can list it and no converter is asked about it. In
62/// settings, a format is written by its short name
63/// ([`name`](ImageFormat::name)): `png`, `jpeg`, `gif`, `webp`, `svg`,
64/// `pdf`.
65///
66/// # Examples
67///
68/// ```
69/// use flm_core::stdlib::features::graphics::ImageFormat;
70///
71/// assert_eq!(ImageFormat::Pdf.media_type(), "application/pdf");
72/// assert_eq!(ImageFormat::from_media_type("image/svg+xml"), Some(ImageFormat::Svg));
73/// assert_eq!(ImageFormat::from_name("jpeg"), Some(ImageFormat::Jpeg));
74/// ```
75#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
76#[derive(serde::Deserialize, serde::Serialize, schemars::JsonSchema)]
77#[serde(rename_all = "lowercase")]
78pub enum ImageFormat {
79 /// A PNG image, `image/png`: a grid of pixels.
80 Png,
81 /// A JPEG image, `image/jpeg`: a grid of pixels.
82 Jpeg,
83 /// A GIF image, `image/gif`: a grid of pixels, possibly animated.
84 Gif,
85 /// A WebP image, `image/webp`: a grid of pixels.
86 Webp,
87 /// An SVG drawing, `image/svg+xml`.
88 Svg,
89 /// A PDF document, `application/pdf`, whose first page is the drawing.
90 Pdf,
91}
92
93impl ImageFormat {
94 /// The six formats, in the order of the enumeration's variants.
95 pub const ALL: [ImageFormat; 6] = [
96 ImageFormat::Png,
97 ImageFormat::Jpeg,
98 ImageFormat::Gif,
99 ImageFormat::Webp,
100 ImageFormat::Svg,
101 ImageFormat::Pdf,
102 ];
103
104 /// Returns the format's media type, such as `image/png`.
105 pub fn media_type(self) -> &'static str {
106 match self {
107 ImageFormat::Png => "image/png",
108 ImageFormat::Jpeg => "image/jpeg",
109 ImageFormat::Gif => "image/gif",
110 ImageFormat::Webp => "image/webp",
111 ImageFormat::Svg => "image/svg+xml",
112 ImageFormat::Pdf => "application/pdf",
113 }
114 }
115
116 /// Returns the format's short name, as settings write it, such as `png`.
117 pub fn name(self) -> &'static str {
118 match self {
119 ImageFormat::Png => "png",
120 ImageFormat::Jpeg => "jpeg",
121 ImageFormat::Gif => "gif",
122 ImageFormat::Webp => "webp",
123 ImageFormat::Svg => "svg",
124 ImageFormat::Pdf => "pdf",
125 }
126 }
127
128 /// Returns the format whose media type is `media_type`, if it is one of
129 /// the six.
130 pub fn from_media_type(media_type: &str) -> Option<ImageFormat> {
131 ImageFormat::ALL.into_iter().find(|format| format.media_type() == media_type)
132 }
133
134 /// Returns the format whose short name is `name`, if it is one of the
135 /// six.
136 pub fn from_name(name: &str) -> Option<ImageFormat> {
137 ImageFormat::ALL.into_iter().find(|format| format.name() == name)
138 }
139}
140
141impl fmt::Display for ImageFormat {
142 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
143 f.write_str(self.name())
144 }
145}
146
147/// What the graphics resolver returns about the file of an image: its
148/// identity, its format and the address that reaches it where it is. It
149/// holds no content: the stage that needs the content asks the resolver for
150/// it ([`GraphicsResolver::read`]).
151///
152/// The record of each image holds it
153/// ([`GraphicsRecord::file`](super::GraphicsRecord::file)).
154#[derive(Debug, Clone, PartialEq, Eq, Hash)]
155#[non_exhaustive]
156pub struct ImageFile {
157 /// The file's identity, in the host's own form: two images that refer to
158 /// one file have the same identity, regardless of their paths as written.
159 /// The resolver reads the file by it.
160 pub identity: String,
161 /// The file's format, as a media type (`image/png`), which the resolver
162 /// reads from the content where it can, else from the file's name. See
163 /// [`ImageFormat::from_media_type`] for the formats a conversion rule can
164 /// list.
165 pub media_type: String,
166 /// The address an output writes to reach the file where it is, under
167 /// the strategy `reference`.
168 pub address: String,
169}
170
171impl ImageFile {
172 /// Returns the file of identity `identity`, of the media type
173 /// `media_type`, reached at `address`.
174 pub fn new(
175 identity: impl Into<String>,
176 media_type: impl Into<String>,
177 address: impl Into<String>,
178 ) -> ImageFile {
179 ImageFile {
180 identity: identity.into(),
181 media_type: media_type.into(),
182 address: address.into(),
183 }
184 }
185
186 /// Returns the file's format, where it is one of the six that a
187 /// conversion rule can list.
188 pub fn format(&self) -> Option<ImageFormat> {
189 ImageFormat::from_media_type(&self.media_type)
190 }
191}
192
193/// A file found and read by the graphics resolver: what the inspector is
194/// given
195/// ([`GraphicsInspectRequest::resolved`](super::GraphicsInspectRequest::resolved)).
196#[derive(Debug, Clone, PartialEq, Eq)]
197pub struct ResolvedImage {
198 /// The file, as the resolver returned it.
199 pub file: ImageFile,
200 /// The file's content.
201 pub content: Arc<[u8]>,
202}
203
204/// What the feature asks a graphics resolver about one image.
205///
206/// New fields may be added in later versions: a resolver reads the fields it
207/// needs, and a request is built with [`new`](GraphicsResolveRequest::new).
208#[derive(Debug, Clone, PartialEq, Eq)]
209#[non_exhaustive]
210pub struct GraphicsResolveRequest {
211 /// The path, as the author wrote it.
212 pub path: String,
213 /// The origin of the source the image is written in, from which a
214 /// relative path is found, as for
215 /// [`GraphicsInspectRequest::origin`](super::GraphicsInspectRequest::origin).
216 pub origin: FlmOrigin,
217}
218
219impl GraphicsResolveRequest {
220 /// Returns the request for the path `path`, written in the source of
221 /// origin `origin`.
222 pub fn new(path: impl Into<String>, origin: FlmOrigin) -> GraphicsResolveRequest {
223 GraphicsResolveRequest { path: path.into(), origin }
224 }
225}
226
227/// Why a graphics resolver could not find or read a file, in the resolver's
228/// own words, which the Error the feature reports shows
229/// ([`ResolveFailed`](super::inspect::ResolveFailed)).
230#[derive(Debug, Clone, PartialEq, Eq)]
231pub struct GraphicsResolveError {
232 /// What went wrong, as the resolver says it, such as `no file named
233 /// plot.png in the folders figures, .`.
234 pub detail: String,
235}
236
237impl GraphicsResolveError {
238 /// Returns the error with the text `detail`.
239 pub fn new(detail: impl Into<String>) -> GraphicsResolveError {
240 GraphicsResolveError { detail: detail.into() }
241 }
242}
243
244impl fmt::Display for GraphicsResolveError {
245 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
246 f.write_str(&self.detail)
247 }
248}
249
250impl std::error::Error for GraphicsResolveError {}
251
252/// The **graphics resolver**: a service that finds and reads image files,
253/// which a host contributes to the service slot [`RESOLVER_SLOT`]. See the
254/// [module documentation](self).
255///
256/// # Examples
257///
258/// ```
259/// use std::sync::Arc;
260///
261/// use flm_core::core::registry::RegistryBuilder;
262/// use flm_core::stdlib::features::graphics::{
263/// GraphicsResolveError, GraphicsResolveRequest, GraphicsResolver, ImageFile, RESOLVER_SLOT,
264/// };
265///
266/// /// Every path refers to the same one-byte PNG file.
267/// struct OneFile;
268///
269/// impl GraphicsResolver for OneFile {
270/// fn resolve(&self, request: &GraphicsResolveRequest) -> Result<ImageFile, GraphicsResolveError> {
271/// Ok(ImageFile::new("the-file", "image/png", request.path.clone()))
272/// }
273///
274/// fn read(&self, _file: &ImageFile) -> Result<Vec<u8>, GraphicsResolveError> {
275/// Ok(vec![0])
276/// }
277/// }
278///
279/// let mut builder = RegistryBuilder::new();
280/// builder.contribute_to(RESOLVER_SLOT, Arc::new(OneFile) as Arc<dyn GraphicsResolver>);
281/// ```
282pub trait GraphicsResolver: Send + Sync {
283 /// Returns the file that `request.path` refers to, found from
284 /// `request.origin`.
285 ///
286 /// # Errors
287 ///
288 /// A [`GraphicsResolveError`] in the resolver's own words when no file is
289 /// found or the file cannot be read.
290 fn resolve(&self, request: &GraphicsResolveRequest)
291 -> Result<ImageFile, GraphicsResolveError>;
292
293 /// Returns the content of `file`, a file this resolver returned. The
294 /// feature calls it again whenever it needs the content.
295 ///
296 /// # Errors
297 ///
298 /// A [`GraphicsResolveError`] in the resolver's own words when the file
299 /// can no longer be read.
300 fn read(&self, file: &ImageFile) -> Result<Vec<u8>, GraphicsResolveError>;
301}
302
303/// Returns whether `path` begins with a scheme, as an address on the web does
304/// (`https://…`, `data:…`, `file:…`): a letter, then letters, digits, `+`, `-`
305/// or `.`, then a colon, the scheme being at least two characters long. A
306/// single letter before a colon is a drive (`C:\figures\plot.png`), not a
307/// scheme. Such a path is not a file: see the [module
308/// documentation](self#a-path-that-begins-with-a-scheme).
309///
310/// # Examples
311///
312/// ```
313/// use flm_core::stdlib::features::graphics::names_scheme;
314///
315/// assert!(names_scheme("https://example.org/a.png"));
316/// assert!(names_scheme("data:image/png;base64,AAAA"));
317/// assert!(!names_scheme("figures/plot.png"));
318/// assert!(!names_scheme("C:/figures/plot.png"));
319/// ```
320pub fn names_scheme(path: &str) -> bool {
321 let Some((scheme, _)) = path.split_once(':') else { return false };
322 let mut chars = scheme.chars();
323 scheme.len() >= 2
324 && chars.next().is_some_and(|first| first.is_ascii_alphabetic())
325 && chars.all(|c| c.is_ascii_alphanumeric() || matches!(c, '+' | '-' | '.'))
326}
327
328/// Returns the file's stem, with which the name of a copy begins: the last
329/// segment of `path` without its extension, every character other than an
330/// ASCII letter, a digit, `-` and `_` written `_`, and `image` where nothing
331/// is left.
332pub(crate) fn stem_of(path: &str) -> Cow<'static, str> {
333 let last = path.rsplit(['/', '\\']).next().unwrap_or(path);
334 let stem = match last.rsplit_once('.') {
335 Some((stem, _)) if !stem.is_empty() => stem,
336 _ => last,
337 };
338 if stem.is_empty() {
339 return Cow::Borrowed("image");
340 }
341 Cow::Owned(name_safe(stem))
342}
343
344#[cfg(test)]
345mod tests {
346 use super::*;
347
348 #[test]
349 fn a_scheme_is_two_characters_at_least_and_a_drive_is_none() {
350 assert!(names_scheme("http://x"));
351 assert!(names_scheme("svn+ssh://x"));
352 assert!(!names_scheme("c:/x"));
353 assert!(!names_scheme("1a:x"));
354 assert!(!names_scheme("fig ures:x"));
355 assert!(!names_scheme("plot.png"));
356 }
357
358 #[test]
359 fn the_stem_is_the_last_segment_without_its_extension() {
360 assert_eq!(stem_of("figures/plot.png"), "plot");
361 assert_eq!(stem_of("a b/my plot.v2.pdf"), "my_plot_v2");
362 assert_eq!(stem_of("figures/.hidden"), "_hidden");
363 assert_eq!(stem_of("dir/"), "image");
364 }
365
366 #[test]
367 fn every_format_reads_back_from_its_names() {
368 for format in ImageFormat::ALL {
369 assert_eq!(ImageFormat::from_name(format.name()), Some(format));
370 assert_eq!(ImageFormat::from_media_type(format.media_type()), Some(format));
371 }
372 }
373}