pub mod convert;
pub mod handler;
pub mod inspect;
pub mod latex;
pub mod options;
pub mod publish;
pub mod resolve;
pub mod rules;
pub mod strategy;
use std::sync::Arc;
use techy::core::node::NodeRef;
use techy::error::DiagnosticInfo;
use crate::core::settings::SettingsDecl;
use crate::model::options::Bind;
use crate::core::lowering::chars_at_lowering;
use crate::core::registry::{BuildError, FeatureBuilder, FeatureInfo, FlmFeature};
use crate::core::services::Arity;
use crate::lang::mint::{ArgDef, ArgStdKind, ElementDef, ScopedPackageDef, SyntaxDef};
use crate::lang::Flm;
use crate::model::aspects::{ApartFromText, BlockRole, BlockRoleAspect, ContentRef};
use crate::model::element::{ElementSpec, element_of};
use crate::model::names::{FeatureName, Name};
use crate::stdlib::backends::lowering::rules::owning_callable;
use crate::stdlib::backends::{html, text};
use crate::stdlib::features::floats::{CONTENT_SLOT, FLOAT, FloatContentHandler};
pub use convert::{
CONVERTERS_SLOT, ConversionOptions, ConversionRequest, ConversionRule, GraphicsConvertError,
GraphicsConverter, NoConverter, choose_converter,
};
pub use handler::IncludeGraphicsContent;
pub use inspect::{
Dimensions, GraphicsInfo, GraphicsInspectError, GraphicsInspectRequest,
GraphicsInspectedInformation, GraphicsInspector, GraphicsRecord, PixelSize,
};
pub use publish::{
CONVERT_KIND, GraphicsContent, GraphicsPublished, IMAGES_KIND, ImageContent, OutputImages,
PublishStage, PublishedImage, content_table, output_images, published_table,
};
pub use resolve::{
GraphicsResolveError, GraphicsResolveRequest, GraphicsResolver, ImageFile, ImageFormat,
RESOLVER_SLOT, ResolvedImage, names_scheme,
};
pub use strategy::{Factor, FactorError, GraphicsRenderOptions, Magnification, Strategy};
pub use rules::{ImageRule, UnknownSize, image_rule};
pub const FEATURE: &str = "graphics";
fn settings() -> SettingsDecl {
SettingsDecl::new(FEATURE)
.config::<GraphicsConfig>(
"Whether `\\includegraphics` can be written wherever text can be written (`global`). \
When `global` is false, which is the default, the command is available only in the \
bodies of the float types that allow it, such as `figure` and `table`. This \
configuration is fixed when the registry is built; it cannot vary per document or \
per render.",
)
.options::<GraphicsRenderOptions>(
Bind::Render,
"The image settings of each output, set per render request. Each key maps the name \
of an output to the value for this output. `strategy` selects how the output refers \
to its images: `reference` (the default) refers to the file where it is, `copy` \
makes a copy of the file part of the output, `data-uri` writes the content of the \
file into a `data:` address, and `content` passes the content of the file to an \
output that renders images itself. `convert` lists the conversion rules that the \
output applies to image files under the strategies `copy`, `data-uri` and \
`content`. `magnification` contains the factors by which the output multiplies the \
size of raster images and of vector images (`raster` and `vector`, 1 by default).",
)
.merge_entries("strategy", || Ok(serde_json::Value::Object(serde_json::Map::new())))
.remove_false("strategy")
.merge_entries("convert", || Ok(serde_json::Value::Object(serde_json::Map::new())))
.remove_false("convert")
.merge_entries("magnification", || Ok(serde_json::Value::Object(serde_json::Map::new())))
.remove_false("magnification")
}
pub const IMAGE_ELEMENT: &str = "flm.graphics.image";
pub const INCLUDEGRAPHICS_PACKAGE: &str = "flm.graphics.includegraphics";
pub const COMMAND: &str = "includegraphics";
pub const OPTIONS_ARG: &str = "options";
pub const PATH_ARG: &str = "path";
pub const PATH_ARG_ROLE: &str = "flm.graphics.path";
pub const INSPECTOR_SLOT: &str = "flm.graphics.inspector";
pub use inspect::{INFO, INSPECT_STAGE};
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash, serde::Deserialize)]
#[derive(schemars::JsonSchema)]
#[serde(default, deny_unknown_fields)]
pub struct GraphicsConfig {
pub global: bool,
}
impl GraphicsConfig {
pub fn new() -> GraphicsConfig {
GraphicsConfig::default()
}
pub fn global(mut self, global: bool) -> GraphicsConfig {
self.global = global;
self
}
pub fn digest_bytes(&self) -> Vec<u8> {
let GraphicsConfig { global } = self;
vec![u8::from(*global)]
}
}
#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]
pub struct GraphicsImage;
impl BlockRoleAspect for GraphicsImage {
fn block_role(&self, node: &NodeRef<'_, Flm>) -> BlockRole {
let in_float_body = owning_callable(node).is_some_and(|owner| {
element_of(&owner).name.as_str() == FLOAT
&& owner.body().is_some_and(|body| body.iter().any(|child| child.id() == node.id()))
});
if in_float_body { BlockRole::Block } else { BlockRole::DEFAULT }
}
}
impl ApartFromText for GraphicsImage {
fn apart_from_text(&self, _node: &NodeRef<'_, Flm>) -> Vec<ContentRef> {
vec![
ContentRef::ArgumentNamed(OPTIONS_ARG.to_string()),
ContentRef::ArgumentNamed(PATH_ARG.to_string()),
]
}
}
#[derive(Debug, Clone, PartialEq, Eq, DiagnosticInfo)]
#[diagnostic(
id = "flm.graphics.path-not-characters",
message = "Invalid path in ‘\\includegraphics’: the path must be plain text"
)]
pub struct PathNotCharacters;
#[derive(Debug, Clone, PartialEq, Eq, DiagnosticInfo)]
#[diagnostic(id = "flm.graphics.empty-path", message = "Missing path in ‘\\includegraphics’")]
pub struct EmptyPath;
pub(crate) enum ImagePath {
Read(String),
Empty,
NotCharacters,
}
pub(crate) fn read_path(
node: &NodeRef<'_, Flm>,
) -> Result<ImagePath, crate::core::lowering::LowerError> {
let Ok(Some(content)) = node.argument_content_nodes_named(PATH_ARG) else {
return Ok(ImagePath::Empty);
};
Ok(match chars_at_lowering(content.iter())? {
Ok(text) if text.is_empty() => ImagePath::Empty,
Ok(text) => ImagePath::Read(text),
Err(_) => ImagePath::NotCharacters,
})
}
fn image_spec() -> Arc<ElementSpec> {
Arc::new(
ElementSpec::new(IMAGE_ELEMENT)
.docs("An image, inserted with `\\includegraphics[options]{path}`.")
.with::<dyn BlockRoleAspect>(Arc::new(GraphicsImage))
.with::<dyn ApartFromText>(Arc::new(GraphicsImage))
.with_value(Arc::new(GraphicsImage)),
)
}
pub fn arguments() -> Vec<ArgDef> {
vec![
ArgDef::named(OPTIONS_ARG, ArgStdKind::KeyVals).docs(
"The options of the image, as key-value pairs, as in `alt=A plot, width=5cm`. The \
keys are `alt` for the alternative text, and `width` and `height` for the size.",
),
ArgDef::named(PATH_ARG, ArgStdKind::Verbatim { delimiters: Some(('{', '}')) })
.docs(
"The path of the image file, as in `figures/plot.png`. The path is raw text up to \
the matching `}`: the characters `%`, `#`, `\\`, `~` and nested braces are part \
of the path.",
)
.role(PATH_ARG_ROLE),
]
}
fn command_def(owner: &FeatureName, spec: &Arc<ElementSpec>) -> ElementDef {
ElementDef::new(owner.clone(), [COMMAND], SyntaxDef::Macro { args: arguments() }, Arc::clone(spec))
.docs("Inserts the image whose file is at `path`.")
}
fn includegraphics_package(owner: &FeatureName, spec: &Arc<ElementSpec>) -> ScopedPackageDef {
ScopedPackageDef {
owner: owner.clone(),
name: Name::from(INCLUDEGRAPHICS_PACKAGE),
elements: vec![command_def(owner, spec)],
docs: String::from(
"Provides `\\includegraphics[options]{path}` in the bodies that refer to this \
package, such as the bodies of the float types `figure` and `table`.",
),
}
}
#[derive(Debug, Default, Clone, Copy)]
pub struct Graphics {
config: GraphicsConfig,
}
impl Graphics {
pub fn new(config: GraphicsConfig) -> Graphics {
Graphics { config }
}
pub fn config(&self) -> &GraphicsConfig {
&self.config
}
}
const BACKENDS: [&str; 4] = [
text::BACKEND,
html::BACKEND,
crate::stdlib::backends::latex_recomposed::BACKEND,
crate::stdlib::backends::latex_rendered::BACKEND,
];
impl FlmFeature for Graphics {
fn info(&self) -> FeatureInfo {
FeatureInfo::new(FEATURE, "Graphics").docs(
"Images, inserted with `\\includegraphics[options]{path}`. By default, the command \
is available in the bodies of the float types that allow it, such as `figure` and \
`table`. With the configuration `global`, it can be written wherever text can be \
written. The program can provide services that find, inspect and convert image \
files. The render options select how each output refers to its images, for \
instance by the path of the file or with a copy of the file. On the plain-text, \
HTML and rendered LaTeX outputs, an image is lowered to `flm.pres.image`; on the \
recomposed LaTeX, it is written as the LaTeX hook `\\flmIncludeGraphics`.",
)
}
fn settings(&self) -> Option<SettingsDecl> {
Some(settings())
}
fn register(&self, b: &mut FeatureBuilder<'_>) -> Result<(), BuildError> {
let owner: FeatureName = b.feature().clone();
b.argument_role(PATH_ARG_ROLE, "The path of an image file.")?;
let spec = image_spec();
b.scoped_package(includegraphics_package(&owner, &spec))?;
b.element_type_text(
IMAGE_ELEMENT,
"An image, given by the path of an image file, with an optional alternative text and \
an optional size.",
)?;
if self.config.global {
b.element(command_def(&owner, &spec))?;
}
b.peer_slot::<dyn FloatContentHandler>(CONTENT_SLOT, Arc::new(IncludeGraphicsContent))?;
b.service_slot::<dyn GraphicsResolver>(
RESOLVER_SLOT,
Arity::Single,
"the graphics resolver, which finds the file that the path of an image refers to and \
reads the content of this file",
)?;
b.service_slot::<dyn GraphicsInspector>(
INSPECTOR_SLOT,
Arity::Single,
"the inspector, which reports the type of an image file (vector or raster image), its \
size in pixels, its resolution and its physical size",
)?;
b.service_slot::<dyn GraphicsConverter>(
CONVERTERS_SLOT,
Arity::OrderedMany,
"the converters, which convert an image file from one format into another; for a \
conversion rule, the first converter in the order of contribution that can perform \
the rule is used",
)?;
inspect::register(b)?;
for backend in BACKENDS {
publish::register(b, backend)?;
}
for backend in [text::BACKEND, html::BACKEND, crate::stdlib::backends::latex_rendered::BACKEND] {
b.peer_backend(backend, "a backend on which the image rule is the default")?;
b.lowering_rule(image_rule(backend))?;
}
latex::register(b)?;
b.digest_input(&self.config.digest_bytes())?;
Ok(())
}
}
pub fn feature() -> Arc<dyn FlmFeature> {
Arc::new(Graphics::default())
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn the_command_takes_key_values_then_a_braced_verbatim_path() {
let args = arguments();
assert_eq!(args.len(), 2);
assert_eq!(args[0].name.as_deref(), Some(OPTIONS_ARG));
assert_eq!(args[0].kind.identity(), ArgDef::new(ArgStdKind::KeyVals).kind.identity());
assert_eq!(args[1].name.as_deref(), Some(PATH_ARG));
let braced = ArgDef::new(ArgStdKind::Verbatim { delimiters: Some(('{', '}')) });
assert_eq!(args[1].kind.identity(), braced.kind.identity());
}
#[test]
fn the_configuration_digests_its_one_switch() {
assert_eq!(GraphicsConfig::new().digest_bytes(), [0]);
assert_eq!(GraphicsConfig::new().global(true).digest_bytes(), [1]);
}
}