use std::sync::Arc;
use techy::core::node::{BuildId, NodeRef};
use crate::core::lowering::{
DefaultMark, Lower, LowerCx, LowerError, Lowerer, Lowering, LoweringDecl, LoweringRule,
};
use crate::core::registry::{BuildError, FeatureBuilder};
use crate::lang::Flm;
use crate::model::names::{ElementName, Name};
use crate::stdlib::backends::latex::construct::{ARG_SLOT, MACRO, RAW};
use crate::stdlib::backends::latex::preamble::stage_length;
use crate::stdlib::backends::latex::{
LatexArgShape, LatexMacroPayload, LatexPreambleDef, LatexRawPayload, escape_url, packages,
preamble,
};
use crate::stdlib::backends::latex_recomposed::BACKEND;
use crate::stdlib::backends::pres::Length;
use super::inspect::INFO;
use super::options::{HEIGHT_KEY, WIDTH_KEY};
use super::publish::published_table;
use super::rules::read_image;
use super::strategy::GraphicsRenderOptions;
use super::IMAGE_ELEMENT;
pub const LATEX_RULE: &str = "flm.graphics.image.lower.latex-recomposed";
pub const PIECE_NAME: &str = "graphics";
pub const PIECE: &str = "flm.latex.def.graphics";
pub const HOOK_COMMAND: &str = "flmIncludeGraphics";
pub fn definition_piece() -> LatexPreambleDef {
LatexPreambleDef::new(
PIECE_NAME,
"\
% An image, as FLM's \\includegraphics writes it:
% \\flmIncludeGraphics[<keys>]{<path>}, <keys> being width=<length> and
% height=<length> where the image is shown at a set size, <path> an ordinary
% argument in which the characters # % \\ are written \\# \\% \\\\.
% The image never runs wider than the line (max width, a key adjustbox adds to
% \\includegraphics). Redefine the hook to show images another way.
\\ProvideDocumentCommand\\flmIncludeGraphics{O{} m}{\\includegraphics[max width=\\linewidth,#1]{#2}}
",
"`\\flmIncludeGraphics[keys]{path}`: the LaTeX hook an image is written as, \
`\\includegraphics` kept within the line's width",
)
.requires([packages::GRAPHICX, packages::ADJUSTBOX])
}
#[derive(Debug, Default, Clone, Copy)]
pub struct ImageLatexRule;
impl Lower for ImageLatexRule {
fn lower(
&self,
node: NodeRef<'_, Flm>,
cx: &mut LowerCx<'_>,
lw: &mut dyn Lowerer,
) -> Result<Lowering, LowerError> {
let (src, (width, height)) = {
let Some(image) = read_image(&node, BACKEND, lw)? else {
return Ok(Lowering::Emit(Vec::new()));
};
(image.published.src.clone(), image.size)
};
let mut shapes = Vec::new();
let mut slots = Vec::new();
let keys = keys(cx, lw, width.as_ref(), height.as_ref())?;
if !keys.is_empty() {
shapes.push(LatexArgShape::Optional);
slots.push(keys);
}
shapes.push(LatexArgShape::Mandatory);
slots.push(raw(cx, lw, &escape_url(&src))?);
lw.require(&Name::from(PIECE));
let hook = lw.pres_slots_with(
cx,
&ElementName::from(MACRO),
LatexMacroPayload::new(HOOK_COMMAND, shapes),
slots.into_iter().map(|slot| (String::from(ARG_SLOT), slot)).collect(),
)?;
Ok(Lowering::Emit(vec![hook]))
}
}
fn raw(cx: &mut LowerCx<'_>, lw: &mut dyn Lowerer, text: &str) -> Result<Vec<BuildId>, LowerError> {
if text.is_empty() {
return Ok(Vec::new());
}
Ok(vec![lw.pres_with(cx, &ElementName::from(RAW), LatexRawPayload::new(text), Vec::new())?])
}
fn keys(
cx: &mut LowerCx<'_>,
lw: &mut dyn Lowerer,
width: Option<&Length>,
height: Option<&Length>,
) -> Result<Vec<BuildId>, LowerError> {
let mut nodes = Vec::new();
for (key, length) in [(WIDTH_KEY, width), (HEIGHT_KEY, height)] {
let Some(length) = length else { continue };
let lead = if nodes.is_empty() { format!("{key}=") } else { format!(",{key}=") };
nodes.extend(raw(cx, lw, &lead)?);
nodes.push(stage_length(cx, lw, length)?);
}
Ok(nodes)
}
pub fn latex_rule() -> LoweringRule {
LoweringRule::new(
LATEX_RULE,
IMAGE_ELEMENT,
LoweringDecl::new()
.reads(INFO)
.reads(published_table(BACKEND))
.option::<GraphicsRenderOptions>()
.produces(MACRO)
.produces(RAW),
Arc::new(ImageLatexRule),
DefaultMark::OnBackends(vec![BACKEND.into()]),
)
.docs(
"an image lowers to the LaTeX hook `\\flmIncludeGraphics`, with its size as keys where it \
has one, and its escaped address",
)
}
pub(super) fn register(b: &mut FeatureBuilder<'_>) -> Result<(), BuildError> {
b.peer_backend(
BACKEND,
"the latex-recomposed backend, on which the image's LaTeX rule is the default",
)?;
b.peer_element::<LatexMacroPayload>(
MACRO,
"the LaTeX family's macro-call construct, which the image's LaTeX rule stages for the \
LaTeX hook `\\flmIncludeGraphics`",
)?;
b.peer_element::<LatexRawPayload>(
RAW,
"the LaTeX family's raw construct, whose raw nodes hold the keys and the address",
)?;
b.peer_slot::<LatexPreambleDef>(preamble::SLOT, Arc::new(definition_piece()))?;
b.lowering_rule(latex_rule())
}
#[cfg(test)]
mod tests {
use super::*;
use crate::stdlib::backends::latex::preamble::piece_id;
#[test]
fn the_piece_defines_the_hook_and_requests_the_two_packages() {
let piece = definition_piece();
assert_eq!(piece.id, piece_id(PIECE_NAME));
assert_eq!(piece.id.as_str(), PIECE);
assert_eq!(piece.requires, [Name::from(packages::GRAPHICX), Name::from(packages::ADJUSTBOX)]);
assert!(piece.content.contains(
"\\ProvideDocumentCommand\\flmIncludeGraphics{O{} m}{\\includegraphics[max \
width=\\linewidth,#1]{#2}}"
));
}
#[test]
fn the_rule_is_the_default_on_the_recomposed_backend_only() {
let rule = latex_rule();
assert_eq!(rule.element, IMAGE_ELEMENT);
assert!(rule.default.is_specific_to(&BACKEND.into()));
}
}