Files
texrra-engine/src/route_d.rs
T

343 lines
11 KiB
Rust
Executable File

//! Route-D preview endpoints: a small, independent TeX-style page pipeline.
//!
//! These endpoints are intentionally separate from the v1 `DocumentModel`
//! preview. They demonstrate checkpointed, page-hashed output from the route-D
//! core. The v1 preview remains the default and the fallback.
use std::cell::RefCell;
use std::fmt::Write as _;
use texrra_tex_core::cmr10::Cmr10Metrics;
use texrra_tex_core::math::parse_math;
use texrra_tex_core::pdf::display_lists_to_pdf;
use texrra_tex_core::{Document, Engine, ParagraphFont, ParagraphStyle, Unit, VerticalItem};
const SCALE: i64 = 65_536;
const PAGE_HEIGHT_PT: i64 = 792;
const PAGE_WIDTH_PT: i64 = 612;
thread_local! {
static ROUTE_D_SESSION: RefCell<Option<(Document, Engine)>> = const { RefCell::new(None) };
}
/// Build a JSON preview from the document body of a small LaTeX file.
///
/// This is the opt-in M7 bridge for v1 projects: the preamble is discarded and
/// the body is handed to the same route-D paragraph parser used by
/// `/api/route-d/preview`. The v1 semantic pipeline remains the default.
pub fn latex_preview_json(source: &str) -> Result<String, String> {
let body = source
.split_once("\\begin{document}")
.map_or(source, |(_, body)| body);
let body = body.split("\\end{document}").next().unwrap_or(body);
preview_json(body)
}
/// Build a JSON preview from blank-line-separated plain-text paragraphs.
pub fn preview_json(source: &str) -> Result<String, String> {
let paragraphs = paragraphs(source)?;
let document = build_document(&paragraphs);
let engine = Engine::layout(&document);
Ok(render_json(&engine, None))
}
/// Render the same checkpointed document as a route-D PDF.
pub fn pdf_bytes(source: &str) -> Result<Vec<u8>, String> {
let paragraphs = paragraphs(source)?;
let document = build_document(&paragraphs);
let engine = Engine::layout(&document);
let pages: Vec<_> = engine
.pages()
.iter()
.map(|page| {
let mut list = page.display_list();
list.width = list.width.max(PAGE_WIDTH_PT * SCALE);
list.height = list.height.max(PAGE_HEIGHT_PT * SCALE);
list
})
.collect();
Ok(display_lists_to_pdf(&pages, PAGE_HEIGHT_PT))
}
/// Apply one paragraph edit to the last route-D document and report page
/// checkpoints that were reused versus rebuilt.
pub fn edit_json(source: &str, unit: usize) -> Result<String, String> {
let paragraphs = paragraphs(source)?;
if unit >= paragraphs.len() {
return Err(format!(
"unit {unit} is out of range for {} paragraphs",
paragraphs.len()
));
}
let next = build_document(&paragraphs);
ROUTE_D_SESSION.with(|slot| {
let mut slot = slot.borrow_mut();
let (_, mut engine) = match slot.take() {
Some(session) => session,
None => {
let engine = Engine::layout(&next);
(next.clone(), engine)
}
};
engine.edit(&next, unit as u64, paragraphs[unit].text.clone());
let changed = engine.changed_pages().to_vec();
let recomputed = engine.recomputed_pages();
let json = render_json(&engine, Some((&changed, recomputed)));
*slot = Some((next, engine));
Ok(json)
})
}
#[derive(Clone)]
struct SourceParagraph {
text: String,
centered: bool,
right_aligned: bool,
font: ParagraphFont,
line_height: i64,
math: bool,
left_skip: i64,
}
fn paragraphs(source: &str) -> Result<Vec<SourceParagraph>, String> {
let paragraphs: Vec<&str> = source
.split("\n\n")
.map(str::trim)
.filter(|paragraph| !paragraph.is_empty())
.collect();
if paragraphs.is_empty() {
return Err("route-D preview needs at least one paragraph".to_string());
}
Ok(paragraphs.into_iter().flat_map(parse_blocks).collect())
}
fn command_body<'a>(text: &'a str, command: &str) -> Option<&'a str> {
let rest = text.strip_prefix(command)?.trim_start();
let rest = rest.strip_prefix('{')?.strip_suffix('}')?;
Some(rest.trim())
}
fn parse_blocks(raw: &str) -> Vec<SourceParagraph> {
for (environment, numbered) in [("itemize", false), ("enumerate", true)] {
let begin = format!("\\begin{{{environment}}}");
let finish = format!("\\end{{{environment}}}");
let Some(body) = raw
.strip_prefix(&begin)
.and_then(|text| text.strip_suffix(&finish))
else {
continue;
};
let mut number = 0;
let items: Vec<SourceParagraph> = body
.split("\\item")
.map(str::trim)
.filter(|item| !item.is_empty())
.map(|item| {
number += 1;
let prefix = if numbered {
format!("{number}. ")
} else {
"• ".to_string()
};
SourceParagraph {
text: format!("{prefix}{item}"),
font: ParagraphFont::Roman,
line_height: 12,
math: false,
left_skip: 12,
centered: false,
right_aligned: false,
}
})
.collect();
if !items.is_empty() {
return items;
}
}
if let Some(body) = raw
.strip_prefix("\\begin{quote}")
.and_then(|text| text.strip_suffix("\\end{quote}"))
{
let text = body.trim();
if !text.is_empty() {
return vec![SourceParagraph {
text: text.to_string(),
font: ParagraphFont::Roman,
line_height: 12,
math: false,
left_skip: 12,
centered: false,
right_aligned: false,
}];
}
}
if let Some(body) = raw
.strip_prefix("\\begin{description}")
.and_then(|text| text.strip_suffix("\\end{description}"))
{
let items: Vec<SourceParagraph> = body
.split("\\item")
.map(str::trim)
.filter(|item| !item.is_empty())
.map(|item| {
let (term, rest) = item
.strip_prefix('[')
.and_then(|text| text.split_once(']'))
.map(|(term, rest)| (term.trim(), rest.trim()))
.unwrap_or(("", item));
let text = if term.is_empty() {
rest.to_string()
} else {
format!("{term} — {rest}")
};
SourceParagraph {
text,
font: ParagraphFont::Roman,
line_height: 12,
math: false,
left_skip: 12,
centered: false,
right_aligned: false,
}
})
.collect();
if !items.is_empty() {
return items;
}
}
vec![parse_paragraph(raw)]
}
/// Map a small, general LaTeX subset onto route-D paragraph faces. This is not
/// a full LaTeX reader; it exists so the live endpoint can show headings and
/// emphasis while the semantic layer is built out.
fn parse_paragraph(raw: &str) -> SourceParagraph {
if let Some(math) = raw
.strip_prefix("$$")
.and_then(|text| text.strip_suffix("$$"))
.or_else(|| {
raw.strip_prefix("\\[")
.and_then(|text| text.strip_suffix("\\]"))
})
{
return SourceParagraph {
text: math.trim().to_string(),
font: ParagraphFont::Roman,
line_height: 12,
math: true,
left_skip: 0,
centered: false,
right_aligned: false,
};
}
let candidates = [
("\\section", ParagraphFont::Bold, 18),
("\\textbf", ParagraphFont::Bold, 12),
("\\emph", ParagraphFont::Italic, 12),
];
for (command, font, line_height) in candidates {
if let Some(text) = command_body(raw, command) {
return SourceParagraph {
text: text.to_string(),
font,
line_height,
math: false,
left_skip: 0,
centered: false,
right_aligned: false,
};
}
}
SourceParagraph {
text: raw.to_string(),
font: ParagraphFont::Roman,
line_height: 12,
math: false,
left_skip: 0,
centered: false,
right_aligned: false,
}
}
fn build_document(paragraphs: &[SourceParagraph]) -> Document {
let units = paragraphs
.iter()
.enumerate()
.map(|(index, paragraph)| {
if paragraph.math {
return Unit::math(
index as u64,
parse_math(&paragraph.text),
&Cmr10Metrics::default(),
);
}
let style = ParagraphStyle {
line_width: 480 * SCALE,
left_skip: paragraph.left_skip * SCALE,
centered: paragraph.centered,
right_aligned: paragraph.right_aligned,
right_skip: 0,
par_indent: 0,
line_height: paragraph.line_height * SCALE,
char_width: 10 * SCALE,
space_width: 4 * SCALE,
space_stretch: 6 * SCALE,
space_shrink: 2 * SCALE,
};
let mut unit = Unit::paragraph_with_style(index as u64, paragraph.text.clone(), style);
if let Some(VerticalItem::Paragraph(paragraph_box)) = unit.items.first_mut() {
paragraph_box.font = paragraph.font;
}
unit
})
.collect();
Document::new(700 * SCALE, units)
}
fn render_json(engine: &Engine, edit: Option<(&[usize], usize)>) -> String {
let mut json = String::new();
json.push_str("{\"status\":\"ok\",\"pageWidthMm\":215.90,\"pageHeightMm\":279.40,\"pages\":[");
for (index, page) in engine.pages().iter().enumerate() {
let mut list = page.display_list();
list.width = list.width.max(PAGE_WIDTH_PT * SCALE);
list.height = list.height.max(PAGE_HEIGHT_PT * SCALE);
if index > 0 {
json.push(',');
}
let _ = write!(
json,
"{{\"index\":{index},\"hash\":\"{:016x}\",\"svg\":\"{}\"}}",
page.hash,
escape_json(&list.to_svg())
);
}
let _ = write!(json, "],\"pageCount\":{}", engine.pages().len());
if let Some((changed, recomputed)) = edit {
let _ = write!(
json,
",\"changedPages\":{:?},\"recomputedPages\":{recomputed}",
changed
);
}
json.push_str(",\"pageHeightPt\":792}");
json
}
fn escape_json(value: &str) -> String {
let mut escaped = String::with_capacity(value.len());
for character in value.chars() {
match character {
'"' => escaped.push_str("\\\""),
'\\' => escaped.push_str("\\\\"),
'\n' => escaped.push_str("\\n"),
'\r' => escaped.push_str("\\r"),
'\t' => escaped.push_str("\\t"),
character if character < '\u{20}' => {
let _ = write!(escaped, "\\u{:04x}", character as u32);
}
character => escaped.push(character),
}
}
escaped
}