diff --git a/crates/texrra-tex-core/src/execution/boxes.rs b/crates/texrra-tex-core/src/execution/boxes.rs index 7f16994..d1e112c 100644 --- a/crates/texrra-tex-core/src/execution/boxes.rs +++ b/crates/texrra-tex-core/src/execution/boxes.rs @@ -180,7 +180,7 @@ struct WalkBudget<'a> { remaining: usize, cancellation: Option<&'a Cancellation>, leader_depth: usize, - xdv_annotations: bool, + xdv_scopes: bool, } impl WalkBudget<'_> { @@ -189,7 +189,7 @@ impl WalkBudget<'_> { remaining: usize::MAX, cancellation: None, leader_depth: 0, - xdv_annotations: false, + xdv_scopes: false, } } @@ -296,7 +296,7 @@ impl NativeBox { remaining: limit, cancellation, leader_depth: 0, - xdv_annotations: false, + xdv_scopes: false, }; self.walk_at(0, 0, 0, false, false, &mut budget, &mut |x, y, item| { if let BoxPaint::Output(o) = item { @@ -856,29 +856,37 @@ impl NativeBox { &self, cancellation: Option<&Cancellation>, mut emit: impl FnMut(GeometryItem), + ) -> Result<(), String> { + self.visit_device_geometry(cancellation, false, |item, _| emit(item)) + } + + pub(super) fn visit_device_geometry( + &self, + cancellation: Option<&Cancellation>, + xdv: bool, + mut emit: impl FnMut(GeometryItem, i64), ) -> Result<(), String> { use crate::math_engine_tex::PositionedItem; let mut unsupported = false; - let mut budget = WalkBudget { cancellation, ..WalkBudget::for_geometry() }; - self.walk_at(0, 0, 0, false, false, &mut budget, &mut |x, y, node| { + self.walk_device(cancellation, xdv, &mut |x, y, node, mut shift| { let b = match node { BoxPaint::Box(b) => b, BoxPaint::PdfColor => { - emit(GeometryItem::PdfColor { x, y }); + emit(GeometryItem::PdfColor { x, y }, shift); return; } BoxPaint::PdfGraphics => { - emit(GeometryItem::PdfGraphics { x, y }); + emit(GeometryItem::PdfGraphics { x, y }, shift); return; } BoxPaint::PdfTextSpace(operation) => { - emit(GeometryItem::PdfTextSpace { x, y, operation }); + emit(GeometryItem::PdfTextSpace { x, y, operation }, shift); return; } BoxPaint::Output(node) => { emit(GeometryItem::Output { special: matches!(node.operation, OutputOperation::Special { .. }), - }); + }, shift); return; } BoxPaint::RowStart(_) | BoxPaint::ScopeStart(_) | BoxPaint::ScopeEnd(_) @@ -891,7 +899,10 @@ impl NativeBox { y: y + p.y, item: p.item.clone(), source: p.source.clone(), - })); + }), shift); + if xdv { + shift += xdv_width_difference(&p.item); + } } } else if b.character.is_some() { unsupported = true; @@ -928,11 +939,11 @@ impl NativeBox { Ok(()) } - pub(super) fn positioned_outputs(&self) -> Vec<[i64; 2]> { + pub(super) fn positioned_outputs(&self, xdv: bool) -> Vec<([i64; 2], i64)> { let mut positions = Vec::new(); - self.walk(0, 0, &mut |x, y, node| { + self.walk_device(None, xdv, &mut |x, y, node, shift| { if matches!(node, BoxPaint::Output(node) if node.needs_shipout_position()) { - positions.push([x, y]); + positions.push(([x, y], shift)); } }) .expect("output traversal of an already measured list"); @@ -953,17 +964,39 @@ impl NativeBox { .expect("link traversal of an already measured list"); } - pub(super) fn walk_xdv_annotations( + pub(super) fn walk_device( &self, cancellation: Option<&Cancellation>, - emit: &mut dyn FnMut(i64, i64, BoxPaint<'_>), + xdv: bool, + emit: &mut dyn FnMut(i64, i64, BoxPaint<'_>, i64), ) -> Result<(), &'static str> { let mut budget = WalkBudget { cancellation, - xdv_annotations: true, + xdv_scopes: xdv, ..WalkBudget::for_geometry() }; - self.walk_at(0, 0, 0, false, false, &mut budget, emit) + let mut shift = 0; + let mut saved = Vec::new(); + self.walk_at(0, 0, 0, false, false, &mut budget, &mut |x, y, node| { + let position = shift; + if xdv { + // The XDV driver adds its own TFM advances to the relative + // movements in the stream. POP restores the enclosing cursor. + match node { + BoxPaint::ScopeStart(_) => saved.push(shift), + BoxPaint::ScopeEnd(_) => shift = saved.pop().expect("balanced XDV box walk"), + BoxPaint::Box(b) => { + if let Some(geometry) = &b.math_geometry { + shift += geometry.items.iter() + .map(|p| xdv_width_difference(&p.item)) + .sum::(); + } + } + _ => {} + } + } + emit(x, y, node, position); + }) } fn walk_at( @@ -979,7 +1012,7 @@ impl NativeBox { if self.kind.is_unset() { return Ok(()); } - if budget.xdv_annotations { + if budget.xdv_scopes { budget.charge(1)?; emit(x, y, BoxPaint::ScopeStart(level)); } @@ -1097,7 +1130,7 @@ impl NativeBox { } } } - if budget.xdv_annotations { + if budget.xdv_scopes { emit(x, y, BoxPaint::ScopeEnd(level)); } Ok(()) @@ -1132,6 +1165,15 @@ impl NativeBox { result } } +pub(super) fn xdv_width_difference(item: &crate::math_engine_tex::MathItem) -> i64 { + match item { + crate::math_engine_tex::MathItem::NativeGlyph { font, slot, .. } => { + font.xdv_advance(*slot) - font.advance(*slot) + } + _ => 0, + } +} + pub(super) fn bp(n: i64) -> i64 { if n < 0 { -((-n * 800 + 401) / 803) diff --git a/crates/texrra-tex-core/src/execution/device.rs b/crates/texrra-tex-core/src/execution/device.rs index 8a0c724..025f7ad 100644 --- a/crates/texrra-tex-core/src/execution/device.rs +++ b/crates/texrra-tex-core/src/execution/device.rs @@ -125,7 +125,9 @@ impl NativeShipout { let mut missing_graphics_step = false; let mut output_index = 0; let mut reached_boundary = false; - self.box_node.visit_geometry(|item| { + let xdv = page.pdf.as_ref() + .is_some_and(|pdf| pdf.driver == crate::pdf_device::PdfDriver::Xdv); + self.box_node.visit_device_geometry(None, xdv, |item, shift| { if reached_boundary { return; } @@ -139,7 +141,7 @@ impl NativeShipout { boxes::GeometryItem::PdfColor { x, y } => { match color_steps.next() { Some(Some(color)) => { - page.items.push(color.display_item(left + x, baseline + y)) + page.push_device_item(color.display_item(left + x + shift, baseline + y), shift) } Some(None) => {} None => missing_color_step = true, @@ -147,30 +149,30 @@ impl NativeShipout { return; } boxes::GeometryItem::PdfTextSpace { x, y, operation } => { - page.items.push(DisplayItem::PdfTextSpace { - x: self.device.horizontal_origin + x, + page.push_device_item(DisplayItem::PdfTextSpace { + x: self.device.horizontal_origin + x + shift, y: self.device.vertical_origin + self.box_node.height + y, operation, - }); + }, shift); return; } boxes::GeometryItem::PdfGraphics { x, y } => { match graphics_steps.next() { Some((step, operation)) => { if let Some(operation) = operation { - page.items.push(DisplayItem::PdfGraphics { - x: self.device.horizontal_origin + x, + page.push_device_item(DisplayItem::PdfGraphics { + x: self.device.horizontal_origin + x + shift, y: self.device.vertical_origin + self.box_node.height + y, operation: operation.clone(), - }); + }, shift); } if let Some(program) = self.xdv_color_steps.get(&step) { - page.items.push(DisplayItem::PdfColor { - x: left + x, + page.push_device_item(DisplayItem::PdfColor { + x: left + x + shift, y: baseline + y, program: program.clone(), mode: crate::pdf_device::PdfLiteralMode::Page, - }); + }, shift); } if let Some((image, origin)) = self.pdf_special_images.get(&step) { let [left, bottom] = image.xdv.as_ref().unwrap().layout_offset; @@ -178,14 +180,14 @@ impl NativeShipout { page.items.len(), crate::provenance::PaintSource::token(*origin), ); - page.items.push(DisplayItem::PdfImage { - x: self.device.horizontal_origin + x + left, + page.push_device_item(DisplayItem::PdfImage { + x: self.device.horizontal_origin + x + shift + left, y: self.device.vertical_origin + self.box_node.height + y - image.height - bottom, width: image.width, height: image.height, image: image.clone(), - }); + }, shift); } } None => missing_graphics_step = true, @@ -196,18 +198,18 @@ impl NativeShipout { if !p.source.tokens.is_empty() { page.sources.insert(page.items.len(), p.source); } - let x = self.device.horizontal_origin + p.x; - let y = self.device.vertical_origin + self.box_node.height + p.y; + let x = left + p.x + shift; + let y = baseline + p.y; if let MathItem::OpenType(run) = p.item { run.paint(x, y, |value| value, |item, source| { if !matches!(item, DisplayItem::OpenTypeActualText(_) | DisplayItem::OpenTypeColor(_)) { page.sources.insert(page.items.len(), source); } - page.items.push(item); + page.push_device_item(item, shift); }); return; } - page.items.push(match p.item { + let item = match p.item { MathItem::NativeGlyph { font, slot, @@ -245,7 +247,8 @@ impl NativeShipout { invalid_geometry = true; return; } - }); + }; + page.push_device_item(item, shift); })?; if before_output.is_some() && !reached_boundary { return Err("missing deferred output boundary in its packed list".into()); diff --git a/crates/texrra-tex-core/src/execution/engine/page.rs b/crates/texrra-tex-core/src/execution/engine/page.rs index 96a545e..c59e3ae 100644 --- a/crates/texrra-tex-core/src/execution/engine/page.rs +++ b/crates/texrra-tex-core/src/execution/engine/page.rs @@ -48,6 +48,7 @@ enum XdvOutput { index: usize, graphics_step: usize, point: [i64; 2], + device_position: [i64; 2], origin: Option, content_origin: Option<[i64; 2]>, text: Option, @@ -544,13 +545,13 @@ impl Executor { }); self.begin_pdf_link_shipout(b, device, thread_rows) }); - let mut output_positions = if let Some(effects) = &leader_effects { - effects.output_positions.clone().into_iter() + let mut output_positions = if let Some(effects) = &leader_effects && !xdv { + effects.output_positions.iter().map(|&point| (point, 0)).collect() } else if outputs.iter().any(|node| node.needs_shipout_position()) { - b.positioned_outputs().into_iter() + b.positioned_outputs(xdv) } else { - Vec::new().into_iter() - }; + Vec::new() + }.into_iter(); let mut font_uses = if device.pdf.is_some() { shipout.virtual_glyphs = Some(VirtualGlyphs::new()); shipout_font_uses(b, &self.pdf_virtual_fonts, &self.state.fonts).map_err(|e| self.error(e, b.span))? @@ -577,7 +578,7 @@ impl Executor { layout.advance(self, (index, usage.before_paint), &outputs, &shipout.pdf_graphics_steps, files)?; } self.current = current; - self.prepare_virtual_glyph(shipout.virtual_glyphs.as_mut().unwrap(), usage, files)?; + self.prepare_virtual_glyph(shipout.virtual_glyphs.as_mut().unwrap(), usage, xdv, files)?; } if let Some(layout) = &mut pdf_link_shipout { layout.advance(self, (index, usize::MAX), &outputs, &shipout.pdf_graphics_steps, files)?; @@ -596,12 +597,13 @@ impl Executor { self.current = output.span; self.probe_pdf_space_font(&shipout, Some(index), files)?; } - let position = if output.needs_shipout_position() { - Some(output_positions.next().ok_or_else(|| { + let (position, xdv_shift) = if output.needs_shipout_position() { + let (position, shift) = output_positions.next().ok_or_else(|| { self.error("missing positioned native output node", output.span) - })?) + })?; + (Some(position), shift) } else { - None + (None, 0) }; if let OutputOperation::PdfObject(number) = output.operation { self.current = output.span; @@ -634,6 +636,8 @@ impl Executor { let special = self.resolve_special( output, position.expect("special needs a shipout position"), files, )?; + let [x, y] = special.position; + let device_position = [x + xdv_shift, y]; let graphics_step = shipout.pdf_graphics_steps.len(); let graphics = if let Some(pdf) = &device.pdf { if xdv && crate::pdf_device::xdv_color::ColorState::recognizes(&special.bytes) { @@ -647,14 +651,15 @@ impl Executor { None } else if xdv && let Some((kind, _)) = super::specials::xdv_navigation_operand(&special.bytes) { let point = xdv_transform.point( - (special.position[0] + horizontal_origin) as f64, - (special.position[1] + vertical_origin + b.height) as f64, + (device_position[0] + horizontal_origin) as f64, + (device_position[1] + vertical_origin + b.height) as f64, ).map(|coordinate| coordinate.round() as i64); let text = matches!(kind, b"docview" | b"outline").then(|| self.xdv_text.clone()); xdv_output.push(XdvOutput::Navigation { index: shipout.specials.len(), graphics_step, point, + device_position, origin: *origin, content_origin: content_origins.last().copied(), text, @@ -671,7 +676,7 @@ impl Executor { use crate::pdf_device::{PdfGraphics, PdfLiteralMode}; if let Some(PdfGraphics::Literal { mode, .. }) = &graphics { match mode { - PdfLiteralMode::XdvBeginContent => content_origins.push(special.position), + PdfLiteralMode::XdvBeginContent => content_origins.push(device_position), PdfLiteralMode::XdvEndContent => { content_origins.pop(); } _ => {} } @@ -686,7 +691,7 @@ impl Executor { xdv_graphics_stack.push((special.span, xdv_transform)); xdv_output.push(XdvOutput::SaveColor); } - let [x, y] = special.position; + let [x, y] = device_position; let pivot = matrix.about( (x + horizontal_origin) as f64, (y + vertical_origin + b.height) as f64, @@ -805,7 +810,7 @@ impl Executor { if let Some(layout) = &mut pdf_link_shipout { layout.advance(self, (output_count, usage.before_paint), &outputs, &shipout.pdf_graphics_steps, files)?; } - self.prepare_virtual_glyph(shipout.virtual_glyphs.as_mut().unwrap(), usage, files)?; + self.prepare_virtual_glyph(shipout.virtual_glyphs.as_mut().unwrap(), usage, xdv, files)?; } if let Some(layout) = pdf_link_shipout { let mut links = layout.finish(self, &outputs, &shipout.pdf_graphics_steps, files)?; @@ -877,7 +882,7 @@ impl Executor { ]; let mut saved_colors = Vec::new(); for operation in xdv_output { - let (index, graphics_step, [x, y], origin, content_origin, text) = match operation { + let (index, graphics_step, [x, y], device_position, origin, content_origin, text) = match operation { XdvOutput::SaveColor => { saved_colors.push(self.xdv_colors.current()); continue; @@ -907,8 +912,8 @@ impl Executor { } continue; } - XdvOutput::Navigation { index, graphics_step, point, origin, content_origin, text } => { - (index, graphics_step, point, origin, content_origin, text) + XdvOutput::Navigation { index, graphics_step, point, device_position, origin, content_origin, text } => { + (index, graphics_step, point, device_position, origin, content_origin, text) } }; let special = &shipout.specials[index]; @@ -934,7 +939,7 @@ impl Executor { } } else { let [left, top] = content_origin.unwrap_or(default_content_origin); - let [x, y] = special.position; + let [x, y] = device_position; let capture_origin = [x - left, top - y] .map(|coordinate| crate::render::DisplayUnits::TeX.bp(coordinate)); if let Some(operation) = self.ship_xdv_navigation( @@ -1040,7 +1045,7 @@ impl Executor { } fn prepare_virtual_glyph( - &mut self, glyphs: &mut VirtualGlyphs, usage: ShipoutFontUse, + &mut self, glyphs: &mut VirtualGlyphs, usage: ShipoutFontUse, xdv: bool, files: &mut impl SourceProvider, ) -> Result<(), Error> { self.check_cancellation()?; @@ -1052,7 +1057,7 @@ impl Executor { } let defaults = self.font_defaults(); let (packet, work) = Arc::make_mut(&mut self.pdf_virtual_fonts).glyph( - &mut self.state.fonts, defaults, files, usage.font.clone(), usage.slot, + &mut self.state.fonts, defaults, files, usage.font.clone(), usage.slot, xdv, self.limits.steps.saturating_sub(self.steps), self.cancellation.as_ref(), ).map_err(|e| self.error(e, self.current))?; self.steps += work; diff --git a/crates/texrra-tex-core/src/execution/engine/xdv_annotation.rs b/crates/texrra-tex-core/src/execution/engine/xdv_annotation.rs index 5beb8a6..6b61f19 100644 --- a/crates/texrra-tex-core/src/execution/engine/xdv_annotation.rs +++ b/crates/texrra-tex-core/src/execution/engine/xdv_annotation.rs @@ -39,11 +39,11 @@ impl Executor { let mut failure = None; shipout .box_node - .walk_xdv_annotations(self.cancellation.as_ref(), &mut |x, y, node| { + .walk_device(self.cancellation.as_ref(), true, &mut |x, y, node, shift| { if failure.is_some() { return; } - let point = [(x + origin[0]) as f64, (y + origin[1]) as f64]; + let point = [(x + origin[0] + shift) as f64, (y + origin[1]) as f64]; let result = match node { BoxPaint::ScopeStart(level) => { page.enter(level); @@ -238,8 +238,12 @@ impl Frame { items: &[PositionedItem], virtuals: Option<&VirtualGlyphs>, ) -> Result<(), String> { + let mut shift = 0; for item in items { - let [x, y] = [origin_x + item.x as f64, origin_y + item.y as f64]; + let [x, y] = [origin_x + (item.x + shift) as f64, origin_y + item.y as f64]; + if virtuals.is_some() { + shift += super::super::boxes::xdv_width_difference(&item.item); + } match &item.item { MathItem::NativeGlyph { font, slot, .. } => { if let Some(packet) = virtuals @@ -253,7 +257,7 @@ impl Frame { self.expand( page, [x, y], - font.advance(*slot), + font.xdv_advance(*slot), metrics.height(character), metrics.depth(character), ); diff --git a/crates/texrra-tex-core/src/native_font.rs b/crates/texrra-tex-core/src/native_font.rs index 87c4db9..ebbf619 100644 --- a/crates/texrra-tex-core/src/native_font.rs +++ b/crates/texrra-tex-core/src/native_font.rs @@ -229,6 +229,9 @@ impl NativeFont { self.horizontal(width) } } + pub(crate) fn xdv_advance(&self, slot: u8) -> i64 { + self.horizontal(self.metrics().xdv_width(slot)) + } pub(crate) fn horizontal(&self, value: i64) -> i64 { if self.expansion == 0 { value diff --git a/crates/texrra-tex-core/src/native_font/virtual_paint.rs b/crates/texrra-tex-core/src/native_font/virtual_paint.rs index 6bda461..5caa9a6 100644 --- a/crates/texrra-tex-core/src/native_font/virtual_paint.rs +++ b/crates/texrra-tex-core/src/native_font/virtual_paint.rs @@ -60,6 +60,7 @@ struct Expansion<'a, F> { files: &'a mut F, fonts: FontPrograms<'a>, commands: usize, + xdv: bool, limit: usize, cancellation: Option<&'a Cancellation>, } @@ -94,6 +95,14 @@ fn offset(point: i64, delta: i64) -> Result { .ok_or_else(|| "VF position overflow".into()) } +fn scale_packet_word(raw: i32, size: i64, xdv: bool) -> Result { + if xdv { + Ok(TfmMetrics::scale_xdv_fix_word(raw, size)) + } else { + TfmMetrics::scale_fix_word(raw, size) + } +} + impl<'a, F: SourceProvider> Expansion<'a, F> { fn is_virtual(&mut self, font: &Arc) -> Result { Ok(self.lookup(font)?.is_some()) @@ -125,7 +134,7 @@ impl<'a, F: SourceProvider> Expansion<'a, F> { programs, catalog, defaults, - } => programs.lookup(font, catalog, *defaults, self.files), + } => programs.lookup(font, catalog, *defaults, self.xdv, self.files), FontPrograms::Standalone(state) => { if let Some(program) = &font.letter_spacing { let base = standalone_expansion(state, program.base.clone(), font.expansion); @@ -157,8 +166,9 @@ impl<'a, F: SourceProvider> Expansion<'a, F> { from: &str, local: &LocalFont, size: i64, + xdv: bool, ) -> Result, String> { - let size = TfmMetrics::scale_fix_word(local.scale, size)?; + let size = scale_packet_word(local.scale, size, xdv)?; let key = (from.to_owned(), local.name.clone(), size); if let Some(font) = state.local_fonts.get(&key) { check_metrics( @@ -249,7 +259,8 @@ impl<'a, F: SourceProvider> Expansion<'a, F> { vf.program.packets.get(&glyph.slot).ok_or_else(|| { format!("{} has no VF packet for TFM slot {}", vf.from, glyph.slot) })?; - let dimension = |raw| TfmMetrics::scale_fix_word(raw, glyph.size); + let xdv = self.xdv; + let dimension = |raw| scale_packet_word(raw, glyph.size, xdv); let mut point = Position { x: glyph.x, y: glyph.y, @@ -274,6 +285,7 @@ impl<'a, F: SourceProvider> Expansion<'a, F> { &vf.from, &vf.program.local_fonts[&id], glyph.size, + xdv, )?; standalone_expansion(state, font, glyph.font.expansion) }; @@ -283,7 +295,7 @@ impl<'a, F: SourceProvider> Expansion<'a, F> { font.name )); } - let width = font.advance(slot); + let width = if xdv { font.xdv_advance(slot) } else { font.advance(slot) }; let size = font.size_sp(); self.expand( Glyph { @@ -429,7 +441,7 @@ impl JobVirtualFonts { &mut self, font: &Arc, catalog: &mut FontCatalog, defaults: FontIntegers, files: &mut impl SourceProvider, ) -> Result<(), String> { - if self.lookup(font, catalog, defaults, files)?.is_some() { + if self.lookup(font, catalog, defaults, false, files)?.is_some() { return Err("PDF font object command cannot be used with virtual font".into()); } Ok(()) @@ -444,6 +456,7 @@ impl JobVirtualFonts { font: &Arc, catalog: &mut FontCatalog, defaults: FontIntegers, + xdv: bool, files: &mut impl SourceProvider, ) -> Result, String> { if let Some(program) = self.programs.get(&font.id) { @@ -451,7 +464,7 @@ impl JobVirtualFonts { } let program = if let Some((base, ratio)) = catalog.automatic_origin(font.id) { let base = catalog.glyph_font(base)?.clone(); - match self.lookup(&base, catalog, defaults, files)? { + match self.lookup(&base, catalog, defaults, xdv, files)? { Some(Program::File { vf, locals: Some(locals), @@ -484,7 +497,7 @@ impl JobVirtualFonts { let mut locals = BTreeMap::new(); for id in &vf.program.local_order { let local = &vf.program.local_fonts[id]; - let size = TfmMetrics::scale_fix_word(local.scale, font.size_sp())?; + let size = scale_packet_word(local.scale, font.size_sp(), xdv)?; let local_id = catalog.load_virtual_local(&local.name, &vf.from, size, defaults, files)?; let local_font = catalog.glyph_font(local_id)?.clone(); @@ -564,6 +577,7 @@ impl JobVirtualFonts { files: &mut impl SourceProvider, font: Arc, slot: u8, + xdv: bool, limit: usize, cancellation: Option<&Cancellation>, ) -> Result<(Option>>, usize), String> { @@ -575,6 +589,7 @@ impl JobVirtualFonts { defaults, }, commands: 0, + xdv, limit: limit.min(5_000_000), cancellation, }; @@ -661,6 +676,7 @@ pub(super) fn expand_pages( files, fonts: FontPrograms::Standalone(state), commands: 0, + xdv: false, limit: 5_000_000, cancellation: None, }; @@ -681,6 +697,7 @@ pub(super) fn expand_pages( } let mut result = Vec::with_capacity(pages.len()); for page in pages { + expansion.xdv = page.pdf.as_ref().is_some_and(|pdf| pdf.driver == crate::pdf_device::PdfDriver::Xdv); let mut resolved = DisplayList { width: page.width, height: page.height, @@ -695,6 +712,7 @@ pub(super) fn expand_pages( images: page.images.clone(), ..DisplayList::default() }; + let mut offsets = page.xdv_horizontal_offsets.iter().copied().peekable(); for (index, item) in page.items.iter().enumerate() { let start = resolved.items.len(); let virtual_glyph = if let DisplayItem::NativeGlyph { @@ -735,6 +753,9 @@ pub(super) fn expand_pages( if !virtual_glyph { resolved.items.push(item.clone()); } + if let Some((_, shift)) = offsets.next_if(|&(i, _)| i == index) { + resolved.xdv_horizontal_offsets.extend((start..resolved.items.len()).map(|i| (i, shift))); + } if let Some(source) = page.sources.get(&index) { let source = if virtual_glyph { source.clone().derived(Derivation::FontProgram) diff --git a/crates/texrra-tex-core/src/pdf_device/xdv_navigation/forms.rs b/crates/texrra-tex-core/src/pdf_device/xdv_navigation/forms.rs index d1aca22..421def7 100644 --- a/crates/texrra-tex-core/src/pdf_device/xdv_navigation/forms.rs +++ b/crates/texrra-tex-core/src/pdf_device/xdv_navigation/forms.rs @@ -571,9 +571,11 @@ impl Navigation { let mut content_origins = Vec::new(); let mut captures: Vec<(u32, XdvCanvas, DisplayList)> = Vec::new(); let mut sources = std::mem::take(&mut page.sources); + let mut offsets = std::mem::take(&mut page.xdv_horizontal_offsets).into_iter().peekable(); let mut packets = page.prepared_virtual_glyphs.as_mut().map(std::mem::take); for (index, item) in std::mem::take(&mut page.items).into_iter().enumerate() { let origin = sources.remove(&index); + let shift = offsets.next_if(|&(i, _)| i == index).map_or(0, |(_, shift)| shift); let packet = packets.as_mut().and_then(|packets| packets.remove(&index)); if let DisplayItem::PdfGraphics { x, @@ -686,7 +688,7 @@ impl Navigation { .unwrap() .insert(output.items.len(), packet); } - output.items.push(item); + output.push_device_item(item, shift); } if !captures.is_empty() { return Err("incomplete XDV form display list".into()); diff --git a/crates/texrra-tex-core/src/pdf_text.rs b/crates/texrra-tex-core/src/pdf_text.rs index 1e596ee..39180cf 100644 --- a/crates/texrra-tex-core/src/pdf_text.rs +++ b/crates/texrra-tex-core/src/pdf_text.rs @@ -244,10 +244,7 @@ impl NativeText { if self.xdv { // xdvipdfmx follows the advances in the DVI/XDV stream. The PDF // viewer separately uses the embedded font's declared widths. - return crate::pdf_device::magnify( - font.metrics().xdv_width(slot), - 1000 + font.expansion, - ); + return font.xdv_advance(slot); } let expansion = self.expansion; let advance = match &paint.program { diff --git a/crates/texrra-tex-core/src/render.rs b/crates/texrra-tex-core/src/render.rs index ad339b4..6f5c7e0 100755 --- a/crates/texrra-tex-core/src/render.rs +++ b/crates/texrra-tex-core/src/render.rs @@ -285,6 +285,9 @@ pub struct DisplayList { pub prepared_virtual_glyphs: Option>>>, /// Paint-order indices into `items`; absent entries have unknown origin. pub sources: std::collections::BTreeMap, + /// Nonzero XDV device shifts from the packed TeX coordinates, in paint order. + #[doc(hidden)] + pub xdv_horizontal_offsets: Vec<(usize, i64)>, pub images: Vec, /// A common physical transform for preview/PDF, without altering fonts or /// logical TeX geometry. 1000 is unit magnification. @@ -308,6 +311,7 @@ impl Default for DisplayList { forms: Vec::new(), prepared_virtual_glyphs: None, sources: Default::default(), + xdv_horizontal_offsets: Vec::new(), images: Vec::new(), magnification: 1000, units: DisplayUnits::PostScript, @@ -414,6 +418,20 @@ impl DisplayList { && right.next().is_none() } + #[doc(hidden)] + pub fn xdv_horizontal_offset(&self, index: usize) -> i64 { + self.xdv_horizontal_offsets + .binary_search_by_key(&index, |&(index, _)| index) + .map_or(0, |position| self.xdv_horizontal_offsets[position].1) + } + + pub(crate) fn push_device_item(&mut self, item: DisplayItem, offset: i64) { + if offset != 0 { + self.xdv_horizontal_offsets.push((self.items.len(), offset)); + } + self.items.push(item); + } + pub fn push(&mut self, item: DisplayItem) { self.items.push(item); } diff --git a/crates/texrra-tex-core/src/tfm.rs b/crates/texrra-tex-core/src/tfm.rs index 24c5c37..2b50778 100755 --- a/crates/texrra-tex-core/src/tfm.rs +++ b/crates/texrra-tex-core/src/tfm.rs @@ -411,7 +411,11 @@ impl TfmMetrics { /// driver rounds the exact fixword product to a scaled point. pub(crate) fn xdv_width(&self, slot: u8) -> i64 { let Some(info) = self.char_info(char::from(slot)) else { return 0 }; - let product = i64::from(self.widths[usize::from(info.width_index)]) * self.size; + Self::scale_xdv_fix_word(self.widths[usize::from(info.width_index)], self.size) + } + + pub(crate) fn scale_xdv_fix_word(raw: i32, size: i64) -> i64 { + let product = i64::from(raw) * size; product.signum() * ((product.abs() + (1 << 19)) >> 20) } diff --git a/crates/texrra-tex-core/tests/execution_diagnostics.rs b/crates/texrra-tex-core/tests/execution_diagnostics.rs index 4edf78d..05defeb 100644 --- a/crates/texrra-tex-core/tests/execution_diagnostics.rs +++ b/crates/texrra-tex-core/tests/execution_diagnostics.rs @@ -461,6 +461,37 @@ fn paragraph_protrusion_observes_profile_specific_whatsit_boundaries() { } } +#[test] +fn xdv_device_advances_are_restored_with_the_packed_box_stack() { + use texrra_tex_core::render::DisplayItem; + + let source = r"\catcode123=1 \catcode125=2 +\font\probe=cmr10 \probe +\shipout\hbox{C\hbox{CC}\kern1sp CC\special{pdf:literal direct 0 0 m}\vrule width1pt height1pt} +\end"; + let execution = Executor::new( + State::initex().with_etex().with_input_profile(InputProfile::XeTeX), + Limits::default(), + ) + .with_native_pages() + .run( + SourceFile { name: "xdv-cursor.tex".into(), data: source.as_bytes().into() }, + &mut font_world::FontFiles, + ) + .unwrap(); + let pages = execution.shipout_display_lists().unwrap(); + let page = &pages[0]; + let glyph_offsets: Vec<_> = page.items.iter().enumerate().filter_map(|(index, item)| { + matches!(item, DisplayItem::NativeGlyph { .. }).then(|| page.xdv_horizontal_offset(index)) + }).collect(); + assert_eq!(glyph_offsets, [0, 1, 2, 1, 2]); + let drawing_offsets: Vec<_> = page.items.iter().enumerate().filter_map(|(index, item)| { + matches!(item, DisplayItem::Rule { .. } | DisplayItem::PdfGraphics { .. }) + .then(|| page.xdv_horizontal_offset(index)) + }).collect(); + assert_eq!(drawing_offsets, [3, 3]); +} + #[test] fn shipout_applies_the_stored_glue_ratio_before_rounding() { use texrra_tex_core::render::DisplayItem; diff --git a/docs/P2_M1_PROGRESS.md b/docs/P2_M1_PROGRESS.md index d266104..03ff149 100644 --- a/docs/P2_M1_PROGRESS.md +++ b/docs/P2_M1_PROGRESS.md @@ -18,6 +18,37 @@ | W6 会话 | 实施中 | 共享库/CLI 与当前原生文字/数学/规则来源进入公共结果;真实 A4 副本九类/27 revision 与独立干净作业页面/PDF/aux/映射一致,新增数学场景独立参考通过;详细失败/捕获重放及宿主/离线/CLI观察已通过;原子项目版本/已知生成初态及TeX流记录已接通;完整副作用/恢复契约、旧来源和性能仍缺 | | W7 总验收 | 未满足 | 原有和新增测试、原样项目、格式与会话门禁全部通过才能结项 | +## 2026-11-29 XDV 设备字宽与原样 NeurIPS 导出 + +XDV 设备根据实际 TFM 的 fixword 舍入得到字形前进量,累加到 +相对移动后的坐标。盒栈恢复时继承外层坐标。该位置用于字形、 +规则、图像、特殊指令和链接范围。VF 的局部字体字号、内嵌字形、 +移动及规则也按设备的取整处理。布局清单仍使用原始 TeX 坐标。 +七项定向检查通过,覆盖嵌套盒、双向字形、链接、表单和命名资源。 +[XDV 驱动字宽](https://raw.githubusercontent.com/TeX-Live/texlive-source/e49735c7ed1aa2ed9c2e68e6632d27f20d42eca7/texk/dvipdfm-x/dvi.c#L1432-L1542) · [虚拟字体驱动](https://raw.githubusercontent.com/TeX-Live/texlive-source/e49735c7ed1aa2ed9c2e68e6632d27f20d42eca7/texk/dvipdfm-x/vf.c) + +已冻结的 36 个字形标题见证中,原始坐标保持一致。PDF 的六处 +TJ 调整与原版相同,144 DPI 光栅逐像素匹配。真实 Times VF +样例使用原始 ptmr7t.vf 与局部字体,光栅同样逐像素一致。 + +从空辅助文件编译原样 NeurIPS 2025 两轮,逐轮 aux/out 与参考 +一致。第二轮 12 页的 29,586 个原始字形坐标、5,836 个词及词框 +全部一致,144 DPI 灰度像素差异由 7,070 降为 0。 +同版原样 xeCJK 六页的 999 个词、词框、光栅和 aux 也一致。 +原生嵌入的 SimSun 与 LASY6 程序和上一版相同,仍有与参考的 +字体结构差异。 +[原样出版矩阵](PUBLISHER_TEMPLATE_MATRIX.md#2026-11-29-原样-neurips-2025-的-xelatex-复验) + +原样 NeurIPS 的第 3 页编辑和错误恢复各只刷新一页。发布 PDF、 +绘制列表、SVG、资源读取、来源映射和辅助文件都与独立全量一致。 +失败保留已发布结果。两次成功修订均重新转换 10 页,仍有缩减 +内部重做范围的空间。浏览器可见延迟按冻结后的原门槛统一验收。 + +下一功能批次从 XeTeX 的 TrueType 子集 CID、CIDSet 和 +Type 1C 字形程序开始。原始产物、对照和 SHA256SUMS 存于 +target/p3-xdv-device-positions/,清单指纹为 +a4e63c1621159a0a8e082f82971edaa7d0027d056df73be95571eee7b39d0c7c。 + ## 2026-11-29 XeTeX 边缘节点与胶水取整 XeTeX 的边缘字形搜索遇到实际语言切换与特殊指令节点时停止。 diff --git a/docs/PUBLISHER_TEMPLATE_MATRIX.md b/docs/PUBLISHER_TEMPLATE_MATRIX.md index 19e6bc5..aa7b1c0 100644 --- a/docs/PUBLISHER_TEMPLATE_MATRIX.md +++ b/docs/PUBLISHER_TEMPLATE_MATRIX.md @@ -1293,6 +1293,13 @@ Web2c 胶水取整后,逐轮 aux/out 仍完全一致。第二轮 12 页的 29, 仍待闭合。对照见 target/p3-xdv-layout-next/original-candidate/audit-second/。 [阶段记录](P2_M1_PROGRESS.md#2026-11-29-xetex-边缘节点与胶水取整) +接通 XDV 驱动的实际字体前进量和盒栈位置后,原样 NeurIPS 2025 的 +收敛版本共 12 页。29,586 个原始字形及坐标、5,836 个提取词及词框、 +144 DPI 灰度光栅全部与参考一致,逐轮 aux/out 完全相同。 +本次对照使用同样的官方交付、参考格式和字体。详细结果在 +target/p3-xdv-device-positions/original/audit-second/comparison.json。 +[阶段记录](P2_M1_PROGRESS.md#2026-11-29-xdv-设备字宽与原样-neurips-导出) + 单纯生成 PDF 或 DVI 只说明编译路径可达。完整验收要在参考环境闭合后比较页数、 双栏位置及跨栏材料、实际字体/字形、图表浮动、引用收敛、词框及墨迹;测试源 与容差都不得为通过而替换。类 Typst 的编辑延迟另用同批原样项目分规模测量, diff --git a/src/native_job.rs b/src/native_job.rs index 1333c8f..ce756da 100644 --- a/src/native_job.rs +++ b/src/native_job.rs @@ -775,7 +775,8 @@ impl Files { let mut images = Vec::new(); let mut graphics = Vec::new(); let mut paint_order = Vec::new(); - for item in &page.items { + for (index, item) in page.items.iter().enumerate() { + let shift = page.xdv_horizontal_offset(index); match item { DisplayItem::NativeGlyph { x, @@ -787,13 +788,13 @@ impl Files { } => { paint_order.push(json!(["glyph", glyphs.len()])); glyphs.push( - json!({"x": x, "y": y, "size": size, "slot": slot, "font": font.name}), + json!({"x": x - shift, "y": y, "size": size, "slot": slot, "font": font.name}), ); } DisplayItem::OpenTypeGlyph { x, y, size, glyph, text, font, .. } => { paint_order.push(json!(["glyph", glyphs.len()])); glyphs.push(json!({ - "x": x, "y": y, "size": size, "glyph": glyph, + "x": x - shift, "y": y, "size": size, "glyph": glyph, "font": font.name, "text": text, "resource": font.resource.version, })); } @@ -804,11 +805,11 @@ impl Files { height, } => { paint_order.push(json!(["rule", rules.len()])); - rules.push(json!({"x": x, "y": y, "width": width, "height": height})); + rules.push(json!({"x": x - shift, "y": y, "width": width, "height": height})); } DisplayItem::PdfForm { x, y, form } => { paint_order.push(json!(["pdf_form", images.len()])); - images.push(json!({"x": x, "y": y, "width": form.width, + images.push(json!({"x": x - shift, "y": y, "width": form.width, "height": form.height, "depth": form.depth, "id": form.number})); } DisplayItem::PdfImage { @@ -820,7 +821,7 @@ impl Files { } => { paint_order.push(json!(["pdf_image", images.len()])); images.push(json!({ - "x":x, "y":y, "width":width, "height":height, + "x": x - shift, "y":y, "width":width, "height":height, "id":image.id, "page":image.image.page, "resource":image.image.version, })); } @@ -828,7 +829,7 @@ impl Files { | DisplayItem::OpenTypeActualText(_) | DisplayItem::OpenTypeColor(_) => {} DisplayItem::PdfGraphics { x, y, operation } => { paint_order.push(json!(["pdf_graphics", graphics.len()])); - graphics.push(json!({"x": x, "y": y, "operation": operation})); + graphics.push(json!({"x": x - shift, "y": y, "operation": operation})); } _ => { return Err("unsupported material in native shipout layout manifest".into());