Files
texrra-engine/src/route_d.rs
T

556 lines
19 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::collections::HashMap;
use std::fmt::Write as _;
use std::sync::{Mutex, OnceLock};
use texrra_tex_core::cmr10::Cmr10Metrics;
use texrra_tex_core::math::parse_math;
use texrra_tex_core::pdf::{PageOrigin, display_lists_to_pdf_with_origin};
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) };
}
struct ProjectSession {
paragraphs: Vec<SourceParagraph>,
engine: Engine,
}
fn project_sessions() -> &'static Mutex<HashMap<String, ProjectSession>> {
static SESSIONS: OnceLock<Mutex<HashMap<String, ProjectSession>>> = OnceLock::new();
SESSIONS.get_or_init(|| Mutex::new(HashMap::new()))
}
fn latex_body(source: &str) -> &str {
let body = source
.split_once("\\begin{document}")
.map_or(source, |(_, body)| body);
body.split("\\end{document}").next().unwrap_or(body)
}
/// Project-scoped route-D preview. Reuses the previous engine when the
/// paragraph list is unchanged and applies each changed paragraph through
/// `Engine::edit`, starting from the earliest changed paragraph. Structural
/// edits fall back to a full layout. The v1 project preview remains the default.
pub fn project_preview_json(project_id: &str, source: &str) -> Result<String, String> {
let paragraphs = paragraphs(latex_body(source))?;
let document = build_document(&paragraphs);
let mut sessions = project_sessions()
.lock()
.map_err(|_| "route-D session lock".to_string())?;
let previous = sessions.remove(project_id);
let (engine, changed, recomputed) = match previous {
Some(mut session) => {
if session.paragraphs == paragraphs {
(session.engine, Vec::new(), 0)
} else {
let prefix = session
.paragraphs
.iter()
.zip(&paragraphs)
.take_while(|(a, b)| a == b)
.count();
if prefix > 0 && prefix < session.paragraphs.len() && prefix < paragraphs.len() {
session.engine.relayout_from(&document, prefix);
let changed = session.engine.changed_pages().to_vec();
let recomputed = session.engine.recomputed_pages();
(session.engine, changed, recomputed)
} else {
let engine = Engine::layout(&document);
let changed: Vec<usize> = (0..engine.pages().len()).collect();
let recomputed = changed.len();
(engine, changed, recomputed)
}
}
}
_ => {
let engine = Engine::layout(&document);
let changed: Vec<usize> = (0..engine.pages().len()).collect();
let recomputed = changed.len();
(engine, changed, recomputed)
}
};
let json = render_json(&engine, Some((&changed, recomputed)));
sessions.insert(
project_id.to_string(),
ProjectSession { paragraphs, engine },
);
Ok(json)
}
/// Pull `\hoffset`/`\voffset` assignments out of the source and return the
/// remaining body. Both commands take a TeX dimension.
fn strip_page_offsets(source: &str) -> (String, PageOrigin) {
let mut origin = PageOrigin::default();
let mut body = String::new();
for line in source.lines() {
let trimmed = line.trim();
if let Some(value) = dimension_assignment(trimmed, "hoffset") {
origin.h_offset = value;
} else if let Some(value) = dimension_assignment(trimmed, "voffset") {
origin.v_offset = value;
} else {
body.push_str(line);
body.push('\n');
}
}
(body, origin)
}
fn dimension_assignment(line: &str, name: &str) -> Option<i64> {
let rest = line.strip_prefix('\\')?;
let rest = rest.strip_prefix(name)?;
let rest = rest.trim_start().strip_prefix('=')?;
parse_dimension(rest.trim())
}
fn parse_dimension(text: &str) -> Option<i64> {
let end = text
.find(|character: char| {
!(character.is_ascii_digit() || character == '.' || character == '-')
})
.unwrap_or(text.len());
let number: f64 = text[..end].parse().ok()?;
let factor = match text[end..].trim() {
"pt" => 1.0,
"bp" => 72.27 / 72.0,
"in" => 72.27,
"cm" => 72.27 / 2.54,
"mm" => 72.27 / 25.4,
_ => return None,
};
Some((number * factor * 65_536.0).round() as i64)
}
/// 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);
let json = render_json(&engine, None);
// Keep the layout so a following `/edit` request can diff against it and
// reuse page checkpoints instead of starting from a no-op document.
ROUTE_D_SESSION.with(|slot| {
*slot.borrow_mut() = Some((document, engine));
});
Ok(json)
}
/// Render the same checkpointed document as a route-D PDF.
pub fn pdf_bytes(source: &str) -> Result<Vec<u8>, String> {
let (body, origin) = strip_page_offsets(latex_body(source));
let paragraphs = paragraphs(&body)?;
let mut document = build_document(&paragraphs);
document.h_offset = origin.h_offset;
document.v_offset = origin.v_offset;
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_with_origin(
&pages,
PAGE_HEIGHT_PT,
origin,
))
}
/// 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, PartialEq, Eq)]
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,
hang_indent: 0,
hang_after: 1,
par_shape: Vec::new(),
par_fillskip: 0,
par_fillskip_stretch: 0,
par_fillskip_fil: true,
frenchspacing: false,
space_factor_codes: Vec::new(),
baselineskip: 12 * 65536,
lineskip: 65536,
lineskiplimit: 0,
par_indent: 0,
emergencystretch: 0,
pretolerance: 100,
tolerance: 200,
hyphen_penalty: 50,
ex_hyphen_penalty: 50,
double_hyphen_demerits: 10_000,
final_hyphen_demerits: 5_000,
line_penalty: 10,
adj_demerits: 10_000,
hyphenation_exceptions: Vec::new(),
line_height: paragraph.line_height * SCALE,
char_width: 10 * SCALE,
space_width: 4 * SCALE,
space_stretch: 6 * SCALE,
space_shrink: 2 * SCALE,
space_skip: None,
xspace_skip: None,
};
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
}
#[cfg(test)]
mod tests {
use super::*;
fn multi_page_source() -> String {
let mut source = String::from("\\documentclass{article}\n\\begin{document}\n\n");
for index in 0..36 {
source.push_str(&format!("Paragraph {index:02} "));
for _ in 0..4 {
source.push_str(
"lorem ipsum dolor sit amet consectetur adipiscing elit sed do eiusmod tempor. ",
);
}
source.push_str("\n\n");
}
source.push_str("\\end{document}\n");
source
}
#[test]
fn multi_paragraph_edits_reuse_earlier_pages() {
let source = multi_page_source();
let first = project_preview_json("route-d-multi-edit", &source).expect("first preview");
let first: serde_json::Value = serde_json::from_str(&first).expect("first JSON");
let page_count = first["pageCount"].as_u64().expect("page count");
assert!(
page_count >= 2,
"expected a multi-page preview, got {page_count}"
);
let edited = source
.replace("Paragraph 30 ", "Paragraph 30 changed ")
.replace("Paragraph 33 ", "Paragraph 33 changed ");
let second = project_preview_json("route-d-multi-edit", &edited).expect("edited preview");
let second: serde_json::Value = serde_json::from_str(&second).expect("edited JSON");
assert!(
second["changedPages"]
.as_array()
.is_some_and(|pages| !pages.is_empty())
);
let recomputed = second["recomputedPages"].as_u64().expect("recomputed");
assert!(recomputed < page_count, "changed pages should be a subset");
}
#[test]
fn structural_edit_keeps_pages_before_the_inserted_paragraph() {
let source = multi_page_source();
let first =
project_preview_json("route-d-structural-edit", &source).expect("first preview");
let first: serde_json::Value = serde_json::from_str(&first).expect("first JSON");
let first_hash = first["pages"][0]["hash"].as_str().expect("first hash");
let inserted = source.replacen(
"Paragraph 21 ",
"Paragraph inserted before twenty-one with enough words to make a line.\n\nParagraph 21 ",
1,
);
let second =
project_preview_json("route-d-structural-edit", &inserted).expect("inserted preview");
let second: serde_json::Value = serde_json::from_str(&second).expect("second JSON");
assert_eq!(
second["pages"][0]["hash"].as_str().expect("second hash"),
first_hash
);
let page_count = second["pageCount"].as_u64().expect("page count");
assert!(
second["changedPages"]
.as_array()
.is_some_and(|pages| !pages.is_empty())
);
assert!(
second["recomputedPages"].as_u64().expect("recomputed") < page_count,
"the unchanged prefix should not be recomputed"
);
}
}