1162 lines
46 KiB
Rust
Executable File
1162 lines
46 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_paper};
|
|
use texrra_tex_core::{Document, Engine, ParagraphFont, ParagraphStyle, Unit};
|
|
|
|
const SCALE: i64 = 65_536;
|
|
|
|
thread_local! {
|
|
static ROUTE_D_SESSION: RefCell<Option<(Document, Engine)>> = const { RefCell::new(None) };
|
|
}
|
|
|
|
struct ProjectSession {
|
|
paragraphs: Vec<SourceParagraph>,
|
|
geometry: PageGeometry,
|
|
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 (body, geometry) = geometry_and_body(source);
|
|
let paragraphs = paragraphs(&body)?;
|
|
let mut document = build_document(¶graphs, &geometry);
|
|
apply_geometry(&mut document, &geometry);
|
|
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.geometry == geometry {
|
|
(session.engine, Vec::new(), 0)
|
|
} else if session.geometry == geometry {
|
|
let prefix = session
|
|
.paragraphs
|
|
.iter()
|
|
.zip(¶graphs)
|
|
.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)
|
|
}
|
|
} 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(&document, &engine, Some((&changed, recomputed)));
|
|
sessions.insert(
|
|
project_id.to_string(),
|
|
ProjectSession {
|
|
paragraphs,
|
|
geometry,
|
|
engine,
|
|
},
|
|
);
|
|
Ok(json)
|
|
}
|
|
|
|
/// Page geometry pulled out of the source preamble.
|
|
#[derive(Clone, Debug, Default, PartialEq, Eq)]
|
|
struct PageGeometry {
|
|
origin: PageOrigin,
|
|
paper_width: Option<i64>,
|
|
paper_height: Option<i64>,
|
|
vsize: Option<i64>,
|
|
textheight: Option<i64>,
|
|
par_indent: Option<i64>,
|
|
par_skip: Option<i64>,
|
|
baseline_skip: Option<i64>,
|
|
left_skip: Option<i64>,
|
|
right_skip: Option<i64>,
|
|
tolerance: Option<i64>,
|
|
pretolerance: Option<i64>,
|
|
looseness: Option<i64>,
|
|
emergency_stretch: Option<i64>,
|
|
hang_indent: Option<i64>,
|
|
hang_after: Option<i64>,
|
|
french_spacing: Option<bool>,
|
|
space_skip: Option<(i64, i64, i64)>,
|
|
xspace_skip: Option<(i64, i64, i64)>,
|
|
hyphenation_exceptions: Vec<String>,
|
|
par_shape: Vec<(i64, i64)>,
|
|
lineskip: Option<i64>,
|
|
lineskiplimit: Option<i64>,
|
|
par_fillskip: Option<(i64, i64, bool)>,
|
|
top_skip: Option<i64>,
|
|
max_depth: Option<i64>,
|
|
split_top_skip: Option<i64>,
|
|
hyphen_penalty: Option<i64>,
|
|
ex_hyphen_penalty: Option<i64>,
|
|
double_hyphen_demerits: Option<i64>,
|
|
final_hyphen_demerits: Option<i64>,
|
|
line_penalty: Option<i64>,
|
|
adj_demerits: Option<i64>,
|
|
space_factor_codes: Vec<(char, i64)>,
|
|
}
|
|
|
|
/// Pull `\hoffset`/`\voffset`/`\paperwidth`/`\paperheight`/`\vsize`/
|
|
/// `\textheight` assignments out of the source and return the remaining body.
|
|
/// Each command takes a TeX dimension. LaTeX resets `\vsize` from
|
|
/// `\textheight` at every page, so `\textheight` wins when both appear.
|
|
fn strip_page_geometry(source: &str) -> (String, PageGeometry) {
|
|
let mut geometry = PageGeometry::default();
|
|
let mut body = String::new();
|
|
for line in source.lines() {
|
|
let trimmed = line.trim();
|
|
if let Some(value) = dimension_assignment(trimmed, "hoffset") {
|
|
geometry.origin.h_offset = value;
|
|
} else if let Some(value) = dimension_assignment(trimmed, "voffset") {
|
|
geometry.origin.v_offset = value;
|
|
} else if let Some(value) = dimension_assignment(trimmed, "paperwidth") {
|
|
geometry.paper_width = Some(value);
|
|
} else if let Some(value) = dimension_assignment(trimmed, "paperheight") {
|
|
geometry.paper_height = Some(value);
|
|
} else if let Some(value) = dimension_assignment(trimmed, "vsize") {
|
|
geometry.vsize = Some(value);
|
|
} else if let Some(value) = dimension_assignment(trimmed, "textheight") {
|
|
geometry.textheight = Some(value);
|
|
} else if let Some(value) = dimension_assignment(trimmed, "parindent") {
|
|
geometry.par_indent = Some(value);
|
|
} else if let Some(value) = dimension_assignment(trimmed, "parskip") {
|
|
geometry.par_skip = Some(value);
|
|
} else if let Some(value) = dimension_assignment(trimmed, "baselineskip") {
|
|
geometry.baseline_skip = Some(value);
|
|
} else if let Some(value) = dimension_assignment(trimmed, "leftskip") {
|
|
geometry.left_skip = Some(value);
|
|
} else if let Some(value) = dimension_assignment(trimmed, "rightskip") {
|
|
geometry.right_skip = Some(value);
|
|
} else if let Some(value) = dimension_assignment(trimmed, "emergencystretch") {
|
|
geometry.emergency_stretch = Some(value);
|
|
} else if let Some(value) = integer_assignment(trimmed, "tolerance") {
|
|
geometry.tolerance = Some(value);
|
|
} else if let Some(value) = integer_assignment(trimmed, "pretolerance") {
|
|
geometry.pretolerance = Some(value);
|
|
} else if let Some(value) = signed_integer_assignment(trimmed, "looseness") {
|
|
geometry.looseness = Some(value.clamp(-9, 9));
|
|
} else if let Some(value) = dimension_assignment(trimmed, "hangindent") {
|
|
geometry.hang_indent = Some(value);
|
|
} else if let Some(value) = integer_assignment(trimmed, "hangafter") {
|
|
geometry.hang_after = Some(value);
|
|
} else if let Some(value) = glue_assignment(trimmed, "spaceskip") {
|
|
geometry.space_skip = Some(value);
|
|
} else if let Some(value) = glue_assignment(trimmed, "xspaceskip") {
|
|
geometry.xspace_skip = Some(value);
|
|
} else if let Some(value) = dimension_assignment(trimmed, "lineskip") {
|
|
geometry.lineskip = Some(value);
|
|
} else if let Some(value) = dimension_assignment(trimmed, "lineskiplimit") {
|
|
geometry.lineskiplimit = Some(value);
|
|
} else if let Some((character, value)) = sfcode_assignment(trimmed) {
|
|
geometry.space_factor_codes.push((character, value));
|
|
} else if let Some(value) = integer_assignment(trimmed, "hyphenpenalty") {
|
|
geometry.hyphen_penalty = Some(value);
|
|
} else if let Some(value) = integer_assignment(trimmed, "exhyphenpenalty") {
|
|
geometry.ex_hyphen_penalty = Some(value);
|
|
} else if let Some(value) = integer_assignment(trimmed, "doublehyphendemerits") {
|
|
geometry.double_hyphen_demerits = Some(value);
|
|
} else if let Some(value) = integer_assignment(trimmed, "finalhyphendemerits") {
|
|
geometry.final_hyphen_demerits = Some(value);
|
|
} else if let Some(value) = integer_assignment(trimmed, "linepenalty") {
|
|
geometry.line_penalty = Some(value);
|
|
} else if let Some(value) = integer_assignment(trimmed, "adjdemerits") {
|
|
geometry.adj_demerits = Some(value);
|
|
} else if let Some(value) = dimension_assignment(trimmed, "topskip") {
|
|
geometry.top_skip = Some(value);
|
|
} else if let Some(value) = dimension_assignment(trimmed, "maxdepth") {
|
|
geometry.max_depth = Some(value);
|
|
} else if let Some(value) = dimension_assignment(trimmed, "splittopskip") {
|
|
geometry.split_top_skip = Some(value);
|
|
} else if let Some(value) = parfillskip_assignment(trimmed) {
|
|
geometry.par_fillskip = Some(value);
|
|
} else if let Some(value) = parshape_assignment(trimmed) {
|
|
geometry.par_shape = value;
|
|
} else if let Some(value) = braced_argument(trimmed, "\\hyphenation") {
|
|
geometry
|
|
.hyphenation_exceptions
|
|
.extend(value.split_whitespace().map(str::to_string));
|
|
} else if trimmed == "\\frenchspacing" {
|
|
geometry.french_spacing = Some(true);
|
|
} else if trimmed == "\\nonfrenchspacing" {
|
|
geometry.french_spacing = Some(false);
|
|
} else {
|
|
body.push_str(line);
|
|
body.push('\n');
|
|
}
|
|
}
|
|
(body, geometry)
|
|
}
|
|
|
|
/// Strip geometry assignments from the whole source (preamble included) and
|
|
/// return the LaTeX body with them removed.
|
|
fn geometry_and_body(source: &str) -> (String, PageGeometry) {
|
|
let (stripped, geometry) = strip_page_geometry(source);
|
|
// Removed assignments can leave blank lines at the edges; they are not
|
|
// paragraphs of their own.
|
|
let body = latex_body(&stripped).trim_matches('\n').to_string();
|
|
(body, geometry)
|
|
}
|
|
|
|
fn apply_geometry(document: &mut Document, geometry: &PageGeometry) {
|
|
document.h_offset = geometry.origin.h_offset;
|
|
document.v_offset = geometry.origin.v_offset;
|
|
if let Some(width) = geometry.paper_width {
|
|
document.paper_width = width;
|
|
}
|
|
if let Some(height) = geometry.paper_height {
|
|
document.paper_height = height;
|
|
}
|
|
if let Some(height) = geometry.textheight.or(geometry.vsize) {
|
|
document.page_goal = height;
|
|
}
|
|
if let Some(skip) = geometry.par_skip {
|
|
document.par_skip = skip;
|
|
}
|
|
if let Some(skip) = geometry.top_skip {
|
|
document.top_skip = skip;
|
|
}
|
|
if let Some(depth) = geometry.max_depth {
|
|
document.max_depth = depth;
|
|
}
|
|
if let Some(skip) = geometry.split_top_skip {
|
|
document.split_top_skip = skip;
|
|
}
|
|
}
|
|
|
|
/// Read a `\parfillskip` glue assignment, preserving the `1fil` order.
|
|
fn parfillskip_assignment(line: &str) -> Option<(i64, i64, bool)> {
|
|
let rest = line.strip_prefix("\\parfillskip")?.trim_start();
|
|
let rest = rest.strip_prefix('=')?.trim();
|
|
let (width, rest) = split_glue_part(rest)?;
|
|
let mut stretch = 0_i64;
|
|
let mut fil = false;
|
|
let rest = rest.trim_start();
|
|
let rest = if let Some(rest) = rest.strip_prefix("plus") {
|
|
let rest = rest.trim_start();
|
|
if let Some(rest) = rest.strip_prefix("1fil") {
|
|
fil = true;
|
|
rest
|
|
} else {
|
|
let (value, rest) = split_glue_part(rest)?;
|
|
stretch = value;
|
|
rest
|
|
}
|
|
} else {
|
|
rest
|
|
};
|
|
let _ = rest;
|
|
Some((width, stretch, fil))
|
|
}
|
|
|
|
/// Read a `\parshape` specification such as `\parshape=2 0pt 100pt 20pt 80pt`.
|
|
fn parshape_assignment(line: &str) -> Option<Vec<(i64, i64)>> {
|
|
let rest = line.strip_prefix("\\parshape")?.trim_start();
|
|
let rest = rest.strip_prefix('=').unwrap_or(rest).trim();
|
|
let mut parts = rest.split_whitespace();
|
|
let count: usize = parts.next()?.parse().ok()?;
|
|
let mut shape = Vec::with_capacity(count);
|
|
for _ in 0..count {
|
|
let indent = parse_dimension(parts.next()?)?;
|
|
let width = parse_dimension(parts.next()?)?;
|
|
shape.push((indent, width));
|
|
}
|
|
Some(shape)
|
|
}
|
|
|
|
/// Read a braced argument such as `\hyphenation{hy-phen-a-tion}`.
|
|
fn braced_argument<'a>(line: &'a str, command: &str) -> Option<&'a str> {
|
|
let rest = line.strip_prefix(command)?.trim_start();
|
|
let rest = rest.strip_prefix('{')?;
|
|
let mut depth = 1_usize;
|
|
for (index, character) in rest.char_indices() {
|
|
match character {
|
|
'{' => depth += 1,
|
|
'}' => {
|
|
depth -= 1;
|
|
if depth == 0 {
|
|
return Some(&rest[..index]);
|
|
}
|
|
}
|
|
_ => {}
|
|
}
|
|
}
|
|
None
|
|
}
|
|
|
|
/// Read a `\sfcode` assignment such as ``\sfcode`x=2000`` or `\sfcode46=1000`.
|
|
fn sfcode_assignment(line: &str) -> Option<(char, i64)> {
|
|
let rest = line.strip_prefix("\\sfcode")?;
|
|
let rest = rest.trim_start();
|
|
let rest = rest.strip_prefix('=').unwrap_or(rest).trim_start();
|
|
let (character, rest) = if let Some(rest) = rest.strip_prefix('`') {
|
|
let rest = rest.strip_prefix('\\').unwrap_or(rest);
|
|
let mut characters = rest.chars();
|
|
let character = characters.next()?;
|
|
(character, characters.as_str())
|
|
} else {
|
|
let end = rest
|
|
.find(|character: char| !character.is_ascii_digit())
|
|
.unwrap_or(rest.len());
|
|
let code: u32 = rest[..end].parse().ok()?;
|
|
(char::from_u32(code)?, &rest[end..])
|
|
};
|
|
let rest = rest.trim_start().strip_prefix('=')?;
|
|
Some((character, rest.trim().parse().ok()?))
|
|
}
|
|
|
|
/// Read a plain integer assignment such as `\tolerance=1000`.
|
|
fn glue_assignment(line: &str, name: &str) -> Option<(i64, i64, i64)> {
|
|
let rest = line.strip_prefix('\\')?;
|
|
let rest = rest.strip_prefix(name)?;
|
|
let rest = rest.trim_start().strip_prefix('=')?;
|
|
let rest = rest.trim();
|
|
let (width, rest) = split_glue_part(rest)?;
|
|
let (stretch, rest) = match rest.trim_start().strip_prefix("plus") {
|
|
Some(rest) => split_glue_part(rest.trim_start())?,
|
|
None => (0, rest),
|
|
};
|
|
let shrink = match rest.trim_start().strip_prefix("minus") {
|
|
Some(rest) => split_glue_part(rest.trim_start())?.0,
|
|
None => 0,
|
|
};
|
|
Some((width, stretch, shrink))
|
|
}
|
|
|
|
fn split_glue_part(text: &str) -> Option<(i64, &str)> {
|
|
let end = text
|
|
.find(|character: char| {
|
|
!(character.is_ascii_digit() || character == '.' || character == '-')
|
|
})
|
|
.unwrap_or(text.len());
|
|
let number: f64 = text[..end].parse().ok()?;
|
|
let unit_text = &text[end..];
|
|
let (unit, rest) = ["pt", "bp", "in", "cm", "mm", "pc"]
|
|
.iter()
|
|
.find_map(|unit| unit_text.strip_prefix(unit).map(|rest| (*unit, rest)))?;
|
|
let factor = match unit {
|
|
"pt" => 65_536.0,
|
|
"bp" => 65_782.0,
|
|
"in" => 4_736_286.0,
|
|
"cm" => 1_864_680.0,
|
|
"mm" => 186_468.0,
|
|
_ => 786_432.0,
|
|
};
|
|
Some(((number * factor).round() as i64, rest))
|
|
}
|
|
|
|
fn integer_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('=')?;
|
|
rest.trim()
|
|
.parse::<i64>()
|
|
.ok()
|
|
.map(|value| value.clamp(0, 10_000))
|
|
}
|
|
|
|
/// Read a signed integer assignment such as `\\looseness=-1`.
|
|
fn signed_integer_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('=')?;
|
|
rest.trim().parse::<i64>().ok()
|
|
}
|
|
|
|
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 (body, geometry) = geometry_and_body(source);
|
|
let paragraphs = paragraphs(&body)?;
|
|
let mut document = build_document(¶graphs, &geometry);
|
|
apply_geometry(&mut document, &geometry);
|
|
let engine = Engine::layout(&document);
|
|
let json = render_json(&document, &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, geometry) = geometry_and_body(source);
|
|
let paragraphs = paragraphs(&body)?;
|
|
let mut document = build_document(¶graphs, &geometry);
|
|
apply_geometry(&mut document, &geometry);
|
|
let engine = Engine::layout(&document);
|
|
let pages: Vec<_> = engine
|
|
.pages()
|
|
.iter()
|
|
.map(|page| {
|
|
let mut list =
|
|
page.display_list_with_layout(document.page_goal, document.text_float_sep);
|
|
list.width = list.width.max(document.paper_width);
|
|
list.height = list.height.max(document.paper_height);
|
|
list
|
|
})
|
|
.collect();
|
|
Ok(display_lists_to_pdf_with_paper(
|
|
&pages,
|
|
document.paper_width,
|
|
document.paper_height,
|
|
geometry.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 (body, geometry) = geometry_and_body(source);
|
|
let paragraphs = paragraphs(&body)?;
|
|
if unit >= paragraphs.len() {
|
|
return Err(format!(
|
|
"unit {unit} is out of range for {} paragraphs",
|
|
paragraphs.len()
|
|
));
|
|
}
|
|
let next = build_document(¶graphs, &geometry);
|
|
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(&next, &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,
|
|
space_before: i64,
|
|
space_stretch: i64,
|
|
space_shrink: i64,
|
|
}
|
|
|
|
/// Recognise an explicit vertical skip command standing alone between
|
|
/// paragraphs.
|
|
fn vertical_skip(text: &str) -> Option<(i64, i64, i64)> {
|
|
match text.trim() {
|
|
"\\smallskip" => Some((3 * SCALE, SCALE, SCALE)),
|
|
"\\medskip" => Some((6 * SCALE, 2 * SCALE, 2 * SCALE)),
|
|
"\\bigskip" => Some((12 * SCALE, 4 * SCALE, 4 * SCALE)),
|
|
other => other
|
|
.strip_prefix("\\vskip")
|
|
.and_then(|rest| skip_glue(rest.trim_start())),
|
|
}
|
|
}
|
|
|
|
/// Parse `\vskip` glue: a width with optional `plus` and `minus` parts.
|
|
fn skip_glue(rest: &str) -> Option<(i64, i64, i64)> {
|
|
let mut width = None;
|
|
let mut stretch = 0_i64;
|
|
let mut shrink = 0_i64;
|
|
let mut mode = 0_u8;
|
|
for token in rest.split_whitespace() {
|
|
match token {
|
|
"plus" => mode = 1,
|
|
"minus" => mode = 2,
|
|
_ => {
|
|
let value = parse_dimension(token)?;
|
|
match mode {
|
|
0 => width = Some(value),
|
|
1 => stretch = value,
|
|
_ => shrink = value,
|
|
}
|
|
}
|
|
}
|
|
}
|
|
Some((width?, stretch, shrink))
|
|
}
|
|
|
|
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());
|
|
}
|
|
let mut result = Vec::new();
|
|
let mut pending = (0_i64, 0_i64, 0_i64);
|
|
for chunk in paragraphs {
|
|
if let Some(skip) = vertical_skip(chunk) {
|
|
pending.0 += skip.0;
|
|
pending.1 += skip.1;
|
|
pending.2 += skip.2;
|
|
continue;
|
|
}
|
|
let mut blocks = parse_blocks(chunk);
|
|
if let Some(first) = blocks.first_mut() {
|
|
first.space_before += pending.0;
|
|
first.space_stretch += pending.1;
|
|
first.space_shrink += pending.2;
|
|
pending = (0, 0, 0);
|
|
}
|
|
result.extend(blocks);
|
|
}
|
|
Ok(result)
|
|
}
|
|
|
|
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,
|
|
space_before: 0,
|
|
space_stretch: 0,
|
|
space_shrink: 0,
|
|
}
|
|
})
|
|
.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,
|
|
space_before: 0,
|
|
space_stretch: 0,
|
|
space_shrink: 0,
|
|
}];
|
|
}
|
|
}
|
|
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,
|
|
space_before: 0,
|
|
space_stretch: 0,
|
|
space_shrink: 0,
|
|
}
|
|
})
|
|
.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,
|
|
space_before: 0,
|
|
space_stretch: 0,
|
|
space_shrink: 0,
|
|
};
|
|
}
|
|
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,
|
|
space_before: 0,
|
|
space_stretch: 0,
|
|
space_shrink: 0,
|
|
};
|
|
}
|
|
}
|
|
SourceParagraph {
|
|
text: raw.to_string(),
|
|
font: ParagraphFont::Roman,
|
|
line_height: 12,
|
|
math: false,
|
|
left_skip: 0,
|
|
centered: false,
|
|
right_aligned: false,
|
|
space_before: 0,
|
|
space_stretch: 0,
|
|
space_shrink: 0,
|
|
}
|
|
}
|
|
|
|
fn build_document(paragraphs: &[SourceParagraph], geometry: &PageGeometry) -> Document {
|
|
let units = paragraphs
|
|
.iter()
|
|
.enumerate()
|
|
.map(|(index, paragraph)| {
|
|
if paragraph.math {
|
|
let mut unit = Unit::math(
|
|
index as u64,
|
|
parse_math(¶graph.text),
|
|
&Cmr10Metrics::default(),
|
|
);
|
|
unit.space_before = paragraph.space_before;
|
|
unit.space_stretch = paragraph.space_stretch;
|
|
unit.space_shrink = paragraph.space_shrink;
|
|
return unit;
|
|
}
|
|
let style = ParagraphStyle {
|
|
line_width: 480 * SCALE,
|
|
left_skip: paragraph.left_skip * SCALE + geometry.left_skip.unwrap_or(0),
|
|
centered: paragraph.centered,
|
|
right_aligned: paragraph.right_aligned,
|
|
looseness: geometry.looseness.unwrap_or(0),
|
|
ragged_right: false,
|
|
right_skip: geometry.right_skip.unwrap_or(0),
|
|
hang_indent: geometry.hang_indent.unwrap_or(0),
|
|
hang_after: geometry.hang_after.unwrap_or(1) as i32,
|
|
par_shape: geometry.par_shape.clone(),
|
|
par_fillskip: geometry
|
|
.par_fillskip
|
|
.map(|(width, _, _)| width)
|
|
.unwrap_or(0),
|
|
par_fillskip_stretch: geometry
|
|
.par_fillskip
|
|
.map(|(_, stretch, _)| stretch)
|
|
.unwrap_or(0),
|
|
par_fillskip_fil: geometry.par_fillskip.map(|(_, _, fil)| fil).unwrap_or(true),
|
|
frenchspacing: geometry.french_spacing.unwrap_or(false),
|
|
space_factor_codes: geometry.space_factor_codes.clone(),
|
|
baselineskip: geometry.baseline_skip.unwrap_or(12 * 65536),
|
|
lineskip: geometry.lineskip.unwrap_or(65536),
|
|
lineskiplimit: geometry.lineskiplimit.unwrap_or(0),
|
|
par_indent: geometry.par_indent.unwrap_or(0),
|
|
emergencystretch: geometry.emergency_stretch.unwrap_or(0),
|
|
pretolerance: geometry.pretolerance.unwrap_or(100),
|
|
tolerance: geometry.tolerance.unwrap_or(200),
|
|
hyphen_penalty: geometry.hyphen_penalty.unwrap_or(50),
|
|
ex_hyphen_penalty: geometry.ex_hyphen_penalty.unwrap_or(50),
|
|
double_hyphen_demerits: geometry.double_hyphen_demerits.unwrap_or(10_000),
|
|
final_hyphen_demerits: geometry.final_hyphen_demerits.unwrap_or(5_000),
|
|
line_penalty: geometry.line_penalty.unwrap_or(10),
|
|
adj_demerits: geometry.adj_demerits.unwrap_or(10_000),
|
|
hyphenation_exceptions: geometry.hyphenation_exceptions.clone(),
|
|
line_height: if paragraph.line_height == 12 {
|
|
geometry.baseline_skip.unwrap_or(12 * 65536)
|
|
} else {
|
|
paragraph.line_height * SCALE
|
|
},
|
|
char_width: 10 * SCALE,
|
|
space_width: 4 * SCALE,
|
|
space_stretch: 6 * SCALE,
|
|
space_shrink: 2 * SCALE,
|
|
space_skip: geometry.space_skip,
|
|
xspace_skip: geometry.xspace_skip,
|
|
};
|
|
let mut unit = Unit::paragraph_with_style_and_face(
|
|
index as u64,
|
|
paragraph.text.clone(),
|
|
style,
|
|
paragraph.font,
|
|
);
|
|
unit.space_before = paragraph.space_before;
|
|
unit.space_stretch = paragraph.space_stretch;
|
|
unit.space_shrink = paragraph.space_shrink;
|
|
unit
|
|
})
|
|
.collect();
|
|
Document::new(700 * SCALE, units)
|
|
}
|
|
|
|
fn render_json(document: &Document, engine: &Engine, edit: Option<(&[usize], usize)>) -> String {
|
|
let mut json = String::new();
|
|
let page_width_mm = document.paper_width as f64 / SCALE as f64 * 25.4 / 72.0;
|
|
let page_height_mm = document.paper_height as f64 / SCALE as f64 * 25.4 / 72.0;
|
|
let page_height_pt = document.paper_height as f64 / SCALE as f64;
|
|
let _ = write!(
|
|
json,
|
|
"{{\"status\":\"ok\",\"pageWidthMm\":{page_width_mm:.2},\"pageHeightMm\":{page_height_mm:.2},\"pages\":["
|
|
);
|
|
for (index, page) in engine.pages().iter().enumerate() {
|
|
let mut list = page.display_list_with_layout(document.page_goal, document.text_float_sep);
|
|
list.width = list.width.max(document.paper_width);
|
|
list.height = list.height.max(document.paper_height);
|
|
list.place(document.h_offset, document.v_offset);
|
|
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
|
|
);
|
|
}
|
|
let _ = write!(json, ",\"pageHeightPt\":{page_height_pt:.0}}}");
|
|
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"
|
|
);
|
|
}
|
|
}
|
|
|
|
#[cfg(test)]
|
|
mod source_tests {
|
|
use super::*;
|
|
|
|
#[test]
|
|
fn reads_hang_registers_from_the_preamble() {
|
|
let (body, geometry) = geometry_and_body(
|
|
"\\hangindent=20pt\n\\hangafter=1\n\\tolerance=1000\n\\pretolerance=50\n\\looseness=-1\n\\spaceskip=6pt plus 1pt minus 0.5pt\n\\frenchspacing\n\nword word",
|
|
);
|
|
assert_eq!(geometry.hang_indent, Some(20 * 65_536));
|
|
assert_eq!(geometry.hang_after, Some(1));
|
|
let pt = 65_536;
|
|
assert_eq!(geometry.tolerance, Some(1000));
|
|
assert_eq!(geometry.pretolerance, Some(50));
|
|
assert_eq!(geometry.looseness, Some(-1));
|
|
assert_eq!(geometry.space_skip, Some((6 * pt, pt, pt / 2)));
|
|
assert_eq!(geometry.french_spacing, Some(true));
|
|
let paragraphs = paragraphs(&body).expect("paragraphs");
|
|
assert_eq!(paragraphs.len(), 1, "{body:?}");
|
|
let document = build_document(¶graphs, &geometry);
|
|
let style = document.units[0].paragraph_style.clone().expect("style");
|
|
assert_eq!(style.hang_indent, 20 * 65_536);
|
|
assert_eq!(style.hang_after, 1);
|
|
assert_eq!(style.tolerance, 1000);
|
|
assert_eq!(style.pretolerance, 50);
|
|
assert_eq!(style.looseness, -1);
|
|
assert_eq!(style.space_skip, Some((6 * pt, pt, pt / 2)));
|
|
assert!(style.frenchspacing);
|
|
}
|
|
#[test]
|
|
fn geometry_reads_hyphenation_exceptions() {
|
|
let source = "\\documentclass{article}\n\\hyphenation{zzz-zzz alpha-beta}\n\\begin{document}\n\nzzzzzz\n\n\\end{document}\n";
|
|
let (body, geometry) = geometry_and_body(source);
|
|
assert_eq!(
|
|
geometry.hyphenation_exceptions,
|
|
vec!["zzz-zzz".to_string(), "alpha-beta".to_string()]
|
|
);
|
|
assert!(!body.contains("hyphenation"));
|
|
let paragraphs = paragraphs(&body).expect("paragraphs");
|
|
let document = build_document(¶graphs, &geometry);
|
|
let style = document.units[0]
|
|
.paragraph_style
|
|
.clone()
|
|
.expect("paragraph style");
|
|
assert_eq!(
|
|
style.hyphenation_exceptions,
|
|
geometry.hyphenation_exceptions
|
|
);
|
|
}
|
|
#[test]
|
|
fn geometry_reads_parshape() {
|
|
let source = "\\documentclass{article}\n\\parshape=2 0pt 100pt 20pt 80pt\n\\begin{document}\n\nSome words here.\n\n\\end{document}\n";
|
|
let (body, geometry) = geometry_and_body(source);
|
|
assert_eq!(
|
|
geometry.par_shape,
|
|
vec![(0, 100 * SCALE), (20 * SCALE, 80 * SCALE)]
|
|
);
|
|
assert!(!body.contains("parshape"));
|
|
let paragraphs = paragraphs(&body).expect("paragraphs");
|
|
let document = build_document(¶graphs, &geometry);
|
|
let style = document.units[0]
|
|
.paragraph_style
|
|
.clone()
|
|
.expect("paragraph style");
|
|
assert_eq!(style.par_shape, geometry.par_shape);
|
|
}
|
|
#[test]
|
|
fn geometry_reads_parfillskip_and_lineskip() {
|
|
let source = "\\documentclass{article}\n\\parfillskip=0pt plus 1fil\n\\lineskip=2pt\n\\lineskiplimit=3pt\n\\begin{document}\n\nSome words here.\n\n\\end{document}\n";
|
|
let (body, geometry) = geometry_and_body(source);
|
|
assert_eq!(geometry.par_fillskip, Some((0, 0, true)));
|
|
assert_eq!(geometry.lineskip, Some(2 * SCALE));
|
|
assert_eq!(geometry.lineskiplimit, Some(3 * SCALE));
|
|
assert!(!body.contains("parfillskip"));
|
|
let paragraphs = paragraphs(&body).expect("paragraphs");
|
|
let document = build_document(¶graphs, &geometry);
|
|
let style = document.units[0]
|
|
.paragraph_style
|
|
.clone()
|
|
.expect("paragraph style");
|
|
assert_eq!(style.par_fillskip, 0);
|
|
assert!(style.par_fillskip_fil);
|
|
assert_eq!(style.lineskip, 2 * SCALE);
|
|
assert_eq!(style.lineskiplimit, 3 * SCALE);
|
|
}
|
|
#[test]
|
|
fn geometry_reads_page_skip_registers() {
|
|
let source = "\\documentclass{article}\n\\topskip=10pt\n\\maxdepth=5pt\n\\splittopskip=3pt\n\\begin{document}\n\nSome words here.\n\n\\end{document}\n";
|
|
let (body, geometry) = geometry_and_body(source);
|
|
assert_eq!(geometry.top_skip, Some(10 * SCALE));
|
|
assert_eq!(geometry.max_depth, Some(5 * SCALE));
|
|
assert_eq!(geometry.split_top_skip, Some(3 * SCALE));
|
|
assert!(!body.contains("topskip"));
|
|
let paragraphs = paragraphs(&body).expect("paragraphs");
|
|
let mut document = build_document(¶graphs, &geometry);
|
|
apply_geometry(&mut document, &geometry);
|
|
assert_eq!(document.top_skip, 10 * SCALE);
|
|
assert_eq!(document.max_depth, 5 * SCALE);
|
|
assert_eq!(document.split_top_skip, 3 * SCALE);
|
|
}
|
|
#[test]
|
|
fn geometry_reads_demerit_registers() {
|
|
let source = "\\documentclass{article}\n\\hyphenpenalty=77\n\\exhyphenpenalty=88\n\\doublehyphendemerits=1234\n\\finalhyphendemerits=4321\n\\linepenalty=20\n\\adjdemerits=999\n\\begin{document}\n\nSome words here.\n\n\\end{document}\n";
|
|
let (body, geometry) = geometry_and_body(source);
|
|
assert_eq!(geometry.hyphen_penalty, Some(77));
|
|
assert_eq!(geometry.ex_hyphen_penalty, Some(88));
|
|
assert_eq!(geometry.double_hyphen_demerits, Some(1234));
|
|
assert_eq!(geometry.final_hyphen_demerits, Some(4321));
|
|
assert_eq!(geometry.line_penalty, Some(20));
|
|
assert_eq!(geometry.adj_demerits, Some(999));
|
|
assert!(!body.contains("hyphenpenalty"));
|
|
let paragraphs = paragraphs(&body).expect("paragraphs");
|
|
let document = build_document(¶graphs, &geometry);
|
|
let style = document.units[0]
|
|
.paragraph_style
|
|
.clone()
|
|
.expect("paragraph style");
|
|
assert_eq!(style.hyphen_penalty, 77);
|
|
assert_eq!(style.ex_hyphen_penalty, 88);
|
|
assert_eq!(style.double_hyphen_demerits, 1234);
|
|
assert_eq!(style.final_hyphen_demerits, 4321);
|
|
assert_eq!(style.line_penalty, 20);
|
|
assert_eq!(style.adj_demerits, 999);
|
|
}
|
|
#[test]
|
|
fn geometry_reads_sfcode_assignments() {
|
|
let source = "\\documentclass{article}\n\\sfcode61=1000\n\\sfcode`x=2000\n\\begin{document}\n\nSome words here.\n\n\\end{document}\n";
|
|
let (body, geometry) = geometry_and_body(source);
|
|
assert_eq!(geometry.space_factor_codes, vec![('=', 1000), ('x', 2000)]);
|
|
assert!(!body.contains("sfcode"));
|
|
let paragraphs = paragraphs(&body).expect("paragraphs");
|
|
let document = build_document(¶graphs, &geometry);
|
|
let style = document.units[0]
|
|
.paragraph_style
|
|
.clone()
|
|
.expect("paragraph style");
|
|
assert_eq!(style.space_factor_codes, geometry.space_factor_codes);
|
|
}
|
|
#[test]
|
|
fn preview_pages_honour_page_offsets() {
|
|
let plain = preview_json("Hello route D").expect("plain preview");
|
|
let shifted =
|
|
preview_json("\\hoffset=10pt\n\\voffset=5pt\nHello route D").expect("shifted");
|
|
fn first_text_position(json: &str) -> (f64, f64) {
|
|
let value: serde_json::Value = serde_json::from_str(json).expect("JSON");
|
|
let svg = value["pages"][0]["svg"].as_str().expect("svg");
|
|
let start = svg.find("<text").expect("text element");
|
|
let rest = &svg[start..];
|
|
let x_start = rest.find("x=\"").expect("x") + 3;
|
|
let x_end = rest[x_start..].find('"').expect("x end") + x_start;
|
|
let y_start = rest.find("y=\"").expect("y") + 3;
|
|
let y_end = rest[y_start..].find('"').expect("y end") + y_start;
|
|
(
|
|
rest[x_start..x_end].parse().expect("x value"),
|
|
rest[y_start..y_end].parse().expect("y value"),
|
|
)
|
|
}
|
|
let (plain_x, plain_y) = first_text_position(&plain);
|
|
let (shifted_x, shifted_y) = first_text_position(&shifted);
|
|
assert!(
|
|
(shifted_x - plain_x - 10.0).abs() < 1.0,
|
|
"x shift {} from {}",
|
|
shifted_x,
|
|
plain_x
|
|
);
|
|
assert!(
|
|
(shifted_y - plain_y - 5.0).abs() < 1.0,
|
|
"y shift {} from {}",
|
|
shifted_y,
|
|
plain_y
|
|
);
|
|
}
|
|
#[test]
|
|
fn paragraphs_read_vertical_skip_commands() {
|
|
let source = "Alpha.\n\n\\medskip\n\nBeta.\n\n\\bigskip\n\nGamma.\n\n\\vskip 5pt plus 2pt minus 1pt\n\nDelta.";
|
|
let parsed = paragraphs(source).expect("paragraphs");
|
|
assert_eq!(parsed.len(), 4);
|
|
assert_eq!(parsed[0].space_before, 0);
|
|
assert_eq!(parsed[1].space_before, 6 * SCALE);
|
|
assert_eq!(parsed[1].space_stretch, 2 * SCALE);
|
|
assert_eq!(parsed[1].space_shrink, 2 * SCALE);
|
|
assert_eq!(parsed[2].space_before, 12 * SCALE);
|
|
assert_eq!(parsed[2].space_stretch, 4 * SCALE);
|
|
assert_eq!(parsed[2].space_shrink, 4 * SCALE);
|
|
assert_eq!(parsed[3].space_before, 5 * SCALE);
|
|
assert_eq!(parsed[3].space_stretch, 2 * SCALE);
|
|
assert_eq!(parsed[3].space_shrink, SCALE);
|
|
assert!(
|
|
!parsed
|
|
.iter()
|
|
.any(|paragraph| paragraph.text.contains("skip"))
|
|
);
|
|
let document = build_document(&parsed, &PageGeometry::default());
|
|
assert_eq!(document.units[1].space_before, 6 * SCALE);
|
|
assert_eq!(document.units[1].space_stretch, 2 * SCALE);
|
|
assert_eq!(document.units[1].space_shrink, 2 * SCALE);
|
|
assert_eq!(document.units[2].space_before, 12 * SCALE);
|
|
assert_eq!(document.units[3].space_before, 5 * SCALE);
|
|
assert_eq!(document.units[3].space_stretch, 2 * SCALE);
|
|
assert_eq!(document.units[3].space_shrink, SCALE);
|
|
}
|
|
}
|