diff --git a/crates/texrra-tex-core/src/execution/engine/page.rs b/crates/texrra-tex-core/src/execution/engine/page.rs index ad2311a..2a668c8 100644 --- a/crates/texrra-tex-core/src/execution/engine/page.rs +++ b/crates/texrra-tex-core/src/execution/engine/page.rs @@ -634,12 +634,15 @@ impl Executor { } else if xdv && crate::pdf_device::xdv_paper::Special::parse(&special.bytes).is_some() { xdv_paper_specials.push(shipout.specials.len()); None - } else if xdv && super::specials::xdv_navigation_operand(&special.bytes).is_some() { + } else if xdv && let Some((kind, _)) = super::specials::xdv_navigation_operand(&special.bytes) { + if kind == b"bxobj" && let Some(program) = self.xdv_colors.start_page() { + shipout.xdv_color_steps.insert(graphics_step, program); + } let point = xdv_transform.point( (special.position[0] + horizontal_origin) as f64, (special.position[1] + vertical_origin + b.height) as f64, ).map(|coordinate| coordinate.round() as i64); - xdv_navigation.push((shipout.specials.len(), graphics_step, point)); + xdv_navigation.push((shipout.specials.len(), graphics_step, point, *origin)); None } else if xdv && self.xdv_setup_special(&special)? { None @@ -856,8 +859,8 @@ impl Executor { device.vertical_origin = offset + v_offset; } let delta = [device.horizontal_origin - horizontal_origin, device.vertical_origin - vertical_origin]; - for (index, graphics_step, [x, y]) in xdv_navigation { - self.ship_xdv_navigation( + for (index, graphics_step, [x, y], origin) in xdv_navigation { + if let Some(operation) = self.ship_xdv_navigation( &shipout.specials[index], crate::pdf_device::xdv_object::Position { page: self.shipped_pages + 1, @@ -865,8 +868,13 @@ impl Executor { height: device.page_height, magnification, }, - graphics_step, &mut shipout.pdf_links, files, - )?; + graphics_step, &mut shipout.pdf_links, origin, files, + )? { + shipout.pdf_graphics_steps[graphics_step] = Some(operation); + } + } + if let Some(navigation) = &self.state.xdv_navigation { + navigation.validate_form_boundary().map_err(|error| self.error(error, current))?; } } if xdv && let Some(navigation) = &mut self.state.xdv_navigation diff --git a/crates/texrra-tex-core/src/execution/engine/pdf_form.rs b/crates/texrra-tex-core/src/execution/engine/pdf_form.rs index 071b538..7c364f1 100644 --- a/crates/texrra-tex-core/src/execution/engine/pdf_form.rs +++ b/crates/texrra-tex-core/src/execution/engine/pdf_form.rs @@ -45,6 +45,7 @@ impl Executor { .reserve_form(limit) .map_err(|message| self.error(message, self.current))?; let form = FormUse { + xdv: None, number, width: box_node.width, height: box_node.height, diff --git a/crates/texrra-tex-core/src/execution/engine/pdf_links.rs b/crates/texrra-tex-core/src/execution/engine/pdf_links.rs index 56b4429..e942e73 100644 --- a/crates/texrra-tex-core/src/execution/engine/pdf_links.rs +++ b/crates/texrra-tex-core/src/execution/engine/pdf_links.rs @@ -472,7 +472,9 @@ impl PdfLinkShipout { *matrix = previous; } } - Some(PdfGraphics::Literal { .. } | PdfGraphics::TextBoundary) | None => {} + Some(PdfGraphics::Literal { .. } | PdfGraphics::TextBoundary + | PdfGraphics::XdvFormBegin(_) | PdfGraphics::XdvFormEnd(_) + | PdfGraphics::XdvFormUse { .. }) | None => {} } } LinkPaint::RowStart(row) if !row.horizontal => { diff --git a/crates/texrra-tex-core/src/execution/engine/specials.rs b/crates/texrra-tex-core/src/execution/engine/specials.rs index 8a34eed..67c6428 100644 --- a/crates/texrra-tex-core/src/execution/engine/specials.rs +++ b/crates/texrra-tex-core/src/execution/engine/specials.rs @@ -56,8 +56,9 @@ impl Executor { position: crate::pdf_device::xdv_object::Position, graphics_step: usize, links: &mut crate::pdf_device::links::PageLinks, + origin: Option, files: &mut impl SourceProvider, - ) -> Result<(), Error> { + ) -> Result, Error> { let Some((kind, operands)) = xdv_navigation_operand(&special.bytes) else { return self.fail("missing shipped XDV navigation operands"); }; @@ -66,10 +67,18 @@ impl Executor { operands, position.page, position.coordinates, ).map_err(|error| self.error(error, special.span))?; links.xdv_destinations.push(destination); - return Ok(()); + return Ok(None); } self.reads.insert(Dependency::PdfCatalogState); - let warnings = if matches!(kind, b"docview" | b"outline" | b"pageresources") { + let mut graphics = None; + let warnings = if matches!(kind, b"bxobj" | b"exobj" | b"uxobj") { + let source = origin.unwrap_or(TokenOrigin { span: special.span, invocation: None }); + let navigation = Arc::make_mut(self.state.xdv_navigation.get_or_insert_with(Default::default)); + let (operation, warnings) = navigation.form_special(kind, operands, position, source, self.limits.tokens) + .map_err(|error| self.error(error, special.span))?; + graphics = Some(operation); + Ok(warnings) + } else 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) @@ -100,7 +109,7 @@ impl Executor { files.observe_diagnostic(WriteDestination::TerminalAndLog, &warning) .map_err(|error| self.error(error, special.span))?; } - Ok(()) + Ok(graphics) } pub(super) fn xdv_setup_special( @@ -357,6 +366,9 @@ pub(super) fn xdv_navigation_operand(data: &[u8]) -> Option<(&'static [u8], &[u8 (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"pageresources", b"pageresources"), + (b"bxobj", b"bxobj"), (b"bform", b"bxobj"), (b"beginxobj", b"bxobj"), + (b"exobj", b"exobj"), (b"eform", b"exobj"), (b"endxobj", b"exobj"), + (b"uxobj", b"uxobj"), (b"usexobj", b"uxobj"), ] { if let Some(operands) = xdv_operand(body, name) { return Some((kind, operands)); diff --git a/crates/texrra-tex-core/src/execution/mod.rs b/crates/texrra-tex-core/src/execution/mod.rs index 9e8e78f..55235d9 100644 --- a/crates/texrra-tex-core/src/execution/mod.rs +++ b/crates/texrra-tex-core/src/execution/mod.rs @@ -799,7 +799,7 @@ impl Execution { })?; list.pdf_resources.attributes = form.attributes.clone().into(); forms.push(crate::pdf_device::forms::FormDisplay { - form: form.form, resource_number: form.resource_number, list, + form: form.form, resource_number: form.resource_number, list, xdv: None, }); } if let Event::Shipout(b) = e { @@ -813,6 +813,11 @@ impl Execution { })?); } } + if let Some(navigation) = &self.state.xdv_navigation { + forms.extend(navigation.split_forms(&mut pages).map_err(|message| { + Error::at(&self.sources, self.state.input_profile(), message, Span::default()) + })?); + } if !self.state.pdf_draft_mode() { self.resolve_page_graphics_resources(&mut pages)?; if let Some(navigation) = &self.state.xdv_navigation { diff --git a/crates/texrra-tex-core/src/pdf.rs b/crates/texrra-tex-core/src/pdf.rs index 8aef9a7..c527b61 100755 --- a/crates/texrra-tex-core/src/pdf.rs +++ b/crates/texrra-tex-core/src/pdf.rs @@ -735,6 +735,7 @@ fn page_content( xdv_font_aliases: &BTreeMap, opentype: &BTreeMap>, font_opacities: &BTreeMap, + xdv_form: bool, ) -> Vec { let digits = list.pdf.as_ref().map_or(3, |p| p.file.decimal_digits); let pt = |n: i64| { @@ -778,7 +779,14 @@ fn page_content( pt(-origin.v_offset) )); } - content.move_origin(page_origin, list.units, digits); + if xdv_form { + // Captured XDV content uses device-relative coordinates. Keep the + // logical origin used by glyphs and specials without emitting the + // enclosing sheet's translation into the Form stream. + content.origin.move_to(page_origin, list.units, digits); + } else { + content.move_origin(page_origin, list.units, digits); + } let mut native_text: Option = None; let mut tex_text: Option = None; let mut opentype_text = opentype_fonts::TextState::default(); @@ -1215,6 +1223,14 @@ fn page_content( } DisplayItem::Link { .. } | DisplayItem::PdfTextSpace { .. } => {} DisplayItem::PdfForm { x, y, form } => { + if let Some(placement) = form.xdv { + let [a,b,c,d,e,f] = placement.matrix.map(f64::from_bits); + let tx = px(*x).parse::().expect("formatted XDV x") + e; + let ty = py(*y).parse::().expect("formatted XDV y") + f; + let [a,b,c,d,tx,ty] = [a,b,c,d,tx,ty].map(crate::pdf_image::real); + content.push_str(&format!("q {a} {b} {c} {d} {tx} {ty} cm /Fm{} Do Q\n", form.number)); + continue; + } content.push_str(&format!( "q 1 0 0 1 {} {} cm /Fm{} Do Q\n", px(*x), py(*y + form.depth), form.number, )); @@ -1275,6 +1291,9 @@ fn page_content( PdfGraphics::Literal { .. } | PdfGraphics::TextBoundary => { unreachable!("handled before graphics transforms") } + PdfGraphics::XdvFormBegin(_) | PdfGraphics::XdvFormEnd(_) | PdfGraphics::XdvFormUse { .. } => { + unreachable!("XDV form operations were projected before export") + } } } } @@ -2936,6 +2955,10 @@ fn write_pdf( ); (image.id, object) }).collect(); + for form in forms.iter().filter(|form| form.xdv.is_some()) { + objects.push(Vec::new()); + device_objects.insert(form.form.number, objects.len() as u32); + } let append_xobjects = |list: &DisplayList, xobjects: &mut String| -> Result<(), String> { let images = list .items @@ -3002,12 +3025,24 @@ fn write_pdf( } fonts }; + let mut xdv_forms = Vec::new(); for (index, form) in forms.into_iter().enumerate() { let list = &form.list; let slot = pages.len() + index; let mut xobjects = String::new(); append_xobjects(list, &mut xobjects)?; let fonts = mapped_font_resources(list); + if form.xdv.is_some() { + let mut resources = format!("<< /Font << {fonts} >>"); + if !xobjects.is_empty() { + resources.push_str(&format!(" /XObject << {xobjects} >>")); + } + resources.push_str(" >>"); + let content = page_content(list, list.height, &BTreeMap::new(), faces, &cm_views, + &fallback_font_ids, PageOrigin::default(), &xdv_font_aliases, &opentype, &BTreeMap::new(), true); + xdv_forms.push((form, resources, content)); + continue; + } let digits = list.pdf.as_ref().map_or(3, |pdf| pdf.file.decimal_digits); let width = crate::pdf_device::print_sp(form.form.width, digits); let height = crate::pdf_device::print_sp(form.form.height + form.form.depth, digits); @@ -3036,7 +3071,7 @@ fn write_pdf( let font_opacities = remapped.as_ref().map_or(&no_font_opacity, |r| &r.font_opacities[slot]); let content = page_content( list, list.height, &names, faces, &cm_views, - &fallback_font_ids, PageOrigin::default(), &xdv_font_aliases, &opentype, font_opacities, + &fallback_font_ids, PageOrigin::default(), &xdv_font_aliases, &opentype, font_opacities, false, ); objects[device_objects[&form.form.number] as usize - 1] = objects::stream_bytes( &entries, &content, list.pdf.as_ref().map_or(0, |pdf| pdf.stream_compression), @@ -3227,6 +3262,7 @@ fn write_pdf( &xdv_font_aliases, &opentype, font_opacities, + false, ); let stream = objects::stream("", &content, list.pdf.as_ref().map_or(0, |p| p.stream_compression)); if let Some(id) = content_slot { @@ -3565,7 +3601,7 @@ fn write_pdf( destination.collect_references(&mut pending); } } - let named_objects = xdv_objects.reserve_objects(pending, &mut objects)?; + let named_objects = xdv_objects.reserve_objects(pending, &mut objects, &device_objects)?; let references = crate::pdf_device::xdv_object::References { pages: &navigation.pages, named: &named_objects, @@ -3573,6 +3609,10 @@ fn write_pdf( 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 { + for (form, resources, content) in xdv_forms { + let id = device_objects[&form.form.number] as usize; + objects[id - 1] = xdv.write_form(form, resources.as_bytes(), &content, &references, &mut objects, diagnostics)?; + } xdv.write_page_dictionaries(pages, &references, &mut objects)?; xdv.write_page_resources(&references, &mut objects, diagnostics)?; } diff --git a/crates/texrra-tex-core/src/pdf_device/forms.rs b/crates/texrra-tex-core/src/pdf_device/forms.rs index b324ffc..883fd26 100644 --- a/crates/texrra-tex-core/src/pdf_device/forms.rs +++ b/crates/texrra-tex-core/src/pdf_device/forms.rs @@ -10,6 +10,20 @@ pub struct FormUse { pub width: i64, pub height: i64, pub depth: i64, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub(crate) xdv: Option, +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)] +pub(crate) struct XdvPlacement { + pub(crate) matrix: [u64; 6], + pub(crate) bounds: [i64; 4], +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) struct XdvCanvas { + pub(crate) anchor: [i64; 2], + pub(crate) bounds: [i64; 4], } #[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)] @@ -45,4 +59,5 @@ pub struct FormDisplay { pub form: FormUse, pub resource_number: u32, pub list: DisplayList, + pub(crate) xdv: Option, } diff --git a/crates/texrra-tex-core/src/pdf_device/graphics.rs b/crates/texrra-tex-core/src/pdf_device/graphics.rs index 7b753b2..a799511 100644 --- a/crates/texrra-tex-core/src/pdf_device/graphics.rs +++ b/crates/texrra-tex-core/src/pdf_device/graphics.rs @@ -46,6 +46,13 @@ pub enum PdfGraphics { SaveMatrix(PdfMatrix), /// An XDV special switched the device from text to graphics mode. TextBoundary, + XdvFormBegin(u32), + XdvFormEnd(u32), + XdvFormUse { + number: u32, + options: super::xdv_navigation::FormOptions, + source: crate::execution::TokenOrigin, + }, } #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)] 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 d5b4609..707ab04 100644 --- a/crates/texrra-tex-core/src/pdf_device/xdv_navigation.rs +++ b/crates/texrra-tex-core/src/pdf_device/xdv_navigation.rs @@ -14,6 +14,9 @@ use super::xdv_object::{ mod named_objects; mod page_dictionaries; mod page_resources; +mod forms; +pub use forms::FormOptions; +use forms::Forms; use page_resources::PageResources; use page_dictionaries::PageDictionaries; pub(crate) use named_objects::ObjectCommand; @@ -31,6 +34,8 @@ pub(crate) struct Navigation { page_dictionaries: PageDictionaries, #[serde(default, skip_serializing_if = "PageResources::is_empty")] page_resources: PageResources, + #[serde(default, skip_serializing_if = "Forms::is_empty")] + forms: Forms, } #[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)] @@ -123,12 +128,14 @@ impl Navigation { } self.page_dictionaries.collect_references(pending); self.page_resources.collect_references(pending); + self.forms.collect_references(pending); } pub(crate) fn reserve_objects<'a>( &'a self, mut pending: Vec<&'a [u8]>, objects: &mut Vec>, + device_objects: &BTreeMap, ) -> Result, u32>, String> { let mut names = BTreeSet::new(); while let Some(name) = pending.pop() { @@ -137,6 +144,9 @@ impl Navigation { } } names.into_iter().map(|name| { + if let Some(number) = self.forms.number(name) { + return Ok((name.to_vec(), *device_objects.get(&number).ok_or("unallocated XDV form reference")?)); + } 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)) @@ -151,6 +161,9 @@ impl Navigation { diagnostics: &mut Vec, ) -> Result<(), String> { for (name, &id) in references.named { + if self.forms.number(name).is_some() { + continue; + } objects[id as usize - 1] = if let Some(object) = self.objects.get(name) { object.pdf(references, compression)? } else { 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 new file mode 100644 index 0000000..7f405d1 --- /dev/null +++ b/crates/texrra-tex-core/src/pdf_device/xdv_navigation/forms.rs @@ -0,0 +1,458 @@ +use std::collections::BTreeMap; + +use lopdf::{Dictionary as PdfDictionary, Object}; +use serde::{Deserialize, Serialize}; + +use crate::{ + execution::TokenOrigin, + pdf_device::{ + Affine, DeviceOrigin, PdfGraphics, + forms::{FormDisplay, FormUse, XdvCanvas, XdvPlacement}, + xdv_image::{length, number}, + xdv_page_origin, + }, + provenance::PaintSource, + render::{DisplayItem, DisplayList}, +}; + +use super::super::xdv_object::{identifier, trim_pdf}; +use super::{ + Dictionary, Navigation, Position, References, dictionary, encode_device_value, + output_dictionary, page_resources::merge_output_resources, parse_value, +}; + +const SP_PER_BP: f64 = 65536.0 * 803.0 / 800.0; + +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)] +pub struct FormOptions { + bbox: Option<[u64; 4]>, + size: [Option; 3], + scale: [Option; 2], + offset: [u64; 2], + rotation: u64, +} + +impl FormOptions { + fn parse(input: &[u8], magnification: i32) -> Result { + let mut words = std::str::from_utf8(input) + .map_err(|_| "invalid XDV form options")? + .split_ascii_whitespace() + .peekable(); + let mut options = Self::default(); + while let Some(word) = words.next() { + match word { + "bbox" => { + let mut bounds = [0; 4]; + for entry in &mut bounds { + *entry = number(words.next())?.to_bits(); + } + options.bbox = Some(bounds); + } + "width" | "height" | "depth" => { + let index = match word { + "width" => 0, + "height" => 1, + _ => 2, + }; + options.size[index] = Some(length(&mut words, magnification)?.to_bits()); + } + "xoffset" | "yoffset" => { + options.offset[usize::from(word == "yoffset")] = + length(&mut words, magnification)?.to_bits(); + } + "scale" => options.scale = [Some(number(words.next())?.to_bits()); 2], + "xscale" | "yscale" => { + options.scale[usize::from(word == "yscale")] = + Some(number(words.next())?.to_bits()); + } + "rotate" => options.rotation = number(words.next())?.to_bits(), + _ => return Err(format!("unsupported XDV form option {word}")), + } + } + Ok(options) + } + + fn capture_bounds(self) -> Result<[i64; 4], String> { + let [width, height, depth] = self.size.map(|v| v.map_or(0.0, f64::from_bits)); + let bbox = self + .bbox + .map_or([0.0, -depth, width, height], |v| v.map(f64::from_bits)); + let [left, bottom, right, top] = checked_box(bbox)?; + if left >= right || bottom >= top { + return Err("XDV form bounding box must have positive dimensions".into()); + } + Ok([left, bottom, right, top]) + } + + fn place(self, number: u32, bounds: [i64; 4]) -> Result { + if self.bbox.is_some() { + return Err("unsupported XDV form placement bounding box".into()); + } + let [left, bottom, right, top] = bounds.map(|p| p as f64 / SP_PER_BP); + let natural = [right - left, top - bottom]; + let [width, height, depth] = self.size.map(|v| v.map(f64::from_bits)); + let vertical = height + .or(depth.map(|_| 0.0)) + .map(|h| h + depth.unwrap_or(0.0)); + let requested = [ + width.map(|w| w / natural[0]), + vertical.map(|h| h / natural[1]), + ]; + let scales = self.scale.map(|v| v.map(f64::from_bits)); + let sx = requested[0].or(scales[0]).or(requested[1]).unwrap_or(1.0); + let sy = requested[1].or(scales[1]).or(requested[0]).unwrap_or(1.0); + if sx == 0.0 || sy == 0.0 { + return Err("zero XDV form placement scale".into()); + } + let [dx, dy] = self.offset.map(f64::from_bits); + let (sin, cos) = f64::from_bits(self.rotation).to_radians().sin_cos(); + let matrix = [ + cos * sx, + sin * sx, + -sin * sy, + cos * sy, + dx, + dy + vertical.map_or(0.0, |_| -depth.unwrap_or(0.0) - bottom * sy), + ]; + let transform = Affine(matrix); + let mut extent = [ + f64::INFINITY, + f64::INFINITY, + f64::NEG_INFINITY, + f64::NEG_INFINITY, + ]; + for [x, y] in [[left, bottom], [left, top], [right, bottom], [right, top]] { + let [x, y] = transform.point(x, y); + extent = [ + extent[0].min(x), + extent[1].min(y), + extent[2].max(x), + extent[3].max(y), + ]; + } + let bounds = checked_box(extent)?; + Ok(FormUse { + number, + width: bounds[2] - bounds[0], + height: bounds[3], + depth: -bounds[1], + xdv: Some(XdvPlacement { + matrix: matrix.map(f64::to_bits), + bounds, + }), + }) + } +} + +fn to_sp(value: f64) -> Result { + let value = (value * SP_PER_BP).round(); + if !(-1_073_741_823.0..=1_073_741_823.0).contains(&value) { + return Err("XDV form dimension out of range".into()); + } + Ok(value as i64) +} + +fn checked_box(values: [f64; 4]) -> Result<[i64; 4], String> { + let [a, b, c, d] = values.map(to_sp); + Ok([a?, b?, c?, d?]) +} + +#[derive(Clone, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)] +pub(super) struct Forms { + names: BTreeMap, u32>, + definitions: BTreeMap, + active: Vec, +} + +#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)] +struct Active { + number: u32, + bounds: [i64; 4], + outer_resources: Dictionary, +} + +#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)] +struct Definition { + bounds: [i64; 4], + attributes: Dictionary, + resources: Dictionary, +} + +impl Forms { + pub(super) fn is_empty(&self) -> bool { + self.names.is_empty() + } + + pub(super) fn number(&self, name: &[u8]) -> Option { + self.names.get(name).copied() + } + + fn register(&mut self, name: &[u8]) -> Result { + if let Some(number) = self.number(name) { + return Ok(number); + } + let number = u32::try_from(self.names.len() + 1).map_err(|_| "XDV form limit exceeded")?; + self.names.insert(name.to_vec(), number); + Ok(number) + } + + pub(super) fn collect_references<'a>(&'a self, pending: &mut Vec<&'a [u8]>) { + for value in self + .definitions + .values() + .flat_map(|entry| entry.attributes.values().chain(entry.resources.values())) + { + value.collect_references(pending); + } + } +} + +impl Navigation { + pub(crate) fn form_special( + &mut self, + kind: &[u8], + input: &[u8], + position: Position, + source: TokenOrigin, + limit: usize, + ) -> Result<(PdfGraphics, Vec), String> { + self.add_payload(input.len(), limit)?; + if kind == b"exobj" { + let attributes = if trim_pdf(input).is_empty() { + Dictionary::new() + } else { + dictionary(input, position)? + }; + let form = self + .forms + .active + .pop() + .ok_or("XDV form capture was not started")?; + let warnings = self.merge_resources((*self.page_resources.defaults).clone(), true)?; + let resources = + std::mem::replace(&mut self.page_resources.current, form.outer_resources); + self.forms.definitions.insert( + form.number, + Definition { + bounds: form.bounds, + attributes, + resources, + }, + ); + return Ok((PdfGraphics::XdvFormEnd(form.number), warnings)); + } + let (name, rest) = identifier(input)?; + let options = FormOptions::parse(rest, position.magnification)?; + let number = self.forms.register(name)?; + let command = if kind == b"bxobj" { + if self.forms.definitions.contains_key(&number) + || self.forms.active.iter().any(|form| form.number == number) + || self.objects.contains_key(name) + { + return Err("duplicate XDV form definition".into()); + } + if self.forms.active.len() >= 64 { + return Err("XDV form nesting limit exceeded".into()); + } + let bounds = options.capture_bounds()?; + let outer_resources = std::mem::take(&mut self.page_resources.current); + self.forms.active.push(Active { + number, + bounds, + outer_resources, + }); + PdfGraphics::XdvFormBegin(number) + } else { + PdfGraphics::XdvFormUse { + number, + options, + source, + } + }; + Ok((command, Vec::new())) + } + + pub(crate) fn validate_form_boundary(&self) -> Result<(), &'static str> { + if self.forms.active.is_empty() { + Ok(()) + } else { + Err("unclosed XDV form capture at shipout") + } + } + + pub(crate) fn split_forms( + &self, + pages: &mut [DisplayList], + ) -> Result, String> { + if self.forms.is_empty() { + return Ok(Vec::new()); + } + let mut forms = Vec::new(); + for page in pages { + let mut captures: Vec<(u32, XdvCanvas, DisplayList)> = Vec::new(); + let mut sources = std::mem::take(&mut page.sources); + 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 packet = packets.as_mut().and_then(|packets| packets.remove(&index)); + let (item, origin) = match item { + DisplayItem::PdfGraphics { + x, + y, + operation: PdfGraphics::XdvFormBegin(number), + } => { + let bounds = self.forms.definitions[&number].bounds; + let list = DisplayList { + width: page.width, + height: page.height, + units: page.units, + magnification: page.magnification, + pdf: page.pdf.clone(), + pdf_font_bindings: page.pdf_font_bindings.clone(), + prepared_virtual_glyphs: packets.as_ref().map(|_| BTreeMap::new()), + ..Default::default() + }; + captures.push(( + number, + XdvCanvas { + anchor: [x, y], + bounds, + }, + list, + )); + continue; + } + DisplayItem::PdfGraphics { + operation: PdfGraphics::XdvFormEnd(expected), + .. + } => { + let (number, geometry, list) = + captures.pop().ok_or("missing started XDV form")?; + if number != expected { + return Err("mismatched XDV form capture".into()); + } + let form = FormOptions::default().place(number, geometry.bounds)?; + forms.push(FormDisplay { + form, + resource_number: 0, + list, + xdv: Some(geometry), + }); + continue; + } + DisplayItem::PdfGraphics { + x, + y, + operation: + PdfGraphics::XdvFormUse { + number, + options, + source, + }, + } => { + let bounds = self + .forms + .definitions + .get(&number) + .ok_or("referenced XDV form is undefined")? + .bounds; + let form = options.place(number, bounds)?; + ( + DisplayItem::PdfForm { x, y, form }, + Some(PaintSource::token(source)), + ) + } + item => (item, origin), + }; + let output = if let Some((_, _, form)) = captures.last_mut() { + form + } else { + &mut *page + }; + if let Some(source) = origin { + output.sources.insert(output.items.len(), source); + } + if let Some(packet) = packet { + output + .prepared_virtual_glyphs + .as_mut() + .unwrap() + .insert(output.items.len(), packet); + } + output.items.push(item); + } + if !captures.is_empty() { + return Err("incomplete XDV form display list".into()); + } + } + Ok(forms) + } + + pub(crate) fn write_form( + &self, + form: &FormDisplay, + resources: &[u8], + content: &[u8], + references: &References<'_>, + objects: &mut [Vec], + diagnostics: &mut Vec, + ) -> Result, String> { + let geometry = form.xdv.expect("XDV form geometry"); + let list = &form.list; + let magnification = f64::from(list.magnification) / 1000.0; + let scale = magnification / SP_PER_BP; + let digits = list.pdf.as_ref().map_or(3, |pdf| pdf.file.decimal_digits); + let mut origin = DeviceOrigin::default(); + origin.move_to( + xdv_page_origin(list.units, list.height, list.magnification), + list.units, + digits, + ); + let [x, y] = geometry.anchor; + let anchor = origin + .move_to([x, list.height - y], list.units, digits) + .unwrap_or([0, 0]) + .map(|value| value as f64 * magnification / 10f64.powi(i32::from(digits))); + let round = |value: f64| (value * 1000.0).round() / 1000.0; + let mut attributes = PdfDictionary::new(); + attributes.set("Type", Object::Name(b"XObject".to_vec())); + attributes.set("Subtype", Object::Name(b"Form".to_vec())); + attributes.set("FormType", 1); + let bbox = geometry + .bounds + .into_iter() + .enumerate() + .map(|(axis, n)| Object::Real(round(anchor[axis % 2] + scale * n as f64))) + .collect(); + attributes.set("BBox", Object::Array(bbox)); + attributes.set( + "Matrix", + Object::Array( + [1.0, 0.0, 0.0, 1.0, round(-anchor[0]), round(-anchor[1])] + .map(Object::Real) + .into(), + ), + ); + let definition = &self.forms.definitions[&form.form.number]; + for (key, value) in &output_dictionary(&definition.attributes, references)? { + attributes.set(key.clone(), value.clone()); + } + let Object::Dictionary(mut resources) = parse_value(resources)? else { + unreachable!("generated XDV form resources"); + }; + merge_output_resources( + &mut resources, + &definition.resources, + references, + objects, + diagnostics, + )?; + attributes.set("Resources", Object::Dictionary(resources)); + let encoded = encode_device_value(Object::Dictionary(attributes))?; + Ok(crate::pdf::objects::stream_bytes( + &encoded[2..encoded.len() - 2], + content, + list.pdf.as_ref().map_or(0, |pdf| pdf.stream_compression), + )) + } +} 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 index 8675f3a..1e42015 100644 --- 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 @@ -11,8 +11,8 @@ use super::{ #[derive(Clone, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)] pub(super) struct PageResources { - current: Dictionary, - defaults: Arc, + pub(super) current: Dictionary, + pub(super) defaults: Arc, pages: BTreeMap, } @@ -58,7 +58,7 @@ impl Navigation { Ok(messages) } - fn merge_resources( + pub(super) fn merge_resources( &mut self, additions: Dictionary, deferred: bool, @@ -131,36 +131,7 @@ impl Navigation { .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); - } + merge_output_resources(&mut resources, fields, references, objects, diagnostics)?; dictionary.set("Resources", Object::Dictionary(resources)); objects[id - 1] = encode_device_value(Object::Dictionary(dictionary))?; } @@ -168,6 +139,46 @@ impl Navigation { } } +pub(super) fn merge_output_resources( + resources: &mut PdfDictionary, + fields: &Dictionary, + references: &References<'_>, + objects: &mut [Vec], + diagnostics: &mut Vec, +) -> Result<(), String> { + 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); + } + Ok(()) +} + fn category_fields<'a>( objects: &'a BTreeMap, NamedObject>, name: &[u8], diff --git a/crates/texrra-tex-core/src/render.rs b/crates/texrra-tex-core/src/render.rs index 7037ff2..29c8045 100755 --- a/crates/texrra-tex-core/src/render.rs +++ b/crates/texrra-tex-core/src/render.rs @@ -813,6 +813,8 @@ impl DisplayList { use crate::pdf_device::PdfGraphics; match operation { PdfGraphics::TextBoundary => {} + PdfGraphics::XdvFormBegin(_) | PdfGraphics::XdvFormEnd(_) | + PdfGraphics::XdvFormUse { .. } => unreachable!("projected XDV form"), PdfGraphics::Literal { .. } => unreachable!("PDF literal requires PDF rendering"), PdfGraphics::Save | PdfGraphics::Matrix(_) | PdfGraphics::SaveMatrix(_) => { if matches!(operation, PdfGraphics::Save | PdfGraphics::SaveMatrix(_)) { diff --git a/crates/texrra-tex-core/src/source_map.rs b/crates/texrra-tex-core/src/source_map.rs index 550d0d5..2ebd796 100644 --- a/crates/texrra-tex-core/src/source_map.rs +++ b/crates/texrra-tex-core/src/source_map.rs @@ -344,6 +344,8 @@ impl SourceMap { } match operation { PdfGraphics::Literal { .. } | PdfGraphics::TextBoundary => {} + PdfGraphics::XdvFormBegin(_) | PdfGraphics::XdvFormEnd(_) | + PdfGraphics::XdvFormUse { .. } => unreachable!("projected XDV form"), PdfGraphics::Save => graphics_stack.push(transform), PdfGraphics::Matrix(matrix) | PdfGraphics::SaveMatrix(matrix) => { if matches!(operation, PdfGraphics::SaveMatrix(_)) { @@ -471,11 +473,11 @@ impl SourceMap { )), DisplayItem::PdfForm { x, y, form } => Some(( PaintKind::PdfForm { number: form.number }, - Bounds { - x: *x, - y: *y - form.height, - width: form.width, - height: form.height + form.depth, + if let Some(placement) = form.xdv { + let [left, bottom, right, top] = placement.bounds; + Bounds { x: *x + left, y: *y - top, width: right - left, height: top - bottom } + } else { + Bounds { x: *x, y: *y - form.height, width: form.width, height: form.height + form.depth } }, )), DisplayItem::PdfImage { 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 c9df39e..57086e4 100644 --- a/crates/texrra-tex-core/src/source_map/pdf_projection.rs +++ b/crates/texrra-tex-core/src/source_map/pdf_projection.rs @@ -215,6 +215,8 @@ impl PdfProjection { }; self.concatenate(matrix.about(x as f64, y as f64, false)); } + PdfGraphics::XdvFormBegin(_) | PdfGraphics::XdvFormEnd(_) | + PdfGraphics::XdvFormUse { .. } => unreachable!("projected XDV form"), PdfGraphics::Literal { .. } | PdfGraphics::TextBoundary => { unreachable!("handled before graphics transforms") } diff --git a/crates/texrra-tex-core/tests/execution_xetex_profile.rs b/crates/texrra-tex-core/tests/execution_xetex_profile.rs index 9cf2525..1581410 100644 --- a/crates/texrra-tex-core/tests/execution_xetex_profile.rs +++ b/crates/texrra-tex-core/tests/execution_xetex_profile.rs @@ -1009,3 +1009,48 @@ fn xdv_scoped_code_uses_shared_resource_categories_and_page_defaults() { assert_eq!(operations[style + 1].operator, "re"); assert_eq!(operations[style + 2].operator, "f"); } + +#[test] +fn xdv_form_capture_isolated_and_reused_as_one_indirect_object() { + use lopdf::Document; + use texrra_tex_core::{pdf::shipout_lists_to_native_pdf_document, render::DisplayItem}; + + 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:bxobj @box width 30pt height 20pt}% + \special{pdf:put @resources << /ExtGState << /A << /ca 0.5 >> >> >>}% + \special{pdf:bcontent}\special{pdf:code q /A gs 0 0 10 10 re f Q}% + \special{pdf:econtent}% + \hbox to0pt{\vrule width5pt height7pt\hss}% + \special{pdf:exobj << /Group << /S /Transparency >> >>}% + \special{pdf:put @catalog << /Captured @box >>}% + \special{pdf:uxobj @box}} + \shipout\hbox{\kern20pt\special{pdf:usexobj @box}} + \end"), + &mut TestDevice, + ) + .unwrap(); + let pages = result.shipout_display_lists().unwrap(); + assert_eq!(pages[0].forms.len(), 1); + assert!(pages[0].forms[0].list.items.iter().any(|item| matches!(item, DisplayItem::Rule { .. }))); + assert!(!pages[0].items.iter().any(|item| matches!(item, DisplayItem::Rule { .. }))); + let output = shipout_lists_to_native_pdf_document(&pages, result.state.pdf_final_options()).unwrap(); + let pdf = Document::load_mem(&output.bytes).unwrap(); + let object = |page| pdf.get_object(page).unwrap().as_dict().unwrap() + .get(b"Resources").unwrap().as_dict().unwrap() + .get(b"XObject").unwrap().as_dict().unwrap() + .get(b"Fm1").unwrap().as_reference().unwrap(); + let ids = pdf.get_pages(); + let form = object(ids[&1]); + assert_eq!(object(ids[&2]), form); + assert_eq!(pdf.catalog().unwrap().get(b"Captured").unwrap().as_reference().unwrap(), form); + let stream = pdf.get_object(form).unwrap().as_stream().unwrap(); + assert_eq!(stream.dict.get(b"Subtype").unwrap().as_name().unwrap(), b"Form"); + let resources = stream.dict.get(b"Resources").unwrap().as_dict().unwrap(); + assert!(resources.get(b"ExtGState").unwrap().as_dict().unwrap().has(b"A")); + assert!(stream.dict.get(b"Group").unwrap().as_dict().unwrap().has(b"S")); +} diff --git a/docs/P2_M1_PROGRESS.md b/docs/P2_M1_PROGRESS.md index 065b178..6b1d992 100644 --- a/docs/P2_M1_PROGRESS.md +++ b/docs/P2_M1_PROGRESS.md @@ -18,6 +18,36 @@ | W6 会话 | 实施中 | 共享库/CLI 与当前原生文字/数学/规则来源进入公共结果;真实 A4 副本九类/27 revision 与独立干净作业页面/PDF/aux/映射一致,新增数学场景独立参考通过;详细失败/捕获重放及宿主/离线/CLI观察已通过;原子项目版本/已知生成初态及TeX流记录已接通;完整副作用/恢复契约、旧来源和性能仍缺 | | W7 总验收 | 未满足 | 原有和新增测试、原样项目、格式与会话门禁全部通过才能结项 | +## 2026-11-28 XeLaTeX 捕获式 PDF Form 与 TikZ 渐变 + +出页时执行 `pdf:bxobj`、`pdf:exobj` 和 `pdf:uxobj`,把实际 +TeX 字形、规则和绘图捕获到 PDF Form。每层捕获保有自己的边界、 +局部资源、内容和来源。放置、跨页前向引用和其他 PDF 字典共享 +同一间接对象。捕获的初始颜色来自设备状态,持续的页面资源按 +捕获边界合并。PDF 导出复用现有字体与绘图资源。 +[参考驱动](https://raw.githubusercontent.com/TeX-Live/texlive-source/trunk/texk/dvipdfm-x/spc_pdfm.c) + +原样 CTAN PGF 3.1.12 与真实 XeLaTeX 格式编译两页 TikZ 渐变。 +另两组原语覆盖字形与绘图捕获、跨页放置、嵌套及继承颜色。 +三组共六页,144 DPI 彩色图逐像素一致。前两组的 Form 引用、 +资源和几何对照通过,article 的 aux 字节一致。首版 Form 坐标 +舍入造成的 114 个边缘像素差异随证据保留,统一设备坐标后归零。 +开发构建与九项定向回归通过。 + +三页会话经历三次修订,各复用 1,130 步。从后页修改前向 Form +更新两个使用页,移动第 2 页放置只更新该页,恢复更新前两页。 +每轮 PDF、测量页、预览、来源映射和 aux 与独立全量编译一致。 + +嵌套 Form 同时显式指定宽、高、深时,已复现纵向缩放差异。样例 +参考矩阵的纵向因子为 0.80132,原生为 1.428570870。下一步按 +参考设备的 Form 固有边界、深度与放置变换完善尺寸语义。显式 +放置 bbox 仍未接入。该失败保存在 `nested-geometry.log`。 +[参考放置逻辑](https://raw.githubusercontent.com/TeX-Live/texlive-source/e49735c7ed1aa2ed9c2e68e6632d27f20d42eca7/texk/dvipdfm-x/pdfximage.c) + +回执在 `target/p3-xdv-captured-forms/receipt.json`,SHA-256 为 +`3f857f8958b9e858993bb5c08141d8cbd6d9e0d86e95ab32cc173e6191c6f919`。原样出版模板矩阵、发布版整体验收及 100 ms +可见延迟门槛继续按总目标执行。 + ## 2026-11-28 XeLaTeX 页面资源与 TikZ 透明叠印 `pdf:put @resources` 合并当前页资源,保留已登记的同名条目。