From e20acc3eb9120c27764e1dde07359196eae99c88 Mon Sep 17 00:00:00 2001 From: GloamXun Date: Sat, 28 Nov 2026 18:36:52 +0800 Subject: [PATCH] Honor XeLaTeX page dictionaries and named rectangle coordinates --- .../src/execution/engine/specials.rs | 2 +- crates/texrra-tex-core/src/execution/mod.rs | 5 + crates/texrra-tex-core/src/pdf.rs | 80 ++++---- .../src/pdf_device/page_attributes.rs | 62 +++--- .../src/pdf_device/xdv_destination.rs | 26 ++- .../src/pdf_device/xdv_navigation.rs | 10 +- .../xdv_navigation/named_objects.rs | 27 ++- .../xdv_navigation/page_dictionaries.rs | 181 ++++++++++++++++++ .../tests/execution_xetex_profile.rs | 55 ++++++ docs/P2_M1_PROGRESS.md | 26 +++ 10 files changed, 403 insertions(+), 71 deletions(-) create mode 100644 crates/texrra-tex-core/src/pdf_device/xdv_navigation/page_dictionaries.rs diff --git a/crates/texrra-tex-core/src/execution/engine/specials.rs b/crates/texrra-tex-core/src/execution/engine/specials.rs index 3b805bf..8fec124 100644 --- a/crates/texrra-tex-core/src/execution/engine/specials.rs +++ b/crates/texrra-tex-core/src/execution/engine/specials.rs @@ -92,7 +92,7 @@ impl Executor { }).map_err(|error| self.error(error, special.span))?; self.check_cancellation()?; let navigation = Arc::make_mut(self.state.xdv_navigation.get_or_insert_with(Default::default)); - navigation.apply_object(command, operands.len().saturating_add(size), self.limits.tokens) + navigation.apply_object(command, position.page, operands.len().saturating_add(size), self.limits.tokens) }.map_err(|error| self.error(error, special.span))?; for warning in warnings { files.observe_diagnostic(WriteDestination::TerminalAndLog, &warning) diff --git a/crates/texrra-tex-core/src/execution/mod.rs b/crates/texrra-tex-core/src/execution/mod.rs index 342fce1..71da882 100644 --- a/crates/texrra-tex-core/src/execution/mod.rs +++ b/crates/texrra-tex-core/src/execution/mod.rs @@ -815,6 +815,11 @@ impl Execution { } if !self.state.pdf_draft_mode() { self.resolve_page_graphics_resources(&mut pages)?; + if let Some(navigation) = &self.state.xdv_navigation { + navigation.resolve_page_dictionaries(&mut pages).map_err(|message| { + Error::at(&self.sources, self.state.input_profile(), message, Span::default()) + })?; + } for form in &mut forms { let attributes = std::mem::take(&mut form.list.pdf_resources.attributes); self.resolve_page_graphics_resources(std::slice::from_mut(&mut form.list))?; diff --git a/crates/texrra-tex-core/src/pdf.rs b/crates/texrra-tex-core/src/pdf.rs index d477aef..3fdca60 100755 --- a/crates/texrra-tex-core/src/pdf.rs +++ b/crates/texrra-tex-core/src/pdf.rs @@ -3510,41 +3510,6 @@ fn write_pdf( xdv_names.entry(name.to_vec()).or_insert_with(|| format!("{index:x}").into_bytes()); } } - let empty_xdv = crate::pdf_device::xdv_navigation::Navigation::default(); - let xdv_objects = xdv.unwrap_or(&empty_xdv); - let mut pending = Vec::new(); - xdv_objects.collect_references(&mut pending); - for (_, annotation) in &xdv_annotations { - annotation.collect_references(&mut pending); - } - let named_objects = xdv_objects.reserve_objects(pending, &mut objects)?; - let references = crate::pdf_device::xdv_object::References { - pages: &navigation.pages, - named: &named_objects, - }; - let compression = pages[0].pdf.as_ref().map_or(0, |pdf| pdf.stream_compression); - xdv_objects.write_objects(&references, &mut objects, compression, diagnostics)?; - for (id, annotation) in xdv_annotations { - objects[id - 1] = annotation.pdf(&references, &xdv_names)?; - } - if let Some(xdv) = xdv { - let open_depth = unicode.unwrap().xdv_outline_open_depth; - if let Some(outlines) = xdv.write_outlines( - &references, &mut objects, &xdv_names, open_depth, - )? { - catalog.push_str(&format!(" /Outlines {outlines} 0 R")); - } - } - if !navigation.threads.is_empty() { - let mut ids: Vec<_> = navigation.threads.into_values().collect(); - ids.sort_unstable_by(|left, right| right.cmp(left)); - let references: Vec<_> = ids.iter().map(|id| format!("{id} 0 R")).collect(); - let slot = registry.and_then(|registry| registry.thread_array()) - .map(|number| device_objects[&number] as usize); - let id = write_destination(&mut objects, slot, format!("[{}]", references.join(" "))); - catalog.push_str(&format!(" /Threads {id} 0 R")); - } - let destinations = navigation.named; let mut xdv_destinations = BTreeMap::new(); for list in pages { for destination in &list.pdf_links.xdv_destinations { @@ -3566,6 +3531,49 @@ fn write_pdf( String::from_utf8_lossy(name))); } } + let empty_xdv = crate::pdf_device::xdv_navigation::Navigation::default(); + let xdv_objects = xdv.unwrap_or(&empty_xdv); + let mut pending = Vec::new(); + xdv_objects.collect_references(&mut pending); + for (_, annotation) in &xdv_annotations { + annotation.collect_references(&mut pending); + } + for (&name, (destination, _, _)) in &xdv_destinations { + if keep_xdv_destinations || xdv_names.contains_key(name) { + destination.collect_references(&mut pending); + } + } + let named_objects = xdv_objects.reserve_objects(pending, &mut objects)?; + let references = crate::pdf_device::xdv_object::References { + pages: &navigation.pages, + named: &named_objects, + }; + let compression = pages[0].pdf.as_ref().map_or(0, |pdf| pdf.stream_compression); + xdv_objects.write_objects(&references, &mut objects, compression, diagnostics)?; + if let Some(xdv) = xdv { + xdv.write_page_dictionaries(pages, &references, &mut objects)?; + } + for (id, annotation) in xdv_annotations { + objects[id - 1] = annotation.pdf(&references, &xdv_names)?; + } + if let Some(xdv) = xdv { + let open_depth = unicode.unwrap().xdv_outline_open_depth; + if let Some(outlines) = xdv.write_outlines( + &references, &mut objects, &xdv_names, open_depth, + )? { + catalog.push_str(&format!(" /Outlines {outlines} 0 R")); + } + } + if !navigation.threads.is_empty() { + let mut ids: Vec<_> = navigation.threads.into_values().collect(); + ids.sort_unstable_by(|left, right| right.cmp(left)); + let references: Vec<_> = ids.iter().map(|id| format!("{id} 0 R")).collect(); + let slot = registry.and_then(|registry| registry.thread_array()) + .map(|number| device_objects[&number] as usize); + let id = write_destination(&mut objects, slot, format!("[{}]", references.join(" "))); + catalog.push_str(&format!(" /Threads {id} 0 R")); + } + let destinations = navigation.named; let mut retained = BTreeMap::new(); for (name, (destination, height, magnification)) in xdv_destinations { let name = if keep_xdv_destinations { @@ -3577,7 +3585,7 @@ fn write_pdf( }; let page_object = navigation.pages.get(destination.page - 1) .ok_or_else(|| format!("XDV destination refers to nonexistent page {}", destination.page))?; - retained.insert(name, destination.array(*page_object, height, magnification)); + retained.insert(name, destination.array(*page_object, height, magnification, &references)?); } if !retained.is_empty() { let entries: Vec<_> = retained.into_iter().map(|(name, value)| { diff --git a/crates/texrra-tex-core/src/pdf_device/page_attributes.rs b/crates/texrra-tex-core/src/pdf_device/page_attributes.rs index 1abc8a1..9a190ef 100644 --- a/crates/texrra-tex-core/src/pdf_device/page_attributes.rs +++ b/crates/texrra-tex-core/src/pdf_device/page_attributes.rs @@ -23,6 +23,35 @@ pub(crate) struct Viewport { } impl Viewport { + pub(crate) fn from_boxes( + media: [f64; 4], + crop: [f64; 4], + rotation: i64, + unit: f64, + ) -> Result { + let x = crop[0].max(media[0]); + let y = crop[1].max(media[1]); + let intersection = [ + x, + y, + crop[2].min(media[2]).max(x), + crop[3].min(media[3]).max(y), + ]; + let viewport = Self { + crop: intersection.map(f64::to_bits), + rotation, + user_unit: unit.to_bits(), + }; + if viewport + .dimensions() + .into_iter() + .any(|value| !value.is_finite()) + { + return Err("native PDF page viewport dimensions overflow".into()); + } + Ok(viewport) + } + pub(crate) fn unit(&self) -> f64 { f64::from_bits(self.user_unit) } @@ -119,26 +148,7 @@ pub(crate) fn resolve( .map(|value| rectangle(value, objects)) .transpose()? .unwrap_or(media); - let x = crop[0].max(media[0]); - let y = crop[1].max(media[1]); - let intersection = [ - x, - y, - crop[2].min(media[2]).max(x), - crop[3].min(media[3]).max(y), - ]; - let viewport = Viewport { - crop: intersection.map(f64::to_bits), - rotation, - user_unit: unit.to_bits(), - }; - if viewport - .dimensions() - .into_iter() - .any(|value| !value.is_finite()) - { - return Err("native PDF page viewport dimensions overflow".into()); - } + let viewport = Viewport::from_boxes(media, crop, rotation, unit)?; resource.viewport = Some(viewport); } Ok(()) @@ -161,7 +171,7 @@ fn attribute( Ok(None) } -fn finite_number(value: &Object) -> Result { +pub(super) fn finite_number(value: &Object) -> Result { let number = match value { Object::Integer(n) => *n as f64, Object::Real(n) => *n, @@ -175,14 +185,20 @@ fn finite_number(value: &Object) -> Result { } fn rectangle(value: Object, objects: &PdfObjects) -> Result<[f64; 4], String> { + rectangle_with(value, |entry| resolve_value(entry, objects)) +} + +pub(super) fn rectangle_with( + value: Object, + resolve: impl Fn(Object) -> Result, +) -> Result<[f64; 4], String> { let Object::Array(values) = value else { return Err("native PDF page box must be an array".into()); }; let Ok(values): Result<[Object; 4], _> = values.try_into() else { return Err("native PDF page box requires four coordinates".into()); }; - let [x0, y0, x1, y1] = - values.map(|entry| resolve_value(entry, objects).and_then(|v| finite_number(&v))); + let [x0, y0, x1, y1] = values.map(|entry| resolve(entry).and_then(|v| finite_number(&v))); let (x0, y0, x1, y1) = (x0?, y0?, x1?, y1?); Ok([x0.min(x1), y0.min(y1), x0.max(x1), y0.max(y1)]) } diff --git a/crates/texrra-tex-core/src/pdf_device/xdv_destination.rs b/crates/texrra-tex-core/src/pdf_device/xdv_destination.rs index 50630f9..f6c1d9a 100644 --- a/crates/texrra-tex-core/src/pdf_device/xdv_destination.rs +++ b/crates/texrra-tex-core/src/pdf_device/xdv_destination.rs @@ -4,7 +4,7 @@ use serde::{Deserialize, Serialize}; use super::page_resources::{parse_name, parse_value}; use super::{PdfFileOptions, magnify, print_sp}; -use super::xdv_object::{atom, page_reference, split_string, trim_pdf}; +use super::xdv_object::{References, atom, identifier, page_reference, split_string, trim_pdf}; #[derive(Clone, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)] pub(crate) struct Setup { @@ -113,6 +113,7 @@ enum Operand { Null, CurrentX, CurrentY, + Named(Vec), } impl Destination { @@ -147,6 +148,12 @@ impl Destination { b"@xpos" => Operand::CurrentX, b"@ypos" => Operand::CurrentY, b"null" => Operand::Null, + named if named.starts_with(b"@") => { + let (name, tail) = identifier(rest)?; + operands.push(Operand::Named(name.to_vec())); + rest = tail; + continue; + } number => match parse_value(number)? { Object::Integer(_) | Object::Real(_) => Operand::Number( std::str::from_utf8(number) @@ -175,13 +182,26 @@ impl Destination { }) } - pub(crate) fn array(&self, page_object: usize, height: i64, magnification: i32) -> String { + pub(crate) fn collect_references<'a>(&'a self, pending: &mut Vec<&'a [u8]>) { + pending.extend(self.operands.iter().filter_map(|operand| match operand { + Operand::Named(name) => Some(name.as_slice()), + _ => None, + })); + } + + pub(crate) fn array( + &self, page_object: usize, height: i64, magnification: i32, references: &References<'_>, + ) -> Result { let mut output = format!("[{page_object} 0 R /{}", self.view); for operand in &self.operands { use std::fmt::Write as _; match operand { Operand::Number(text) => write!(output, " {text}").unwrap(), Operand::Null => output.push_str(" null"), + Operand::Named(name) => { + let id = references.named.get(name).ok_or("unallocated XDV destination operand")?; + write!(output, " {id} 0 R").unwrap(); + } Operand::CurrentX | Operand::CurrentY => { let value = match operand { Operand::CurrentX => self.point[0], @@ -192,6 +212,6 @@ impl Destination { } } output.push(']'); - output + Ok(output) } } diff --git a/crates/texrra-tex-core/src/pdf_device/xdv_navigation.rs b/crates/texrra-tex-core/src/pdf_device/xdv_navigation.rs index 25e2599..2622ec9 100644 --- a/crates/texrra-tex-core/src/pdf_device/xdv_navigation.rs +++ b/crates/texrra-tex-core/src/pdf_device/xdv_navigation.rs @@ -1,4 +1,4 @@ -//! Document-view state and outlines produced by XDV specials. +//! Document-view state, page dictionaries, and objects produced by XDV specials. use std::collections::{BTreeMap, BTreeSet}; use lopdf::Object; @@ -12,6 +12,8 @@ use super::xdv_object::{ }; mod named_objects; +mod page_dictionaries; +use page_dictionaries::PageDictionaries; pub(crate) use named_objects::ObjectCommand; use named_objects::NamedObject; @@ -23,6 +25,8 @@ pub(crate) struct Navigation { payload: usize, #[serde(default, skip_serializing_if = "BTreeMap::is_empty")] objects: BTreeMap, NamedObject>, + #[serde(default, skip_serializing_if = "PageDictionaries::is_empty")] + page_dictionaries: PageDictionaries, } #[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)] @@ -101,17 +105,19 @@ impl Navigation { pub(crate) fn apply_object( &mut self, command: ObjectCommand, + page: usize, bytes: usize, limit: usize, ) -> Result, String> { self.add_payload(bytes, limit)?; - command.apply(&mut self.catalog, &mut self.objects) + command.apply(self, page) } pub(crate) fn collect_references<'a>(&'a self, pending: &mut Vec<&'a [u8]>) { for value in self.catalog.values().chain(self.outlines.iter().flat_map(|o| o.fields.values())) { value.collect_references(pending); } + self.page_dictionaries.collect_references(pending); } pub(crate) fn reserve_objects<'a>( diff --git a/crates/texrra-tex-core/src/pdf_device/xdv_navigation/named_objects.rs b/crates/texrra-tex-core/src/pdf_device/xdv_navigation/named_objects.rs index 487c1a2..6350a77 100644 --- a/crates/texrra-tex-core/src/pdf_device/xdv_navigation/named_objects.rs +++ b/crates/texrra-tex-core/src/pdf_device/xdv_navigation/named_objects.rs @@ -1,11 +1,13 @@ -use std::{collections::BTreeMap, sync::Arc}; +use std::sync::Arc; use serde::{Deserialize, Serialize}; use crate::pdf::objects::stream_bytes; use super::super::xdv_object::{identifier, parse_object, parse_object_prefix, trim_pdf}; -use super::{Dictionary, Position, References, Value, encode_device_value, output_dictionary}; +use super::{ + Dictionary, Navigation, Position, References, Value, encode_device_value, output_dictionary, +}; #[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)] pub(super) struct NamedObject { @@ -112,18 +114,24 @@ impl ObjectCommand { pub(super) fn apply( self, - catalog: &mut Dictionary, - objects: &mut BTreeMap, NamedObject>, + navigation: &mut Navigation, + page: usize, ) -> Result, String> { let Self { name, change } = self; let display = String::from_utf8_lossy(&name); let warning = |message: String| vec![format!("xdvipdfmx: warning: {message}\n")]; - if name == b"catalog" + if matches!(name.as_slice(), b"catalog" | b"pages" | b"thispage") && let Change::Put(values) = change { - catalog.append(&mut only_dictionary(values)?); + let fields = match name.as_slice() { + b"catalog" => &mut navigation.catalog, + b"pages" => &mut navigation.page_dictionaries.root, + _ => navigation.page_dictionaries.pages.entry(page).or_default(), + }; + fields.append(&mut only_dictionary(values)?); return Ok(Vec::new()); } + let objects = &mut navigation.objects; if matches!( name.as_slice(), b"catalog" @@ -199,6 +207,13 @@ fn only_dictionary(values: Vec) -> Result { } impl NamedObject { + pub(super) fn value(&self) -> Option<&Value> { + match &self.data { + ObjectData::Value(value) => Some(value), + ObjectData::Stream { .. } => None, + } + } + pub(super) fn collect_references<'a>(&'a self, pending: &mut Vec<&'a [u8]>) { match &self.data { ObjectData::Value(value) => value.collect_references(pending), diff --git a/crates/texrra-tex-core/src/pdf_device/xdv_navigation/page_dictionaries.rs b/crates/texrra-tex-core/src/pdf_device/xdv_navigation/page_dictionaries.rs new file mode 100644 index 0000000..285e778 --- /dev/null +++ b/crates/texrra-tex-core/src/pdf_device/xdv_navigation/page_dictionaries.rs @@ -0,0 +1,181 @@ +use std::collections::BTreeMap; + +use lopdf::Object; +use serde::{Deserialize, Serialize}; + +use crate::pdf_device::{ + magnify, + page_attributes::{Viewport, finite_number, rectangle_with}, + print_sp, +}; +use crate::render::DisplayList; + +use super::{ + Dictionary, Navigation, References, Value, encode_device_value, output_dictionary, parse_value, +}; + +#[derive(Clone, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)] +pub(super) struct PageDictionaries { + pub(super) root: Dictionary, + pub(super) pages: BTreeMap, +} + +impl PageDictionaries { + pub(super) fn is_empty(&self) -> bool { + self.root.is_empty() && self.pages.is_empty() + } + + pub(super) fn collect_references<'a>(&'a self, pending: &mut Vec<&'a [u8]>) { + for value in self + .root + .values() + .chain(self.pages.values().flat_map(Dictionary::values)) + { + value.collect_references(pending); + } + } +} + +impl Navigation { + pub(crate) fn write_page_dictionaries( + &self, + pages: &[DisplayList], + references: &References<'_>, + objects: &mut [Vec], + ) -> Result<(), String> { + if self.page_dictionaries.is_empty() { + return Ok(()); + } + let root_box = device_box(&pages[0]); + let mut root = generated_dictionary(&objects[1])?; + for (name, value) in &output_dictionary(&self.page_dictionaries.root, references)? { + if !matches!(name.as_slice(), b"Type" | b"Kids" | b"Count" | b"MediaBox") { + root.set(name.clone(), value.clone()); + } + } + root.set("MediaBox", Object::Array(root_box.map(Object::Real).into())); + objects[1] = encode_device_value(Object::Dictionary(root))?; + + for (index, (page, &id)) in pages.iter().zip(references.pages).enumerate() { + let mut dictionary = generated_dictionary(&objects[id - 1])?; + let inherits_media = device_box(page) == root_box; + if inherits_media { + dictionary.remove(b"MediaBox"); + } + if let Some(fields) = self.page_dictionaries.pages.get(&(index + 1)) { + for (name, value) in &output_dictionary(fields, references)? { + let reserved = match name.as_slice() { + b"Type" | b"Parent" | b"Contents" | b"Resources" => true, + b"MediaBox" => !inherits_media, + b"Annots" | b"B" | b"Group" => dictionary.has(name), + _ => false, + }; + if !reserved { + dictionary.set(name.clone(), value.clone()); + } + } + } + objects[id - 1] = encode_device_value(Object::Dictionary(dictionary))?; + } + Ok(()) + } + + pub(crate) fn resolve_page_dictionaries( + &self, + pages: &mut [DisplayList], + ) -> Result<(), String> { + if self.page_dictionaries.is_empty() || pages.is_empty() { + return Ok(()); + } + let root_box = device_box(&pages[0]); + for (index, page) in pages.iter_mut().enumerate() { + let local = self.page_dictionaries.pages.get(&(index + 1)); + let root = &self.page_dictionaries.root; + let attribute = |name: &[u8], inherited: bool| -> Result, String> { + let candidates = [local, inherited.then_some(root)]; + for fields in candidates.into_iter().flatten() { + if let Some(value) = fields.get(name) { + let value = self.geometry_value(value, 0)?; + if !matches!(value, Object::Null) { + return Ok(Some(value)); + } + } + } + Ok(None) + }; + let default_box = device_box(page); + let media = if default_box == root_box { + attribute(b"MediaBox", false)? + .map(|value| rectangle_with(value, Ok)) + .transpose()? + .unwrap_or(default_box) + } else { + default_box + }; + let crop = attribute(b"CropBox", true)? + .map(|value| rectangle_with(value, Ok)) + .transpose()? + .unwrap_or(media); + let rotation = attribute(b"Rotate", true)? + .and_then(|value| value.as_i64().ok()) + .map_or(0, |value| value.rem_euclid(360)); + let rotation = if rotation % 90 == 0 { rotation } else { 0 }; + let unit = + attribute(b"UserUnit", false)?.map_or(Ok(1.0), |value| finite_number(&value))?; + if unit <= 0.0 { + return Err("native PDF UserUnit must be positive".into()); + } + if media != default_box || crop != default_box || rotation != 0 || unit != 1.0 { + page.pdf_resources.viewport = + Some(Viewport::from_boxes(media, crop, rotation, unit)?); + } + if local.is_some_and(|fields| matches!(fields.get(b"Group".as_slice()), Some(value) if !matches!(value, Value::Null))) { + page.pdf_resources.has_page_group = true; + page.pdf_resources.needs_pdf_for_preview = true; + } + } + Ok(()) + } + + fn geometry_value(&self, value: &Value, depth: usize) -> Result { + if depth == 64 { + return Err("native XDV page geometry reference limit exceeded".into()); + } + match value { + Value::Null => Ok(Object::Null), + Value::Integer(value) => Ok(Object::Integer(*value)), + Value::Real(value) => Ok(Object::Real(f64::from_bits(*value))), + Value::Array(values) => Ok(Object::Array( + values + .iter() + .map(|item| self.geometry_value(item, depth + 1)) + .collect::>()?, + )), + Value::Named(name) => match self.objects.get(name) { + Some(object) => self.geometry_value( + object.value().ok_or("invalid XDV geometry stream")?, + depth + 1, + ), + None => Ok(Object::Null), + }, + _ => Err("invalid XDV page geometry object".into()), + } + } +} + +fn device_box(page: &DisplayList) -> [f64; 4] { + let digits = page.pdf.as_ref().map_or(2, |pdf| pdf.file.decimal_digits); + let coordinate = |length| { + print_sp(magnify(length, page.magnification), digits) + .parse() + .expect("formatted XDV paper size is numeric") + }; + [0.0, 0.0, coordinate(page.width), coordinate(page.height)] +} + +fn generated_dictionary(bytes: &[u8]) -> Result { + match parse_value(bytes)? { + Object::Dictionary(fields) => Ok(fields), + _ => Err("expected a generated XDV page dictionary".into()), + } +} diff --git a/crates/texrra-tex-core/tests/execution_xetex_profile.rs b/crates/texrra-tex-core/tests/execution_xetex_profile.rs index d2ff15e..08d34ee 100644 --- a/crates/texrra-tex-core/tests/execution_xetex_profile.rs +++ b/crates/texrra-tex-core/tests/execution_xetex_profile.rs @@ -898,3 +898,58 @@ fn xdv_named_objects_keep_forward_edges_and_file_streams_at_shipout() { assert!(matches!(pdf.get_object(missing), Ok(Object::Null))); assert!(!output.bytes.windows(4).any(|window| window == b"/bad")); } + +#[test] +fn xdv_page_dictionaries_and_rectangular_destinations_keep_real_references() { + use lopdf::Document; + use texrra_tex_core::pdf::shipout_lists_to_native_pdf_document; + + let state = State::initex().with_etex().with_input_profile(InputProfile::XeTeX); + let result = Executor::new(state, Limits::default()) + .with_native_pages() + .run( + source( + r"\catcode123=1 \catcode125=2 + \shipout\hbox{ + \special{dvipdfmx:config C 0x10} + \special{pdf:put @pages << /Feature @later /Count 22 >>} + \special{pdf:put @thispage << /Rotate 90 /CropBox @rect /Type /Other >>} + \special{pdf:dest (area) [@thispage /FitR @left 20 300 @upper]} + \vrule width7pt height8pt} + \shipout\hbox{ + \special{pdf:obj @rect [10 20 300 400]} + \special{pdf:obj @later << /Page @thispage >>} + \special{pdf:obj @left 10} + \special{pdf:obj @upper 400} + \vrule width9pt height8pt} + \end", + ), + &mut TestDevice, + ) + .unwrap(); + let pages = result.shipout_display_lists().unwrap(); + let svg = pages[0].try_to_svg().unwrap(); + assert!(svg.contains("width=\"380.000pt\" height=\"290.000pt\""), "{svg}"); + let page2_svg = pages[1].try_to_svg().unwrap(); + assert!(page2_svg.contains("width=\"612.000pt\" height=\"792.000pt\"")); + let output = shipout_lists_to_native_pdf_document(&pages, result.state.pdf_final_options()).unwrap(); + let pdf = Document::load_mem(&output.bytes).unwrap(); + let resolve = |object: &lopdf::Object| pdf.get_object(object.as_reference().unwrap()).unwrap(); + let ids = pdf.get_pages(); + let catalog = pdf.catalog().unwrap(); + let root = resolve(catalog.get(b"Pages").unwrap()).as_dict().unwrap(); + assert_eq!(root.get(b"Count").unwrap().as_i64().unwrap(), 2); + let feature = resolve(root.get(b"Feature").unwrap()).as_dict().unwrap(); + assert_eq!(feature.get(b"Page").unwrap().as_reference().unwrap(), ids[&2]); + let page = pdf.get_object(ids[&1]).unwrap().as_dict().unwrap(); + assert_eq!(page.get(b"Type").unwrap().as_name().unwrap(), b"Page"); + assert!(page.get(b"CropBox").unwrap().as_reference().is_ok()); + let names = catalog.get(b"Names").unwrap().as_dict().unwrap(); + let destinations = resolve(names.get(b"Dests").unwrap()).as_dict().unwrap(); + let names = destinations.get(b"Names").unwrap().as_array().unwrap(); + let area = names[1].as_array().unwrap(); + assert_eq!(area[0].as_reference().unwrap(), ids[&1]); + assert_eq!(area[1].as_name().unwrap(), b"FitR"); + assert_eq!(resolve(&area[2]).as_i64().unwrap(), 10); + assert_eq!(resolve(&area[5]).as_i64().unwrap(), 400); +} diff --git a/docs/P2_M1_PROGRESS.md b/docs/P2_M1_PROGRESS.md index 1134ba9..3dfc41e 100644 --- a/docs/P2_M1_PROGRESS.md +++ b/docs/P2_M1_PROGRESS.md @@ -18,6 +18,32 @@ | W6 会话 | 实施中 | 共享库/CLI 与当前原生文字/数学/规则来源进入公共结果;真实 A4 副本九类/27 revision 与独立干净作业页面/PDF/aux/映射一致,新增数学场景独立参考通过;详细失败/捕获重放及宿主/离线/CLI观察已通过;原子项目版本/已知生成初态及TeX流记录已接通;完整副作用/恢复契约、旧来源和性能仍缺 | | W7 总验收 | 未满足 | 原有和新增测试、原样项目、格式与会话门禁全部通过才能结项 | +## 2026-11-28 XeLaTeX 页字典与矩形跳转目标 + +原生出页处理 `pdf:put @pages` 和 `pdf:put @thispage`。 +页树和页内字典分别合并,保留实际页引用与命名对象。PDF 设备 +仍生成页树结构、页内容和资源,纸张尺寸按参考设备的全局与页面 +优先级写出。裁切、继承旋转与用户单位进入预览和来源映射。 +`pdf:dest` 的矩形操作数可保留指向命名坐标的间接引用,包括 +跨页前向引用和与目录字段共享的对象。 +[参考驱动源码](https://raw.githubusercontent.com/TeX-Live/texlive-source/trunk/texk/dvipdfm-x/dvipdfmx.c) + +两组原语对照分别覆盖三个页面的字典继承与覆盖,以及两个页面的 +矩形目标与前向坐标。真实 XeLaTeX 镜像加载原样 `article.cls` +和 `l3backend-xetex.def`,通过后端的矩形目标宏生成一页 PDF。 +三项共六页,所查字典、引用、矩形数值与参考一致,144 DPI 裁切 +后灰度图逐像素相同,article 的 aux 字节相同。开发构建与七项 +定向回归通过。 + +三页会话连续三次各复用 1,183 步。局部裁切修改只更新第 2 页, +随后改页树旋转只更新继承的第 1、3 页,恢复时更新三页。PDF、 +测量页、预览、来源映射与 aux 逐修订和同版本独立全量一致。 + +回执在 `target/p3-xdv-page-dictionaries/receipt.json`,SHA-256 为 +`8e518785b2df87f43169b8d7ae684ef1481335794070dc4d4b82a112057d4436`。 +后续补齐 XeLaTeX 页面资源和表单的出页协议,继续从真实项目定位 +缺口。原样出版模板矩阵和正式可见延迟留到同版统一验收。 + ## 2026-11-28 XeLaTeX 命名 PDF 对象与文件流 原样 `l3backend-xetex.def` 的 LaTeX 对象接口在基线出页时遇到