Advance native LaTeX execution and preview

This commit is contained in:
gloamxun committed 2026-11-18 22:17:21 +08:00
1 parent 91f9d76b16
commit 2741546ca8
414 files changed
+99872 -933

No files matched your search

+9 -3
View File
@@ -1,7 +1,13 @@
//! texrra engine library.
//!
//! Process, CLI, and HTTP concerns live in `src/main.rs`; this crate exposes
//! the typesetting session so tests and other frontends can drive the compiler
//! directly.
//! `native` owns strict Route-D jobs and completed revision results. CLI/HTTP
//! argument and transport concerns remain in `src/main.rs`. The legacy
//! typesetting frontend is exposed separately during product migration.
pub mod native;
mod native_generated;
mod native_host;
mod native_job;
mod native_preview;
mod native_stream;
pub mod rust_typeset;
+243 -2
View File
@@ -26,10 +26,150 @@ fn main() {
fn run() -> Result<(), String> {
let mut args = env::args().skip(1);
let Some(command) = args.next() else {
return Err("usage: texrra serve [input.tex] [port]".into());
return Err(
"usage: texrra serve [input.tex] [port] | texrra native [--job] [--initex] [--etex] [--dump-format | --load-format FILE] [--step-limit N] [--input-profile tex8bit|unicode] [--texmf-root DIR] [--input-policy tex|project] [--project-snapshot FILE] [--generated-initial JSON | --observe-generated-initial] [--resource-manifest JSON] [--layout-manifest JSON] [--failure-manifest JSON] input.tex [output.pdf]".into(),
);
};
if command == "native" {
let mut native_job_target = false;
let mut initex = false;
let mut dump_format = false;
let mut limits = texrra_tex_core::execution::Limits::default();
let mut load_format = None;
let mut etex = false;
let mut input_profile = texrra_tex_core::execution::InputProfile::TeX8Bit;
let mut texmf_roots = Vec::new();
let mut resource_manifest = None;
let mut layout_manifest = None;
let mut failure_manifest = None;
let mut project_snapshot = None;
let mut generated_initial = None;
let mut observe_generated_initial = false;
let mut input_policy_explicit = false;
let mut input_policy = texrra_tex_core::resources::InputPolicy::Project;
let input = loop {
match args.next().as_deref() {
Some("--input-profile") => {
input_profile = match args.next().as_deref() {
Some("tex8bit") => texrra_tex_core::execution::InputProfile::TeX8Bit,
Some("unicode") => texrra_tex_core::execution::InputProfile::UnicodeScalar,
_ => return Err("--input-profile requires tex8bit or unicode".into()),
};
}
Some("--job") => native_job_target = true,
Some("--initex") => initex = true,
Some("--etex") => etex = true,
Some("--dump-format") => dump_format = true,
Some("--step-limit") => {
limits.steps = args
.next()
.and_then(|value| value.parse::<usize>().ok())
.filter(|value| *value > 0)
.ok_or("--step-limit requires a positive integer")?;
}
Some("--load-format") => {
load_format = Some(PathBuf::from(
args.next().ok_or("--load-format requires a filename")?,
))
}
Some("--texmf-root") => texmf_roots.push(PathBuf::from(
args.next().ok_or("--texmf-root requires a directory")?,
)),
Some("--layout-manifest") => {
layout_manifest = Some(PathBuf::from(
args.next().ok_or("--layout-manifest requires a filename")?,
));
}
Some("--resource-manifest") => {
resource_manifest = Some(PathBuf::from(
args.next()
.ok_or("--resource-manifest requires a filename")?,
))
}
Some("--failure-manifest") => {
failure_manifest = Some(PathBuf::from(
args.next()
.ok_or("--failure-manifest requires a filename")?,
));
}
Some("--project-snapshot") => {
project_snapshot = Some(PathBuf::from(
args.next()
.ok_or("--project-snapshot requires a filename")?,
));
}
Some("--generated-initial") => {
generated_initial = Some(PathBuf::from(
args.next()
.ok_or("--generated-initial requires a filename")?,
));
}
Some("--observe-generated-initial") => observe_generated_initial = true,
Some("--input-policy") => {
input_policy_explicit = true;
input_policy = match args.next().as_deref() {
Some("tex") => texrra_tex_core::resources::InputPolicy::Tex,
Some("project") => texrra_tex_core::resources::InputPolicy::Project,
_ => return Err("--input-policy requires tex or project".into()),
}
}
Some(value) if value.starts_with('-') => {
return Err(format!("unknown native option: {value}"));
}
Some(value) => break PathBuf::from(value),
None => return Err("native requires input.tex".into()),
}
};
if generated_initial.is_some() && observe_generated_initial {
return Err("select --generated-initial or --observe-generated-initial".into());
}
if project_snapshot.is_some() && (!texmf_roots.is_empty() || input_policy_explicit) {
return Err("--project-snapshot defines its resource paths and input policy; do not combine it with --texmf-root or --input-policy".into());
}
if dump_format && (!initex || load_format.is_some()) || initex && load_format.is_some() {
return Err(
"format dump requires INITEX, and format load requires a new document job".into(),
);
}
if dump_format || load_format.is_some() {
native_job_target = true;
}
if layout_manifest.is_some() && (!native_job_target || dump_format) {
return Err("--layout-manifest requires a native document job".into());
}
let output = args
.next()
.map(PathBuf::from)
.unwrap_or_else(|| input.with_extension(if dump_format { "tfx" } else { "pdf" }));
if args.next().is_some() {
return Err("usage: texrra native [--job] [--initex] [--etex] [--dump-format | --load-format FILE] [--step-limit N] [--input-profile tex8bit|unicode] [--texmf-root DIR] [--input-policy tex|project] [--project-snapshot FILE] [--generated-initial JSON | --observe-generated-initial] [--resource-manifest JSON] [--layout-manifest JSON] [--failure-manifest JSON] input.tex [output.pdf]".into());
}
let diagnostic = native_pdf(
&input,
&output,
initex,
etex,
&texmf_roots,
resource_manifest.as_deref(),
layout_manifest.as_deref(),
failure_manifest.as_deref(),
project_snapshot.as_deref(),
generated_initial.as_deref(),
observe_generated_initial,
input_policy,
input_profile,
native_job_target,
dump_format,
load_format.as_deref(),
limits,
)?;
if diagnostic {
process::exit(1);
}
return Ok(());
}
if command != "serve" {
return Err("the only command is `serve`".into());
return Err("expected serve or native".into());
}
let input_path = args
@@ -85,6 +225,107 @@ fn run() -> Result<(), String> {
Ok(())
}
/// Strict native bootstrap entry: typed execution -> Route-D lists -> PDF.
/// CLI adapter; the library owns compilation, export and publication.
fn native_pdf(
input: &Path,
output: &Path,
initex: bool,
etex: bool,
texmf_roots: &[PathBuf],
manifest: Option<&Path>,
layout_manifest: Option<&Path>,
failure_manifest: Option<&Path>,
project_snapshot: Option<&Path>,
generated_initial: Option<&Path>,
observe_generated_initial: bool,
input_policy: texrra_tex_core::resources::InputPolicy,
input_profile: texrra_tex_core::execution::InputProfile,
native_job_target: bool,
dump_format: bool,
load_format: Option<&Path>,
limits: texrra_tex_core::execution::Limits,
) -> Result<bool, String> {
use texrra_engine::native::{self, CompileRequest, Entry, NativeCompiler, Target};
let project = project_snapshot
.map(|path| -> Result<_, String> {
let bytes =
fs::read(path).map_err(|e| format!("project snapshot {}: {e}", path.display()))?;
let project: native::ProjectSnapshot =
serde_json::from_slice(&bytes).map_err(|e| e.to_string())?;
project.validate()?;
Ok(std::sync::Arc::new(project))
})
.transpose()?;
let world = if let Some(project) = &project {
project.configuration()
} else {
let mut world = texrra_tex_core::resources::WorldConfig::from_environment(
env::current_dir().map_err(|e| e.to_string())?,
texmf_roots.to_vec(),
)?;
world.input_policy = input_policy;
world
};
let mut request = CompileRequest::new(world, input, output, native::job_time()?);
if let Some(project) = project {
request = request.with_project(project);
}
if let Some(path) = generated_initial {
let bytes = fs::read(path)
.map_err(|e| format!("generated initial state {}: {e}", path.display()))?;
let state: native::GeneratedInitialState =
serde_json::from_slice(&bytes).map_err(|e| e.to_string())?;
state.validate()?;
request = request.with_generated_initial(state);
} else if observe_generated_initial {
request = request.observe_generated_initial();
}
request.entry = if let Some(path) = load_format {
Entry::Format(path.into())
} else if initex {
Entry::Initex
} else {
Entry::Bootstrap
};
request.target = if native_job_target {
Target::Shipouts
} else {
Target::Paragraphs
};
request.etex = etex;
request.input_profile = input_profile;
request.limits = limits;
request.resource_manifest = manifest.map(Path::to_owned);
request.layout_manifest = layout_manifest.map(Path::to_owned);
request.failure_manifest = failure_manifest.map(Path::to_owned);
request.terminal = true;
let failure_message = |failure: native::CompileFailure| {
for gap in &failure.evidence_gaps {
eprintln!("native failure evidence: {gap}");
}
failure.to_string()
};
if dump_format {
native::dump_format_detailed(request, texrra_tex_core::execution::Cancellation::default())
.map_err(failure_message)?;
return Ok(false);
}
let result = NativeCompiler::default()
.compile_detailed(request)
.map_err(failure_message)?;
if result.output.is_none() {
println!("native Route-D execution complete (no pages)");
} else {
println!(
"wrote {} ({} pages, native Route-D)",
output.display(),
result.pages.len()
);
}
Ok(result.has_show_diagnostic())
}
fn handle_request(
mut request: Request,
input_path: &PathBuf,
+1117
View File
File diff suppressed because it is too large. Load diff
+90
View File
@@ -0,0 +1,90 @@
//! Version preconditions for known mutable roles. These are actual observations
//! under the job's cooperative lock, not an atomic filesystem snapshot or lease.
use std::{
collections::BTreeMap,
path::{Component, Path, PathBuf},
};
use texrra_tex_core::resources::ResourceVersion;
#[derive(Clone, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
pub struct GeneratedInitialState {
schema: u32,
cwd: PathBuf,
files: BTreeMap<PathBuf, Option<ResourceVersion>>,
}
impl GeneratedInitialState {
pub fn new(
cwd: PathBuf,
files: BTreeMap<PathBuf, Option<ResourceVersion>>,
) -> Result<Self, String> {
let state = Self {
schema: 1,
cwd,
files,
};
state.validate()?;
Ok(state)
}
pub fn cwd(&self) -> &Path {
&self.cwd
}
pub fn files(&self) -> &BTreeMap<PathBuf, Option<ResourceVersion>> {
&self.files
}
pub fn validate(&self) -> Result<(), String> {
if self.schema != 1 || !normalized(&self.cwd) {
return Err("incompatible generated initial state".into());
}
for (path, version) in &self.files {
if !normalized(path)
|| version.as_ref().is_some_and(|v| {
v.path != *path
|| v.sha256.len() != 64
|| !v
.sha256
.bytes()
.all(|c| c.is_ascii_digit() || (b'a'..=b'f').contains(&c))
})
{
return Err(format!(
"invalid generated initial entry: {}",
path.display()
));
}
}
Ok(())
}
pub(crate) fn check(&self, actual: &Self) -> Result<(), String> {
if self.cwd != actual.cwd {
return Err("generated initial workdir differs from the actual host".into());
}
for path in self.files.keys().chain(actual.files.keys()) {
if self.files.get(path) != actual.files.get(path) {
return Err(format!(
"generated initial role or version mismatch: {}",
path.display()
));
}
}
Ok(())
}
}
fn normalized(path: &Path) -> bool {
path.is_absolute()
&& path.components().collect::<PathBuf>().as_os_str() == path.as_os_str()
&& !path
.components()
.any(|c| matches!(c, Component::CurDir | Component::ParentDir))
}
#[derive(Clone, Debug, Default, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
pub enum GeneratedInputPolicy {
/// Existing live I/O policy; no extra initial-state reads.
#[default]
Live,
/// Observe every known mutable role before the transcript is opened.
Observe,
/// Require exactly this role set and these versions. None means absence.
/// This neither adopts files nor authorizes skipping actual I/O.
Expect(GeneratedInitialState),
}
+242
View File
@@ -0,0 +1,242 @@
//! Actual host preparation observations. Locks and filesystem policy must be
//! checked live on every attempt; these records never grant cache permission.
use sha2::{Digest, Sha256};
use std::{
ffi::OsString,
fs,
io::{self, Read},
path::{Path, PathBuf},
sync::Arc,
time::SystemTime,
};
use texrra_tex_core::resources::ResourceVersion;
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
pub enum HostPreparationPhase {
#[default]
Environment,
OutputPaths,
StateDirectory,
MetadataPaths,
Lock,
Ledger,
Protection,
GeneratedInitial,
Log,
Ready,
}
#[derive(Clone, Debug, serde::Serialize, serde::Deserialize)]
pub struct HostMetadata {
pub directory: bool,
pub file: bool,
pub bytes: u64,
pub modified: Result<SystemTime, String>,
pub readonly: bool,
pub unix_identity: Option<(u64, u64)>,
}
#[derive(Clone, Debug, serde::Serialize, serde::Deserialize)]
pub enum VersionExpectation {
Any,
Exact(Option<ResourceVersion>),
}
#[derive(Clone, Debug, serde::Serialize, serde::Deserialize)]
pub enum HostObservation {
LogicalGeneratedPath {
logical: PathBuf,
resolved: Result<PathBuf, String>,
},
VersionCheck {
path: PathBuf,
expected: VersionExpectation,
observed: Result<Option<ResourceVersion>, String>,
},
Environment {
name: String,
value: Option<OsString>,
},
Canonicalize {
path: PathBuf,
result: Result<PathBuf, String>,
},
Metadata {
path: PathBuf,
result: Result<HostMetadata, String>,
},
Alias {
left: PathBuf,
right: PathBuf,
same: bool,
},
Operation {
name: String,
path: PathBuf,
result: Result<(), String>,
},
}
#[derive(Clone, Debug, serde::Serialize, serde::Deserialize)]
pub struct LedgerRead {
pub path: PathBuf,
/// None records absence. A failed/limited read can retain an actual prefix.
pub data: Option<Arc<[u8]>>,
pub eof: bool,
pub error: Option<String>,
/// Only present for bytes read through EOF, never for a partial prefix.
pub version: Option<ResourceVersion>,
}
#[derive(Clone, Debug, Default, serde::Serialize, serde::Deserialize)]
pub struct HostPreparation {
pub phase: HostPreparationPhase,
pub observations: Vec<HostObservation>,
pub ledger: Option<LedgerRead>,
#[serde(default)]
pub generated_initial: Option<crate::native_generated::GeneratedInitialState>,
}
impl HostPreparation {
pub(crate) fn environment(&mut self, name: &str) -> Option<OsString> {
let value = std::env::var_os(name);
self.observations.push(HostObservation::Environment {
name: name.into(),
value: value.clone(),
});
value
}
pub(crate) fn canonicalize(&mut self, path: &Path) -> io::Result<PathBuf> {
let result = path.canonicalize();
self.observations.push(HostObservation::Canonicalize {
path: path.into(),
result: result
.as_ref()
.map(Clone::clone)
.map_err(ToString::to_string),
});
result
}
pub(crate) fn metadata(&mut self, path: &Path) -> io::Result<fs::Metadata> {
let result = path.metadata();
let observed = result
.as_ref()
.map(|m| {
#[cfg(unix)]
let identity = {
use std::os::unix::fs::MetadataExt;
Some((m.dev(), m.ino()))
};
#[cfg(not(unix))]
let identity = None;
HostMetadata {
directory: m.is_dir(),
file: m.is_file(),
bytes: m.len(),
modified: m.modified().map_err(|e| e.to_string()),
readonly: m.permissions().readonly(),
unix_identity: identity,
}
})
.map_err(ToString::to_string);
self.observations.push(HostObservation::Metadata {
path: path.into(),
result: observed,
});
result
}
pub(crate) fn same_file(&mut self, a: &Path, b: &Path) -> bool {
let same = if a == b {
true
} else if self
.canonicalize(a)
.ok()
.zip(self.canonicalize(b).ok())
.is_some_and(|(a, b)| a == b)
{
true
} else {
#[cfg(unix)]
{
use std::os::unix::fs::MetadataExt;
if let (Ok(a), Ok(b)) = (self.metadata(a), self.metadata(b)) {
a.dev() == b.dev() && a.ino() == b.ino()
} else {
false
}
}
#[cfg(not(unix))]
{
false
}
};
self.observations.push(HostObservation::Alias {
left: a.into(),
right: b.into(),
same,
});
same
}
pub(crate) fn output(&mut self, cwd: &Path, path: &Path) -> Result<PathBuf, String> {
let path = cwd.join(path);
if self.metadata(&path).is_ok() {
return self.canonicalize(&path).map_err(|e| e.to_string());
}
let parent = self
.canonicalize(path.parent().unwrap_or(cwd))
.map_err(|e| format!("output directory: {e}"))?;
Ok(parent.join(path.file_name().ok_or("output requires a filename")?))
}
pub(crate) fn operation<T>(
&mut self,
name: &str,
path: &Path,
result: &Result<T, impl ToString>,
) {
self.observations.push(HostObservation::Operation {
name: name.into(),
path: path.into(),
result: result.as_ref().map(|_| ()).map_err(ToString::to_string),
});
}
pub(crate) fn read_ledger(&mut self, path: &Path) -> Result<Option<Arc<[u8]>>, String> {
const LIMIT: u64 = 16 * 1024 * 1024;
let mut data = Vec::new();
let opened = fs::File::open(path);
self.operation("open ledger", path, &opened);
let result = match opened {
Ok(file) => file
.take(LIMIT + 1)
.read_to_end(&mut data)
.map(|_| ())
.map_err(|e| e.to_string()),
Err(e) if e.kind() == io::ErrorKind::NotFound => {
self.ledger = Some(LedgerRead {
path: path.into(),
data: None,
eof: true,
error: None,
version: None,
});
return Ok(None);
}
Err(e) => Err(format!("generated-file version {}: {e}", path.display())),
};
let result = result.and_then(|()| {
if data.len() as u64 > LIMIT {
Err("native generated-file ledger capacity exceeded".into())
} else {
Ok(())
}
});
self.operation("read ledger", path, &result);
let version = result.as_ref().ok().map(|()| ResourceVersion {
path: path.into(),
bytes: data.len() as u64,
sha256: format!("{:x}", Sha256::digest(&data)),
});
let data: Arc<[u8]> = Arc::from(data);
self.ledger = Some(LedgerRead {
path: path.into(),
data: Some(data.clone()),
eof: result.is_ok(),
error: result.as_ref().err().cloned(),
version,
});
result.map(|()| Some(data))
}
}
+1923
View File
File diff suppressed because it is too large. Load diff
+144
View File
@@ -0,0 +1,144 @@
//! Page preview updates produced from the same published native layout as PDF.
use hayro_svg::{
RenderCache, SvgRenderSettings, hayro_interpret::InterpreterSettings, hayro_syntax::Pdf,
};
use std::sync::{Arc, OnceLock};
use texrra_tex_core::render::DisplayList;
#[derive(Clone, Debug, PartialEq, Eq, serde::Serialize)]
pub struct PreviewPage {
pub index: usize,
pub svg: Arc<str>,
}
#[derive(Clone, Debug, PartialEq, Eq, serde::Serialize)]
pub struct PreviewUpdate {
/// None means replace the entire preview. Otherwise the receiver must be
/// displaying this exact revision before applying the update.
pub base_revision: Option<u64>,
pub revision: u64,
/// Remove any displayed pages at or beyond this index.
pub page_count: usize,
/// Zero-based page indices to replace or append.
pub pages: Vec<PreviewPage>,
}
type PageSvg = OnceLock<Result<Arc<str>, String>>;
struct PdfPreview<'a> {
bytes: Option<&'a Arc<[u8]>>,
document: OnceLock<Result<Pdf, String>>,
}
impl PdfPreview<'_> {
fn render_page(&self, index: usize) -> Result<Arc<str>, String> {
let document = self
.document
.get_or_init(|| {
let bytes = self
.bytes
.ok_or("embedded PDF preview has no published PDF")?;
Pdf::new(Arc::new(bytes.clone()))
.map_err(|error| format!("could not read the published preview PDF: {error:?}"))
})
.as_ref()
.map_err(Clone::clone)?;
let page = document
.pages()
.iter()
.nth(index)
.ok_or("preview PDF page is missing")?;
Ok(Arc::from(hayro_svg::convert(
page,
&RenderCache::new(),
&InterpreterSettings::default(),
&SvgRenderSettings::default(),
)))
}
}
pub(crate) struct PreviewState {
previous_revision: Option<u64>,
changed: Vec<usize>,
slots: Vec<Arc<PageSvg>>,
}
impl PreviewState {
pub(crate) fn new(
pages: &[DisplayList],
previous: Option<(u64, &[DisplayList], &Self)>,
pdf_unchanged: bool,
) -> Self {
let mut changed = Vec::new();
let mut slots = Vec::with_capacity(pages.len());
for (index, page) in pages.iter().enumerate() {
if let Some((_, old_pages, old)) = previous
&& (pdf_unchanged || !page.has_embedded_pdf())
&& old_pages
.get(index)
.is_some_and(|old_page| old_page.same_svg_paint(page))
{
slots.push(old.slots[index].clone());
} else {
changed.push(index);
slots.push(Arc::new(OnceLock::new()));
}
}
Self {
previous_revision: previous.map(|(revision, _, _)| revision),
changed,
slots,
}
}
pub(crate) fn render(
&self,
revision: u64,
pages: &[DisplayList],
pdf: Option<&Arc<[u8]>>,
visible: Option<u64>,
) -> Result<PreviewUpdate, String> {
let pdf = PdfPreview {
bytes: pdf,
document: OnceLock::new(),
};
let mut rendered = Vec::new();
let base_revision = if visible == Some(revision) {
visible
} else if visible.is_some() && visible == self.previous_revision {
for &index in &self.changed {
rendered.push(self.render_page(index, &pages[index], &pdf)?);
}
visible
} else {
for (index, page) in pages.iter().enumerate() {
rendered.push(self.render_page(index, page, &pdf)?);
}
None
};
Ok(PreviewUpdate {
base_revision,
revision,
page_count: pages.len(),
pages: rendered,
})
}
fn render_page(
&self,
index: usize,
page: &DisplayList,
pdf: &PdfPreview<'_>,
) -> Result<PreviewPage, String> {
let svg = self.slots[index]
.get_or_init(|| {
if page.has_embedded_pdf() {
pdf.render_page(index)
} else {
page.try_to_svg().map(Arc::from)
}
})
.clone()?;
Ok(PreviewPage { index, svg })
}
}
+316
View File
@@ -0,0 +1,316 @@
//! Actual SourceProvider stream effects. Offsets count bytes consumed/accepted
//! by this handle, not an OS descriptor cursor hidden behind BufReader. This
//! journal does not serialize read-ahead buffers or authorize effect replay.
use std::{
fs::File,
io::{self, BufRead, Write},
path::PathBuf,
sync::Arc,
};
use texrra_tex_core::resources::ResourceVersion;
#[derive(Clone, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
pub struct DescriptorIdentity {
pub regular_file: bool,
pub bytes: u64,
pub unix_identity: Option<(u64, u64)>,
}
pub(crate) fn descriptor(file: &File) -> Result<DescriptorIdentity, String> {
let metadata = file.metadata().map_err(|e| e.to_string())?;
#[cfg(unix)]
let unix_identity = {
use std::os::unix::fs::MetadataExt;
Some((metadata.dev(), metadata.ino()))
};
#[cfg(not(unix))]
let unix_identity = None;
Ok(DescriptorIdentity {
regular_file: metadata.is_file(),
bytes: metadata.len(),
unix_identity,
})
}
#[derive(Clone, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
pub enum InputStorage {
Snapshot(ResourceVersion),
File(Result<DescriptorIdentity, String>),
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
pub enum ReleaseCause {
Explicit,
Replaced,
Finish,
FailureCleanup,
}
#[derive(Clone, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
pub enum WriteOutcome {
Accepted(u64),
Interrupted,
Zero,
Failed(String),
}
#[derive(Clone, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
pub struct WriteAttempt {
pub requested: u64,
pub outcome: WriteOutcome,
}
#[derive(Clone, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
pub struct InputOpened {
pub handle: u64,
pub path: PathBuf,
pub storage: InputStorage,
}
#[derive(Clone, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
pub enum StreamEffect {
OpenInput {
stream: u8,
name: String,
from: String,
result: Result<Option<InputOpened>, String>,
},
ReadLine {
stream: u8,
handle: Option<u64>,
consumed_before: Option<u64>,
consumed: Arc<[u8]>,
observed_eof: bool,
delivered: bool,
error: Option<String>,
},
CloseInput {
stream: u8,
handle: Option<u64>,
path: Option<PathBuf>,
consumed: Option<u64>,
cause: ReleaseCause,
},
OpenOutputRequested {
stream: u8,
name: String,
from: String,
},
/// Emitted only after the real open/truncate succeeds, before ownership
/// persistence. A subsequent OpenOutputResult may still fail.
OutputOpened {
stream: u8,
handle: u64,
path: PathBuf,
before: Option<ResourceVersion>,
descriptor: Result<DescriptorIdentity, String>,
},
OpenOutputResult {
stream: u8,
opened: Option<u64>,
result: Result<String, String>,
},
Write {
stream: u8,
handle: Option<u64>,
accepted_before: Option<u64>,
requested: Arc<[u8]>,
accepted: u64,
attempts: Vec<WriteAttempt>,
error: Option<String>,
},
FlushOutput {
stream: u8,
handle: u64,
path: PathBuf,
result: Result<(), String>,
cause: ReleaseCause,
},
/// Rust drops the descriptor here. This is not a successful close(2) or
/// fsync receipt: File::drop does not expose either guarantee.
ReleaseOutput {
stream: u8,
handle: Option<u64>,
path: Option<PathBuf>,
accepted: Option<u64>,
cause: ReleaseCause,
},
CloseOutputResult {
stream: u8,
result: Result<(), String>,
},
CleanupBoundary {
cause: ReleaseCause,
inputs: Vec<u64>,
outputs: Vec<u64>,
},
}
#[derive(Clone, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
pub struct StreamEvent {
pub sequence: u64,
pub effect: StreamEffect,
}
#[derive(Clone, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
pub struct StreamJournal {
schema: u32,
events: Vec<StreamEvent>,
}
impl Default for StreamJournal {
fn default() -> Self {
Self {
schema: 1,
events: Vec::new(),
}
}
}
impl StreamJournal {
pub fn events(&self) -> &[StreamEvent] {
&self.events
}
pub(crate) fn push(&mut self, effect: StreamEffect) {
self.events.push(StreamEvent {
sequence: self.events.len() as u64 + 1,
effect,
});
}
}
pub(crate) struct LineTransfer {
pub bytes: Vec<u8>,
pub observed_eof: bool,
pub error: Option<io::Error>,
}
pub(crate) fn physical_line(reader: &mut (impl BufRead + ?Sized)) -> LineTransfer {
let mut bytes = Vec::new();
let mut observed_eof = false;
let result = (|| -> io::Result<()> {
loop {
let buffer = reader.fill_buf()?;
if buffer.is_empty() {
observed_eof = true;
break;
}
let end = buffer.iter().position(|c| *c == b'\r' || *c == b'\n');
let count = end.map_or(buffer.len(), |i| i + 1);
let last = buffer[count - 1];
bytes.extend_from_slice(&buffer[..count]);
reader.consume(count);
if end.is_some() {
if last == b'\r' {
let next = reader.fill_buf()?;
observed_eof = next.is_empty();
if next.first() == Some(&b'\n') {
bytes.push(b'\n');
reader.consume(1);
}
}
break;
}
}
Ok(())
})();
LineTransfer {
bytes,
observed_eof,
error: result.err(),
}
}
pub(crate) struct WriteTransfer {
pub accepted: usize,
pub attempts: Vec<WriteAttempt>,
pub error: Option<io::Error>,
}
pub(crate) fn write_all(writer: &mut (impl Write + ?Sized), bytes: &[u8]) -> WriteTransfer {
let mut accepted = 0;
let mut attempts = Vec::new();
let mut error = None;
while accepted < bytes.len() {
let requested = (bytes.len() - accepted) as u64;
match writer.write(&bytes[accepted..]) {
Ok(0) => {
attempts.push(WriteAttempt {
requested,
outcome: WriteOutcome::Zero,
});
error = Some(io::Error::from(io::ErrorKind::WriteZero));
break;
}
Ok(n) => {
attempts.push(WriteAttempt {
requested,
outcome: WriteOutcome::Accepted(n as u64),
});
accepted += n;
}
Err(e) if e.kind() == io::ErrorKind::Interrupted => attempts.push(WriteAttempt {
requested,
outcome: WriteOutcome::Interrupted,
}),
Err(e) => {
attempts.push(WriteAttempt {
requested,
outcome: WriteOutcome::Failed(e.to_string()),
});
error = Some(e);
break;
}
}
}
WriteTransfer {
accepted,
attempts,
error,
}
}
#[cfg(all(test, unix))]
mod tests {
use super::*;
use std::{
io::{BufReader, Read},
os::unix::net::UnixStream,
};
#[test]
fn actual_nonblocking_read_keeps_consumed_cr_before_lookahead_failure() {
let (mut writer, reader) = UnixStream::pair().unwrap();
reader.set_nonblocking(true).unwrap();
writer.write_all(b"PART\r").unwrap();
let mut reader = BufReader::new(reader);
let failed = physical_line(&mut reader);
assert_eq!(failed.bytes, b"PART\r");
assert_eq!(failed.error.unwrap().kind(), io::ErrorKind::WouldBlock);
assert!(!failed.observed_eof);
writer.write_all(b"\nNEXT\r\nTAIL").unwrap();
drop(writer);
let remainder = physical_line(&mut reader);
assert_eq!(remainder.bytes, b"\n");
assert!(remainder.error.is_none());
let next = physical_line(&mut reader);
assert_eq!(next.bytes, b"NEXT\r\n");
let tail = physical_line(&mut reader);
assert_eq!(tail.bytes, b"TAIL");
assert!(tail.observed_eof);
let eof = physical_line(&mut reader);
assert!(eof.bytes.is_empty() && eof.observed_eof && eof.error.is_none());
}
#[test]
fn actual_nonblocking_writes_retain_the_accepted_prefix_and_failed_attempt() {
let (mut writer, mut reader) = UnixStream::pair().unwrap();
writer.set_nonblocking(true).unwrap();
let data: Vec<_> = (0..2 * 1024 * 1024).map(|n| (n % 251) as u8).collect();
let result = write_all(&mut writer, &data);
assert!(result.accepted > 0 && result.accepted < data.len());
assert_eq!(result.error.unwrap().kind(), io::ErrorKind::WouldBlock);
assert_eq!(
result
.attempts
.iter()
.map(|a| match a.outcome {
WriteOutcome::Accepted(n) => n,
_ => 0,
})
.sum::<u64>(),
result.accepted as u64
);
assert!(matches!(
result.attempts.last().unwrap().outcome,
WriteOutcome::Failed(_)
));
let mut received = vec![0; result.accepted];
reader.read_exact(&mut received).unwrap();
assert_eq!(received, data[..result.accepted]);
}
}
+425 -237
View File
@@ -1,8 +1,7 @@
//! 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.
//! Transitional document frontend and Route-D preview/export host.
//! Native token/state execution lives in texrra_tex_core::execution. The
//! native CLI bypasses this string frontend; textual processing below remains
//! migration debt until native format execution covers these inputs.
use std::cell::RefCell;
use std::collections::HashMap;
@@ -71,7 +70,7 @@ fn latex_body(source: &str) -> &str {
/// 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.
/// edits fall back to a full layout. This endpoint still uses the transitional document frontend.
#[allow(dead_code)] // Kept as the no-image entry point for callers and tests.
pub fn project_preview_json(project_id: &str, source: &str) -> Result<String, String> {
project_preview_json_with_images(project_id, source, &HashMap::new())
@@ -231,6 +230,7 @@ struct PageGeometry {
par_skip_stretch: Option<i64>,
par_skip_shrink: Option<i64>,
baseline_skip: Option<i64>,
ragged_bottom: Option<bool>,
/// `\linespread` factor in thousandths.
linespread: Option<i64>,
/// `\tabcolsep` on each side of a tabular column.
@@ -2326,6 +2326,117 @@ fn class_baselineskip(font_size: i64) -> i64 {
}
}
/// NFSS size declarations carry both the size and the baseline distance.
/// These are LaTeX kernel constants (ltfsstrc), independent of the text font.
fn nfss_size(geometry: &PageGeometry, name: &str) -> Option<(i64, i64)> {
fn argument(text: &str) -> Option<(String, &str)> {
let text = text.trim_start();
if text.starts_with('{') {
let (value, used) = braced_group(text)?;
Some((value.to_string(), &text[used..]))
} else {
let (value, used) = control_sequence(text)?;
Some((value.to_string(), &text[used..]))
}
}
fn points(value: &str) -> Option<i64> {
let value = match value.trim() {
"\\@vpt" => "5",
"\\@vipt" => "6",
"\\@viipt" => "7",
"\\@viiipt" => "8",
"\\@ixpt" => "9",
"\\@xpt" => "10",
"\\@xipt" => "10.95",
"\\@xiipt" => "12",
"\\@xivpt" => "14.4",
"\\@xviipt" => "17.28",
"\\@xxpt" => "20.74",
"\\@xxvpt" => "24.88",
other => other,
};
parse_dimension(&format!("{value}pt")).or_else(|| parse_dimension(value))
}
let definition = geometry.macros.iter().rev().find(|m| m.name == name)?;
let body = definition
.body
.replace('\u{E022}', "")
.replace('\u{E021}', "@");
let (_, rest) = body.split_once("\\@setfontsize")?;
let (_, rest) = argument(rest)?;
let (size, rest) = argument(rest)?;
let (baseline, _) = argument(rest)?;
Some((points(&size)?, points(&baseline)?))
}
#[derive(Clone, Copy, Debug)]
struct SectionSpacing {
size: i64,
before: (i64, i64, i64),
after: (i64, i64, i64),
}
/// Read the standard six arguments of \@startsection into layout state.
fn section_spacing(geometry: &PageGeometry, level: u8) -> Option<SectionSpacing> {
let name = match level {
1 => "\\section",
2 => "\\subsection",
3 => "\\subsubsection",
4 => "\\paragraph",
5 => "\\subparagraph",
_ => return None,
};
let definition = geometry.macros.iter().rev().find(|m| m.name == name)?;
let body = definition
.body
.replace('\u{E022}', "")
.replace('\u{E021}', "@");
let (_, mut rest) = body.split_once("\\@startsection")?;
let mut args = Vec::new();
for _ in 0..6 {
rest = rest.trim_start();
let (value, used) = braced_group(rest)?;
args.push(value);
rest = &rest[used..];
}
let base = geometry.base_font_size.unwrap_or(10 * SCALE);
let font = if geometry.roman_family.as_deref() == Some("ptm") {
Cmr10Metrics::TimesRoman
} else {
Cmr10Metrics::Roman
};
let ex = font.x_height() * base / (10 * SCALE);
let glue = |text: &str| {
let text = text.replace("\\@plus", "plus").replace("\\@minus", "minus");
let dimension = |value: &str| -> Option<i64> {
let value = value.trim();
if let Some(number) = value.strip_suffix("ex") {
Some((number.trim().parse::<f64>().ok()? * ex as f64).round() as i64)
} else {
parse_dimension(value)
}
};
let (head, shrink) = text.split_once("minus").unwrap_or((&text, "0pt"));
let (width, stretch) = head.split_once("plus").unwrap_or((head, "0pt"));
Some((dimension(width)?, dimension(stretch)?, dimension(shrink)?))
};
let before = glue(&args[3])?;
let after = glue(&args[4])?;
let command = SIZE_COMMANDS
.iter()
.find(|(name, _)| args[5].contains(name))?
.0;
let size = nfss_size(geometry, command)
.map(|p| p.0)
.or_else(|| font_size_command(command).map(|p| p.0))
.unwrap_or(base);
Some(SectionSpacing {
size,
before: (before.0.abs(), before.1.abs(), before.2.abs()),
after,
})
}
/// A `\linespread`-style factor in thousandths, clamped to a sane range.
fn spread_percent(argument: &str) -> Option<i64> {
let factor: f64 = argument.trim().parse().ok()?;
@@ -3593,6 +3704,14 @@ fn strip_page_geometry(
geometry.linespread = Some(spread);
continue;
}
if trimmed == "\\flushbottom" {
geometry.ragged_bottom = Some(false);
continue;
}
if trimmed == "\\raggedbottom" {
geometry.ragged_bottom = Some(true);
continue;
}
if let Some(value) = dimension_assignment(trimmed, "hoffset") {
geometry.origin.h_offset = value;
} else if let Some(value) = dimension_assignment(trimmed, "voffset") {
@@ -6494,6 +6613,50 @@ fn geometry_and_body_with_images(
let source = collapse_braced_command(&source, "\\date");
let (stripped, mut geometry) = strip_page_geometry(&source, images);
dedupe_macros(&mut geometry.macros);
if let Some((size, baseline)) = nfss_size(&geometry, "\\normalsize") {
geometry.base_font_size = Some(size);
if geometry.baseline_skip.is_none() {
geometry.baseline_skip = Some(baseline);
}
if let Some(definition) = geometry
.macros
.iter()
.rev()
.find(|m| m.name == "\\normalsize")
{
let body = definition
.body
.replace('\u{E022}', "")
.replace('\u{E021}', "@");
for name in [
"abovedisplayskip",
"abovedisplayshortskip",
"belowdisplayskip",
"belowdisplayshortskip",
] {
if let Some(index) = body.find(&format!("\\{name}")) {
let spacing = if name == "belowdisplayskip"
&& body[index + name.len() + 1..]
.trim_start()
.starts_with("\\abovedisplayskip")
{
geometry.above_display_skip
} else {
glue_assignment(&body[index..], name)
};
let target = match name {
"abovedisplayskip" => &mut geometry.above_display_skip,
"belowdisplayskip" => &mut geometry.below_display_skip,
"abovedisplayshortskip" => &mut geometry.above_display_short_skip,
_ => &mut geometry.below_display_short_skip,
};
if target.is_none() {
*target = spacing;
}
}
}
}
}
// Removed assignments can leave blank lines at the edges; they are not
// paragraphs of their own.
let mut body = latex_body(&stripped).trim_matches('\n').to_string();
@@ -7240,6 +7403,7 @@ fn renewcommand_length(line: &str, name: &str) -> Option<i64> {
}
fn apply_geometry(document: &mut Document, geometry: &PageGeometry) {
document.ragged_bottom = geometry.ragged_bottom.unwrap_or(true);
document.h_offset = geometry.origin.h_offset;
if geometry.geometry_package && document.h_offset == 0 {
let paper_width = geometry.paper_width.unwrap_or(612 * SCALE);
@@ -13734,79 +13898,6 @@ fn build_document(paragraphs: &[SourceParagraph], geometry: &PageGeometry) -> Do
build_document_with_labels(paragraphs, geometry, &mut HashMap::new(), &mut Vec::new())
}
/// TeX leaves a thick relation space before a display fraction. The route
/// layout is currently about 17 pt tighter there, so add that gap explicitly
/// for tagged display equations in the Times layout.
fn add_display_fraction_space(atom: MathAtom) -> MathAtom {
add_fraction_space_in(atom).0
}
fn add_fraction_space_in(atom: MathAtom) -> (MathAtom, bool) {
match atom {
MathAtom::Row(atoms) => {
let mut out = Vec::with_capacity(atoms.len() + 1);
let mut added = false;
for atom in atoms {
if !added && matches!(atom, MathAtom::Fraction { .. }) {
out.push(MathAtom::Space(17 * SCALE));
added = true;
out.push(atom);
continue;
}
if !added {
let (atom, found) = add_fraction_space_in(atom);
added = found;
out.push(atom);
} else {
out.push(atom);
}
}
(MathAtom::Row(out), added)
}
MathAtom::Delimited { left, right, body } => {
let (body, added) = add_fraction_space_in(*body);
(
MathAtom::Delimited {
left,
right,
body: Box::new(body),
},
added,
)
}
MathAtom::Classed { class, body } => {
let (body, added) = add_fraction_space_in(*body);
(
MathAtom::Classed {
class,
body: Box::new(body),
},
added,
)
}
MathAtom::Boxed { body } => {
let (body, added) = add_fraction_space_in(*body);
(
MathAtom::Boxed {
body: Box::new(body),
},
added,
)
}
MathAtom::Sqrt { radicand, degree } => {
let (radicand, added) = add_fraction_space_in(*radicand);
(
MathAtom::Sqrt {
radicand: Box::new(radicand),
degree,
},
added,
)
}
other => (other, false),
}
}
fn build_document_with_labels(
paragraphs: &[SourceParagraph],
geometry: &PageGeometry,
@@ -13815,37 +13906,44 @@ fn build_document_with_labels(
) -> Document {
// Do not format the whole PageGeometry: it contains the decoded raster
// images. These fields cover paragraph shaping and line breaking.
let heading_styles: Vec<_> = (0..=5)
.map(|level| section_spacing(geometry, level))
.collect();
let cache_signature = format!(
"{:?}|{:?}|{:?}|{:?}|{:?}|{:?}|{:?}|{:?}|{:?}|{:?}|{:?}|{:?}|{:?}|{:?}|{:?}|{:?}|{:?}|{:?}|{:?}|{:?}|{:?}|{:?}|{:?}|{:?}|{:?}|{:?}|{:?}|{:?}|{:?}",
geometry.line_width,
geometry.base_font_size,
geometry.par_indent,
geometry.baseline_skip,
geometry.linespread,
geometry.left_skip,
geometry.right_skip,
geometry.par_shape,
geometry.hang_indent,
geometry.hang_after,
geometry.par_fillskip,
geometry.looseness,
geometry.lineskip,
geometry.lineskiplimit,
geometry.emergency_stretch,
geometry.pretolerance,
geometry.tolerance,
geometry.hyphen_penalty,
geometry.ex_hyphen_penalty,
geometry.double_hyphen_demerits,
geometry.final_hyphen_demerits,
geometry.line_penalty,
geometry.adj_demerits,
geometry.french_spacing,
geometry.hyphenation_exceptions,
geometry.space_skip,
geometry.xspace_skip,
geometry.space_factor_codes,
geometry.document_class,
"{:?}|{}",
heading_styles,
format!(
"{:?}|{:?}|{:?}|{:?}|{:?}|{:?}|{:?}|{:?}|{:?}|{:?}|{:?}|{:?}|{:?}|{:?}|{:?}|{:?}|{:?}|{:?}|{:?}|{:?}|{:?}|{:?}|{:?}|{:?}|{:?}|{:?}|{:?}|{:?}|{:?}",
geometry.line_width,
geometry.base_font_size,
geometry.par_indent,
geometry.baseline_skip,
geometry.linespread,
geometry.left_skip,
geometry.right_skip,
geometry.par_shape,
geometry.hang_indent,
geometry.hang_after,
geometry.par_fillskip,
geometry.looseness,
geometry.lineskip,
geometry.lineskiplimit,
geometry.emergency_stretch,
geometry.pretolerance,
geometry.tolerance,
geometry.hyphen_penalty,
geometry.ex_hyphen_penalty,
geometry.double_hyphen_demerits,
geometry.final_hyphen_demerits,
geometry.line_penalty,
geometry.adj_demerits,
geometry.french_spacing,
geometry.hyphenation_exceptions,
geometry.space_skip,
geometry.xspace_skip,
geometry.space_factor_codes,
geometry.document_class,
)
);
PARAGRAPH_CACHE.with(|cache| {
let mut cache = cache.borrow_mut();
@@ -13855,14 +13953,6 @@ fn build_document_with_labels(
}
});
let mut paragraphs = expand_maketitle(paragraphs, geometry);
if geometry.roman_family.as_deref() == Some("ptm") {
for index in 1..paragraphs.len() {
if paragraphs[index].heading_level.is_some() && paragraphs[index - 1].math {
paragraphs[index].space_before =
(paragraphs[index].space_before - 15 * SCALE).max(0);
}
}
}
if let Some(name) = geometry.abstract_name.as_deref() {
rename_abstract_heading(&mut paragraphs, name);
}
@@ -13929,36 +14019,31 @@ fn build_document_with_labels(
&geometry.bibliography,
geometry.ref_name.as_deref().unwrap_or("References"),
);
if geometry.roman_family.as_deref() == Some("ptm") {
// TeX puts a subsection directly under a section with only its normal
// heading glue. The route heading boxes are taller and the two
// \space_before values add up; compact only this consecutive-heading
// case, leaving body paragraphs untouched.
let mut previous_heading: Option<usize> = None;
for index in 0..paragraphs.len() {
if paragraphs[index].heading_level.is_some() {
if let Some(previous) = previous_heading {
paragraphs[previous].space_before =
(paragraphs[previous].space_before - 9 * SCALE).max(0);
paragraphs[index].space_before = 0;
}
previous_heading = Some(index);
} else if !paragraphs[index].text.trim().is_empty() {
previous_heading = None;
}
}
}
if geometry.roman_family.as_deref() == Some("ptm") {
for paragraph in &mut paragraphs {
if paragraph
.heading_number
.as_deref()
.is_some_and(|number| number == "3" || number.starts_with("3."))
{
paragraph.space_before = 0;
}
let mut run_in_heads = HashMap::new();
let mut joined = Vec::with_capacity(paragraphs.len());
let mut pending = paragraphs.into_iter().peekable();
while let Some(heading) = pending.next() {
let spacing = heading
.heading_level
.and_then(|level| heading_styles.get(level as usize).copied().flatten());
if let Some(spacing) = spacing.filter(|s| s.after.0 < 0)
&& pending
.peek()
.is_some_and(|p| p.heading_level.is_none() && !p.math && p.float.is_none())
{
let mut body = pending.next().unwrap();
body.page_break |= heading.page_break;
body.heading_number = heading.heading_number;
body.space_before += spacing.before.0;
body.space_stretch += spacing.before.1;
body.space_shrink += spacing.before.2;
run_in_heads.insert(joined.len(), (heading.text, heading.font, -spacing.after.0));
joined.push(body);
} else {
joined.push(heading);
}
}
let mut paragraphs = joined;
// Table-of-contents entries carry an invisible marker naming the heading
// whose page number they show; resolve it once the units exist.
let mut toc_targets: Vec<(usize, String)> = Vec::new();
@@ -14119,7 +14204,8 @@ fn build_document_with_labels(
return unit;
}
}
let cache_key = if paragraph.footnotes.is_empty() {
let cache_key = if paragraph.footnotes.is_empty() && !run_in_heads.contains_key(&index)
{
Some(ParagraphCacheKey {
text: paragraph.text.clone(),
font: paragraph.font,
@@ -14185,13 +14271,6 @@ fn build_document_with_labels(
centered: paragraph.align_centered,
}
};
let atom = if geometry.roman_family.as_deref() == Some("ptm")
&& (paragraph.equation_tag.is_some() || paragraph.equation_number.is_some())
{
add_display_fraction_space(atom)
} else {
atom
};
let tag = paragraph.equation_tag.clone().or_else(|| {
paragraph
.equation_number
@@ -14293,7 +14372,11 @@ fn build_document_with_labels(
.or(geometry.base_font_size)
.unwrap_or(655_360);
let base_font_size = match paragraph.heading_level {
Some(level) => heading_font_size(level, class_size),
Some(level) => heading_styles
.get(level as usize)
.copied()
.flatten()
.map_or_else(|| heading_font_size(level, class_size), |s| s.size),
None => class_size,
};
let baselineskip = geometry
@@ -14303,11 +14386,6 @@ fn build_document_with_labels(
.linespread
.map(|spread| baselineskip.saturating_mul(spread) / 1000)
.unwrap_or(baselineskip);
let baselineskip = if geometry.roman_family.as_deref() == Some("ptm") {
1150 * SCALE / 100
} else {
baselineskip
};
let (left_skip, par_indent) = match paragraph.list_depth {
Some(_) => {
let indent = paragraph.left_skip * SCALE + geometry.left_skip.unwrap_or(0);
@@ -14399,7 +14477,7 @@ fn build_document_with_labels(
} else {
paragraph.font
};
let mut unit = match inline_segments_with_boxes(
let parsed_segments = inline_segments_with_boxes(
&text,
face,
&style,
@@ -14408,7 +14486,30 @@ fn build_document_with_labels(
.link_color
.as_deref()
.and_then(|name| color_spec(name, &geometry.colors)),
) {
);
let segments = if let Some((title, font, kern)) = run_in_heads.get(&index) {
use texrra_tex_core::paragraph::InlineSegment;
let font = if face == ParagraphFont::TimesRoman {
ParagraphFont::TimesBold
} else {
*font
};
let mut prefix = vec![
InlineSegment::Text(font, title.clone()),
InlineSegment::Kern(*kern),
];
prefix.extend(parsed_segments.unwrap_or_else(|| {
inline_runs(&plain, face)
.unwrap_or_else(|| vec![(face, strip_group_braces(&plain))])
.into_iter()
.map(|(font, text)| InlineSegment::Text(font, text))
.collect()
}));
Some(prefix)
} else {
parsed_segments
};
let mut unit = match segments {
Some(segments) => Unit::paragraph_with_style_and_segments(
index as u64,
text.clone(),
@@ -14430,6 +14531,9 @@ fn build_document_with_labels(
),
},
};
if let Some((title, _, _)) = run_in_heads.get(&index) {
unit.source = format!("{title} {}", unit.source);
}
unit.space_before = paragraph.space_before;
unit.space_stretch = paragraph.space_stretch;
unit.space_shrink = paragraph.space_shrink;
@@ -14444,17 +14548,25 @@ fn build_document_with_labels(
unit
})
.collect();
for index in 0..base_units.len().min(paragraphs.len()) {
if let Some(spacing) = paragraphs[index]
.heading_level
.and_then(|level| heading_styles.get(level as usize).copied().flatten())
{
base_units[index].space_before = spacing.before.0;
base_units[index].space_stretch = spacing.before.1;
base_units[index].space_shrink = spacing.before.2;
if index + 1 < base_units.len() {
base_units[index + 1].space_before += spacing.after.0;
base_units[index + 1].space_stretch += spacing.after.1;
base_units[index + 1].space_shrink += spacing.after.2;
}
}
}
// Footnotes follow their anchor paragraph as insertion units, so the page
// builder reserves room for them on the page that mentions them.
let (default_above_display, default_below_display) =
display_skip_defaults(geometry.base_font_size.unwrap_or(655_360));
let times_displays = ((7 * SCALE, 2 * SCALE, 5 * SCALE), (0, 0, 0));
let (default_above_display, default_below_display) =
if geometry.roman_family.as_deref() == Some("ptm") {
times_displays
} else {
(default_above_display, default_below_display)
};
let above_display = geometry.above_display_skip.unwrap_or(default_above_display);
let below_display = geometry.below_display_skip.unwrap_or(default_below_display);
for index in 0..base_units.len().min(paragraphs.len()) {
@@ -14612,7 +14724,7 @@ fn build_document_with_labels(
};
document
.headings
.push((*unit as u64, scrub_title_metadata(&title)));
.push((document.units[*unit].id, scrub_title_metadata(&title)));
}
}
if footnote_count > 0 {
@@ -14625,6 +14737,9 @@ fn build_document_with_labels(
});
document.insertion_skip = 12 * SCALE;
}
if geometry.document_class.is_some() {
document.top_skip = geometry.base_font_size.unwrap_or(10 * SCALE);
}
// LaTeX sets \maxdepth=.5\topskip; sources may override it later.
document.max_depth = 5 * SCALE;
document.club_penalty = geometry.club_penalty.unwrap_or(150);
@@ -20103,8 +20218,16 @@ left & right \\
value["warnings"]
);
let svg = value["pages"][0]["svg"].as_str().expect("svg");
let scaled_math = svg.split("<text").any(|chunk| {
chunk.contains("font-style=\"italic\"") && chunk.contains("font-size=\"12.000\"")
let scaled_math = svg.split("<g ").any(|chunk| {
if !chunk.starts_with("data-font=\"CMMI10\"") {
return false;
}
let scale = chunk
.split("scale(")
.nth(1)
.and_then(|text| text.split_whitespace().next())
.and_then(|text| text.parse::<f64>().ok());
scale.is_some_and(|value| (value - 12.0 * 800.0 / 803.0 / 1000.0).abs() < 0.0000001)
});
assert!(scaled_math, "math glyph was not scaled: {svg}");
assert!(!svg.contains('$'), "{svg}");
@@ -20160,63 +20283,116 @@ left & right \\
}
#[test]
fn consecutive_times_headings_use_tex_glue() {
let source = "\\renewcommand{\\rmdefault}{ptm}\n\\section{One}\n\\subsection{Two}\n\nBody.";
let (body, geometry) = geometry_and_body(source);
let paragraphs = paragraphs(&body).expect("paragraphs");
let document = build_document(&paragraphs, &geometry);
let section = document
.units
.iter()
.find(|unit| unit.source == "1 One" || unit.source == "One")
.expect("section unit");
let subsection = document
.units
.iter()
.find(|unit| unit.source == "1.1 Two" || unit.source == "Two")
.expect("subsection unit");
assert_eq!(subsection.space_before, 0);
assert!(
section.space_before <= 3 * SCALE,
"section glue was not compacted: {}",
section.space_before
);
fn text_font_does_not_select_heading_or_display_glue() {
let mut expected = None;
for family in ["cmr", "ptm"] {
let source = format!(
"\\documentclass{{article}}\n\\renewcommand{{\\rmdefault}}{{{family}}}\n\\begin{{document}}\n\\section{{One}}\n\\subsection{{Two}}\n\nBody.\n\n\\[x\\]\n\n\\subsection{{Three}}\n\nAfter.\n\\end{{document}}"
);
let (body, geometry) = geometry_and_body(&source);
let blocks = paragraphs(&body).unwrap();
let document = build_document(&blocks, &geometry);
let spaces: Vec<_> = document
.units
.iter()
.map(|u| (u.space_before, u.space_stretch, u.space_shrink))
.collect();
if let Some(expected) = &expected {
assert_eq!(&spaces, expected);
} else {
expected = Some(spaces);
}
let math = document
.units
.iter()
.find(|u| {
u.items
.iter()
.any(|i| matches!(i, VerticalItem::Math { .. }))
})
.unwrap();
assert_eq!(
(math.space_before, math.space_stretch, math.space_shrink),
(10 * SCALE, 2 * SCALE, 5 * SCALE)
);
}
}
#[test]
fn times_display_math_uses_arxiv_skips() {
let source = "\\documentclass{article}\n\\renewcommand{\\rmdefault}{ptm}\n\\begin{document}\n\nBefore.\n\n\\[ x \\]\n\nAfter.\n\n\\end{document}\n";
let (body, geometry) = geometry_and_body(source);
let paragraphs = paragraphs(&body).expect("paragraphs");
let document = build_document(&paragraphs, &geometry);
let math_index = document
.units
.iter()
.position(|unit| {
unit.items
.iter()
.any(|item| matches!(item, VerticalItem::Math { .. }))
})
.expect("display math unit");
let math = &document.units[math_index];
assert_eq!(math.space_before, 7 * SCALE);
assert_eq!(math.space_stretch, 2 * SCALE);
assert_eq!(math.space_shrink, 5 * SCALE);
assert_eq!(document.units[math_index + 1].space_before, 0);
}
fn nfss_and_startsection_supply_native_layout_state() {
for family in ["cmr", "ptm"] {
let source = format!(
r"\documentclass{{article}}
\makeatletter
\renewcommand{{\rmdefault}}{{{family}}}
\renewcommand{{\normalsize}}{{\@setfontsize\normalsize{{10}}{{13}}}}
\renewcommand{{\subsection}}{{\@startsection{{subsection}}{{2}}{{0pt}}{{2pt plus1pt minus1pt}}{{5pt}}{{\normalsize\bfseries}}}}
\renewcommand{{\paragraph}}{{\@startsection{{paragraph}}{{4}}{{0pt}}{{3pt}}{{-1em}}{{\normalsize\bfseries}}}}
\makeatother
\begin{{document}}
\subsection{{Heading}}
#[test]
fn times_heading_after_display_math_is_compacted() {
let source = "\\renewcommand{\\rmdefault}{ptm}\n\\section{One}\n\nText.\n\n\\[ x \\]\n\n\\subsection{Two}\n\nBody.";
let (body, geometry) = geometry_and_body(source);
let paragraphs = paragraphs(&body).expect("paragraphs");
let document = build_document(&paragraphs, &geometry);
let heading = document
.units
.iter()
.find(|unit| unit.source.contains("Two"))
.expect("subsection unit");
assert_eq!(heading.space_before, 0);
Before.
\[x\]
\paragraph{{Run in}}
Body \textit{{text}}.
\end{{document}}"
);
let (body, geometry) = geometry_and_body(&source);
assert_eq!(geometry.baseline_skip, Some(13 * SCALE));
let blocks =
paragraphs_with_geometry(&body, &geometry.theorem_definitions, 0, &geometry)
.unwrap();
let document = build_document(&blocks, &geometry);
let heading = document
.units
.iter()
.find(|u| u.source.contains("Heading"))
.unwrap();
assert_eq!(
(
heading.space_before,
heading.space_stretch,
heading.space_shrink
),
(2 * SCALE, SCALE, SCALE)
);
assert_eq!(
heading.paragraph_style.as_ref().unwrap().font_size,
10 * SCALE
);
let paragraph = document
.units
.iter()
.find_map(|u| {
if u.source.contains("Body ") {
u.items.iter().find_map(|i| match i {
VerticalItem::Paragraph(p) => Some(p),
_ => None,
})
} else {
None
}
})
.unwrap();
assert_eq!(
paragraph.lines.len(),
1,
"run-in heading must share the body baseline"
);
assert!(paragraph.lines[0].iter().any(|i| matches!(i, HorizontalItem::Box(b) if matches!(b.font, Some(ParagraphFont::Italic | ParagraphFont::TimesItalic)))));
let chars: String = paragraph.lines[0]
.iter()
.filter_map(|i| match i {
HorizontalItem::Box(b) => b.character,
_ => None,
})
.collect();
assert!(chars.contains("RuninBodytext."), "{chars}");
assert!(paragraph.lines[0].iter().any(|i| matches!(i, HorizontalItem::Box(b) if b.character.is_none() && b.width == 10*SCALE)));
}
}
#[test]
@@ -20241,16 +20417,28 @@ left & right \\
}
#[test]
fn display_fraction_gap_widens_the_math_box() {
let atom = texrra_tex_core::math::parse_math(r"x={\frac{a}{b}}");
let font = texrra_tex_core::cmr10::Cmr10Metrics::Math;
let before = texrra_tex_core::math::layout_math(&atom, &font).width;
let after =
texrra_tex_core::math::layout_math(&add_display_fraction_space(atom), &font).width;
assert!(
after >= before + 16 * SCALE,
"fraction gap did not widen: {before} -> {after}"
);
fn tagged_fraction_geometry_does_not_depend_on_text_family() {
let geometry_for = |family: &str| {
let source = format!(
"\\documentclass{{article}}\n\\renewcommand{{\\rmdefault}}{{{family}}}\n\\begin{{document}}\n\\begin{{equation}}\nx={{\\frac{{a}}{{b}}}}\n\\end{{equation}}\n\\end{{document}}\n"
);
let (body, geometry) = geometry_and_body(&source);
let blocks = paragraphs(&body).unwrap();
let document = build_document(&blocks, &geometry);
document
.units
.iter()
.flat_map(|unit| &unit.items)
.find_map(|item| match item {
VerticalItem::Math {
geometry: Some(geometry),
..
} => Some(geometry.clone()),
_ => None,
})
.expect("native math geometry")
};
assert_eq!(geometry_for("cmr"), geometry_for("ptm"));
}
#[test]
@@ -21158,7 +21346,7 @@ left & right \\
fn inline_math_paints_italic_glyphs() {
let json = preview_json("Value $x^2$ tail.").expect("preview");
assert!(
json.contains("font-style=") && json.contains("italic"),
json.contains("data-font=\\\"CMMI10\\\""),
"math letters use the italic face"
);
}
@@ -21319,7 +21507,7 @@ left & right \\
fn math_environment_becomes_inline_math() {
let svg = preview_json("Body \\begin{math}x\\end{math}.").expect("preview");
assert!(
svg.contains("font-style=\\\"italic\\\""),
svg.contains("data-font=\\\"CMMI10\\\""),
"missing math: {svg}"
);
assert!(!svg.contains("begin{math}"), "environment leaked: {svg}");
@@ -21643,7 +21831,7 @@ left & right \\
#[test]
fn ensuremath_makes_inline_math() {
let preview = preview_json("A \\ensuremath{x^2} B").expect("preview");
assert!(preview.contains("font-style=\\\"italic\\\""));
assert!(preview.contains("data-font=\\\"CMMI10\\\""));
assert!(!preview.contains("ensuremath"));
}