diff --git a/README.md b/README.md index 3a12137..e449005 100644 --- a/README.md +++ b/README.md @@ -84,7 +84,11 @@ execute; the 15-job/29-page device oracle passes. [Real PDF file state, versions compression, object streams/xref and original-sp precision](docs/NATIVE_PDF_CONFIG.md) now execute. The new 28-configuration/56-page and retained device matrices have zero word-box, paper and raster XOR differences. Independent 105-page object -stream rollover also passes. Native binary DVI export is explicitly unsupported. +stream rollover also passes. Native jobs with `\pdfoutput=0` can write binary DVI. +Specify the DVI destination explicitly with `texrra native --load-format latex.tfx +--input-profile tex8bit input.tex output.dvi`. The writer serializes the actual +shipouts. DVI drivers receive special payloads in their original page order. +[DVI evidence](docs/P2_M1_PROGRESS.md#原生-dvi-出页设备) [Actual PK resolution, bitmap decoding, Type3 output and shared text cursor](docs/NATIVE_PK_FONTS.md) now execute; 384 independent glyphs and a 43-job/86-page oracle pass with zero bitmap/word-box/paper/raster differences. Missing devices/resources fail. diff --git a/crates/texrra-tex-core/src/execution/boxes.rs b/crates/texrra-tex-core/src/execution/boxes.rs index 45f1b38..7cd3037 100644 --- a/crates/texrra-tex-core/src/execution/boxes.rs +++ b/crates/texrra-tex-core/src/execution/boxes.rs @@ -207,6 +207,8 @@ impl WalkBudget<'_> { fn inside_leader(&mut self, count: usize) -> Result<(), &'static str> { if self.leader_depth > 0 { self.charge(count)?; + } else if self.cancellation.is_some_and(Cancellation::is_cancelled) { + return Err("native compilation cancelled"); } Ok(()) } @@ -230,7 +232,7 @@ pub(super) struct BoxLayout { } pub(super) enum GeometryItem { - Output, + Output { special: bool }, Paint(crate::math_engine_tex::PositionedItem), PdfColor { x: i64, y: i64 }, PdfGraphics { x: i64, y: i64 }, @@ -840,10 +842,19 @@ impl NativeBox { Ok(g) } - pub(super) fn visit_geometry(&self, mut emit: impl FnMut(GeometryItem)) -> Result<(), String> { + pub(super) fn visit_geometry(&self, emit: impl FnMut(GeometryItem)) -> Result<(), String> { + self.visit_geometry_cancellable(None, emit) + } + + pub(super) fn visit_geometry_cancellable( + &self, + cancellation: Option<&Cancellation>, + mut emit: impl FnMut(GeometryItem), + ) -> Result<(), String> { use crate::math_engine_tex::PositionedItem; let mut unsupported = false; - self.walk(0, 0, &mut |x, y, node| { + let mut budget = WalkBudget { cancellation, ..WalkBudget::for_geometry() }; + self.walk_at(0, 0, 0, false, false, &mut budget, &mut |x, y, node| { let b = match node { BoxPaint::Box(b) => b, BoxPaint::PdfColor => { @@ -858,8 +869,10 @@ impl NativeBox { emit(GeometryItem::PdfTextSpace { x, y, operation }); return; } - BoxPaint::Output(_) => { - emit(GeometryItem::Output); + BoxPaint::Output(node) => { + emit(GeometryItem::Output { + special: matches!(node.operation, OutputOperation::Special { .. }), + }); return; } BoxPaint::RowStart(_) | BoxPaint::ScopeStart(_) | BoxPaint::ScopeEnd(_) diff --git a/crates/texrra-tex-core/src/execution/device.rs b/crates/texrra-tex-core/src/execution/device.rs index 0baa987..efe57ee 100644 --- a/crates/texrra-tex-core/src/execution/device.rs +++ b/crates/texrra-tex-core/src/execution/device.rs @@ -29,6 +29,8 @@ pub struct NativeShipout { pub box_node: NativeBox, pub device: ShipoutDevice, #[serde(default, skip_serializing_if = "Option::is_none")] + pub(super) dvi: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] pub(super) pdf_objects: Option, #[serde(default, skip_serializing_if = "BTreeMap::is_empty")] pub(super) font_overrides: BTreeMap>, @@ -113,7 +115,7 @@ impl NativeShipout { return; } let p = match item { - boxes::GeometryItem::Output => { + boxes::GeometryItem::Output { .. } => { reached_boundary = before_output == Some(output_index); output_index += 1; return; diff --git a/crates/texrra-tex-core/src/execution/dvi.rs b/crates/texrra-tex-core/src/execution/dvi.rs new file mode 100644 index 0000000..642b176 --- /dev/null +++ b/crates/texrra-tex-core/src/execution/dvi.rs @@ -0,0 +1,258 @@ +//! DVI serialization of the same packed lists used by native previews. +use super::{Cancellation, Event, Execution, NativeShipout, State, boxes::GeometryItem}; +use crate::{math_engine_tex::MathItem, native_font::NativeFont}; +use std::collections::BTreeMap; + +const ID: u8 = 2; +const NUMERATOR: i32 = 25_400_000; +const DENOMINATOR: i32 = 473_628_672; + +#[derive(Clone, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)] +pub(super) struct DviPage { + pub offset: [i64; 2], + pub counts: [i32; 10], + /// TeX constructs the preamble comment from the live date at first shipout. + pub clock: Option<[i32; 4]>, +} + +impl Execution { + /// Serialize raw DVI shipouts without resolving PDF device fonts or + /// running a DVI driver. An empty job has no output file. + pub fn dvi_output(&self, cancellation: &Cancellation) -> Result>, String> { + let mut ships = self.events.iter().filter_map(|event| match event { + Event::Shipout(ship) => Some(ship.as_ref()), + _ => None, + }); + let Some(first) = ships.next() else { + return Ok(None); + }; + let [year, month, day, time] = first + .dvi + .as_ref() + .and_then(|page| page.clock) + .ok_or("DVI output requires a captured DVI preamble")?; + let two_digits = |value: i32| value.unsigned_abs() % 100; + let (month, day) = (two_digits(month), two_digits(day)); + let (hour, minute) = (two_digits(time / 60), two_digits(time % 60)); + let comment = format!(" TeX output {year}.{month:02}.{day:02}:{hour:02}{minute:02}"); + let mag = first.device.magnification; + let mut dvi = Writer { + bytes: vec![247, ID], + fonts: BTreeMap::new(), + page_count: 0, + last_page: -1, + max_width: 0, + max_height: 0, + }; + dvi.scale(mag); + dvi.bytes.push(comment.len() as u8); + dvi.bytes.extend_from_slice(comment.as_bytes()); + for ship in std::iter::once(first).chain(ships) { + if cancellation.is_cancelled() { + return Err("native compilation cancelled".into()); + } + if ship.device.magnification != mag { + return Err("DVI magnification changed during output".into()); + } + dvi.page(ship, &self.state, cancellation)?; + } + dvi.finish(mag).map(Some) + } +} + +struct Writer { + bytes: Vec, + fonts: BTreeMap>, + page_count: u16, + last_page: i32, + max_width: i32, + max_height: i32, +} + +impl Writer { + fn four(&mut self, n: i32) { + self.bytes.extend_from_slice(&n.to_be_bytes()); + } + + fn scale(&mut self, magnification: i32) { + self.four(NUMERATOR); + self.four(DENOMINATOR); + self.four(magnification); + } + + fn file_offset(&self) -> Result { + i32::try_from(self.bytes.len()).map_err(|_| "DVI file offset overflow".into()) + } + + fn page( + &mut self, + ship: &NativeShipout, + state: &State, + cancellation: &Cancellation, + ) -> Result<(), String> { + let page = ship + .dvi + .as_ref() + .ok_or("DVI and PDF shipouts cannot share a file")?; + self.page_count = self + .page_count + .checked_add(1) + .ok_or("DVI page count overflow")?; + let page_at = self.file_offset()?; + self.bytes.push(139); // bop + for count in page.counts { + self.four(count); + } + self.four(self.last_page); + self.last_page = page_at; + let b = &ship.box_node; + let [left, top] = page.offset; + let baseline = top + b.height; + self.max_width = self.max_width.max(dimension(left + b.width)?); + self.max_height = self.max_height.max(dimension(baseline + b.depth)?); + let mut cursor = [0, 0]; + let mut current_font = None; + let mut specials = ship.specials.iter(); + let mut result: Result<(), String> = Ok(()); + b.visit_geometry_cancellable(Some(cancellation), |item| { + if result.is_err() { + return; + } + result = match item { + GeometryItem::Paint(p) => { + let position = [left + p.x, baseline + p.y]; + match p.item { + MathItem::NativeGlyph { font, slot, .. } => (|| { + let number = self.font(&font, state)?; + if Some(number) != current_font { + self.select_font(number); + current_font = Some(number); + } + self.move_to(&mut cursor, position)?; + // PUT does not consume a TFM advance. The packed + // list supplies the actual position of every item. + self.bytes.extend_from_slice(&[133, slot]); + Ok(()) + })(), + MathItem::Rule { width, height } => (|| { + self.move_to(&mut cursor, [position[0], position[1] + height])?; + self.bytes.push(137); // put_rule + self.four(dimension(height)?); + self.four(dimension(width)?); + Ok(()) + })(), + _ => Err("DVI requires actual TFM glyphs and rules".into()), + } + } + GeometryItem::Output { special: true } => (|| { + let special = specials.next().ok_or("missing resolved DVI special")?; + let [x, y] = special.position; + self.move_to(&mut cursor, [left + x, baseline + y])?; + let len = i32::try_from(special.bytes.len()) + .map_err(|_| "DVI special length overflow")?; + if let Ok(len) = u8::try_from(len) { + self.bytes.extend_from_slice(&[239, len]); + } else { + self.bytes.push(242); + self.four(len); + } + self.bytes.extend_from_slice(&special.bytes); + Ok(()) + })(), + _ => Ok(()), + }; + })?; + result?; + if specials.next().is_some() { + return Err("unmatched resolved DVI specials".into()); + } + self.bytes.push(140); // eop + Ok(()) + } + + fn move_to(&mut self, cursor: &mut [i64; 2], position: [i64; 2]) -> Result<(), String> { + for (index, opcode) in [143, 157].into_iter().enumerate() { + let delta = dimension(position[index] - cursor[index])?; + if delta != 0 { + let size = match delta { + -128..=127 => 1, + -32768..=32767 => 2, + -8388608..=8388607 => 3, + _ => 4, + }; + self.bytes.push(opcode + size as u8 - 1); + self.bytes + .extend_from_slice(&delta.to_be_bytes()[4 - size..]); + } + } + *cursor = position; + Ok(()) + } + + fn font(&mut self, glyph_font: &NativeFont, state: &State) -> Result { + use std::collections::btree_map::Entry; + let number = glyph_font + .id + .index() + .checked_sub(1) + .ok_or("null DVI glyph font")?; + if let Entry::Vacant(entry) = self.fonts.entry(number) { + let instance = state.fonts.font(glyph_font.id)?; + let area = instance.area().as_bytes(); + let name = instance.name().as_bytes(); + let area_len = u8::try_from(area.len()).map_err(|_| "DVI font area is too long")?; + let name_len = u8::try_from(name.len()).map_err(|_| "DVI font name is too long")?; + let metrics = instance.metrics().ok_or("DVI font has no TFM metrics")?; + let mut definition = Vec::new(); + font_number(&mut definition, 243, number); + definition.extend_from_slice(&metrics.checksum().to_be_bytes()); + definition.extend_from_slice(&dimension(instance.size_sp())?.to_be_bytes()); + definition.extend_from_slice(&dimension(metrics.design_size_sp())?.to_be_bytes()); + definition.extend_from_slice(&[area_len, name_len]); + definition.extend_from_slice(area); + definition.extend_from_slice(name); + self.bytes.extend_from_slice(&definition); + entry.insert(definition); + } + Ok(number) + } + + fn select_font(&mut self, number: u32) { + if number < 64 { + self.bytes.push(171 + number as u8); + } else { + font_number(&mut self.bytes, 235, number); + } + } + + fn finish(mut self, mag: i32) -> Result, String> { + let post = self.file_offset()?; + self.bytes.push(248); + self.four(self.last_page); + self.scale(mag); + self.four(self.max_height); + self.four(self.max_width); + self.bytes.extend_from_slice(&0u16.to_be_bytes()); // no PUSH instructions + self.bytes.extend_from_slice(&self.page_count.to_be_bytes()); + for definition in self.fonts.values().rev() { + self.bytes.extend_from_slice(definition); + } + self.bytes.push(249); + self.four(post); + self.bytes.push(ID); + let padding = 4 + (4 - self.bytes.len() % 4) % 4; + self.bytes.resize(self.bytes.len() + padding, 223); + self.file_offset()?; + Ok(self.bytes) + } +} + +fn font_number(output: &mut Vec, opcode: u8, number: u32) { + let len = (32 - number.leading_zeros()).max(1).div_ceil(8) as usize; + output.push(opcode + len as u8 - 1); + output.extend_from_slice(&number.to_be_bytes()[4 - len..]); +} + +fn dimension(value: i64) -> Result { + i32::try_from(value).map_err(|_| "DVI dimension overflow".into()) +} diff --git a/crates/texrra-tex-core/src/execution/engine/page.rs b/crates/texrra-tex-core/src/execution/engine/page.rs index dcf91c5..435829d 100644 --- a/crates/texrra-tex-core/src/execution/engine/page.rs +++ b/crates/texrra-tex-core/src/execution/engine/page.rs @@ -430,9 +430,25 @@ impl Executor { } else { None }; + let dvi = device.pdf.is_none().then(|| { + let counts = std::array::from_fn(|index| { + let index = index as u16; + self.reads.insert(Dependency::Count(index)); + self.state.count(index) + }); + let clock = (self.shipped_pages == 0).then(|| { + [JobParameter::Year, JobParameter::Month, JobParameter::Day, JobParameter::Time] + .map(|parameter| { + self.reads.insert(Dependency::JobParameter(parameter)); + self.state.job_parameter(parameter).unwrap_or(0) + }) + }); + super::super::dvi::DviPage { offset: [h_offset, v_offset], counts, clock } + }); let mut shipout = NativeShipout { box_node: b, device, + dvi, pdf_objects, font_overrides, virtual_glyphs: None, diff --git a/crates/texrra-tex-core/src/execution/mod.rs b/crates/texrra-tex-core/src/execution/mod.rs index 598d6de..0feeca0 100644 --- a/crates/texrra-tex-core/src/execution/mod.rs +++ b/crates/texrra-tex-core/src/execution/mod.rs @@ -7,6 +7,7 @@ mod context; mod device; mod diagnostics; mod direction; +mod dvi; pub use direction::DirectionBoundary; mod engine; #[cfg(all(target_os = "linux", target_env = "gnu"))] diff --git a/docs/P2_M1_PROGRESS.md b/docs/P2_M1_PROGRESS.md index 0f8dcee..50af5d9 100644 --- a/docs/P2_M1_PROGRESS.md +++ b/docs/P2_M1_PROGRESS.md @@ -819,6 +819,35 @@ letterspace-fresh.log 和 device-pdftex-spaced-moved.log。 [原版字距虚拟字体构造](https://github.com/TeX-Live/texlive-source/blob/fb6158926661cb7a7246b3a94a0cb170a9624d5a/texk/web2c/pdftexdir/pdftex.web#L16400-L16492) [原版格式所写字体字段](https://github.com/TeX-Live/texlive-source/blob/fb6158926661cb7a7246b3a94a0cb170a9624d5a/texk/web2c/pdftexdir/pdftex.web#L30627-L30696) +### 原生 DVI 出页设备 + +实际选中 \pdfoutput=0 的作业可以指定 .dvi 出口。DVI 写出器用 +发页原始盒和实际 TFM 字形。页首记录十个 count 值和首发页 +时间,写出倍率、前后页指针、实际偏移、字体校验和、字号、 +字形槽、规则及原始顺序的 special。前置文件变更引起这些值 +变化时进入实际依赖。输出文件和生成文件沿用版本化发布。 +库结果独立保留当前修订的 DVI 字节,CLI 使用同一作业路径。 +DVI 可以只依赖 TFM。预览解析实际可用的轮廓,special 的设备 +解释由 DVI 驱动承担。 + +原样 sample2e.tex 使用实际 schema78 pdfLaTeX 格式,保持发行版 +源文件不变。三页 DVI 解码后的 3,559 个字形、规则、字体定义、 +设备坐标、页计数、special 及前后置数据与实际 pdfTeX 参考一致。 +aux 逐字节相同。两端 DVI 都通过 dvips 转成 PostScript。 +独立原语样例的负偏移、页计数及字形也完全匹配,144 DPI 灰度 +光栅一致。只有 TFM 的两页作业对照覆盖 1200 倍率和首发页 +时间。保留原样文档尝试通过 xdvipdfmx 转换时缺少物理字体的 +参考侧记录。写出采用显式定位,DVI 编码长度仍可优化。 + +辅助文件稳定后的连续编辑两次各复用 77 步。只改页计数时 +更新 DVI 字节,预览页面保持不变。输入出错保留已发布的 DVI、 +预览和 aux。恢复并改变排版后只刷新第 2 页。DVI、测量页面、 +SVG、来源映射与生成文件均与独立全量编译一致。保留首次 +生成辅助文件时增量回退至全量的记录。21 项定向回归通过。 + +实测回执 target/p3-native-dvi-baseline/implementation-receipt.json +的 SHA-256 为 c9b3bf25d73c4a43e02b413361aa41bf43116d61b2667628b4e14c019759db60。 + ### e-TeX 拆盒的无限收缩胶水 原样 LaTeX 的页面标记提取会在组内设置 \ignoreprimitiveerror 的 diff --git a/src/main.rs b/src/main.rs index a38de58..8113434 100644 --- a/src/main.rs +++ b/src/main.rs @@ -30,7 +30,7 @@ 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] | texrra native [--job] [--initex] [--etex] [--dump-format | --load-format FILE] [--step-limit N] [--input-profile tex8bit|unicode|xetex] [--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(), + "usage: texrra serve [input.tex] [port] | texrra native [--job] [--initex] [--etex] [--dump-format | --load-format FILE] [--step-limit N] [--input-profile tex8bit|unicode|xetex] [--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|output.dvi]".into(), ); }; if command == "native" { @@ -146,9 +146,9 @@ fn run() -> Result<(), String> { .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|xetex] [--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()); + return Err("usage: texrra native [--job] [--initex] [--etex] [--dump-format | --load-format FILE] [--step-limit N] [--input-profile tex8bit|unicode|xetex] [--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|output.dvi]".into()); } - let diagnostic = native_pdf( + let diagnostic = native_compile( &input, &output, initex, @@ -229,9 +229,9 @@ fn run() -> Result<(), String> { Ok(()) } -/// Strict native bootstrap entry: typed execution -> Route-D lists -> PDF. +/// Execute original TeX input through the native artifact pipeline. /// CLI adapter; the library owns compilation, export and publication. -fn native_pdf( +fn native_compile( input: &Path, output: &Path, initex: bool, diff --git a/src/native.rs b/src/native.rs index e41bd42..a5f6e49 100644 --- a/src/native.rs +++ b/src/native.rs @@ -244,6 +244,8 @@ pub struct CompiledDocument { pub export_diagnostics: Vec, /// Immutable bytes stay associated with this revision after another publish. pub pdf: Option>, + /// The same revision’s bytes when TeX selected the DVI device. + pub dvi: Option>, pub output: Option, preview: PreviewState, } @@ -1095,7 +1097,6 @@ impl CompileJob { notify(&request, revision, CompileStage::Executed, &cancellation)?; evidence.phase = AttemptPhase::Layout; let e = &execution.execution; - let draft_mode = request.target == Target::Shipouts && e.state.pdf_draft_mode(); let (mut pages, paper_width, paper_height, origin) = if request.target == Target::Shipouts { @@ -1119,6 +1120,17 @@ impl CompileJob { }, ) }; + let dvi_mode = request.target == Target::Shipouts + && pages.first().is_some_and(|page| page.pdf.is_none()); + if dvi_mode + && output.extension().is_some_and(|extension| extension.eq_ignore_ascii_case("pdf")) + { + return Err(CompileError::Host( + "DVI mode requires a DVI output path, for example output.dvi".into(), + )); + } + let draft_mode = + request.target == Target::Shipouts && !dvi_mode && e.state.pdf_draft_mode(); if let Some(path) = &request.layout_manifest { let source_map = self.compiler.session.source_map(&execution, &pages)?; files.write_layout_manifest(path, e, &pages, &source_map)?; @@ -1147,6 +1159,12 @@ impl CompileJob { reported?; preview } + Err(_) if dvi_mode => { + // A DVI driver resolves the requested outlines later. + // Unavailable preview fonts do not prevent DVI output. + reported?; + PreviewFonts::default() + } Err(error) => { if let Err(report) = reported { evidence.gaps.push(report.to_string()); @@ -1174,10 +1192,16 @@ impl CompileJob { } else { None }; + let mut dvi = None; let (pdf, export_diagnostics) = if pages.is_empty() { (None, Vec::new()) } else if draft_mode { (None, vec![r"\pdfdraftmode enabled, not changing output pdf".into()]) + } else if dvi_mode { + let encoded = e.dvi_output(&cancellation); + check(&cancellation)?; + dvi = encoded?; + (None, Vec::new()) } else if request.target == Target::Shipouts { let mut options = e.state.pdf_final_options(); options.xdv_glyph_names = xdv_glyph_names.as_ref(); @@ -1219,6 +1243,7 @@ impl CompileJob { let inputs = files.input_snapshot(); let prepared = pdf .as_ref() + .or(dvi.as_ref()) .map(|bytes| { if checkpoints.is_some() { PreparedOutput::write_for_draft(&output, bytes) @@ -1260,6 +1285,7 @@ impl CompileJob { host_runtime: files.runtime_observations(), export_diagnostics, pdf: pdf.map(Arc::from), + dvi: dvi.map(Arc::from), output: receipt, preview, }); diff --git a/tests/native_device.rs b/tests/native_device.rs index d3611bb..5f09f02 100644 --- a/tests/native_device.rs +++ b/tests/native_device.rs @@ -1,4 +1,4 @@ -//! Actual native PDF device state, without changing original TeX geometry. +//! Actual native device state, without changing original TeX geometry. #[path = "support/native_fonts.rs"] mod native_fonts; use std::{ @@ -89,6 +89,102 @@ fn real_device_fixture_keeps_each_physical_page_and_actual_late_aux_writes() { fs::remove_dir_all(p).unwrap(); } +#[test] +fn dvi_job_emits_original_glyphs_rules_and_opaque_specials() { + let p = directory(); + let oracle = + PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("scripts/native-math-dvi-oracle.py"); + let special = "payload:".repeat(36); + let source = format!( + r"\catcode123=1 \catcode125=2 +\pdfoutput=0 \hoffset=5pt \voffset=-3pt +\font\roman=cmr10 \roman +\count0=7 \count1=-42 +\shipout\vbox{{\hbox{{left\special{{{special}}}\kern2pt right}}\hrule height1pt}} +\count0=8 \count1=20 +\shipout\hbox{{\vrule height4pt width10pt right}} +\end +" + ); + fs::write(p.join("probe.tex"), source).unwrap(); + let reference = Command::new("pdftex") + .args([ + "-ini", + "-etex", + "-halt-on-error", + "-interaction=nonstopmode", + "probe.tex", + ]) + .current_dir(&p) + .output() + .unwrap(); + assert!( + reference.status.success(), + "{}", + String::from_utf8_lossy(&reference.stdout) + ); + let native = native_fonts::command() + .args([ + "native", + "--job", + "--initex", + "--etex", + "--input-profile", + "tex8bit", + "probe.tex", + "native.dvi", + ]) + .current_dir(&p) + .output() + .unwrap(); + assert!( + native.status.success(), + "{}", + String::from_utf8_lossy(&native.stderr) + ); + let decode = |name| { + let result = Command::new("python3") + .arg(&oracle) + .arg(p.join(name)) + .output() + .unwrap(); + assert!( + result.status.success(), + "{}", + String::from_utf8_lossy(&result.stderr) + ); + serde_json::from_slice::(&result.stdout).unwrap() + }; + assert_eq!(decode("native.dvi"), decode("probe.dvi")); + let bytes = fs::read(p.join("native.dvi")).unwrap(); + assert!( + bytes + .windows(special.len()) + .any(|payload| payload == special.as_bytes()) + ); + let read = |index| i32::from_be_bytes(bytes[index..index + 4].try_into().unwrap()); + let end = bytes.iter().rposition(|&byte| byte != 223).unwrap(); + assert_eq!(bytes[end], 2); + let post = read(end - 4) as usize; + assert_eq!(bytes[post], 248); + let second = read(post + 1) as usize; + let first = read(second + 41) as usize; + assert_eq!( + ( + bytes[first], + read(first + 1), + read(first + 5), + read(first + 41) + ), + (139, 7, -42, -1) + ); + assert_eq!( + (bytes[second], read(second + 1), read(second + 5)), + (139, 8, 20) + ); + fs::remove_dir_all(p).unwrap(); +} + #[test] fn illegal_or_incompatible_magnification_and_huge_pages_protect_existing_pdf() { let p = directory();