use std::collections::BTreeMap;
use std::hash::Hash;
use std::sync::Arc;
use base64::Engine as _;
use techy::core::node::NodeRef;
use techy::error::{Diagnostic, DiagnosticInfo};
use techy::serialize::SerialValue;
use crate::core::artifact::{Artifact, ArtifactId, ArtifactNamer, ArtifactRef, ArtifactSet, NamingScope, digest_name};
use crate::core::data::store::StageOut;
use crate::core::data::table::{ProjectCx, Table, TableHandle, TableName};
use crate::core::plan::PlanCx;
use crate::core::registry::{BuildError, FeatureBuilder};
use crate::core::run::StageCx;
use crate::core::stage::{Effect, Needs, Scope, Stage, StageDecl};
use crate::lang::{Flm, FlmDiagnostic, FlmSpan};
use crate::model::addr::NodeAddr;
use crate::model::digest::Fnv1a64;
use crate::model::names::StageName;
use crate::progress::{self, Counted, Kind, Unit};
use crate::stdlib::backends::lowering::NAMER_SLOT;
use crate::stdlib::backends::pres::SrcsetCandidate;
use crate::stdlib::backends::{html, latex_recomposed, latex_rendered};
use crate::stdlib::features::index::ELEMENT_INDEX;
use super::convert::{
CONVERTERS_SLOT, ConversionOptions, ConversionRequest, ConversionRule, GraphicsConverter,
NoConverter, choose_converter,
};
use super::inspect::{GraphicsInfo, GraphicsRecord, INFO, ResolveFailed, stage_failed};
use super::resolve::{GraphicsResolver, ImageFile, ImageFormat, RESOLVER_SLOT, names_scheme, stem_of};
use super::strategy::{GraphicsRenderOptions, Strategy};
use super::{FEATURE, GraphicsImage, ImagePath, read_path};
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct PublishedImage {
pub src: String,
pub srcset: Vec<SrcsetCandidate>,
}
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct GraphicsPublished {
images: BTreeMap<NodeAddr, PublishedImage>,
}
impl GraphicsPublished {
pub fn get(&self, addr: NodeAddr) -> Option<&PublishedImage> {
self.images.get(&addr)
}
pub fn iter(&self) -> impl Iterator<Item = (NodeAddr, &PublishedImage)> + '_ {
self.images.iter().map(|(addr, image)| (*addr, image))
}
pub fn len(&self) -> usize {
self.images.len()
}
pub fn is_empty(&self) -> bool {
self.images.is_empty()
}
}
impl Table for GraphicsPublished {
fn absorb(&mut self, piece: GraphicsPublished) {
self.images.extend(piece.images);
}
fn project(&self, cx: &dyn ProjectCx) -> SerialValue {
SerialValue::List(
self.images
.iter()
.map(|(addr, image)| {
let mut entries = vec![
(String::from("node"), cx.node_ref(*addr)),
(String::from("src"), SerialValue::Str(image.src.clone())),
];
if !image.srcset.is_empty() {
entries.push((
String::from("srcset"),
SerialValue::List(
image
.srcset
.iter()
.map(|candidate| {
SerialValue::Str(format!(
"{} {}",
candidate.src, candidate.descriptor
))
})
.collect(),
),
));
}
SerialValue::Map(entries)
})
.collect(),
)
}
}
pub fn published_table(backend: &str) -> TableHandle<GraphicsPublished> {
TableHandle::new(format!("flm.graphics.published.{backend}"))
}
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct ImageContent {
pub src: String,
pub media_type: String,
pub content: Vec<u8>,
}
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct GraphicsContent {
images: BTreeMap<NodeAddr, ImageContent>,
}
impl GraphicsContent {
pub fn get(&self, addr: NodeAddr) -> Option<&ImageContent> {
self.images.get(&addr)
}
pub fn iter(&self) -> impl Iterator<Item = (NodeAddr, &ImageContent)> + '_ {
self.images.iter().map(|(addr, image)| (*addr, image))
}
pub fn len(&self) -> usize {
self.images.len()
}
pub fn is_empty(&self) -> bool {
self.images.is_empty()
}
}
impl Table for GraphicsContent {
fn absorb(&mut self, piece: GraphicsContent) {
self.images.extend(piece.images);
}
fn project(&self, cx: &dyn ProjectCx) -> SerialValue {
SerialValue::List(
self.images
.iter()
.map(|(addr, image)| {
SerialValue::Map(vec![
(String::from("node"), cx.node_ref(*addr)),
(String::from("src"), SerialValue::Str(image.src.clone())),
(String::from("media_type"), SerialValue::Str(image.media_type.clone())),
(String::from("content"), content_value(&image.content)),
])
})
.collect(),
)
}
}
fn content_value(bytes: &[u8]) -> SerialValue {
let entry = match std::str::from_utf8(bytes) {
Ok(text) => (String::from("text"), SerialValue::Str(text.to_string())),
Err(_) => {
(String::from("base64"), SerialValue::Str(base64::engine::general_purpose::STANDARD.encode(bytes)))
}
};
SerialValue::Map(vec![entry])
}
pub fn content_table(backend: &str) -> TableHandle<GraphicsContent> {
TableHandle::new(format!("flm.graphics.content.{backend}"))
}
pub fn publish_stage_name(backend: &str) -> StageName {
StageName::from(format!("flm.graphics.publish.{backend}"))
}
pub const IMAGES_KIND: Kind = Kind::new("flm.graphics.images");
pub const CONVERT_KIND: Kind = Kind::titled("flm.graphics.convert", "Converting graphics");
#[derive(Debug, Clone, Copy)]
pub struct OutputImages {
pub artifacts: Option<TableName<ArtifactSet>>,
pub data_address: bool,
}
pub fn output_images(backend: &str) -> OutputImages {
match backend {
html::BACKEND => OutputImages { artifacts: Some(html::ARTIFACTS), data_address: true },
latex_recomposed::BACKEND => {
OutputImages { artifacts: Some(latex_recomposed::ARTIFACTS), data_address: false }
}
latex_rendered::BACKEND => {
OutputImages { artifacts: Some(latex_rendered::ARTIFACTS), data_address: false }
}
_ => OutputImages { artifacts: None, data_address: false },
}
}
#[derive(Debug, Clone, PartialEq, Eq, DiagnosticInfo)]
#[diagnostic(
id = "flm.graphics.needs-resolver",
message = "Unsupported strategy ‘{strategy}’ for output ‘{output}’ (image file ‘{path}’): \
reading image files is not available"
)]
pub struct NeedsResolver {
pub output: String,
pub path: String,
pub strategy: String,
}
#[derive(Debug, Clone, PartialEq, Eq, DiagnosticInfo)]
#[diagnostic(
id = "flm.graphics.needs-namer",
message = "Unsupported strategy ‘copy’ for output ‘{output}’ (image file ‘{path}’): \
choosing file names for copies is not available"
)]
pub struct NeedsNamer {
pub output: String,
pub path: String,
}
#[derive(Debug, Clone, PartialEq, Eq, DiagnosticInfo)]
#[diagnostic(
id = "flm.graphics.copy-in-one-file",
message = "Unsupported strategy ‘copy’ for output ‘{output}’ (image file ‘{path}’): \
this output is a single file"
)]
pub struct CopyInOneFile {
pub output: String,
pub path: String,
}
#[derive(Debug, Clone, PartialEq, Eq, DiagnosticInfo)]
#[diagnostic(
id = "flm.graphics.data-uri-not-shown",
message = "Unsupported strategy ‘data-uri’ for output ‘{output}’ (image file ‘{path}’): \
this output cannot use ‘data:’ addresses"
)]
pub struct DataUriNotShown {
pub output: String,
pub path: String,
}
#[derive(Debug, Clone, PartialEq, Eq, DiagnosticInfo)]
#[diagnostic(
id = "flm.graphics.unknown-converter",
message = "Unknown converter ‘{converter}’ in ‘via’ of the conversion rule from ‘{from}’ \
to ‘{to}’ for output ‘{output}’"
)]
pub struct UnknownConverter {
pub output: String,
pub from: String,
pub to: String,
pub converter: String,
}
#[derive(Debug, Clone, PartialEq, Eq, DiagnosticInfo)]
#[diagnostic(
id = "flm.graphics.no-converter",
message = "No converter available to convert image file ‘{path}’ from ‘{from}’ to ‘{to}’ \
(conversion rule for output ‘{output}’)"
)]
pub struct NoConverterOffers {
pub output: String,
pub path: String,
pub from: String,
pub to: String,
}
#[derive(Debug, Clone, PartialEq, Eq, DiagnosticInfo)]
#[diagnostic(
id = "flm.graphics.conversion-failed",
message = "Failed to convert image file ‘{path}’ from ‘{from}’ to ‘{to}’ with converter \
‘{converter}’: {detail}"
)]
pub struct ConversionFailed {
pub path: String,
pub from: String,
pub to: String,
pub converter: String,
pub detail: String,
}
struct Publishing<'r> {
output: &'r str,
strategy: Strategy,
rules: &'r [ConversionRule],
resolver: Option<&'r dyn GraphicsResolver>,
converters: Vec<&'r dyn GraphicsConverter>,
namer: Option<&'r dyn ArtifactNamer>,
scope: &'r NamingScope,
holds: OutputImages,
}
struct Content {
bytes: Vec<u8>,
media_type: String,
options: Option<ConversionOptions>,
}
struct Publication {
src: String,
copy: Option<Artifact>,
content: Option<Content>,
}
impl Publication {
fn at(src: String) -> Publication {
Publication { src, copy: None, content: None }
}
}
enum Unread {
Quietly,
CopyInOneFile,
DataUriNotShown,
NeedsResolver,
NeedsNamer,
}
impl<'r> Publishing<'r> {
fn readable<'f>(
&self,
path: &str,
file: Option<&'f ImageFile>,
) -> Result<(&'r dyn GraphicsResolver, &'f ImageFile), Unread> {
if names_scheme(path) || !self.strategy.needs_content() {
return Err(Unread::Quietly);
}
match self.strategy {
Strategy::Copy if self.holds.artifacts.is_none() => return Err(Unread::CopyInOneFile),
Strategy::DataUri if !self.holds.data_address => return Err(Unread::DataUriNotShown),
_ => {}
}
let resolver = self.resolver.ok_or(Unread::NeedsResolver)?;
let file = file.ok_or(Unread::Quietly)?;
if self.strategy == Strategy::Copy && self.namer.is_none() {
return Err(Unread::NeedsNamer);
}
Ok((resolver, file))
}
fn report_unread(&self, unread: Unread, path: &str, span: &FlmSpan, diags: &mut Vec<FlmDiagnostic>) {
if matches!(unread, Unread::Quietly) {
return;
}
let (output, path, span) = (self.output.to_string(), path.to_string(), span.clone());
match unread {
Unread::Quietly => {}
Unread::CopyInOneFile => diags.push(Diagnostic::error(CopyInOneFile { output, path }, span)),
Unread::DataUriNotShown => diags.push(Diagnostic::error(DataUriNotShown { output, path }, span)),
Unread::NeedsResolver => {
let strategy = self.strategy.name().to_string();
diags.push(Diagnostic::error(NeedsResolver { output, path, strategy }, span));
}
Unread::NeedsNamer => diags.push(Diagnostic::error(NeedsNamer { output, path }, span)),
}
}
fn rule_for(&self, file: &ImageFile) -> Option<(ImageFormat, &'r ConversionRule)> {
let from = file.format()?;
self.rules.iter().find(|rule| rule.applies_to(from)).map(|rule| (from, rule))
}
fn converts(&self, path: &str, record: Option<&GraphicsRecord>) -> bool {
let file = record.and_then(|record| record.file.as_ref());
self.readable(path, file).is_ok_and(|(_, file)| self.rule_for(file).is_some())
}
fn publish(
&self,
node: &NodeRef<'_, Flm>,
path: &str,
record: Option<&GraphicsRecord>,
images: &Counted,
diags: &mut Vec<FlmDiagnostic>,
) -> Publication {
let file = record.and_then(|record| record.file.as_ref());
let reference = file.map_or_else(|| path.to_string(), |file| file.address.clone());
let (resolver, file) = match self.readable(path, file) {
Ok(readable) => readable,
Err(unread) => {
self.report_unread(unread, path, node.span(), diags);
return Publication::at(reference);
}
};
let original = match resolver.read(file) {
Ok(bytes) => bytes,
Err(failed) => {
let failed = ResolveFailed { path: path.to_string(), detail: failed.detail };
diags.push(Diagnostic::error(failed, node.span().clone()));
return Publication::at(reference);
}
};
let content = self.convert(node, path, file, &original, images, diags);
match self.strategy {
Strategy::Reference => Publication::at(reference),
Strategy::Content => Publication { src: reference, copy: None, content: Some(content) },
Strategy::DataUri => {
let encoded = base64::engine::general_purpose::STANDARD.encode(&content.bytes);
Publication::at(format!("data:{};base64,{encoded}", content.media_type))
}
Strategy::Copy => {
let Some(namer) = self.namer else { return Publication::at(reference) };
let id = ArtifactId::new(FEATURE, copy_name(path, &original, &content));
let extension = ImageFormat::from_media_type(&content.media_type).map(ImageFormat::name);
let artifact = ArtifactRef {
id: &id,
entry: false,
media_type: &content.media_type,
extension,
output: None,
folder: false,
};
let address = namer.url_of(&artifact, self.scope);
let mut copy = Artifact::bytes(id, content.media_type, content.bytes);
copy.extension = extension.map(String::from);
Publication { src: address.as_str().to_string(), copy: Some(copy), content: None }
}
}
}
fn convert(
&self,
node: &NodeRef<'_, Flm>,
path: &str,
file: &ImageFile,
original: &[u8],
images: &Counted,
diags: &mut Vec<FlmDiagnostic>,
) -> Content {
let unconverted = || Content {
bytes: original.to_vec(),
media_type: file.media_type.clone(),
options: None,
};
let Some((from, rule)) = self.rule_for(file) else { return unconverted() };
let span = node.span().clone();
let (from_name, to_name) = (from.name().to_string(), rule.to.name().to_string());
let converter = match choose_converter(rule, from, &self.converters) {
Ok(converter) => converter,
Err(NoConverter::Unknown(converter)) => {
let output = self.output.to_string();
let unknown = UnknownConverter { output, from: from_name, to: to_name, converter };
diags.push(Diagnostic::error(unknown, span));
return unconverted();
}
Err(NoConverter::NoneOffers) => {
let none = NoConverterOffers {
output: self.output.to_string(),
path: path.to_string(),
from: from_name,
to: to_name,
};
diags.push(Diagnostic::error(none, span));
return unconverted();
}
};
let request = ConversionRequest::new(original, from, rule.to, &rule.options);
let row = images.scope().child(&CONVERT_KIND, Some(path)).start();
match converter.convert(&request, &row.scope()) {
Ok(bytes) => {
row.finish();
Content { bytes, media_type: rule.to.media_type().to_string(), options: Some(rule.options) }
}
Err(failed) => {
let failed = ConversionFailed {
path: path.to_string(),
from: from_name,
to: to_name,
converter: converter.name().to_string(),
detail: failed.detail,
};
diags.push(Diagnostic::error(failed, span));
unconverted()
}
}
}
}
fn copy_name(path: &str, original: &[u8], content: &Content) -> String {
let mut digest = Fnv1a64::new();
digest.write_bytes(original);
digest.write_str(&content.media_type);
content.options.hash(&mut digest);
digest_name(&stem_of(path), &digest)
}
#[derive(Debug, Clone)]
pub struct PublishStage {
backend: String,
}
impl PublishStage {
pub fn new(backend: impl Into<String>) -> PublishStage {
PublishStage { backend: backend.into() }
}
}
impl Stage for PublishStage {
fn decl(&self) -> StageDecl {
let decl = StageDecl::new(publish_stage_name(&self.backend), Effect::Compute, Scope::PerTree)
.writes(published_table(&self.backend))
.writes(content_table(&self.backend));
let decl = match output_images(&self.backend).artifacts {
Some(table) => decl.writes(table),
None => decl,
};
let backend = &self.backend;
let copies = match output_images(backend).artifacts {
Some(table) => format!(
" Under the strategy `copy`, writes the copies of the image files into `{}`.",
table.name()
),
None => String::new(),
};
decl.docs(format!(
"Writes the address at which the `{backend}` output refers to each image into \
`flm.graphics.published.{backend}`, according to the strategy set for this output. \
Under the strategy `content`, writes the content of each image file into \
`flm.graphics.content.{backend}`.{copies} Reports an error for each image whose \
strategy or conversion cannot be carried out."
))
}
fn needs(&self, _cx: &PlanCx<'_>) -> Needs {
Needs::new().reads(ELEMENT_INDEX).reads(INFO).option::<GraphicsRenderOptions>()
}
fn run(&self, cx: &StageCx<'_>, out: &mut StageOut<'_>) {
let (Some(id), Some(tree)) = (cx.tree_id(), cx.my_tree()) else { return };
let stage = publish_stage_name(&self.backend);
let index = match cx.get(ELEMENT_INDEX) {
Ok(Some(index)) => index,
Ok(None) => return,
Err(error) => return stage_failed(out, stage.as_str(), error),
};
let info: Option<&GraphicsInfo> = match cx.get(INFO) {
Ok(info) => info,
Err(error) => return stage_failed(out, stage.as_str(), error),
};
let options = match cx.option::<GraphicsRenderOptions>() {
Ok(options) => options,
Err(error) => return stage_failed(out, stage.as_str(), error),
};
let services = cx.registry().services();
let scope = NamingScope::of(cx.registry(), cx.plan().demands());
let publishing = Publishing {
output: &self.backend,
strategy: options.strategy_for(&self.backend),
rules: options.rules_for(&self.backend),
resolver: services.service_named::<dyn GraphicsResolver>(RESOLVER_SLOT),
converters: services.services_by_precedence_named::<dyn GraphicsConverter>(CONVERTERS_SLOT).collect(),
namer: services.service_named::<dyn ArtifactNamer>(NAMER_SLOT),
scope: &scope,
holds: output_images(&self.backend),
};
let images: Vec<_> = index
.values_of::<GraphicsImage>(id, &tree)
.filter_map(|(addr, node, _)| match read_path(&node) {
Ok(ImagePath::Read(path)) => {
let record = info.and_then(|info| info.get(addr));
let converts = publishing.converts(&path, record);
Some((addr, node, path, record, converts))
}
_ => None,
})
.collect();
let total = images.iter().filter(|(.., converts)| *converts).count() as u64;
let no_row = progress::Scope::none();
let parent = if total == 0 { &no_row } else { cx.progress() };
let label = cx.fragment(id).and_then(|fragment| fragment.source().origin().canonical_path());
let converting = parent.child(&IMAGES_KIND, label).start_counted(Unit::Items, total);
let mut published = GraphicsPublished::default();
let mut contents = GraphicsContent::default();
let mut copies = ArtifactSet::new();
let mut diags = Vec::new();
let mut first = true;
for (addr, node, path, record, converts) in images {
if converts {
if !first && cx.progress().cancelled() {
return;
}
first = false;
}
let Publication { src, copy, content } =
publishing.publish(&node, &path, record, &converting, &mut diags);
if converts {
converting.advance(1);
}
if let Some(content) = content {
let image = ImageContent { src: src.clone(), media_type: content.media_type, content: content.bytes };
contents.images.insert(addr, image);
}
if let Some(copy) = copy {
let mut one = ArtifactSet::new();
one.insert(copy)
.expect("a new artifact set accepts one artifact that is not an entry artifact");
copies.absorb(one);
}
published.images.insert(addr, PublishedImage { src, srcset: Vec::new() });
}
converting.finish();
for diagnostic in diags {
out.diags.push(diagnostic);
}
match out.table(&published_table(&self.backend)) {
Ok(table) => *table = published,
Err(error) => return stage_failed(out, stage.as_str(), error),
}
match out.table(&content_table(&self.backend)) {
Ok(table) => *table = contents,
Err(error) => return stage_failed(out, stage.as_str(), error),
}
if let (Some(table), false) = (publishing.holds.artifacts, id.is_value()) {
match out.table(table) {
Ok(written) => *written = copies,
Err(error) => stage_failed(out, stage.as_str(), error),
}
}
}
}
pub(super) fn register(b: &mut FeatureBuilder<'_>, backend: &str) -> Result<(), BuildError> {
b.peer_backend(
backend,
format!(
"the `{backend}` backend, for which the publish stage computes the address of each image"
),
)?;
b.table_named::<GraphicsPublished>(
published_table(backend).name().clone(),
format!(
"The address at which the `{backend}` output refers to each image, keyed by the \
address of the image's node."
),
)?;
b.table_named::<GraphicsContent>(
content_table(backend).name().clone(),
format!(
"The content of each image file under the strategy `content`, for a stage of the \
`{backend}` output that renders images itself, keyed by the address of the image's \
node. Empty under the other strategies."
),
)?;
if let Some(table) = output_images(backend).artifacts {
b.peer_table::<ArtifactSet>(
table.name(),
format!(
"the artifact table of the `{backend}` output, into which the publish stage writes \
the copies of image files"
),
)?;
}
b.stage(Arc::new(PublishStage::new(backend)))
}