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

+285
View File
@@ -0,0 +1,285 @@
//! Host job environment and native I/O whatsits. No wall clock or filesystem
//! policy is hidden in the token executor.
use std::collections::{BTreeMap, BTreeSet};
use super::{Span, Token};
#[derive(
Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, serde::Serialize, serde::Deserialize,
)]
pub enum JobParameter {
Time,
Day,
Month,
Year,
}
/// One real host-local timestamp, captured at job start. Tests may inject an
/// explicit timestamp; absence is an error on access, never a fake zero date.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
pub struct JobTime {
pub year: i32,
pub month: i32,
pub day: i32,
pub minutes: i32,
#[serde(default)]
pdf_clock: Option<(u8, i16)>,
}
impl JobTime {
pub fn new(year: i32, month: i32, day: i32, minutes: i32) -> Result<Self, &'static str> {
let leap = year % 4 == 0 && (year % 100 != 0 || year % 400 == 0);
let days = match month {
2 if leap => 29,
2 => 28,
4 | 6 | 9 | 11 => 30,
1 | 3 | 5 | 7 | 8 | 10 | 12 => 31,
_ => 0,
};
if year < 1 || day < 1 || day > days || !(0..1440).contains(&minutes) {
return Err("invalid host job timestamp");
}
Ok(Self {
year,
month,
day,
minutes,
pdf_clock: None,
})
}
/// Add the seconds and UTC offset supplied by the job host.
pub fn with_pdf_clock(
mut self,
seconds: u8,
offset_minutes: i16,
) -> Result<Self, &'static str> {
if seconds > 59 || !(-1439..=1439).contains(&offset_minutes) || self.year > 9999 {
return Err("invalid host PDF creation timestamp");
}
self.pdf_clock = Some((seconds, offset_minutes));
Ok(self)
}
pub fn pdf_creation_date(self) -> Option<String> {
let (seconds, offset) = self.pdf_clock?;
let zone = if offset == 0 {
"Z".to_owned()
} else {
let sign = if offset < 0 { '-' } else { '+' };
let offset = offset.abs();
format!("{sign}{:02}'{:02}'", offset / 60, offset % 60)
};
Some(format!(
"D:{:04}{:02}{:02}{:02}{:02}{seconds:02}{zone}",
self.year,
self.month,
self.day,
self.minutes / 60,
self.minutes % 60
))
}
pub(super) fn parameters(self) -> [(JobParameter, i32); 4] {
[
(JobParameter::Time, self.minutes),
(JobParameter::Day, self.day),
(JobParameter::Month, self.month),
(JobParameter::Year, self.year),
]
}
}
#[cfg(test)]
mod tests {
use super::JobTime;
use crate::execution::{
Dependency, Event, Executor, Limits, NoFiles, SourceFile, SourceProvider, State,
};
#[test]
fn pdf_creation_date_uses_seconds_and_signed_host_offset() {
let time = JobTime::new(2026, 11, 3, 7 * 60 + 54).unwrap();
assert_eq!(time.pdf_creation_date(), None);
for (offset, zone) in [(0, "Z"), (480, "+08'00'"), (-210, "-03'30'")] {
assert_eq!(
time.with_pdf_clock(55, offset)
.unwrap()
.pdf_creation_date()
.as_deref(),
Some(format!("D:20261103075455{zone}").as_str()),
);
}
assert!(time.with_pdf_clock(60, 0).is_err());
}
#[test]
fn creation_date_expands_from_the_host_clock_after_tex_time_changes() {
let time = JobTime::new(2026, 11, 3, 474)
.unwrap()
.with_pdf_clock(55, 0)
.unwrap();
let execution = Executor::new(State::initex().with_job_time(time), Limits::default())
.run(
SourceFile {
name: "probe.tex".into(),
data: br"\catcode123=1\catcode125=2\time=0\edef\stamp{\pdfcreationdate}\message{\stamp}\end".to_vec(),
},
&mut NoFiles,
)
.unwrap();
assert!(execution.reads.contains(&Dependency::PdfCreationDate));
assert!(execution.events.iter().any(|event| {
matches!(event, Event::Message { text, .. } if text == "D:20261103075455Z")
}));
}
#[test]
fn shell_escape_query_matches_immediate_and_shipped_disabled_writes() {
struct Host(Vec<(super::WriteDestination, String)>);
impl SourceProvider for Host {
fn read(&mut self, name: &str, _: &str) -> Result<SourceFile, String> {
Err(format!("unexpected input {name}"))
}
fn diagnostic(
&mut self,
destination: super::WriteDestination,
text: &str,
) -> Result<(), String> {
self.0.push((destination, text.into()));
Ok(())
}
}
let mut host = Host(Vec::new());
let execution = Executor::new(State::initex(), Limits::default())
.with_native_pages()
.run(
SourceFile {
name: "probe.tex".into(),
data: br"\catcode123=1\catcode125=2
\message{SHELL=\the\pdfshellescape/\number\pdfshellescape}
\immediate\write18{printf immediate}
\setbox0=\hbox{\write18{printf discarded}}
\shipout\hbox{\write18{printf shipped}}
\end"
.to_vec(),
},
&mut host,
)
.unwrap();
assert!(
execution.events.iter().any(|event| {
matches!(event, Event::Message { text, .. } if text == "SHELL=0/0")
})
);
assert_eq!(
host.0,
[
(
super::WriteDestination::Log,
"runsystem(printf immediate)...disabled.\n".into()
),
(
super::WriteDestination::Log,
"runsystem(printf shipped)...disabled.\n".into()
),
]
);
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
pub enum WriteDestination {
TerminalAndLog,
Log,
TerminalOnly,
}
#[derive(Clone, Debug, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
pub enum OutputOperation {
Open {
stream: u8,
name: String,
from: String,
},
Write {
stream: i32,
tokens: Vec<Token>,
},
Close {
stream: u8,
},
PdfColor {
stack: usize,
action: crate::pdf_device::PdfColorStackAction,
},
PdfSave,
PdfSetMatrix(Vec<Token>),
PdfRestore,
PdfImage {
image: std::sync::Arc<crate::pdf_image::PdfImageUse>,
origin: super::TokenOrigin,
},
}
#[derive(Clone, Debug, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
pub struct OutputNode {
pub operation: OutputOperation,
pub span: Span,
}
impl OutputNode {
pub(super) fn is_pdf_graphics(&self) -> bool {
matches!(
self.operation,
OutputOperation::PdfSave
| OutputOperation::PdfSetMatrix(_)
| OutputOperation::PdfRestore
)
}
pub(super) fn dimensions(&self) -> Option<(i64, i64, i64)> {
match &self.operation {
OutputOperation::PdfImage { image, .. } => Some(image.dimensions()),
_ => None,
}
}
pub(super) fn image_box(&self) -> Option<crate::HorizontalBox> {
use crate::math_engine_tex::{MathGeometry, MathItem, PositionedItem};
let OutputOperation::PdfImage { image, origin } = &self.operation else {
return None;
};
let (width, height, depth) = image.dimensions();
Some(crate::HorizontalBox {
width,
height,
depth,
math_geometry: Some(Box::new(MathGeometry {
metrics: crate::math::MathBox {
width,
height,
depth,
},
items: vec![PositionedItem {
x: 0,
y: 0,
item: MathItem::PdfImage(image.clone()),
source: crate::provenance::PaintSource::token(*origin),
}],
})),
..Default::default()
})
}
}
#[derive(Clone, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
pub(super) struct InputStream {
pub source: usize,
}
/// Logical stream metadata only. Live host handles are NOT serialized. A
/// continuation with open streams requires the same live SourceProvider.
#[derive(Clone, Debug, Default, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
pub struct IoState {
pub(super) inputs: BTreeMap<u8, InputStream>,
pub(super) outputs: BTreeSet<u8>,
}