diff --git a/crates/texrra-tex-core/src/execution/device.rs b/crates/texrra-tex-core/src/execution/device.rs index 988d6a8..440b028 100644 --- a/crates/texrra-tex-core/src/execution/device.rs +++ b/crates/texrra-tex-core/src/execution/device.rs @@ -15,6 +15,15 @@ pub struct ShipoutDevice { pub pdf: Option, } +/// A resolved device special in packed-list order. The position is in +/// unscaled TeX sp relative to the box reference point, with y increasing down. +#[derive(Clone, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)] +pub struct ShipoutSpecial { + pub span: Span, + pub position: [i64; 2], + pub bytes: Arc<[u8]>, +} + #[derive(Clone, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)] pub struct NativeShipout { pub box_node: NativeBox, @@ -30,7 +39,9 @@ pub struct NativeShipout { #[serde(default, skip_serializing_if = "Vec::is_empty")] pub(super) pdf_color_steps: Vec>>, #[serde(default, skip_serializing_if = "Vec::is_empty")] - pub(super) pdf_graphics_steps: Vec, + pub(super) pdf_graphics_steps: Vec>, + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub specials: Vec, #[serde(default, skip_serializing_if = "Option::is_none")] pub(super) pdf_text_spaces: Option, #[serde(default, skip_serializing_if = "pdf_resource_entries_empty")] @@ -116,14 +127,14 @@ impl NativeShipout { return; } boxes::GeometryItem::PdfGraphics { x, y } => { - if let Some(operation) = graphics_steps.next() { - page.items.push(DisplayItem::PdfGraphics { + match graphics_steps.next() { + Some(Some(operation)) => page.items.push(DisplayItem::PdfGraphics { x: self.device.horizontal_origin + x, y: self.device.vertical_origin + self.box_node.height + y, operation: operation.clone(), - }); - } else { - missing_graphics_step = true; + }), + Some(None) => {} + None => missing_graphics_step = true, } return; } diff --git a/crates/texrra-tex-core/src/execution/diagnostics.rs b/crates/texrra-tex-core/src/execution/diagnostics.rs index b850ab7..71497d5 100644 --- a/crates/texrra-tex-core/src/execution/diagnostics.rs +++ b/crates/texrra-tex-core/src/execution/diagnostics.rs @@ -654,10 +654,18 @@ impl Printer<'_> { PdfLiteralMode::Origin => {} PdfLiteralMode::Page => self.literal(" page"), PdfLiteralMode::Direct => self.literal(" direct"), + PdfLiteralMode::XdvOrigin | PdfLiteralMode::XdvDirect => {} } self.tokens(tokens)?; } OutputOperation::PdfSavePosition => self.command("pdfsavepos"), + OutputOperation::Special { shipout, tokens } => { + self.command("special"); + if *shipout { + self.literal(" shipout"); + } + self.tokens(tokens)?; + } OutputOperation::PdfSetMatrix(tokens) => { self.command("pdfsetmatrix"); self.tokens(tokens)?; diff --git a/crates/texrra-tex-core/src/execution/engine.rs b/crates/texrra-tex-core/src/execution/engine.rs index 298512b..3bf707c 100644 --- a/crates/texrra-tex-core/src/execution/engine.rs +++ b/crates/texrra-tex-core/src/execution/engine.rs @@ -33,6 +33,7 @@ mod quantities; mod restores; mod scanning; mod scheduling; +mod specials; mod statistics; #[derive(Clone, Copy, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)] @@ -2885,6 +2886,9 @@ impl Executor { OutputOperation::PdfSavePosition => { return self.fail("PDF position requires a positioned shipout"); } + OutputOperation::Special { .. } => { + return self.fail("special requires a positioned shipout"); + } OutputOperation::PdfSave | OutputOperation::PdfSetMatrix(_) | OutputOperation::PdfRestore diff --git a/crates/texrra-tex-core/src/execution/engine/device.rs b/crates/texrra-tex-core/src/execution/engine/device.rs index 0dee00c..42402cc 100644 --- a/crates/texrra-tex-core/src/execution/engine/device.rs +++ b/crates/texrra-tex-core/src/execution/engine/device.rs @@ -1,5 +1,5 @@ use super::*; -use crate::pdf_device::{PdfFileOptions, PdfPageData}; +use crate::pdf_device::{PdfDriver, PdfFileOptions, PdfPageData}; impl Executor { /// TeX extension commands share the scanner and produce their normal /// effects in math as well as in vertical and horizontal lists. @@ -26,6 +26,7 @@ impl Executor { span: token.span, })?; } + Special => self.scan_special(token.span, files)?, Pdfsave | Pdfsetmatrix | Pdfrestore | Pdfliteral => { self.scan_pdf_graphics(primitive, token.span, files)? } @@ -259,7 +260,12 @@ impl Executor { if level > 9 { return self.fail("invalid native PDF compression level"); } + let driver = match self.state.input_profile() { + InputProfile::TeX8Bit => PdfDriver::PdfTeX, + InputProfile::UnicodeScalar => PdfDriver::Xdv, + }; Ok(Some(PdfPageData { + driver, file: self.state.pdf_file_options.clone().unwrap(), stream_compression: level.max(0) as u8, })) diff --git a/crates/texrra-tex-core/src/execution/engine/page.rs b/crates/texrra-tex-core/src/execution/engine/page.rs index 1505f57..88a08d8 100644 --- a/crates/texrra-tex-core/src/execution/engine/page.rs +++ b/crates/texrra-tex-core/src/execution/engine/page.rs @@ -278,15 +278,23 @@ impl Executor { } let magnification = self.prepare_magnification()?; let pdf = self.pdf_page_data(files)?; + let unicode_pages = self.state.input_profile() == InputProfile::UnicodeScalar; + // The XDV driver uses a physical sheet and origin, then applies + // magnification to the DVI movements relative to that origin. + let origin = |value| { + if unicode_pages { + crate::pdf_device::unmagnify(value, magnification) + } else { + value + } + }; let horizontal_origin = - i64::from(self.read_parameter(Parameter::Pdfhorigin).width()) + h_offset; + origin(i64::from(self.read_parameter(Parameter::Pdfhorigin).width())) + h_offset; let vertical_origin = - i64::from(self.read_parameter(Parameter::Pdfvorigin).width()) + v_offset; + origin(i64::from(self.read_parameter(Parameter::Pdfvorigin).width())) + v_offset; let mut page_width = i64::from(self.read_parameter(Parameter::Pdfpagewidth).width()); let requested_page_height = i64::from(self.read_parameter(Parameter::Pdfpageheight).width()); - let unicode_pages = self.state.input_profile() == super::super::InputProfile::UnicodeScalar; - // The XeTeX PDF device uses the default letter canvas unless a page size was supplied. - let default_canvas = |bp: i64| bp * 803 * 65536 / 800; + let default_canvas = |bp: i64| origin(bp * 803 * 65536 / 800); if page_width == 0 { page_width = if unicode_pages { default_canvas(612) } else { b.width + 2 * horizontal_origin }; } @@ -335,6 +343,7 @@ impl Executor { pdf_color_start, pdf_color_steps: Vec::new(), pdf_graphics_steps: Vec::new(), + specials: Vec::new(), pdf_text_spaces: None, pdf_resource_entries, pdf_page_attributes, @@ -394,6 +403,7 @@ impl Executor { && matches!( output.operation, OutputOperation::Write { .. } | OutputOperation::PdfLiteral { shipout: true, .. } + | OutputOperation::Special { shipout: true, .. } ) { shipout.pdf_font_bindings = self.pdf_virtual_fonts.captured_font_bindings(); @@ -421,16 +431,27 @@ impl Executor { return self.fail("cannot ship a PDF color operation to DVI"); } shipout.pdf_color_steps.push(self.ship_pdf_color(*stack, action, output.span, files)?); + } else if matches!(output.operation, OutputOperation::Special { .. }) { + let special = self.resolve_special( + output, position.expect("special needs a shipout position"), files, + )?; + let graphics = if let Some(pdf) = &device.pdf { + self.render_special(&special, pdf.driver, files)? + } else { + None + }; + shipout.specials.push(special); + shipout.pdf_graphics_steps.push(graphics); } else if output.is_pdf_graphics() { if device.pdf.is_none() { return self.fail("cannot ship a PDF graphics operation to DVI"); } - shipout.pdf_graphics_steps.push(self.ship_pdf_graphics( + shipout.pdf_graphics_steps.push(Some(self.ship_pdf_graphics( output, position.expect("PDF graphics need a shipout position"), &mut graphics_stack, files, - )?); + )?)); } else if let OutputOperation::PdfSavePosition = output.operation { self.current = output.span; self.tick()?; diff --git a/crates/texrra-tex-core/src/execution/engine/pdf_links.rs b/crates/texrra-tex-core/src/execution/engine/pdf_links.rs index 849a5bc..d1fe4a8 100644 --- a/crates/texrra-tex-core/src/execution/engine/pdf_links.rs +++ b/crates/texrra-tex-core/src/execution/engine/pdf_links.rs @@ -229,7 +229,7 @@ impl Executor { &mut self, b: &NativeBox, device: &ShipoutDevice, - graphics: &[PdfGraphics], + graphics: &[Option], files: &mut impl SourceProvider, ) -> Result { let margin = i64::from(self.read_parameter(Parameter::Pdflinkmargin).width()); @@ -250,18 +250,18 @@ impl Executor { row }; match item { - BoxPaint::PdfGraphics => match graphics.next() { - Some(PdfGraphics::Save) => saved.push(transform), - Some(PdfGraphics::Matrix(matrix)) => { + BoxPaint::PdfGraphics => match graphics.next().map(Option::as_ref) { + Some(Some(PdfGraphics::Save)) => saved.push(transform), + Some(Some(PdfGraphics::Matrix(matrix))) => { transform = (transform.0.concatenate(matrix.about(x as f64, y as f64, true)), true); } - Some(PdfGraphics::Restore { shift: [dx, dy] }) => { + Some(Some(PdfGraphics::Restore { shift: [dx, dy] })) => { if let Some(previous) = saved.pop() { transform = (previous.0.concatenate(Affine::translation(*dx as f64, *dy as f64)), previous.1 || *dx != 0 || *dy != 0); } } - Some(PdfGraphics::Literal { .. }) => {} + Some(Some(PdfGraphics::Literal { .. }) | None) => {} None => failure = Some(self.error("missing PDF transform at link shipout", self.current)), }, BoxPaint::RowStart(row) if self.pdf_running_links => { diff --git a/crates/texrra-tex-core/src/execution/engine/specials.rs b/crates/texrra-tex-core/src/execution/engine/specials.rs new file mode 100644 index 0000000..910f78b --- /dev/null +++ b/crates/texrra-tex-core/src/execution/engine/specials.rs @@ -0,0 +1,134 @@ +//! TeX special whatsits and PDF driver dispatch at shipout. +use super::*; +use crate::pdf_device::{PdfDriver, PdfGraphics, PdfLiteralMode}; + +impl Executor { + pub(super) fn scan_special( + &mut self, + span: Span, + files: &mut impl SourceProvider, + ) -> Result<(), Error> { + let shipout = self.keyword("shipout", files)?; + let tokens = if shipout { + self.scan_group(files)? + } else { + self.scan_expanded_group(files)? + }; + self.defer_output(OutputNode { + operation: OutputOperation::Special { shipout, tokens }, + span, + }) + } + + pub(super) fn resolve_special( + &mut self, + node: &OutputNode, + position: [i64; 2], + files: &mut impl SourceProvider, + ) -> Result { + self.current = node.span; + self.tick()?; + let OutputOperation::Special { shipout, tokens } = &node.operation else { + unreachable!() + }; + let expanded; + let tokens = if *shipout { + expanded = self.fully_expand(tokens.clone(), files)?; + &expanded + } else { + tokens + }; + Ok(ShipoutSpecial { + span: node.span, + position, + bytes: self.pdf_token_bytes(tokens)?.into(), + }) + } + + pub(super) fn render_special( + &mut self, + special: &ShipoutSpecial, + driver: PdfDriver, + files: &mut impl SourceProvider, + ) -> Result, Error> { + let data = special.bytes.as_ref(); + let (mode, bytes) = if driver == PdfDriver::PdfTeX { + let Some(body) = data + .strip_prefix(b"pdf:") + .or_else(|| data.strip_prefix(b"PDF:")) + else { + if !data.is_empty() && !data.starts_with(b"src:") && !data.starts_with(b"SRC:") { + let preview: String = + data.iter().take(65).map(|&byte| char::from(byte)).collect(); + let preview = self.external_print(&preview); + let ellipsis = if data.len() > 65 { "..." } else { "" }; + let warning = + format!("Non-PDF special ignored!\n {preview}{ellipsis}\n"); + files + .observe_diagnostic(WriteDestination::TerminalAndLog, &warning) + .map_err(|error| self.error(error, special.span))?; + } + return Ok(None); + }; + if let Some(body) = body.strip_prefix(b"direct:") { + (PdfLiteralMode::Direct, body) + } else if let Some(body) = body.strip_prefix(b"page:") { + (PdfLiteralMode::Page, body) + } else { + (PdfLiteralMode::Origin, body) + } + } else { + let data = data.trim_ascii_start(); + if data.is_empty() { + return Ok(None); + } + let body = data.strip_prefix(b"pdf:").map(<[u8]>::trim_ascii_start); + let Some(mut body) = + body.and_then(|body| body.strip_prefix(b"literal")) + .filter(|body| { + !body + .first() + .is_some_and(|b| b.is_ascii_alphanumeric() || *b == b'_' || *b == b':') + }) + else { + let name = data + .split(|b| b.is_ascii_whitespace()) + .next() + .unwrap_or(data); + return Err(self.error( + format!( + "unsupported native XeTeX device special: {}", + String::from_utf8_lossy(name) + ), + special.span, + )); + }; + let mut mode = PdfLiteralMode::XdvOrigin; + body = body.trim_ascii_start(); + loop { + if let Some(rest) = body.strip_prefix(b"direct") { + mode = PdfLiteralMode::XdvDirect; + body = rest.trim_ascii_start(); + } else if let Some(rest) = body.strip_prefix(b"reverse") { + files + .observe_diagnostic( + WriteDestination::TerminalAndLog, + "xdvipdfmx: warning: pdf:literal reverse is unsupported and ignored\n", + ) + .map_err(|error| self.error(error, special.span))?; + body = rest.trim_ascii_start(); + } else { + break; + } + } + if body.is_empty() { + return Ok(None); + } + (mode, body) + }; + Ok(Some(PdfGraphics::Literal { + mode, + bytes: Arc::from(bytes), + })) + } +} diff --git a/crates/texrra-tex-core/src/execution/format_image.rs b/crates/texrra-tex-core/src/execution/format_image.rs index 2c5128b..2219666 100644 --- a/crates/texrra-tex-core/src/execution/format_image.rs +++ b/crates/texrra-tex-core/src/execution/format_image.rs @@ -8,9 +8,9 @@ use std::{ sync::{Arc, Mutex, OnceLock, Weak}, }; -const SCHEMA: u32 = 56; -const COMPATIBLE_SCHEMAS: [u32; 25] = [ - 27, 28, 31, 32, 33, 34, 35, 36, 37, 38, 39, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, SCHEMA, +const SCHEMA: u32 = 57; +const COMPATIBLE_SCHEMAS: [u32; 26] = [ + 27, 28, 31, 32, 33, 34, 35, 36, 37, 38, 39, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, SCHEMA, ]; const ENGINE: &str = concat!("texrra-native/", env!("CARGO_PKG_VERSION")); diff --git a/crates/texrra-tex-core/src/execution/job.rs b/crates/texrra-tex-core/src/execution/job.rs index c04b08c..d1f41cf 100644 --- a/crates/texrra-tex-core/src/execution/job.rs +++ b/crates/texrra-tex-core/src/execution/job.rs @@ -253,6 +253,10 @@ pub enum OutputOperation { tokens: Vec, }, PdfSavePosition, + Special { + shipout: bool, + tokens: Vec, + }, } #[derive(Clone, Debug, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)] @@ -273,6 +277,7 @@ impl OutputNode { | OutputOperation::PdfSetMatrix(_) | OutputOperation::PdfRestore | OutputOperation::PdfLiteral { .. } + | OutputOperation::Special { .. } ) } diff --git a/crates/texrra-tex-core/src/execution/mod.rs b/crates/texrra-tex-core/src/execution/mod.rs index 2b2f43d..0341433 100644 --- a/crates/texrra-tex-core/src/execution/mod.rs +++ b/crates/texrra-tex-core/src/execution/mod.rs @@ -56,7 +56,7 @@ pub use boxes::{ pub use cancellation::Cancellation; pub use case::CaseCode; pub use context::{ContextFrame, ContextKind, InputContext}; -pub use device::{NativeShipout, ShipoutDevice}; +pub use device::{NativeShipout, ShipoutDevice, ShipoutSpecial}; pub use diagnostics::{DiagnosticBox, DiagnosticNode, ShowBoxReport}; pub use engine::{EntryCheckpoint, Executor, Limits}; pub use font_catalog::{ diff --git a/crates/texrra-tex-core/src/execution/state.rs b/crates/texrra-tex-core/src/execution/state.rs index 0e0b3b1..d12beb9 100644 --- a/crates/texrra-tex-core/src/execution/state.rs +++ b/crates/texrra-tex-core/src/execution/state.rs @@ -352,6 +352,7 @@ pub enum Primitive { Leftmarginkern, Rightmarginkern, Pdflastlink, + Special, } impl Primitive { @@ -991,6 +992,7 @@ impl Default for State { ("openout", Openout), ("closeout", Closeout), ("write", Write), + ("special", Special), ("immediate", Immediate), ("message", Message), ("errmessage", Errmessage), diff --git a/crates/texrra-tex-core/src/execution/statistics.rs b/crates/texrra-tex-core/src/execution/statistics.rs index 888d100..b5cb02a 100644 --- a/crates/texrra-tex-core/src/execution/statistics.rs +++ b/crates/texrra-tex-core/src/execution/statistics.rs @@ -175,7 +175,8 @@ impl Collector { } pub fn output(&mut self, n: &OutputNode) { if let OutputOperation::Write { tokens, .. } - | OutputOperation::PdfLiteral { tokens, .. } = &n.operation + | OutputOperation::PdfLiteral { tokens, .. } + | OutputOperation::Special { tokens, .. } = &n.operation { self.usage.token_list_cells += tokens.len(); } diff --git a/crates/texrra-tex-core/src/pdf.rs b/crates/texrra-tex-core/src/pdf.rs index ec50468..f963b4f 100755 --- a/crates/texrra-tex-core/src/pdf.rs +++ b/crates/texrra-tex-core/src/pdf.rs @@ -704,7 +704,7 @@ fn page_content( pt(n) } }; - use crate::pdf_device::{PdfGraphics, PdfLiteralMode}; + use crate::pdf_device::{PdfDriver, PdfGraphics, PdfLiteralMode}; use crate::render::DisplayUnits; let mut content = PageContent::default(); @@ -757,6 +757,8 @@ fn page_content( } = item { NativeTextRun::flush(&mut native_text, &mut content); + let previous_origin = content.origin.position(); + let special_origin = mode.xdv_origin([*x, height - *y], height, list.magnification); match mode { PdfLiteralMode::Direct => { native_text::NativeText::break_string(&mut tex_text, &mut content); @@ -767,9 +769,18 @@ fn page_content( content.move_origin([*x, height - *y], list.units, digits); } } + PdfLiteralMode::XdvOrigin | PdfLiteralMode::XdvDirect => { + native_text::NativeText::finish(&mut tex_text, &mut content); + if let Some(point) = special_origin { + content.move_origin(point, list.units, digits); + } + } } content.bytes.extend_from_slice(bytes); content.push(b'\n'); + if special_origin.is_some() { + content.move_origin(previous_origin, list.units, digits); + } continue; } if list.units == DisplayUnits::TeX { @@ -810,9 +821,15 @@ fn page_content( } = item { let [h, v] = content.origin.position(); - native_text::rule( - &mut content, *x - h, *y + v, *width, *rule_height, height, digits, - ); + if list.pdf.as_ref().is_some_and(|pdf| pdf.driver == PdfDriver::Xdv) { + native_text::xdv_rule( + &mut content, *x - h, height - *y - v - *rule_height, *width, *rule_height, digits, + ); + } else { + native_text::rule( + &mut content, *x - h, *y + v, *width, *rule_height, height, digits, + ); + } continue; } } diff --git a/crates/texrra-tex-core/src/pdf_device.rs b/crates/texrra-tex-core/src/pdf_device.rs index 3053512..2fa01a9 100644 --- a/crates/texrra-tex-core/src/pdf_device.rs +++ b/crates/texrra-tex-core/src/pdf_device.rs @@ -13,8 +13,23 @@ pub struct PdfFileOptions { pub decimal_digits: u8, pub pk_resolution: u32, } +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)] +pub enum PdfDriver { + #[default] + PdfTeX, + Xdv, +} + +impl PdfDriver { + fn is_pdftex(&self) -> bool { + *self == Self::PdfTeX + } +} + #[derive(Clone, Debug, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)] pub struct PdfPageData { + #[serde(default, skip_serializing_if = "PdfDriver::is_pdftex")] + pub driver: PdfDriver, pub file: PdfFileOptions, pub stream_compression: u8, } @@ -28,6 +43,13 @@ pub fn magnify(value: i64, mag: i32) -> i64 { ((n + 500) / 1000) as i64 } } +/// Convert a physical dimension to the logical coordinates of a magnified page. +pub(crate) fn unmagnify(value: i64, mag: i32) -> i64 { + let mag = i64::from(mag); + let n = value * 1000; + n.signum() * ((n.abs() + mag / 2) / mag) +} + pub fn divide_scaled(value: i64, denominator: i64, digits: u8) -> (i64, i64) { let scale = 10i128.pow(u32::from(digits)); let n = i128::from(value).abs(); diff --git a/crates/texrra-tex-core/src/pdf_device/graphics.rs b/crates/texrra-tex-core/src/pdf_device/graphics.rs index 72c042f..7cd1054 100644 --- a/crates/texrra-tex-core/src/pdf_device/graphics.rs +++ b/crates/texrra-tex-core/src/pdf_device/graphics.rs @@ -8,6 +8,26 @@ pub enum PdfLiteralMode { Origin, Page, Direct, + XdvOrigin, + XdvDirect, +} + +impl PdfLiteralMode { + pub(crate) fn xdv_origin( + self, + point: [i64; 2], + page_height: i64, + magnification: i32, + ) -> Option<[i64; 2]> { + match self { + Self::XdvOrigin => Some(point), + Self::XdvDirect => { + let inch = super::unmagnify(4_736_286, magnification); + Some([inch, page_height - inch]) + } + _ => None, + } + } } #[derive(Clone, Debug, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)] diff --git a/crates/texrra-tex-core/src/pdf_text.rs b/crates/texrra-tex-core/src/pdf_text.rs index 583c04d..0dee710 100644 --- a/crates/texrra-tex-core/src/pdf_text.rs +++ b/crates/texrra-tex-core/src/pdf_text.rs @@ -437,3 +437,33 @@ pub(super) fn rule( } out.push_str("Q\n"); } + + +pub(super) fn xdv_rule( + out: &mut PageContent, + x: i64, + y: i64, + width: i64, + height: i64, + digits: u8, +) { + if width <= 0 || height <= 0 { + return; + } + out.push_str("q\n"); + // The XDV driver strokes rules up to 5 bp wide and fills thicker rules. + if width.min(height) <= 5 * 6_578_176 / 100 { + let (thickness, points) = if width > height { + (height, [x, y + height / 2, x + width, y + height / 2]) + } else { + (width, [x + width / 2, y, x + width / 2, y + height]) + }; + let [x1, y1, x2, y2] = points.map(|value| print_sp(value, digits)); + let thickness = print_sp(thickness, digits + 1); + out.push_str(&format!("{thickness} w {x1} {y1} m {x2} {y2} l S\n")); + } else { + let [x, y, width, height] = [x, y, width, height].map(|value| print_sp(value, digits)); + out.push_str(&format!("{x} {y} {width} {height} re f\n")); + } + out.push_str("Q\n"); +} diff --git a/crates/texrra-tex-core/src/source_map/pdf_projection.rs b/crates/texrra-tex-core/src/source_map/pdf_projection.rs index 5d8df19..fc648d9 100644 --- a/crates/texrra-tex-core/src/source_map/pdf_projection.rs +++ b/crates/texrra-tex-core/src/source_map/pdf_projection.rs @@ -19,6 +19,7 @@ pub(super) struct PdfProjection { stack: Vec, units: DisplayUnits, height: i64, + magnification: i32, digits: u8, units_per_bp: f64, text_active: bool, @@ -48,6 +49,7 @@ impl PdfProjection { stack: vec![graphics], // The page writer begins with q. units: page.units, height: page.height, + magnification: page.magnification, digits: page.pdf.as_ref().map_or(3, |page| page.file.decimal_digits), units_per_bp: 1.0 / page.units.bp(1), text_active: false, @@ -132,13 +134,20 @@ impl PdfProjection { if *mode != PdfLiteralMode::Direct { self.text_active = false; } + let previous_origin = self.origin.position(); + let special_origin = mode.xdv_origin([x, y], self.height, self.magnification); if *mode == PdfLiteralMode::Origin { self.move_origin([x, y]); + } else if let Some(point) = special_origin { + self.move_origin(point); } if self.apply_literal(bytes).is_none() { self.graphics = None; self.stack.clear(); } + if special_origin.is_some() { + self.move_origin(previous_origin); + } return None; } self.text_active = false; diff --git a/crates/texrra-tex-core/tests/execution_specials.rs b/crates/texrra-tex-core/tests/execution_specials.rs new file mode 100644 index 0000000..5f1a96b --- /dev/null +++ b/crates/texrra-tex-core/tests/execution_specials.rs @@ -0,0 +1,98 @@ +use texrra_tex_core::{ + execution::{Event, Executor, InputProfile, Limits, NativeShipout, NoFiles, SourceFile, State}, + pdf_device::{PdfGraphics, PdfLiteralMode}, + render::DisplayItem, +}; + +fn ship(source: &str, pdf: bool) -> NativeShipout { + let mut state = State::initex() + .with_etex() + .with_input_profile(InputProfile::UnicodeScalar); + if pdf { + state = state.with_pdf_output(); + } + let result = Executor::new(state, Limits::default()) + .with_native_pages() + .run( + SourceFile { + name: "specials.tex".into(), + data: format!( + r"\catcode123=1 \catcode125=2 \catcode35=6 \pdfpkresolution=72 {source}" + ) + .into_bytes(), + }, + &mut NoFiles, + ) + .unwrap(); + result + .events + .into_iter() + .find_map(|event| match event { + Event::Shipout(page) => Some(*page), + _ => None, + }) + .expect("the source ships one page") +} + +#[test] +fn special_expansion_and_positions_follow_shipped_box_copies() { + let page = ship( + r"\def\payload{early} + \setbox0=\hbox{\kern10pt\special{test:\payload Café} + \special shipout{test:\payload}\vrule width4pt height2pt depth0pt} + \setbox1=\hbox{\special{discarded}} + \def\payload{late}\shipout\vbox{\kern20pt\copy0\box0}\end", + false, + ); + let specials: Vec<_> = page + .specials + .iter() + .map(|special| (special.bytes.as_ref(), special.position)) + .collect(); + assert_eq!( + specials, + [ + ("test:earlyCafé".as_bytes(), [655360, -131072]), + (b"test:late", [655360, -131072]), + ("test:earlyCafé".as_bytes(), [655360, 0]), + (b"test:late", [655360, 0]), + ] + ); + let restored: NativeShipout = + serde_json::from_str(&serde_json::to_string(&page).unwrap()).unwrap(); + assert_eq!(restored, page); +} + +#[test] +fn unicode_pdf_device_keeps_literal_modes_and_order_with_rules() { + let page = ship( + r"\def\paint#1{1 0 0 rg} + \setbox0=\hbox{\kern10pt\special{pdf:literal \paint{} 0 0 10 10 re f} + \kern5pt\special shipout{pdf:literal direct \paint{} 100 -60 7 9 re f} + \vrule width4pt height2pt depth0pt} + \def\paint#1{0 0 1 rg}\shipout\box0\end", + true, + ); + let display = page.display_list().unwrap(); + assert!(matches!( + display.items.as_slice(), + [ + DisplayItem::PdfGraphics { + operation: PdfGraphics::Literal { + mode: PdfLiteralMode::XdvOrigin, + bytes: early, + }, + .. + }, + DisplayItem::PdfGraphics { + operation: PdfGraphics::Literal { + mode: PdfLiteralMode::XdvDirect, + bytes: late, + }, + .. + }, + DisplayItem::Rule { .. }, + ] if early.as_ref() == b"1 0 0 rg 0 0 10 10 re f" + && late.as_ref() == b"0 0 1 rg 100 -60 7 9 re f" + )); +} diff --git a/docs/P2_M1_PROGRESS.md b/docs/P2_M1_PROGRESS.md index 3323d90..fd80bcd 100644 --- a/docs/P2_M1_PROGRESS.md +++ b/docs/P2_M1_PROGRESS.md @@ -2175,6 +2175,35 @@ PDF,恢复实际 PFB 并反转斜切时复用 1277 步,只替换第二页。 全量编译一致。incremental-receipt.json 的 SHA-256 为 bbc0991b0316e6d76aa58649ec873525f5544ab530d93fe491fc6e16bd00a27d。 +### 实际 special 出页和 XeTeX 设备几何 + +原生列表保存 \special 和 \special shipout。普通指令在扫描时展开,延迟 +指令由已装箱节点在实际出页时展开。保留每个已出页节点的字节、来源和 +实际 TeX sp 坐标。复制盒在各自位置出页,弃用盒中的指令不执行。原生 +布局清单提供已解析的 specials。PDF 设备支持 pdfTeX 的 pdf:、page: +和 direct: 语义,以及 XeTeX 驱动的 pdf:literal 和其 direct 选项。 + +XeTeX 的纸张和页边原点使用物理尺寸,放大作用于相对原点的内容。 +相对 literal 在指令位置执行并恢复局部平移,direct 使用物理页边原点。 +细规则线按驱动语义取描边色,厚规则取填充色。首轮差异产物保存在 +pdf-native-before-rule 和 mag-native-before-origin。参考 XDV 还会 +自动生成 pdf:pagesize default,本次比较的 8 条记录为输入中的实际 +绘制指令。两份参考 XeTeX 作业的指令字节、相对 sp 位置与原生一致, +包含 120% 放大和双向偏移。两页的 600 dpi RGB 像素一致。另一个 +pdfTeX 作业的三种坐标模式、非 PDF 指令警告和 600 dpi 像素通过。 + +30 项定向回归通过。格式 schema57 保存的盒中的延迟指令可以重载, +旧的原样 XeLaTeX schema56 仍可加载执行。连续编辑三页文档中晚定义 +的宏,检查点复用 1006 步,只替换第二页。增量 PDF、页面和来源映射 +与独立全量一致。源、参考 XDV/PDF、失败证据和回执在 +target/p3-xetex-specials,receipt.json 的 SHA-256 为 +1eed55986bd1288eae11273bc237ab3bf3275b7d0294a5e57fb09ae96e577a05。 +下一步补齐真实 Unicode 数学编码及 XeTeX profile 所需的语义,由未改 +的 LaTeX 自行选到 XeTeX 后端。仍需扩充出页协议、系统字体名称选择和 +Unicode 大小写对照,再推进原样类包及统一验收。 +[XeTeX 的 special 扫描与定位](https://github.com/TeX-Live/texlive-source/blob/trunk/texk/web2c/xetexdir/xetex.web#L27480-L27490) +[xdvipdfmx 的规则线与矩形语义](https://github.com/TeX-Live/texlive-source/blob/trunk/texk/dvipdfm-x/pdfdev.c#L1320-L1381) + ### 原样 XeLaTeX 启动的执行路径 读取同一发行版的 xelatex.ini、latex.ltx、expl3 及 Unicode 数据。 diff --git a/src/native_job.rs b/src/native_job.rs index d69f07f..e17e665 100644 --- a/src/native_job.rs +++ b/src/native_job.rs @@ -836,6 +836,9 @@ impl Files { if !graphics.is_empty() { layout["pdf_graphics"] = json!(graphics); } + if !shipout.specials.is_empty() { + layout["specials"] = json!(shipout.specials); + } measured.push(layout); } let sources: Vec<_> = execution diff --git a/tests/native_pipeline.rs b/tests/native_pipeline.rs index 6b79660..60ba5c4 100644 --- a/tests/native_pipeline.rs +++ b/tests/native_pipeline.rs @@ -484,6 +484,76 @@ fn resumed_suffix_reuses_search_for_unchanged_paragraphs() { fs::remove_dir_all(p).unwrap(); } +#[test] +fn checkpoint_keeps_late_special_tokens_until_the_updated_page_is_shipped() { + let p = directory("late-special"); + let mut request = request(&p); + request.input_profile = texrra_tex_core::execution::InputProfile::UnicodeScalar; + let entry = p.join("main.tex"); + let resume_prefix = "\\relax ".repeat(26); + let padding = format!("{resume_prefix}\n").repeat(45); + let first_program = r"\def\paint{pdf:literal 0.5 g 0 0 5 5 re f}"; + let changed_program = r"\def\paint{pdf:literal 0.2 g 0 0 5 5 re f}"; + let source = format!( + r"\catcode123=1 \catcode125=2 + \setbox0=\hbox{{\special shipout{{\paint}}\vrule width7pt height8pt}} + \shipout\hbox{{\vrule width7pt height8pt}} + {padding} + {first_program} + \shipout\copy0 + \shipout\hbox{{\vrule width9pt height8pt}} + \end + " + ); + let project = ProjectSnapshot::new(ProjectDefinition { + configuration: request.world.clone(), + revision: 1, + roots: [p.clone()].into(), + files: [(entry.clone(), Arc::from(source.as_bytes()))].into(), + directories: Default::default(), + aliases: Default::default(), + generated_roots: [p.clone()].into(), + generated: Default::default(), + }) + .unwrap(); + let compiler = NativeCompiler::default().with_automatic_entry_checkpoints(); + let original = compiler + .compile(request.clone().with_project(project.clone())) + .unwrap(); + + let edited = project + .with_file_edits( + 2, + [( + entry, + Arc::from(source.replace(first_program, changed_program).into_bytes()), + )] + .into(), + ) + .unwrap(); + let compile = request.with_project(edited); + let resumed = compiler.compile(compile.clone()).unwrap(); + let full = NativeCompiler::default().compile(compile).unwrap(); + assert!(resumed.entry_checkpoint_work.reused_steps > 0); + assert_eq!(resumed.pdf, full.pdf); + assert_ne!(resumed.pdf, original.pdf); + assert_eq!(resumed.pages, full.pages); + assert_eq!(resumed.source_map.pages, full.source_map.pages); + let changed: Vec<_> = resumed + .preview_since(Some(original.revision())) + .unwrap() + .pages + .iter() + .map(|page| page.index) + .collect(); + assert_eq!(changed, [1]); + eprintln!( + "late special reused {} steps and replaced pages {:?}", + resumed.entry_checkpoint_work.reused_steps, changed + ); + fs::remove_dir_all(p).unwrap(); +} + #[test] fn provisional_preview_matches_published_pages_and_cancellation_keeps_artifacts() { #[derive(Clone, Copy)]