From 009fde04f71a9402773e3e956bad1b055d3fcf21 Mon Sep 17 00:00:00 2001 From: GloamXun Date: Sat, 28 Nov 2026 18:58:49 +0800 Subject: [PATCH] Render XeLaTeX shared page resources and scoped graphics --- .../src/execution/diagnostics.rs | 3 +- .../src/execution/engine/page.rs | 17 +- .../src/execution/engine/specials.rs | 23 +- .../src/execution/engine/xdv_annotation.rs | 8 +- crates/texrra-tex-core/src/execution/mod.rs | 1 + crates/texrra-tex-core/src/pdf.rs | 27 +- .../src/pdf_device/graphics.rs | 3 + .../src/pdf_device/xdv_navigation.rs | 5 + .../xdv_navigation/named_objects.rs | 12 + .../xdv_navigation/page_resources.rs | 245 ++++++++++++++++++ .../src/source_map/pdf_projection.rs | 25 +- .../tests/execution_xetex_profile.rs | 56 ++++ docs/P2_M1_PROGRESS.md | 32 +++ 13 files changed, 445 insertions(+), 12 deletions(-) create mode 100644 crates/texrra-tex-core/src/pdf_device/xdv_navigation/page_resources.rs diff --git a/crates/texrra-tex-core/src/execution/diagnostics.rs b/crates/texrra-tex-core/src/execution/diagnostics.rs index 0ec6fff..b78900e 100644 --- a/crates/texrra-tex-core/src/execution/diagnostics.rs +++ b/crates/texrra-tex-core/src/execution/diagnostics.rs @@ -718,7 +718,8 @@ impl Printer<'_> { PdfLiteralMode::Page => self.literal(" page"), PdfLiteralMode::Direct => self.literal(" direct"), PdfLiteralMode::XdvOrigin | PdfLiteralMode::XdvDirect - | PdfLiteralMode::XdvContent => {} + | PdfLiteralMode::XdvContent | PdfLiteralMode::XdvBeginContent + | PdfLiteralMode::XdvEndContent | PdfLiteralMode::XdvCode => {} } self.tokens(tokens)?; } diff --git a/crates/texrra-tex-core/src/execution/engine/page.rs b/crates/texrra-tex-core/src/execution/engine/page.rs index 7c3eec1..ad2311a 100644 --- a/crates/texrra-tex-core/src/execution/engine/page.rs +++ b/crates/texrra-tex-core/src/execution/engine/page.rs @@ -663,9 +663,9 @@ impl Executor { } else { None }; - use crate::pdf_device::PdfGraphics; + use crate::pdf_device::{PdfGraphics, PdfLiteralMode}; match &graphics { - Some(PdfGraphics::Save) => { + Some(PdfGraphics::Save | PdfGraphics::Literal { mode: PdfLiteralMode::XdvBeginContent, .. }) => { xdv_graphics_stack.push((special.span, xdv_transform, self.xdv_colors.current())); } Some(operation @ (PdfGraphics::SaveMatrix(matrix) | PdfGraphics::Matrix(matrix))) => { @@ -680,7 +680,7 @@ impl Executor { ); xdv_transform = xdv_transform.concatenate(pivot); } - Some(PdfGraphics::Restore { .. }) => { + Some(PdfGraphics::Restore { .. } | PdfGraphics::Literal { mode: PdfLiteralMode::XdvEndContent, .. }) => { let Some((_, previous, color_at_save)) = xdv_graphics_stack.pop() else { return Err(self.error("unmatched XDV graphics restore", special.span)); }; @@ -869,6 +869,17 @@ impl Executor { )?; } } + if xdv && let Some(navigation) = &mut self.state.xdv_navigation + && navigation.has_pending_page_resources() + { + self.reads.insert(Dependency::PdfCatalogState); + let messages = Arc::make_mut(navigation).finish_page_resources(self.shipped_pages + 1) + .map_err(|message| self.error(message, current))?; + for message in messages { + files.observe_diagnostic(WriteDestination::TerminalAndLog, &message) + .map_err(|message| self.error(message, current))?; + } + } if xdv && (!xdv_annotations.is_empty() || self.xdv_annotations.is_active()) { shipout.pdf_links.xdv_annotations = self.ship_xdv_annotations(&shipout, &xdv_annotations, files)?; } diff --git a/crates/texrra-tex-core/src/execution/engine/specials.rs b/crates/texrra-tex-core/src/execution/engine/specials.rs index 8fec124..8a34eed 100644 --- a/crates/texrra-tex-core/src/execution/engine/specials.rs +++ b/crates/texrra-tex-core/src/execution/engine/specials.rs @@ -69,12 +69,14 @@ impl Executor { return Ok(()); } self.reads.insert(Dependency::PdfCatalogState); - let warnings = if matches!(kind, b"docview" | b"outline") { + let warnings = if matches!(kind, b"docview" | b"outline" | b"pageresources") { 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 { + } else if kind == b"outline" { navigation.add_outline(operands, position, (position.page, graphics_step, 1), self.limits.tokens) + } else { + navigation.set_page_resources(operands, position, self.limits.tokens) } } else { use crate::pdf_device::xdv_navigation::ObjectCommand; @@ -176,6 +178,21 @@ impl Executor { return Ok(Some(graphics)); } let body = data.strip_prefix(b"pdf:").map(xdv_skip_white); + if let Some(body) = body { + for (command, mode) in [ + (b"bcontent".as_slice(), PdfLiteralMode::XdvBeginContent), + (b"econtent", PdfLiteralMode::XdvEndContent), + (b"code", PdfLiteralMode::XdvCode), + ] { + if let Some(operands) = xdv_operand(body, command) { + let bytes = xdv_skip_white(operands); + if mode != PdfLiteralMode::XdvCode && !bytes.is_empty() { + return self.fail("unexpected operands to XDV content boundary"); + } + return Ok(Some(PdfGraphics::Literal { mode, bytes: Arc::from(bytes) })); + } + } + } if let Some(content) = body.and_then(|body| xdv_operand(body, b"content")) { let bytes = xdv_skip_white(content); return Ok((!bytes.is_empty()).then(|| PdfGraphics::Literal { @@ -339,7 +356,7 @@ pub(super) fn xdv_navigation_operand(data: &[u8]) -> Option<(&'static [u8], &[u8 (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"), + (b"stream", b"stream"), (b"fstream", b"fstream"), (b"pageresources", b"pageresources"), ] { if let Some(operands) = xdv_operand(body, name) { return Some((kind, operands)); 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 4bcb71d..130058a 100644 --- a/crates/texrra-tex-core/src/execution/engine/xdv_annotation.rs +++ b/crates/texrra-tex-core/src/execution/engine/xdv_annotation.rs @@ -88,7 +88,9 @@ impl Executor { }) } else if let Some(operation) = shipout.pdf_graphics_steps.get(step) { match operation { - Some(PdfGraphics::Save) => saved.push(frame.transform), + Some(PdfGraphics::Save | PdfGraphics::Literal { + mode: crate::pdf_device::PdfLiteralMode::XdvBeginContent, .. + }) => saved.push(frame.transform), Some( operation @ (PdfGraphics::SaveMatrix(matrix) | PdfGraphics::Matrix(matrix)), @@ -100,7 +102,9 @@ impl Executor { .transform .concatenate(matrix.about(point[0], point[1], true)); } - Some(PdfGraphics::Restore { .. }) => { + Some(PdfGraphics::Restore { .. } | PdfGraphics::Literal { + mode: crate::pdf_device::PdfLiteralMode::XdvEndContent, .. + }) => { frame.transform = saved.pop().expect("validated graphics stack"); } diff --git a/crates/texrra-tex-core/src/execution/mod.rs b/crates/texrra-tex-core/src/execution/mod.rs index 71da882..9e8e78f 100644 --- a/crates/texrra-tex-core/src/execution/mod.rs +++ b/crates/texrra-tex-core/src/execution/mod.rs @@ -816,6 +816,7 @@ impl Execution { if !self.state.pdf_draft_mode() { self.resolve_page_graphics_resources(&mut pages)?; if let Some(navigation) = &self.state.xdv_navigation { + navigation.mark_resource_previews(&mut pages); navigation.resolve_page_dictionaries(&mut pages).map_err(|message| { Error::at(&self.sources, self.state.input_profile(), message, Span::default()) })?; diff --git a/crates/texrra-tex-core/src/pdf.rs b/crates/texrra-tex-core/src/pdf.rs index 3fdca60..8aef9a7 100755 --- a/crates/texrra-tex-core/src/pdf.rs +++ b/crates/texrra-tex-core/src/pdf.rs @@ -783,6 +783,7 @@ fn page_content( let mut tex_text: Option = None; let mut opentype_text = opentype_fonts::TextState::default(); let bp_per_unit = list.units.bp(1); + let mut xdv_content_scopes = Vec::new(); for (index, item) in list.items.iter().enumerate() { if !matches!(item, DisplayItem::OpenTypeGlyph { .. }) { opentype_text.finish(&mut content); @@ -820,7 +821,11 @@ fn page_content( if let Some((x, y, mode, bytes)) = literal { NativeTextRun::flush(&mut native_text, &mut content); let previous_origin = content.origin; - let special_origin = mode.xdv_origin([x, height - y], page_origin); + let special_origin = if mode == PdfLiteralMode::XdvCode { + Some(xdv_content_scopes.last().map_or(page_origin, |&(_, point)| point)) + } else { + mode.xdv_origin([x, height - y], page_origin) + }; match mode { PdfLiteralMode::Direct => { native_text::NativeText::break_string(&mut tex_text, &mut content); @@ -831,7 +836,24 @@ fn page_content( content.move_origin([x, height - y], list.units, digits); } } - PdfLiteralMode::XdvOrigin | PdfLiteralMode::XdvDirect | PdfLiteralMode::XdvContent => { + PdfLiteralMode::XdvBeginContent => { + native_text::NativeText::finish(&mut tex_text, &mut content); + let point = [x, height - y]; + xdv_content_scopes.push((previous_origin, point)); + content.push_str("q\n"); + content.move_origin(point, list.units, digits); + continue; + } + PdfLiteralMode::XdvEndContent => { + native_text::NativeText::finish(&mut tex_text, &mut content); + content.push_str("Q\n"); + if let Some((origin, _)) = xdv_content_scopes.pop() { + content.origin = origin; + } + continue; + } + PdfLiteralMode::XdvOrigin | PdfLiteralMode::XdvDirect | PdfLiteralMode::XdvContent + | PdfLiteralMode::XdvCode => { native_text::NativeText::finish(&mut tex_text, &mut content); if mode == PdfLiteralMode::XdvContent { content.push_str("q\n"); @@ -3552,6 +3574,7 @@ fn write_pdf( xdv_objects.write_objects(&references, &mut objects, compression, diagnostics)?; if let Some(xdv) = xdv { xdv.write_page_dictionaries(pages, &references, &mut objects)?; + xdv.write_page_resources(&references, &mut objects, diagnostics)?; } for (id, annotation) in xdv_annotations { objects[id - 1] = annotation.pdf(&references, &xdv_names)?; diff --git a/crates/texrra-tex-core/src/pdf_device/graphics.rs b/crates/texrra-tex-core/src/pdf_device/graphics.rs index 6dbc426..7b753b2 100644 --- a/crates/texrra-tex-core/src/pdf_device/graphics.rs +++ b/crates/texrra-tex-core/src/pdf_device/graphics.rs @@ -12,6 +12,9 @@ pub enum PdfLiteralMode { XdvDirect, /// XDV page content relative to the special, inside a local graphics state. XdvContent, + XdvBeginContent, + XdvEndContent, + XdvCode, } impl PdfLiteralMode { 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 2622ec9..d5b4609 100644 --- a/crates/texrra-tex-core/src/pdf_device/xdv_navigation.rs +++ b/crates/texrra-tex-core/src/pdf_device/xdv_navigation.rs @@ -13,6 +13,8 @@ use super::xdv_object::{ mod named_objects; mod page_dictionaries; +mod page_resources; +use page_resources::PageResources; use page_dictionaries::PageDictionaries; pub(crate) use named_objects::ObjectCommand; use named_objects::NamedObject; @@ -27,6 +29,8 @@ pub(crate) struct Navigation { objects: BTreeMap, NamedObject>, #[serde(default, skip_serializing_if = "PageDictionaries::is_empty")] page_dictionaries: PageDictionaries, + #[serde(default, skip_serializing_if = "PageResources::is_empty")] + page_resources: PageResources, } #[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)] @@ -118,6 +122,7 @@ impl Navigation { value.collect_references(pending); } self.page_dictionaries.collect_references(pending); + self.page_resources.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 6350a77..c9e64d5 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 @@ -131,6 +131,11 @@ impl ObjectCommand { fields.append(&mut only_dictionary(values)?); return Ok(Vec::new()); } + if name == b"resources" + && let Change::Put(values) = change + { + return navigation.put_resources(only_dictionary(values)?); + } let objects = &mut navigation.objects; if matches!( name.as_slice(), @@ -207,6 +212,13 @@ fn only_dictionary(values: Vec) -> Result { } impl NamedObject { + pub(super) fn dictionary_mut(&mut self) -> Option<&mut Dictionary> { + match &mut self.data { + ObjectData::Value(Value::Dictionary(fields)) if !self.closed => Some(fields), + _ => None, + } + } + pub(super) fn value(&self) -> Option<&Value> { match &self.data { ObjectData::Value(value) => Some(value), diff --git a/crates/texrra-tex-core/src/pdf_device/xdv_navigation/page_resources.rs b/crates/texrra-tex-core/src/pdf_device/xdv_navigation/page_resources.rs new file mode 100644 index 0000000..8675f3a --- /dev/null +++ b/crates/texrra-tex-core/src/pdf_device/xdv_navigation/page_resources.rs @@ -0,0 +1,245 @@ +use std::collections::{BTreeMap, btree_map::Entry}; +use std::sync::Arc; + +use lopdf::{Dictionary as PdfDictionary, Object}; +use serde::{Deserialize, Serialize}; + +use super::{ + Dictionary, NamedObject, Navigation, Position, References, Value, dictionary, + encode_device_value, output_dictionary, parse_value, +}; + +#[derive(Clone, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)] +pub(super) struct PageResources { + current: Dictionary, + defaults: Arc, + pages: BTreeMap, +} + +impl PageResources { + pub(super) fn is_empty(&self) -> bool { + self.current.is_empty() && self.defaults.is_empty() && self.pages.is_empty() + } + + pub(super) fn collect_references<'a>(&'a self, pending: &mut Vec<&'a [u8]>) { + for field in self.pages.values().flat_map(Dictionary::values) { + field.collect_references(pending); + } + } +} + +impl Navigation { + pub(super) fn put_resources(&mut self, additions: Dictionary) -> Result, String> { + self.merge_resources(additions, false) + } + + pub(crate) fn set_page_resources( + &mut self, + bytes: &[u8], + position: Position, + limit: usize, + ) -> Result, String> { + let defaults = dictionary(bytes, position)?; + self.add_payload(bytes.len(), limit)?; + self.page_resources.defaults = Arc::new(defaults); + Ok(Vec::new()) + } + + pub(crate) fn has_pending_page_resources(&self) -> bool { + !self.page_resources.current.is_empty() || !self.page_resources.defaults.is_empty() + } + + pub(crate) fn finish_page_resources(&mut self, page: usize) -> Result, String> { + let messages = self.merge_resources((*self.page_resources.defaults).clone(), true)?; + let resources = std::mem::take(&mut self.page_resources.current); + if !resources.is_empty() { + self.page_resources.pages.insert(page, resources); + } + Ok(messages) + } + + fn merge_resources( + &mut self, + additions: Dictionary, + deferred: bool, + ) -> Result, String> { + let mut messages = Vec::new(); + for (category, value) in additions { + let current = self.page_resources.current.entry(category); + match (current, value) { + (Entry::Vacant(entry), Value::Dictionary(data)) => { + entry.insert(Value::Dictionary(data)); + } + (Entry::Vacant(entry), Value::Named(name)) => { + if deferred { + category_fields(&self.objects, &name)?; + } + entry.insert(Value::Named(name)); + } + (Entry::Occupied(mut entry), Value::Dictionary(data)) => { + let existing = match entry.get_mut() { + Value::Dictionary(fields) => fields, + Value::Named(name) => category_fields_mut(&mut self.objects, name)?, + _ => unreachable!("validated resource category"), + }; + append_missing(existing, data, deferred, &mut messages); + } + (Entry::Occupied(mut entry), Value::Named(name)) => { + let old = match entry.get() { + Value::Dictionary(fields) => fields.clone(), + Value::Named(old) if *old == name => continue, + Value::Named(old) => category_fields(&self.objects, old)?.clone(), + _ => unreachable!("validated resource category"), + }; + let destination = category_fields_mut(&mut self.objects, &name)?; + append_missing(destination, old, deferred, &mut messages); + entry.insert(Value::Named(name)); + } + (_, _) => { + return Err( + "XDV resource category requires a dictionary or named reference".into(), + ); + } + } + } + Ok(messages) + } + + pub(crate) fn mark_resource_previews(&self, pages: &mut [crate::render::DisplayList]) { + for &page in self.page_resources.pages.keys() { + if let Some(list) = pages.get_mut(page - 1) { + list.pdf_resources.needs_pdf_for_preview = true; + } + } + } + + pub(crate) fn write_page_resources( + &self, + references: &References<'_>, + objects: &mut [Vec], + diagnostics: &mut Vec, + ) -> Result<(), String> { + for (&page, fields) in &self.page_resources.pages { + let id = *references + .pages + .get(page - 1) + .ok_or("unallocated XDV resource page")?; + let mut dictionary = pdf_dictionary(&objects[id - 1])?; + let mut resources = dictionary + .remove(b"Resources") + .ok_or("XDV page is missing its generated resource dictionary")? + .as_dict() + .map_err(|_| "expected inline XDV resource dictionary")? + .clone(); + for (category, new) in &output_dictionary(fields, references)? { + let generated = resources.remove(category); + let generated = generated + .as_ref() + .map(Object::as_dict) + .transpose() + .map_err(|_| "cannot merge a non-dictionary generated resource category")?; + let effective = match new { + Object::Dictionary(fields) => { + if let Some(generated) = generated { + let mut combined = generated.clone(); + merge_pdf_entries(&mut combined, fields, diagnostics); + Object::Dictionary(combined) + } else { + new.clone() + } + } + Object::Reference((number, 0)) => { + if let Some(generated) = generated { + let slot = &mut objects[*number as usize - 1]; + let mut shared = pdf_dictionary(slot)?; + merge_pdf_entries(&mut shared, generated, diagnostics); + *slot = encode_device_value(Object::Dictionary(shared))?; + } + new.clone() + } + _ => unreachable!("typed PDF resource category"), + }; + resources.set(category.clone(), effective); + } + dictionary.set("Resources", Object::Dictionary(resources)); + objects[id - 1] = encode_device_value(Object::Dictionary(dictionary))?; + } + Ok(()) + } +} + +fn category_fields<'a>( + objects: &'a BTreeMap, NamedObject>, + name: &[u8], +) -> Result<&'a Dictionary, String> { + match objects.get(name).and_then(NamedObject::value) { + Some(Value::Dictionary(fields)) => Ok(fields), + _ => Err(category_error(name)), + } +} + +fn category_fields_mut<'a>( + objects: &'a mut BTreeMap, NamedObject>, + name: &[u8], +) -> Result<&'a mut Dictionary, String> { + objects + .get_mut(name) + .and_then(NamedObject::dictionary_mut) + .ok_or_else(|| category_error(name)) +} + +fn category_error(name: &[u8]) -> String { + format!( + "invalid XDV resource category object @{}", + String::from_utf8_lossy(name) + ) +} + +fn append_missing( + existing: &mut Dictionary, + data: Dictionary, + deferred: bool, + messages: &mut Vec, +) { + for (key, value) in data { + match existing.entry(key) { + Entry::Vacant(entry) => { + entry.insert(value); + } + Entry::Occupied(entry) if !deferred || entry.get() != &value => { + messages.push(format!( + "xdvipdfmx: warning: Object \"{}\" already defined in dict! (ignored)\n", + String::from_utf8_lossy(entry.key()), + )); + } + Entry::Occupied(_) => {} + } + } +} + +fn merge_pdf_entries( + target: &mut PdfDictionary, + additions: &PdfDictionary, + diagnostics: &mut Vec, +) { + for (name, value) in additions { + if let Ok(existing) = target.get(name) { + if !matches!((existing.as_reference(), value.as_reference()), (Ok(left), Ok(right)) if left == right) + { + diagnostics.push(format!( + "xdvipdfmx: warning: Object \"{}\" already defined in dict! (ignored)", + String::from_utf8_lossy(name), + )); + } + } else { + target.set(name.clone(), value.clone()); + } + } +} + +fn pdf_dictionary(bytes: &[u8]) -> Result { + match parse_value(bytes)? { + Object::Dictionary(fields) => Ok(fields), + _ => Err("expected an XDV PDF resource dictionary".into()), + } +} 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 1648335..c9df39e 100644 --- a/crates/texrra-tex-core/src/source_map/pdf_projection.rs +++ b/crates/texrra-tex-core/src/source_map/pdf_projection.rs @@ -20,6 +20,7 @@ pub(super) struct PdfProjection { stack: Vec, units: DisplayUnits, xdv_origin: Option<[i64; 2]>, + xdv_content_scopes: Vec<(DeviceOrigin, [i64; 2])>, height: i64, digits: u8, units_per_bp: f64, @@ -53,6 +54,7 @@ impl PdfProjection { stack: vec![graphics], // The page writer begins with q. units: page.units, xdv_origin, + xdv_content_scopes: Vec::new(), height: page.height, digits: page.pdf.as_ref().map_or(3, |page| page.file.decimal_digits), units_per_bp: 1.0 / page.units.bp(1), @@ -141,10 +143,31 @@ impl PdfProjection { self.text_active = false; } let previous_origin = self.origin; + match mode { + PdfLiteralMode::XdvBeginContent => { + self.save(); + self.xdv_content_scopes.push((previous_origin, [x, y])); + self.move_origin([x, y]); + return None; + } + PdfLiteralMode::XdvEndContent => { + self.restore(); + if let Some((origin, _)) = self.xdv_content_scopes.pop() { + self.origin = origin; + } + return None; + } + _ => {} + } if *mode == PdfLiteralMode::XdvContent { self.save(); } - let special_origin = mode.xdv_origin([x, y], self.xdv_origin.unwrap_or([0, 0])); + let page_origin = self.xdv_origin.unwrap_or([0, 0]); + let special_origin = if *mode == PdfLiteralMode::XdvCode { + Some(self.xdv_content_scopes.last().map_or(page_origin, |&(_, point)| point)) + } else { + mode.xdv_origin([x, y], page_origin) + }; if *mode == PdfLiteralMode::Origin { self.move_origin([x, y]); } else if let Some(point) = special_origin { diff --git a/crates/texrra-tex-core/tests/execution_xetex_profile.rs b/crates/texrra-tex-core/tests/execution_xetex_profile.rs index 08d34ee..9cf2525 100644 --- a/crates/texrra-tex-core/tests/execution_xetex_profile.rs +++ b/crates/texrra-tex-core/tests/execution_xetex_profile.rs @@ -953,3 +953,59 @@ fn xdv_page_dictionaries_and_rectangular_destinations_keep_real_references() { assert_eq!(resolve(&area[2]).as_i64().unwrap(), 10); assert_eq!(resolve(&area[5]).as_i64().unwrap(), 400); } + +#[test] +fn xdv_scoped_code_uses_shared_resource_categories_and_page_defaults() { + use lopdf::{Document, Object, content::Content}; + 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{pdf:obj @shared << >>}% + \special{pdf:obj @soft << /ca 0.25 >>}% + \special{pdf:put @resources << /ExtGState << /Half << /ca 0.5 >> >> >>}% + \special{pdf:put @resources << /ExtGState @shared >>}% + \special{pdf:pageresources << /ExtGState << /Soft @soft >> >>}% + \special{pdf:bcontent}% + \special{pdf:code q /Half gs}% + \kern10pt\special{pdf:code 0 0 10 10 re f Q}% + \special{pdf:econtent}% + \vrule width15pt height1pt} + \shipout\hbox{% + \special{pdf:put @resources << /ExtGState @shared >>}% + \special{pdf:put @shared << /Late << /ca 0.75 >> >>}% + \vrule width20pt height1pt} + \shipout\hbox{% + \special{pdf:pageresources << >>}% + \vrule width25pt height1pt} + \end", + ), + &mut TestDevice, + ) + .unwrap(); + let pages = result.shipout_display_lists().unwrap(); + assert!(pages[0].has_embedded_pdf()); + assert!(pages[1].has_embedded_pdf()); + assert!(!pages[2].has_embedded_pdf()); + let output = shipout_lists_to_native_pdf_document(&pages, result.state.pdf_final_options()).unwrap(); + let pdf = Document::load_mem(&output.bytes).unwrap(); + let ids = pdf.get_pages(); + let resources = |id| pdf.get_object(id).unwrap().as_dict().unwrap() + .get(b"Resources").unwrap().as_dict().unwrap(); + let shared = resources(ids[&1]).get(b"ExtGState").unwrap().as_reference().unwrap(); + assert_eq!(resources(ids[&2]).get(b"ExtGState").unwrap().as_reference().unwrap(), shared); + assert!(!resources(ids[&3]).has(b"ExtGState")); + let fields = pdf.get_object(shared).unwrap().as_dict().unwrap(); + assert!(fields.has(b"Half") && fields.has(b"Soft") && fields.has(b"Late")); + + let operations = Content::decode(&pdf.get_page_content(ids[&1]).unwrap()).unwrap().operations; + let style = operations.iter().position(|op| op.operator == "gs").unwrap(); + assert!(matches!(&operations[style].operands[..], [Object::Name(name)] if name == b"Half")); + assert_eq!(operations[style + 1].operator, "re"); + assert_eq!(operations[style + 2].operator, "f"); +} diff --git a/docs/P2_M1_PROGRESS.md b/docs/P2_M1_PROGRESS.md index 3dfc41e..065b178 100644 --- a/docs/P2_M1_PROGRESS.md +++ b/docs/P2_M1_PROGRESS.md @@ -18,6 +18,38 @@ | W6 会话 | 实施中 | 共享库/CLI 与当前原生文字/数学/规则来源进入公共结果;真实 A4 副本九类/27 revision 与独立干净作业页面/PDF/aux/映射一致,新增数学场景独立参考通过;详细失败/捕获重放及宿主/离线/CLI观察已通过;原子项目版本/已知生成初态及TeX流记录已接通;完整副作用/恢复契约、旧来源和性能仍缺 | | W7 总验收 | 未满足 | 原有和新增测试、原样项目、格式与会话门禁全部通过才能结项 | +## 2026-11-28 XeLaTeX 页面资源与 TikZ 透明叠印 + +`pdf:put @resources` 合并当前页资源,保留已登记的同名条目。 +`pdf:pageresources` 在页末应用并持续到下次设置,可用空字典清除。 +命名类别在多页保持相同的间接对象,输出时并入实际生成的字体和 +其他设备资源。`pdf:bcontent`、`pdf:code`、`pdf:econtent` 用实际 +出页坐标执行局部绘图程序,预览消费同一份 PDF。资源状态随检查点 +保存,来源映射处理新增绘图边界。 +[参考驱动](https://raw.githubusercontent.com/TeX-Live/texlive-source/trunk/texk/dvipdfm-x/spc_pdfm.c) + +真实 XeLaTeX 格式与 CTAN 原样 PGF 3.1.12 编译两页 TikZ 透明 +叠印文档。基线停在 `pdf:bcontent`,候选通过,实际共享透明度、 +颜色空间、两页 144 DPI 彩色像素以及 aux 均与参考一致。 +直接出页对照三页也逐像素一致,核对了共享字典、重复条目、持续 +资源和实际绘制的 Form 流。另三页核对了两个字体进入同一间接 +类别及清除后的字体集合。保留了上游对两种冲突输入的原始失败。 +开发构建与八项定向回归通过。 +[PGF 发布包](https://ctan.org/pkg/pgf) + +三页项目三个修订各复用 1,285 步。修改局部透明度只更新第二页, +从后页修改共享对象只更新实际使用该透明度的第一页,恢复时更新 +前两页。每轮 PDF、测量页、预览、来源映射及 aux 与同版本独立 +全量编译一致。 + +回执位于 `target/p3-xdv-page-resources/receipt.json`,SHA-256 为 +`b641bd78544cb4597456451b338b8ae44958e87c76864118aae1f74a2347db08`。 +下一入口为捕获式 Form。已保存 `forms-next` 两页参考,其中 +`pdf:bxobj` 开始捕获 TeX 字形和带资源的绘图,`pdf:exobj` 封装, +`pdf:uxobj` 与 `pdf:usexobj` 跨页复用。当前原生在首个 +`pdf:bxobj` 明确失败。原样出版矩阵、发布版整体验收及正式 +可见时延继续按原目标执行。 + ## 2026-11-28 XeLaTeX 页字典与矩形跳转目标 原生出页处理 `pdf:put @pages` 和 `pdf:put @thispage`。