use std::borrow::Cow;
use std::fmt;
use std::sync::Arc;
use crate::core::artifact::name_safe;
use crate::lang::FlmOrigin;
pub const RESOLVER_SLOT: &str = "flm.graphics.resolver";
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[derive(serde::Deserialize, serde::Serialize, schemars::JsonSchema)]
#[serde(rename_all = "lowercase")]
pub enum ImageFormat {
Png,
Jpeg,
Gif,
Webp,
Svg,
Pdf,
}
impl ImageFormat {
pub const ALL: [ImageFormat; 6] = [
ImageFormat::Png,
ImageFormat::Jpeg,
ImageFormat::Gif,
ImageFormat::Webp,
ImageFormat::Svg,
ImageFormat::Pdf,
];
pub fn media_type(self) -> &'static str {
match self {
ImageFormat::Png => "image/png",
ImageFormat::Jpeg => "image/jpeg",
ImageFormat::Gif => "image/gif",
ImageFormat::Webp => "image/webp",
ImageFormat::Svg => "image/svg+xml",
ImageFormat::Pdf => "application/pdf",
}
}
pub fn name(self) -> &'static str {
match self {
ImageFormat::Png => "png",
ImageFormat::Jpeg => "jpeg",
ImageFormat::Gif => "gif",
ImageFormat::Webp => "webp",
ImageFormat::Svg => "svg",
ImageFormat::Pdf => "pdf",
}
}
pub fn from_media_type(media_type: &str) -> Option<ImageFormat> {
ImageFormat::ALL.into_iter().find(|format| format.media_type() == media_type)
}
pub fn from_name(name: &str) -> Option<ImageFormat> {
ImageFormat::ALL.into_iter().find(|format| format.name() == name)
}
}
impl fmt::Display for ImageFormat {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(self.name())
}
}
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub struct ImageFile {
pub identity: String,
pub media_type: String,
pub address: String,
}
impl ImageFile {
pub fn new(
identity: impl Into<String>,
media_type: impl Into<String>,
address: impl Into<String>,
) -> ImageFile {
ImageFile {
identity: identity.into(),
media_type: media_type.into(),
address: address.into(),
}
}
pub fn format(&self) -> Option<ImageFormat> {
ImageFormat::from_media_type(&self.media_type)
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ResolvedImage {
pub file: ImageFile,
pub content: Arc<[u8]>,
}
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub struct GraphicsResolveRequest {
pub path: String,
pub origin: FlmOrigin,
}
impl GraphicsResolveRequest {
pub fn new(path: impl Into<String>, origin: FlmOrigin) -> GraphicsResolveRequest {
GraphicsResolveRequest { path: path.into(), origin }
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct GraphicsResolveError {
pub detail: String,
}
impl GraphicsResolveError {
pub fn new(detail: impl Into<String>) -> GraphicsResolveError {
GraphicsResolveError { detail: detail.into() }
}
}
impl fmt::Display for GraphicsResolveError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(&self.detail)
}
}
impl std::error::Error for GraphicsResolveError {}
pub trait GraphicsResolver: Send + Sync {
fn resolve(&self, request: &GraphicsResolveRequest)
-> Result<ImageFile, GraphicsResolveError>;
fn read(&self, file: &ImageFile) -> Result<Vec<u8>, GraphicsResolveError>;
}
pub fn names_scheme(path: &str) -> bool {
let Some((scheme, _)) = path.split_once(':') else { return false };
let mut chars = scheme.chars();
scheme.len() >= 2
&& chars.next().is_some_and(|first| first.is_ascii_alphabetic())
&& chars.all(|c| c.is_ascii_alphanumeric() || matches!(c, '+' | '-' | '.'))
}
pub(crate) fn stem_of(path: &str) -> Cow<'static, str> {
let last = path.rsplit(['/', '\\']).next().unwrap_or(path);
let stem = match last.rsplit_once('.') {
Some((stem, _)) if !stem.is_empty() => stem,
_ => last,
};
if stem.is_empty() {
return Cow::Borrowed("image");
}
Cow::Owned(name_safe(stem))
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn a_scheme_is_two_characters_at_least_and_a_drive_is_none() {
assert!(names_scheme("http://x"));
assert!(names_scheme("svn+ssh://x"));
assert!(!names_scheme("c:/x"));
assert!(!names_scheme("1a:x"));
assert!(!names_scheme("fig ures:x"));
assert!(!names_scheme("plot.png"));
}
#[test]
fn the_stem_is_the_last_segment_without_its_extension() {
assert_eq!(stem_of("figures/plot.png"), "plot");
assert_eq!(stem_of("a b/my plot.v2.pdf"), "my_plot_v2");
assert_eq!(stem_of("figures/.hidden"), "_hidden");
assert_eq!(stem_of("dir/"), "image");
}
#[test]
fn every_format_reads_back_from_its_names() {
for format in ImageFormat::ALL {
assert_eq!(ImageFormat::from_name(format.name()), Some(format));
assert_eq!(ImageFormat::from_media_type(format.media_type()), Some(format));
}
}
}