337 lines
11 KiB
Rust
337 lines
11 KiB
Rust
//! 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,
|
|
}
|
|
|
|
/// The TeX time registers and PDF creation timestamp captured at job start.
|
|
/// The host can supply a separate PDF date for reproducible builds.
|
|
#[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)>,
|
|
#[serde(default, skip_serializing_if = "Option::is_none")]
|
|
pdf_calendar: Option<(i32, i32, i32, i32)>,
|
|
#[serde(default, skip_serializing_if = "Option::is_none")]
|
|
pub(super) random_seed: Option<i32>,
|
|
}
|
|
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,
|
|
pdf_calendar: None,
|
|
random_seed: None,
|
|
})
|
|
}
|
|
/// Fix the job's initial pdfTeX random sequence across equivalent runs.
|
|
pub fn with_random_seed(mut self, seed: i32) -> Self {
|
|
self.random_seed = Some(seed.saturating_abs());
|
|
self
|
|
}
|
|
|
|
/// 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));
|
|
self.pdf_calendar = None;
|
|
Ok(self)
|
|
}
|
|
|
|
/// Use the PDF timestamp from another host clock without changing TeX's registers.
|
|
pub fn with_pdf_date(mut self, source: Self) -> Self {
|
|
let calendar =
|
|
source
|
|
.pdf_calendar
|
|
.unwrap_or((source.year, source.month, source.day, source.minutes));
|
|
self.pdf_clock = source.pdf_clock;
|
|
self.pdf_calendar = (source.pdf_clock.is_some()
|
|
&& calendar != (self.year, self.month, self.day, self.minutes))
|
|
.then_some(calendar);
|
|
self
|
|
}
|
|
|
|
pub fn pdf_creation_date(self) -> Option<String> {
|
|
let (seconds, offset) = self.pdf_clock?;
|
|
let (year, month, day, minutes) =
|
|
self.pdf_calendar
|
|
.unwrap_or((self.year, self.month, self.day, self.minutes));
|
|
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:{year:04}{month:02}{day:02}{:02}{:02}{seconds:02}{zone}",
|
|
minutes / 60,
|
|
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,
|
|
},
|
|
PdfObject(u32),
|
|
PdfSave,
|
|
PdfSetMatrix(Vec<Token>),
|
|
PdfRestore,
|
|
PdfTextSpace(crate::pdf_device::text_spaces::SpaceOperation),
|
|
PdfLink(crate::pdf_device::links::LinkNode),
|
|
PdfImage {
|
|
image: std::sync::Arc<crate::pdf_image::PdfImageUse>,
|
|
origin: super::TokenOrigin,
|
|
},
|
|
PdfLiteral {
|
|
mode: crate::pdf_device::PdfLiteralMode,
|
|
shipout: bool,
|
|
tokens: Vec<Token>,
|
|
},
|
|
PdfSavePosition,
|
|
Special {
|
|
shipout: bool,
|
|
tokens: Vec<Token>,
|
|
#[serde(default, skip_serializing_if = "Option::is_none")]
|
|
origin: Option<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_link(&self) -> bool {
|
|
matches!(self.operation, OutputOperation::PdfLink(_))
|
|
}
|
|
|
|
pub(super) fn is_pdf_graphics(&self) -> bool {
|
|
matches!(
|
|
self.operation,
|
|
OutputOperation::PdfSave
|
|
| OutputOperation::PdfSetMatrix(_)
|
|
| OutputOperation::PdfRestore
|
|
| OutputOperation::PdfLiteral { .. }
|
|
| OutputOperation::Special { .. }
|
|
)
|
|
}
|
|
|
|
pub(super) fn needs_shipout_position(&self) -> bool {
|
|
self.is_pdf_graphics() || matches!(self.operation, OutputOperation::PdfSavePosition)
|
|
}
|
|
|
|
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>,
|
|
}
|