Files
texrra-engine/src/route_d.rs
T

137 lines
4.5 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::{Document, Engine, ParagraphStyle, Unit};
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 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))
}
/// 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].to_string());
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)
})
}
fn paragraphs(source: &str) -> Result<Vec<&str>, 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)
}
fn build_document(paragraphs: &[&str]) -> Document {
let style = ParagraphStyle {
line_width: 480 * SCALE,
left_skip: 0,
right_skip: 0,
par_indent: 0,
line_height: 12 * SCALE,
char_width: 10 * SCALE,
space_width: 4 * SCALE,
space_stretch: 6 * SCALE,
space_shrink: 2 * SCALE,
};
let units = paragraphs
.iter()
.enumerate()
.map(|(index, paragraph)| {
Unit::paragraph_with_style(index as u64, (*paragraph).to_string(), style.clone())
})
.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
}