From e14361fec60d70cd102613b679cd9050896258c6 Mon Sep 17 00:00:00 2001 From: GloamXun Date: Sat, 28 Nov 2026 18:22:15 +0800 Subject: [PATCH] Write XeLaTeX named PDF objects and streams in native shipout --- .../src/execution/engine/specials.rs | 30 ++- crates/texrra-tex-core/src/pdf.rs | 20 +- .../src/pdf_device/xdv_annotation.rs | 12 +- .../src/pdf_device/xdv_navigation.rs | 73 +++++- .../xdv_navigation/named_objects.rs | 237 ++++++++++++++++++ .../src/pdf_device/xdv_object.rs | 110 ++++++-- .../tests/execution_xetex_profile.rs | 84 +++++++ docs/P2_M1_PROGRESS.md | 28 +++ 8 files changed, 551 insertions(+), 43 deletions(-) create mode 100644 crates/texrra-tex-core/src/pdf_device/xdv_navigation/named_objects.rs diff --git a/crates/texrra-tex-core/src/execution/engine/specials.rs b/crates/texrra-tex-core/src/execution/engine/specials.rs index f5353a3..3b805bf 100644 --- a/crates/texrra-tex-core/src/execution/engine/specials.rs +++ b/crates/texrra-tex-core/src/execution/engine/specials.rs @@ -1,6 +1,7 @@ //! TeX special whatsits and PDF driver dispatch at shipout. use super::*; use crate::pdf_device::{PdfDriver, PdfGraphics, PdfLiteralMode, PdfMatrix}; +use crate::resources::ResourceKind; impl Executor { pub(super) fn scan_special( @@ -68,11 +69,30 @@ impl Executor { return Ok(()); } self.reads.insert(Dependency::PdfCatalogState); - let navigation = Arc::make_mut(self.state.xdv_navigation.get_or_insert_with(Default::default)); - let warnings = if kind == b"docview" { - navigation.merge_catalog(operands, position, self.limits.tokens) + let warnings = if matches!(kind, b"docview" | b"outline") { + let navigation = Arc::make_mut(self.state.xdv_navigation.get_or_insert_with(Default::default)); + if kind == b"docview" { + navigation.merge_catalog(operands, position, self.limits.tokens) + } else { + navigation.add_outline(operands, position, (position.page, graphics_step, 1), self.limits.tokens) + } } else { - navigation.add_outline(operands, position, (position.page, graphics_step, 1), self.limits.tokens) + use crate::pdf_device::xdv_navigation::ObjectCommand; + let mut command = ObjectCommand::parse(kind, operands, position) + .map_err(|error| self.error(error, special.span))?; + let size = command.load_file(|name| { + let from = self.source_name(special.span); + self.reads.insert(Dependency::FileLookup { + name: name.to_owned(), + from: from.clone(), + }); + files.resource(ResourceKind::PdfImage, name, &from) + .map(|resource| resource.data) + .map_err(|error| format!("cannot open XDV PDF stream file {name}: {error}")) + }).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) }.map_err(|error| self.error(error, special.span))?; for warning in warnings { files.observe_diagnostic(WriteDestination::TerminalAndLog, &warning) @@ -318,6 +338,8 @@ pub(super) fn xdv_navigation_operand(data: &[u8]) -> Option<(&'static [u8], &[u8 for (name, kind) in [ (b"dest".as_slice(), b"dest".as_slice()), (b"destination", b"dest"), (b"docview", b"docview"), (b"outline", b"outline"), (b"out", b"outline"), + (b"obj", b"obj"), (b"object", b"obj"), (b"put", b"put"), (b"close", b"close"), + (b"stream", b"stream"), (b"fstream", b"fstream"), ] { if let Some(operands) = xdv_operand(body, name) { return Some((kind, operands)); diff --git a/crates/texrra-tex-core/src/pdf.rs b/crates/texrra-tex-core/src/pdf.rs index 0296fb2..d477aef 100755 --- a/crates/texrra-tex-core/src/pdf.rs +++ b/crates/texrra-tex-core/src/pdf.rs @@ -3510,13 +3510,27 @@ 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(&navigation.pages, &xdv_names)?; + 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( - &navigation.pages, &mut objects, &xdv_names, open_depth, + &references, &mut objects, &xdv_names, open_depth, )? { catalog.push_str(&format!(" /Outlines {outlines} 0 R")); } @@ -3593,7 +3607,7 @@ fn write_pdf( } } objects[0] = if let Some(xdv) = xdv { - xdv.finish_catalog(&catalog, &navigation.pages)? + xdv.finish_catalog(&catalog, &references)? } else { let mut catalog = catalog.into_bytes(); if let Some(extra) = extra { diff --git a/crates/texrra-tex-core/src/pdf_device/xdv_annotation.rs b/crates/texrra-tex-core/src/pdf_device/xdv_annotation.rs index d5e3927..02f26a6 100644 --- a/crates/texrra-tex-core/src/pdf_device/xdv_annotation.rs +++ b/crates/texrra-tex-core/src/pdf_device/xdv_annotation.rs @@ -5,7 +5,7 @@ use lopdf::Object; use super::xdv_navigation::read_fields; use super::xdv_object::{ - Dictionary, Position, atom, encode_device_value, output_with_destination, target_name, trim_pdf, + Dictionary, Position, References, atom, encode_device_value, output_with_destination, target_name, trim_pdf, }; use super::{Affine, xdv_image}; @@ -50,12 +50,18 @@ impl Annotation { target_name(&self.fields).map(|name| (self.order, name)) } + pub(crate) fn collect_references<'a>(&'a self, pending: &mut Vec<&'a [u8]>) { + for value in self.fields.values() { + value.collect_references(pending); + } + } + pub(crate) fn pdf( &self, - pages: &[usize], + references: &References<'_>, names: &BTreeMap, Vec>, ) -> Result, String> { - let mut dictionary = output_with_destination(&self.fields, pages, names)?; + let mut dictionary = output_with_destination(&self.fields, references, names)?; dictionary.set( "Rect", Object::Array( 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 6d7c4e3..25e2599 100644 --- a/crates/texrra-tex-core/src/pdf_device/xdv_navigation.rs +++ b/crates/texrra-tex-core/src/pdf_device/xdv_navigation.rs @@ -1,5 +1,5 @@ //! Document-view state and outlines produced by XDV specials. -use std::collections::BTreeMap; +use std::collections::{BTreeMap, BTreeSet}; use lopdf::Object; use serde::{Deserialize, Serialize}; @@ -7,16 +7,22 @@ use serde::{Deserialize, Serialize}; use super::page_resources::parse_value; use super::xdv_annotation::Order; use super::xdv_object::{ - Dictionary, Position, Value, atom, dictionary, encode_device_value, output_dictionary, + Dictionary, Position, References, Value, atom, dictionary, encode_device_value, output_dictionary, output_with_destination, target_name, trim_pdf, }; +mod named_objects; +pub(crate) use named_objects::ObjectCommand; +use named_objects::NamedObject; + #[derive(Clone, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)] pub(crate) struct Navigation { catalog: Dictionary, outlines: Vec, lowest_level: Option, payload: usize, + #[serde(default, skip_serializing_if = "BTreeMap::is_empty")] + objects: BTreeMap, NamedObject>, } #[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)] @@ -92,11 +98,66 @@ impl Navigation { Ok(()) } - pub(crate) fn finish_catalog(&self, base: &str, pages: &[usize]) -> Result, String> { + pub(crate) fn apply_object( + &mut self, + command: ObjectCommand, + bytes: usize, + limit: usize, + ) -> Result, String> { + self.add_payload(bytes, limit)?; + command.apply(&mut self.catalog, &mut self.objects) + } + + 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); + } + } + + pub(crate) fn reserve_objects<'a>( + &'a self, + mut pending: Vec<&'a [u8]>, + objects: &mut Vec>, + ) -> Result, u32>, String> { + let mut names = BTreeSet::new(); + while let Some(name) = pending.pop() { + if names.insert(name) && let Some(object) = self.objects.get(name) { + object.collect_references(&mut pending); + } + } + names.into_iter().map(|name| { + objects.push(Vec::new()); + let id = u32::try_from(objects.len()).map_err(|_| "XDV PDF object ID out of range")?; + Ok((name.to_vec(), id)) + }).collect() + } + + pub(crate) fn write_objects( + &self, + references: &References<'_>, + objects: &mut [Vec], + compression: u8, + diagnostics: &mut Vec, + ) -> Result<(), String> { + for (name, &id) in references.named { + objects[id as usize - 1] = if let Some(object) = self.objects.get(name) { + object.pdf(references, compression)? + } else { + diagnostics.push(format!( + "xdvipdfmx: warning: Object @{} used, but not defined. Replaced by null.", + String::from_utf8_lossy(name) + )); + b"null".to_vec() + }; + } + Ok(()) + } + + pub(crate) fn finish_catalog(&self, base: &str, references: &References<'_>) -> Result, String> { let Object::Dictionary(mut catalog) = parse_value(format!("{base} >>").as_bytes())? else { unreachable!("native PDF catalog is a dictionary"); }; - let additions = output_dictionary(&self.catalog, pages)?; + let additions = output_dictionary(&self.catalog, references)?; for (key, value) in &additions { match key.as_slice() { b"Type" | b"Pages" => {} @@ -124,7 +185,7 @@ impl Navigation { pub(crate) fn write_outlines( &self, - pages: &[usize], + references: &References<'_>, objects: &mut Vec>, names: &BTreeMap, Vec>, open_depth: usize, @@ -181,7 +242,7 @@ impl Navigation { objects.push(encode_device_value(Object::Dictionary(fields))?); for (offset, outline) in self.outlines.iter().enumerate() { let entry = &entries[offset + 1]; - let mut fields = output_with_destination(&outline.fields, pages, names)?; + let mut fields = output_with_destination(&outline.fields, references, names)?; fields.set("Parent", object(entry.parent)); for field in [b"Prev".as_slice(), b"Next", b"First", b"Last", b"Count"] { fields.remove(field); 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 new file mode 100644 index 0000000..487c1a2 --- /dev/null +++ b/crates/texrra-tex-core/src/pdf_device/xdv_navigation/named_objects.rs @@ -0,0 +1,237 @@ +use std::{collections::BTreeMap, 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}; + +#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)] +pub(super) struct NamedObject { + data: ObjectData, + closed: bool, +} + +#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)] +enum ObjectData { + Value(Value), + Stream { + attributes: Dictionary, + data: Arc<[u8]>, + }, +} + +pub(crate) struct ObjectCommand { + name: Vec, + change: Change, +} + +enum Change { + Define(ObjectData), + FileStream { + attributes: Dictionary, + filename: String, + }, + Put(Vec), + Close, +} + +impl ObjectCommand { + pub(crate) fn parse(kind: &[u8], bytes: &[u8], position: Position) -> Result { + let (name, rest) = identifier(bytes)?; + let rest = trim_pdf(rest); + let change = match kind { + b"obj" => Change::Define(ObjectData::Value(parse_object(rest, position)?)), + b"stream" | b"fstream" => { + let (input, trailing) = parse_object_prefix(rest, position)?; + let Value::String(input) = input else { + return Err("expected a PDF string for XDV stream input".into()); + }; + let attributes = if trailing.is_empty() { + Dictionary::new() + } else { + super::dictionary(trailing, position)? + }; + if kind == b"fstream" { + let filename = + String::from_utf8(input).map_err(|_| "XDV stream filename is not UTF-8")?; + Change::FileStream { + attributes, + filename, + } + } else { + Change::Define(ObjectData::Stream { + attributes, + data: input.into(), + }) + } + } + b"put" => { + let mut values = Vec::new(); + let mut remaining = rest; + while !remaining.is_empty() { + let (value, trailing) = parse_object_prefix(remaining, position)?; + values.push(value); + remaining = trailing; + } + if values.is_empty() { + return Err("missing object to put into XDV PDF object".into()); + } + Change::Put(values) + } + b"close" if rest.is_empty() => Change::Close, + b"close" => return Err("unexpected material after XDV PDF object identifier".into()), + _ => unreachable!("recognized XDV PDF object special"), + }; + Ok(Self { + name: name.to_vec(), + change, + }) + } + + pub(crate) fn load_file( + &mut self, + read: impl FnOnce(&str) -> Result, String>, + ) -> Result { + let Change::FileStream { + attributes, + filename, + } = &mut self.change + else { + return Ok(0); + }; + let data = read(filename)?; + let length = data.len(); + self.change = Change::Define(ObjectData::Stream { + attributes: std::mem::take(attributes), + data: data.into(), + }); + Ok(length) + } + + pub(super) fn apply( + self, + catalog: &mut Dictionary, + objects: &mut BTreeMap, NamedObject>, + ) -> 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" + && let Change::Put(values) = change + { + catalog.append(&mut only_dictionary(values)?); + return Ok(Vec::new()); + } + if matches!( + name.as_slice(), + b"catalog" + | b"pages" + | b"thispage" + | b"prevpage" + | b"nextpage" + | b"names" + | b"resources" + | b"docinfo" + | b"xpos" + | b"ypos", + ) { + return Err(format!( + "unsupported mutation of XDV PDF device object @{display}" + )); + } + + match change { + Change::Define(data) => { + use std::collections::btree_map::Entry; + match objects.entry(name.clone()) { + Entry::Occupied(_) => { + return Ok(warning(format!("Object @{display} already defined."))); + } + Entry::Vacant(entry) => { + entry.insert(NamedObject { + data, + closed: false, + }); + } + } + } + Change::Put(values) => { + let object = objects + .get_mut(&name) + .ok_or_else(|| format!("XDV PDF object @{display} is not defined"))?; + if object.closed { + return Err(format!("XDV PDF object @{display} is closed")); + } + match &mut object.data { + ObjectData::Value(Value::Array(items)) => items.extend(values), + ObjectData::Value(Value::Dictionary(fields)) + | ObjectData::Stream { + attributes: fields, .. + } => { + fields.append(&mut only_dictionary(values)?); + } + _ => return Err(format!("XDV PDF object @{display} cannot be extended")), + } + } + Change::Close => match objects.get_mut(&name) { + Some(object) if !object.closed => object.closed = true, + Some(_) => return Ok(warning(format!("Object @{display} already closed."))), + None => { + return Ok(warning(format!( + "Cannot close undefined object @{display}." + ))); + } + }, + Change::FileStream { .. } => unreachable!("file stream was loaded at shipout"), + } + Ok(Vec::new()) + } +} + +fn only_dictionary(values: Vec) -> Result { + let mut values = values.into_iter(); + match (values.next(), values.next()) { + (Some(Value::Dictionary(fields)), None) => Ok(fields), + _ => Err("XDV PDF dictionary merge requires one dictionary".into()), + } +} + +impl NamedObject { + pub(super) fn collect_references<'a>(&'a self, pending: &mut Vec<&'a [u8]>) { + match &self.data { + ObjectData::Value(value) => value.collect_references(pending), + ObjectData::Stream { attributes, .. } => { + for value in attributes.values() { + value.collect_references(pending); + } + } + } + } + + pub(super) fn pdf( + &self, + references: &References<'_>, + compression: u8, + ) -> Result, String> { + match &self.data { + ObjectData::Value(value) => encode_device_value(value.output(references)?), + ObjectData::Stream { attributes, data } => { + let mut attributes = output_dictionary(attributes, references)?; + attributes.remove(b"Length"); + let compression = if attributes.has(b"Filter") { + 0 + } else { + compression + }; + let dictionary = encode_device_value(lopdf::Object::Dictionary(attributes))?; + Ok(stream_bytes( + &dictionary[2..dictionary.len() - 2], + data, + compression, + )) + } + } + } +} diff --git a/crates/texrra-tex-core/src/pdf_device/xdv_object.rs b/crates/texrra-tex-core/src/pdf_device/xdv_object.rs index 7e8db00..93bd63f 100644 --- a/crates/texrra-tex-core/src/pdf_device/xdv_object.rs +++ b/crates/texrra-tex-core/src/pdf_device/xdv_object.rs @@ -74,6 +74,23 @@ pub(super) fn page_reference(page: &[u8], current_page: usize) -> Option } } +/// Read the same identifier alphabet as the device's special scanner. +pub(super) fn identifier(input: &[u8]) -> Result<(&[u8], &[u8]), String> { + let name = trim_pdf(input) + .strip_prefix(b"@") + .ok_or("missing XDV PDF object identifier")?; + let length = name + .iter() + .take_while(|byte| { + byte.is_ascii_alphanumeric() || b"!\"#$&'*+,-.:;=?@\\^_`|~".contains(byte) + }) + .count(); + if length == 0 { + return Err("empty XDV PDF object identifier".into()); + } + Ok(name.split_at(length)) +} + pub(super) type Dictionary = BTreeMap, Value>; #[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)] @@ -89,6 +106,7 @@ pub(super) enum Value { Page(usize), Catalog, PageTree, + Named(Vec), } #[derive(Clone, Copy)] @@ -119,32 +137,41 @@ impl Position { } b"@catalog" => Ok(Value::Catalog), b"@pages" => Ok(Value::PageTree), - _ => page_reference(token, self.page) - .map(Value::Page) - .ok_or_else(|| { - format!( - "unsupported XDV PDF object reference {}", - String::from_utf8_lossy(token) - ) - }), + b"@prevpage" => self.page.checked_sub(1).filter(|page| *page > 0) + .map(Value::Page).ok_or_else(|| "XDV has no previous page".into()), + b"@names" | b"@resources" | b"@docinfo" => Err(format!( + "unsupported XDV PDF device reference {}", + String::from_utf8_lossy(token) + )), + _ => Ok(match page_reference(token, self.page) { + Some(page) => Value::Page(page), + None => Value::Named(token[1..].to_vec()), + }), } } } pub(super) fn dictionary(input: &[u8], position: Position) -> Result { - let mut parser = Parser { - rest: input, - position, - }; - let Value::Dictionary(dictionary) = parser.value(0)? else { + let Value::Dictionary(dictionary) = parse_object(input, position)? else { return Err("expected an XDV PDF dictionary".into()); }; - if !trim_pdf(parser.rest).is_empty() { - return Err("unexpected material after XDV PDF dictionary".into()); - } Ok(dictionary) } +pub(super) fn parse_object(bytes: &[u8], position: Position) -> Result { + let (value, rest) = parse_object_prefix(bytes, position)?; + if !rest.is_empty() { + return Err("unexpected material after XDV PDF object".into()); + } + Ok(value) +} + +pub(super) fn parse_object_prefix(bytes: &[u8], position: Position) -> Result<(Value, &[u8]), String> { + let mut parser = Parser { rest: bytes, position }; + let value = parser.value(0)?; + Ok((value, trim_pdf(parser.rest))) +} + struct Parser<'a> { rest: &'a [u8], position: Position, @@ -184,15 +211,18 @@ impl Parser<'_> { return Ok(Value::Array(array)); } + if self.rest.starts_with(b"@") { + let (name, rest) = identifier(self.rest)?; + let token = &self.rest[..name.len() + 1]; + self.rest = rest; + return self.position.reference(token); + } let (token, rest) = match self.rest.first() { Some(b'(' | b'<') => split_string(self.rest)?, Some(_) => atom(self.rest), None => return Err("unexpected end of XDV PDF object".into()), }; self.rest = rest; - if token.starts_with(b"@") { - return self.position.reference(token); - } match parse_value(token)? { Object::Null => Ok(Value::Null), Object::Boolean(value) => Ok(Value::Boolean(value)), @@ -205,18 +235,23 @@ impl Parser<'_> { } } +pub(crate) struct References<'a> { + pub(crate) pages: &'a [usize], + pub(crate) named: &'a BTreeMap, u32>, +} + pub(super) fn output_dictionary( dictionary: &Dictionary, - pages: &[usize], + references: &References<'_>, ) -> Result { dictionary .iter() - .map(|(key, value)| Ok((key.clone(), value.output(pages)?))) + .map(|(key, value)| Ok((key.clone(), value.output(references)?))) .collect() } impl Value { - fn output(&self, pages: &[usize]) -> Result { + pub(super) fn output(&self, references: &References<'_>) -> Result { Ok(match self { Self::Null => Object::Null, Self::Boolean(value) => Object::Boolean(*value), @@ -227,14 +262,14 @@ impl Value { Self::Array(values) => Object::Array( values .iter() - .map(|value| value.output(pages)) + .map(|value| value.output(references)) .collect::>()?, ), Self::Dictionary(dictionary) => { - Object::Dictionary(output_dictionary(dictionary, pages)?) + Object::Dictionary(output_dictionary(dictionary, references)?) } Self::Page(page) => { - let id = pages + let id = references.pages .get(page - 1) .ok_or_else(|| format!("XDV PDF object refers to nonexistent page {page}"))?; Object::Reference(( @@ -244,11 +279,32 @@ impl Value { } Self::Catalog => Object::Reference((1, 0)), Self::PageTree => Object::Reference((2, 0)), + Self::Named(name) => Object::Reference(( + *references.named.get(name).ok_or("unallocated XDV PDF object reference")?, + 0, + )), }) } } impl Value { + pub(super) fn collect_references<'a>(&'a self, pending: &mut Vec<&'a [u8]>) { + match self { + Self::Named(name) => pending.push(name), + Self::Array(items) => { + for item in items { + item.collect_references(pending); + } + } + Self::Dictionary(fields) => { + for field in fields.values() { + field.collect_references(pending); + } + } + _ => {} + } + } + pub(super) fn normalize_text(&mut self, key: &[u8], warnings: &mut Vec) { match self { Self::String(bytes) => { @@ -293,10 +349,10 @@ pub(super) fn target_name(fields: &Dictionary) -> Option<&[u8]> { pub(super) fn output_with_destination( fields: &Dictionary, - pages: &[usize], + references: &References<'_>, names: &BTreeMap, Vec>, ) -> Result { - let mut dictionary = output_dictionary(fields, pages)?; + let mut dictionary = output_dictionary(fields, references)?; if let Some(compact) = target_name(fields).and_then(|name| names.get(name)) { let compact = Object::String(compact.clone(), StringFormat::Hexadecimal); if dictionary.has(b"Dest") { diff --git a/crates/texrra-tex-core/tests/execution_xetex_profile.rs b/crates/texrra-tex-core/tests/execution_xetex_profile.rs index 3ea5367..d2ff15e 100644 --- a/crates/texrra-tex-core/tests/execution_xetex_profile.rs +++ b/crates/texrra-tex-core/tests/execution_xetex_profile.rs @@ -814,3 +814,87 @@ fn xdv_root_annotation_keeps_its_extent_and_destination_across_shipouts() { assert_eq!(names[2].as_str().unwrap(), b"1"); assert_eq!(names[3].as_array().unwrap()[0].as_reference().unwrap(), page_ids[&1]); } + +#[test] +fn xdv_named_objects_keep_forward_edges_and_file_streams_at_shipout() { + use lopdf::{Document, Object}; + use texrra_tex_core::pdf::shipout_lists_to_native_pdf_document; + use texrra_tex_core::resources::{LoadedResource, ResourceKind, ResourceVersion}; + + struct Device; + impl SourceProvider for Device { + fn read(&mut self, name: &str, _: &str) -> Result { + Err(format!("unexpected input {name}")) + } + + fn default_pk_resolution(&mut self) -> Result { + Ok(600) + } + + fn resource(&mut self, kind: ResourceKind, name: &str, from: &str) -> Result { + assert_eq!((kind, name, from), (ResourceKind::PdfImage, "object.bin", "profile.tex")); + Ok(LoadedResource { + version: ResourceVersion { + path: name.into(), + bytes: 3, + sha256: "5240672d7b51756b829ad0ef8d9468b7a078afa2f410484fd3892dab47becb72".into(), + }, + data: vec![0, 128, 255], + }) + } + } + + 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 + \setbox0=\hbox{\special{pdf:obj @discarded << /bad true >>}} + \shipout\hbox{ + \special{pdf:put @catalog << /Data @root /Missing @missing >>} + \special{pdf:object @root << /Self @root /Page @nextpage /Items @items >>} + \special{pdf:obj @items [1]} + \special{pdf:put @items 2 @binary} + \special{pdf:fstream @binary (object.bin) << /Tag /First >>} + \special{pdf:put @binary << /Tag /Final >>} + \special{pdf:close @root} + \vrule width7pt height8pt} + \shipout\hbox{ + \special{pdf:put @catalog << /Same @root >>} + \vrule width9pt height8pt} + \end", + ), + &mut Device, + ) + .unwrap(); + assert!(result.reads.contains(&Dependency::FileLookup { + name: "object.bin".to_owned(), + from: "profile.tex".to_owned(), + })); + + let pages = result.shipout_display_lists().unwrap(); + let output = shipout_lists_to_native_pdf_document(&pages, result.state.pdf_final_options()).unwrap(); + assert!(output.diagnostics.iter().any(|warning| warning.contains("Object @missing used, but not defined"))); + let pdf = Document::load_mem(&output.bytes).unwrap(); + let catalog = pdf.catalog().unwrap(); + let id = catalog.get(b"Data").unwrap().as_reference().unwrap(); + assert_eq!(catalog.get(b"Same").unwrap().as_reference().unwrap(), id); + let root = pdf.get_object(id).unwrap().as_dict().unwrap(); + assert_eq!(root.get(b"Self").unwrap().as_reference().unwrap(), id); + assert_eq!(root.get(b"Page").unwrap().as_reference().unwrap(), pdf.get_pages()[&2]); + let items = pdf.get_object(root.get(b"Items").unwrap().as_reference().unwrap()).unwrap().as_array().unwrap(); + assert_eq!(items[0].as_i64().unwrap(), 1); + assert_eq!(items[1].as_i64().unwrap(), 2); + let stream = pdf.get_object(items[2].as_reference().unwrap()).unwrap().as_stream().unwrap(); + assert_eq!(stream.dict.get(b"Tag").unwrap().as_name().unwrap(), b"Final"); + let bytes = if stream.dict.has(b"Filter") { + stream.decompressed_content().unwrap() + } else { + stream.content.clone() + }; + assert_eq!(bytes, [0, 128, 255]); + let missing = catalog.get(b"Missing").unwrap().as_reference().unwrap(); + assert!(matches!(pdf.get_object(missing), Ok(Object::Null))); + assert!(!output.bytes.windows(4).any(|window| window == b"/bad")); +} diff --git a/docs/P2_M1_PROGRESS.md b/docs/P2_M1_PROGRESS.md index 4b462f2..1134ba9 100644 --- a/docs/P2_M1_PROGRESS.md +++ b/docs/P2_M1_PROGRESS.md @@ -18,6 +18,34 @@ | W6 会话 | 实施中 | 共享库/CLI 与当前原生文字/数学/规则来源进入公共结果;真实 A4 副本九类/27 revision 与独立干净作业页面/PDF/aux/映射一致,新增数学场景独立参考通过;详细失败/捕获重放及宿主/离线/CLI观察已通过;原子项目版本/已知生成初态及TeX流记录已接通;完整副作用/恢复契约、旧来源和性能仍缺 | | W7 总验收 | 未满足 | 原有和新增测试、原样项目、格式与会话门禁全部通过才能结项 | +## 2026-11-28 XeLaTeX 命名 PDF 对象与文件流 + +原样 `l3backend-xetex.def` 的 LaTeX 对象接口在基线出页时遇到 +`pdf:put` 即停止。现在从实际发出的 special 执行 `obj`、`object`、 +`stream`、`fstream`、`close`、普通命名对象的 `put` 与 +`put @catalog`。字典合并、数组追加、流属性、同对象间接引用和跨页 +前向引用均进入原生导出。文件流通过作业资源解析器读取实际字节, +保留查找与内容版本。对象图随检查点恢复,格式镜像仍隔离作业设备状态。 +[上游出页指令](https://raw.githubusercontent.com/TeX-Live/texlive-source/trunk/texk/dvipdfm-x/spc_pdfm.c) + +用已有真实 XeLaTeX 格式、原样 `article.cls` 与 `expl3` 后端生成 +一页 PDF。对照 XeTeX 0.999998 与 xdvipdfmx 20260113,目录间接引用 +及目标对象内容、aux 和灰度光栅一致。两页对象对照还核对了数组、 +流属性、内联流、256 字节的二进制文件以及跨对象共享和跨页引用。 +既有三页目录及书签对照继续通过。三项共六页,144 DPI 灰度图 +逐像素相同。开发构建及六项定向回归通过。 + +三页编辑会话连续三轮各复用 1,192 步。编辑子文件和恢复时只更新 +第二页。只改嵌入文件时,实际 PDF 流字节从 17 更新为 36,预览 +没有变更页。每轮的 PDF、测量页、预览、来源映射及 aux 均与 +同版本独立全量一致。 + +回执在 `target/p3-xdv-named-objects/receipt.json`,SHA-256 为 +`b70ebab030733409c1a3e3c8fcd9f838aedf83ae0efdb9b0478e530c813c187e`。 +下一步接通内置页字典的 `put`、矩形目标中的命名坐标,以及实际项目 +的后续 PDF 设备缺口。完整出版矩阵、同版发布验收和正式可见延迟测量 +保持在功能里程碑统一执行。 + ## 2026-11-28 A4 命令表共享试验 用 d9143dd 与隔离候选版加载同一真实 schema104 LaTeX 格式。候选版