use std::collections::BTreeSet;
use std::sync::Arc;
use crate::core::region::RegionsOutput;
use crate::core::registry::{
BackendDef, BuildError, FeatureBuilder, FeatureInfo, FlmFeature, OutputDef, WorkflowDef,
};
use crate::core::settings::SettingsDecl;
use crate::lang::structural;
use crate::model::names::ElementName;
use crate::model::options::Bind;
use crate::stdlib::VALIDATED;
use crate::stdlib::backends::latex::packages::{self, AMSMATH, GRAPHICX, TABULARRAY, XCOLOR};
use crate::stdlib::backends::latex::preamble;
use crate::stdlib::backends::latex::{ExtraPreamble, LatexPackageDef, LatexPreambleDef, construct};
use crate::stdlib::backends::lowering::{LoweredTrees, REGIONS_SLOT, lowered_table_name};
use crate::stdlib::backends::pieces::{LoweredPieces, PiecesStage, lowered_pieces_table_name};
use crate::stdlib::backends::pres;
use super::contract::{
CELLS_CHUNK, CORE_CHUNK, HEADINGS_CHUNK, IMAGES_CHUNK, LINES_CHUNK, LINKS_CHUNK, LISTS_CHUNK,
MARKS_CHUNK, VERBATIM_CHUNK,
};
use super::stages::{
ARTIFACTS, DOCUMENT, EXTENSION, LatexRenderedEmitPiecesStage, LatexRenderedRegionsStage,
MEDIA_TYPE, OUTPUT_TABLE, PIECES_TABLE, REGIONS, STYLE_FILE, stages,
};
pub const FEATURE_NAME: &str = "latex-rendered";
pub const BACKEND: &str = "latex-rendered";
pub const OUTPUT: &str = "latex-rendered";
pub const WORKFLOW: &str = "latex-rendered";
pub const DEFAULT_STYLE_STEM: &str = "flmx";
pub const FONTSPEC: &str = "flm.latex.pkg.fontspec";
pub const FLOW_THROUGH: [&str; 6] = [
structural::TEXT,
structural::GROUP,
structural::OPAQUE_WRAPPER,
structural::COMMENT,
structural::CONTAINER,
structural::PARBREAK,
];
pub fn native_elements() -> Vec<ElementName> {
pres::ALL
.iter()
.chain(construct::ALL.iter())
.chain(FLOW_THROUGH.iter())
.map(|name| ElementName::from(*name))
.collect()
}
#[derive(Debug, Clone, PartialEq, Eq, Hash, serde::Deserialize)]
#[derive(schemars::JsonSchema)]
#[serde(default, deny_unknown_fields)]
pub struct LatexRenderedRenderOptions {
pub style_stem: String,
pub run_in_stop: String,
pub skip_packages: BTreeSet<String>,
pub extra_packages: Vec<LatexPackageDef>,
pub extra_preamble: ExtraPreamble,
}
impl Default for LatexRenderedRenderOptions {
fn default() -> LatexRenderedRenderOptions {
LatexRenderedRenderOptions {
style_stem: String::from(DEFAULT_STYLE_STEM),
run_in_stop: String::from(pres::DEFAULT_RUN_IN_STOP),
skip_packages: BTreeSet::new(),
extra_packages: Vec::new(),
extra_preamble: ExtraPreamble::default(),
}
}
}
fn settings() -> SettingsDecl {
SettingsDecl::new(FEATURE_NAME)
.options::<LatexRenderedRenderOptions>(
Bind::Render,
"the stem of the style file's name (default `flmx`), to which the program's naming \
of files may add a prefix; the stop written after a run-in heading's title; the \
LaTeX packages this backend never requests, for a template that loads them \
itself; the packages the style file always requests, with their options; and \
three parts of LaTeX text written byte for byte into the style file, after the \
engine check, after the packages and at its end. Set per render request.",
)
.markup("run_in_stop")
}
pub fn chunks() -> Vec<LatexPreambleDef> {
let chunk = |id: &str, content: &str, docs: &str| {
let name = id.strip_prefix(preamble::ID_PREFIX).unwrap_or(id);
LatexPreambleDef::new(name, content, docs)
};
vec![
chunk(
CORE_CHUNK,
include_str!("sty/flmx-core.sty"),
"the core of the latex-rendered contract: the keys, the registrations, the target \
of an anchor, blocks, spans and decorations",
)
.requires([FONTSPEC, AMSMATH, XCOLOR]),
chunk(HEADINGS_CHUNK, include_str!("sty/flmx-headings.sty"), "headings")
.requires([CORE_CHUNK]),
chunk(LINKS_CHUNK, include_str!("sty/flmx-links.sty"), "links").requires([CORE_CHUNK]),
chunk(LISTS_CHUNK, include_str!("sty/flmx-lists.sty"), "lists").requires([CORE_CHUNK]),
chunk(LINES_CHUNK, include_str!("sty/flmx-lines.sty"), "lines").requires([CORE_CHUNK]),
chunk(VERBATIM_CHUNK, include_str!("sty/flmx-verbatim.sty"), "verbatim text")
.requires([CORE_CHUNK]),
chunk(CELLS_CHUNK, include_str!("sty/flmx-cells.sty"), "tables of cells")
.requires([CORE_CHUNK, TABULARRAY]),
chunk(IMAGES_CHUNK, include_str!("sty/flmx-images.sty"), "images")
.requires([CORE_CHUNK, GRAPHICX]),
chunk(
MARKS_CHUNK,
include_str!("sty/flmx-marks.sty"),
"the marks of what could not be written",
)
.requires([CORE_CHUNK]),
]
}
fn fontspec() -> LatexPackageDef {
LatexPackageDef::new(
"fontspec",
"the fonts of a document compiled with LuaLaTeX; the latex-rendered backend always \
requests it",
)
}
#[derive(Debug, Default, Clone, Copy)]
pub struct LatexRendered;
impl FlmFeature for LatexRendered {
fn info(&self) -> FeatureInfo {
FeatureInfo::new(FEATURE_NAME, "LaTeX (rendered) backend").docs(
"the document as fully resolved LaTeX for LuaLaTeX, written through one command or \
environment per presentation element: the `latex-rendered` output and workflow, a \
document and a style file",
)
}
fn settings(&self) -> Option<SettingsDecl> {
Some(settings())
}
fn register(&self, b: &mut FeatureBuilder<'_>) -> Result<(), BuildError> {
b.table_named::<LoweredTrees>(
lowered_table_name(&BACKEND.into()),
"the rendered-LaTeX backend's lowered trees, one per document tree",
)?;
b.table(
OUTPUT_TABLE,
"per tree: the rendered LaTeX with the trees placed in it, the requirement \
identifiers and the definitions it staged",
)?;
b.table_named::<LoweredPieces>(
lowered_pieces_table_name(&BACKEND.into()),
"the pieces that the render request places, lowered for the rendered-LaTeX backend",
)?;
b.stage(Arc::new(PiecesStage::new(BACKEND)))?;
b.table(
PIECES_TABLE,
"the rendered LaTeX of each piece the render request places, with its words and \
requirements",
)?;
b.stage(Arc::new(LatexRenderedEmitPiecesStage))?;
b.table(REGIONS, "the content, the pieces and the style file's package name")?;
b.table(STYLE_FILE, "the style file beside the rendered LaTeX")?;
b.table(DOCUMENT, "the rendered LaTeX document, its style file and the files beside it")?;
b.table(
ARTIFACTS,
"files a stage produces beside the rendered LaTeX for it to refer to (copies of \
images), added to the document's set after the style file",
)?;
b.stage(Arc::new(LatexRenderedRegionsStage))?;
b.contribute_to::<RegionsOutput>(
REGIONS_SLOT,
Arc::new(RegionsOutput {
output: OUTPUT.into(),
backend: BACKEND.into(),
document: DOCUMENT.name().into(),
capability: DOCUMENT.name().into(),
regions: REGIONS.handle(),
artifacts: vec![STYLE_FILE.handle(), ARTIFACTS.handle()],
}),
)?;
let (lowering, emit, final_stage) = stages();
b.backend(
BackendDef::new(BACKEND, native_elements(), lowering, emit, final_stage)
.docs("fully resolved LaTeX for LuaLaTeX, with a style file"),
)?;
b.output(
OutputDef::new(OUTPUT, DOCUMENT.name(), DOCUMENT.name(), MEDIA_TYPE, EXTENSION)
.docs("the document as fully resolved LaTeX for LuaLaTeX, with its style file"),
)?;
b.workflow(
WorkflowDef::new(WORKFLOW).output(OUTPUT).demand(VALIDATED).docs(
"render the document as LaTeX for LuaLaTeX, running every check and leaving \
only the typesetting to LaTeX",
),
)?;
b.peer_slot::<LatexPackageDef>(packages::SLOT, Arc::new(fontspec()))?;
for chunk in chunks() {
b.peer_slot::<LatexPreambleDef>(preamble::SLOT, Arc::new(chunk))?;
}
Ok(())
}
}
pub fn feature() -> Arc<dyn FlmFeature> {
Arc::new(LatexRendered)
}
#[cfg(test)]
mod tests {
use super::*;
use crate::stdlib::backends::latex::packages::package_id;
#[test]
fn every_chunk_of_the_contract_is_a_piece_and_each_requires_the_core() {
let chunks = chunks();
let ids: Vec<&str> = chunks.iter().map(|chunk| chunk.id.as_str()).collect();
assert_eq!(ids, super::super::contract::CHUNKS);
for chunk in &chunks[1..] {
assert!(chunk.requires.iter().any(|id| id.as_str() == CORE_CHUNK), "{}", chunk.id);
assert!(chunk.content.starts_with(&format!("% {} -- ", chunk.id)), "{}", chunk.id);
}
assert_eq!(package_id("fontspec").as_str(), FONTSPEC);
}
}