diff --git a/crates/texrra-tex-core/src/execution/device.rs b/crates/texrra-tex-core/src/execution/device.rs index 1ed37e3..4e60cb0 100644 --- a/crates/texrra-tex-core/src/execution/device.rs +++ b/crates/texrra-tex-core/src/execution/device.rs @@ -29,6 +29,8 @@ pub struct NativeShipout { pub(super) pdf_text_spaces: Option, #[serde(default, skip_serializing_if = "pdf_resource_entries_empty")] pub(super) pdf_resource_entries: Arc<[u8]>, + #[serde(default, skip_serializing_if = "pdf_resource_entries_empty")] + pub(super) pdf_page_attributes: Arc<[u8]>, #[serde(default, skip_serializing_if = "crate::pdf_device::links::PageLinks::is_empty")] pub(super) pdf_links: crate::pdf_device::links::PageLinks, } @@ -48,6 +50,7 @@ impl NativeShipout { pdf_text_spaces: self.pdf_text_spaces.clone(), pdf_resources: crate::pdf_device::page_resources::PageResources { entries: self.pdf_resource_entries.clone(), + attributes: self.pdf_page_attributes.clone(), ..Default::default() }, ..Default::default() diff --git a/crates/texrra-tex-core/src/execution/engine/device.rs b/crates/texrra-tex-core/src/execution/engine/device.rs index bae1eee..324076f 100644 --- a/crates/texrra-tex-core/src/execution/engine/device.rs +++ b/crates/texrra-tex-core/src/execution/engine/device.rs @@ -1,10 +1,25 @@ use super::*; use crate::pdf_device::{PdfFileOptions, PdfPageData}; impl Executor { + pub(super) fn pdf_token_parameter_bytes( + &mut self, + parameter: TokenParameter, + ) -> Result, Error> { + self.reads.insert(Dependency::TokenParameter(parameter)); + match self.state.token_parameter(parameter).cloned() { + Some(tokens) => self.pdf_token_bytes(&tokens), + None => Ok(Vec::new()), + } + } + pub(super) fn validate_pdf_final_state(&mut self) -> Result<(), Error> { if let Some(options) = self.state.pdf_file_options.clone() { self.reads.insert(Dependency::GlyphUnicode); self.read_parameter(Parameter::Pdfgentounicode); + if self.shipped_pages != 0 { + self.state.pdf_pages_attributes = + self.pdf_token_parameter_bytes(TokenParameter::Pdfpagesattr)?; + } self.reads.insert(Dependency::PdfFileState); let mode = self.read_parameter(Parameter::Pdfoutput).width(); if self.state.output_mode_set != Some(mode) { diff --git a/crates/texrra-tex-core/src/execution/engine/page.rs b/crates/texrra-tex-core/src/execution/engine/page.rs index 34a71df..1214806 100644 --- a/crates/texrra-tex-core/src/execution/engine/page.rs +++ b/crates/texrra-tex-core/src/execution/engine/page.rs @@ -264,16 +264,13 @@ impl Executor { }; self.trace_shipout(&b, files)?; let current = self.current; - let pdf_resource_entries = if device.pdf.is_some() { - let parameter = TokenParameter::Pdfpageresources; - self.reads.insert(Dependency::TokenParameter(parameter)); - if let Some(tokens) = self.state.token_parameter(parameter).cloned() { - self.pdf_token_bytes(&tokens)?.into() - } else { - Default::default() - } + let (pdf_resource_entries, pdf_page_attributes) = if device.pdf.is_some() { + ( + self.pdf_token_parameter_bytes(TokenParameter::Pdfpageresources)?.into(), + self.pdf_token_parameter_bytes(TokenParameter::Pdfpageattr)?.into(), + ) } else { - Default::default() + (Default::default(), Default::default()) }; let pdf_color_start = if device.pdf.is_some() { self.pdf_colors.start_page() @@ -426,6 +423,7 @@ impl Executor { pdf_graphics_steps, pdf_text_spaces, pdf_resource_entries, + pdf_page_attributes, pdf_links, }))); self.statistics_after_shipout(before, files)?; diff --git a/crates/texrra-tex-core/src/execution/format_image.rs b/crates/texrra-tex-core/src/execution/format_image.rs index 9b1f8f7..13ed277 100644 --- a/crates/texrra-tex-core/src/execution/format_image.rs +++ b/crates/texrra-tex-core/src/execution/format_image.rs @@ -8,7 +8,7 @@ use std::{ sync::{Arc, Mutex, OnceLock, Weak}, }; -const SCHEMA: u32 = 42; +const SCHEMA: u32 = 43; const COMPATIBLE_SCHEMAS: [u32; 12] = [27, 28, 31, 32, 33, 34, 35, 36, 37, 38, 39, SCHEMA]; const ENGINE: &str = concat!("texrra-native/", env!("CARGO_PKG_VERSION")); diff --git a/crates/texrra-tex-core/src/execution/hooks.rs b/crates/texrra-tex-core/src/execution/hooks.rs index e2709e4..6f8c097 100644 --- a/crates/texrra-tex-core/src/execution/hooks.rs +++ b/crates/texrra-tex-core/src/execution/hooks.rs @@ -16,6 +16,8 @@ pub enum TokenParameter { Errhelp, Everycr, Pdfpageresources, + Pdfpageattr, + Pdfpagesattr, } impl TokenParameter { pub const ALL: &'static [Self] = &[ @@ -30,6 +32,8 @@ impl TokenParameter { Self::Errhelp, Self::Everycr, Self::Pdfpageresources, + Self::Pdfpageattr, + Self::Pdfpagesattr, ]; pub fn name(self) -> String { format!("{self:?}").to_ascii_lowercase() diff --git a/crates/texrra-tex-core/src/execution/mod.rs b/crates/texrra-tex-core/src/execution/mod.rs index 567c5ec..7ce5472 100644 --- a/crates/texrra-tex-core/src/execution/mod.rs +++ b/crates/texrra-tex-core/src/execution/mod.rs @@ -700,13 +700,16 @@ impl Execution { let empty = PdfObjects::default(); let objects = self.state.pdf_objects.as_deref().unwrap_or(&empty); let mut font_affects_paint = BTreeMap::new(); - for page in pages { + for page in pages.iter_mut() { let states = page.items.iter().filter_map(|item| match item { DisplayItem::PdfColor(program) => Some(&program.graphics_states), _ => None, }).flatten().cloned().collect(); page.pdf_resources = PageResources::from_page( - page.pdf_resources.entries.clone(), &states, objects, + page.pdf_resources.entries.clone(), + page.pdf_resources.attributes.clone(), + &states, + objects, ).map_err(|message| Error::at( &self.sources, self.state.input_profile(), message, Span::default(), ))?; @@ -737,7 +740,10 @@ impl Execution { } } } - Ok(()) + crate::pdf_device::page_attributes::resolve(pages, &self.state.pdf_pages_attributes, objects) + .map_err(|message| Error::at( + &self.sources, self.state.input_profile(), message, Span::default(), + )) } /// Export the paragraphs already measured during token execution. No text diff --git a/crates/texrra-tex-core/src/execution/state.rs b/crates/texrra-tex-core/src/execution/state.rs index 72770df..62749fc 100644 --- a/crates/texrra-tex-core/src/execution/state.rs +++ b/crates/texrra-tex-core/src/execution/state.rs @@ -646,6 +646,8 @@ pub struct State { #[serde(default, skip_serializing_if = "Option::is_none")] pub(super) pdf_objects: Option>, pub(super) pdf_info: Vec, + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub(super) pdf_pages_attributes: Vec, pub(super) glyph_unicode: crate::pdf_unicode::GlyphUnicodeMap, pub(super) hyphenation: super::hyphenation::HyphenationData, } @@ -751,6 +753,7 @@ impl Default for State { initial_random_seed: None, random: None, pdf_info: Vec::new(), + pdf_pages_attributes: Vec::new(), glyph_unicode: crate::pdf_unicode::GlyphUnicodeMap::default(), hyphenation: super::hyphenation::HyphenationData::default(), }; @@ -1422,6 +1425,7 @@ impl State { self.pdf_objects = None; } self.pdf_info.clear(); + self.pdf_pages_attributes.clear(); self.fonts.pdf_settings.clear(); self } @@ -1436,6 +1440,7 @@ impl State { generate_unicode: self.parameter(Parameter::Pdfgentounicode).width(), glyph_unicode: &self.glyph_unicode, fonts: &self.fonts, + page_tree_attributes: &self.pdf_pages_attributes, catalog: self.pdf_catalog.as_deref(), objects: self.pdf_objects.as_deref(), info: crate::pdf_device::PdfInfo { diff --git a/crates/texrra-tex-core/src/pdf.rs b/crates/texrra-tex-core/src/pdf.rs index 40d1161..3450d01 100755 --- a/crates/texrra-tex-core/src/pdf.rs +++ b/crates/texrra-tex-core/src/pdf.rs @@ -1384,13 +1384,16 @@ fn native_pdf( return Err("invalid native PDF final stream compression level".into()); } let raw_objects = unicode.and_then(|options| options.objects); + let page_tree = unicode.map_or(&[][..], |options| options.page_tree_attributes); let font_attributes: BTreeMap<_, _> = fonts.keys().filter_map(|&font| { let settings = unicode?.fonts.pdf_settings(font)?; (!settings.attributes.is_empty()).then_some((font, settings.attributes.as_slice())) }).collect(); let resources = if raw_objects.is_some() || !font_attributes.is_empty() - || pages.iter().any(|page| !page.pdf_resources.entries.is_empty()) + || !page_tree.is_empty() + || pages.iter().any(|page| !page.pdf_resources.entries.is_empty() + || !page.pdf_resources.attributes.is_empty()) { let (catalog, info) = if raw_objects.is_some() { ( @@ -1401,7 +1404,7 @@ fn native_pdf( (None, None) }; Some(crate::pdf_device::page_resources::ResourceOutput::prepare( - pages, raw_objects, font_attributes, catalog, info, + pages, raw_objects, font_attributes, page_tree, catalog, info, )?) } else { None @@ -2319,10 +2322,15 @@ fn write_pdf( }; page_ids.push(page_id); kids.push(format!("{page_id} 0 R")); - let mut page = format!( - "<< /Type /Page /Parent 2 0 R /MediaBox [0 0 {} {}] /Resources ", - physical(width), physical(height), - ).into_bytes(); + let decorated = !list.pdf_resources.attributes.is_empty(); + let mut page = b"<< /Type /Page".to_vec(); + if !decorated { + page.extend_from_slice(b" /Parent 2 0 R"); + } + if !crate::pdf_device::page_attributes::supplies_media_box(&list.pdf_resources.attributes) { + page.extend_from_slice(format!(" /MediaBox [0 0 {} {}]", physical(width), physical(height)).as_bytes()); + } + page.extend_from_slice(b" /Resources "); if let Some(additional) = remapped.as_ref().map(|resources| &resources.pages[page_index]) && !additional.is_empty() { @@ -2332,7 +2340,13 @@ fn write_pdf( } else { page.extend_from_slice(resources.as_bytes()); } - page.extend_from_slice(format!("{annots} /Contents {content_id} 0 R >>").as_bytes()); + if decorated { + page.extend_from_slice(format!(" /Contents {content_id} 0 R ").as_bytes()); + page.extend_from_slice(&remapped.as_ref().expect("validated page dictionary").page_attributes[page_index]); + page.extend_from_slice(format!(" /Parent 2 0 R{annots} >>").as_bytes()); + } else { + page.extend_from_slice(format!("{annots} /Contents {content_id} 0 R >>").as_bytes()); + } if let Some(id) = reserved_page { objects[id - 1] = page; } else { @@ -2456,11 +2470,16 @@ fn write_pdf( } } objects[1] = format!( - "<< /Type /Pages /Kids [{}] /Count {} >>", + "<< /Type /Pages /Kids [{}] /Count {}", kids.join(" "), pages.len() ) .into_bytes(); + if let Some(resources) = &remapped && !resources.page_tree_attributes.is_empty() { + objects[1].push(b' '); + objects[1].extend_from_slice(&resources.page_tree_attributes); + } + objects[1].extend_from_slice(b" >>"); let mut catalog = "<< /Type /Catalog /Pages 2 0 R".to_owned(); if !metadata.outline.is_empty() { diff --git a/crates/texrra-tex-core/src/pdf_device.rs b/crates/texrra-tex-core/src/pdf_device.rs index f30aecc..3053512 100644 --- a/crates/texrra-tex-core/src/pdf_device.rs +++ b/crates/texrra-tex-core/src/pdf_device.rs @@ -82,6 +82,7 @@ pub(crate) use graphics::{Affine, DeviceOrigin}; pub use graphics::{PdfGraphics, PdfLiteralMode, PdfMatrix}; pub mod catalog; pub mod text_spaces; +pub(crate) mod page_attributes; pub mod links; #[doc(hidden)] diff --git a/crates/texrra-tex-core/src/pdf_device/page_attributes.rs b/crates/texrra-tex-core/src/pdf_device/page_attributes.rs new file mode 100644 index 0000000..e180893 --- /dev/null +++ b/crates/texrra-tex-core/src/pdf_device/page_attributes.rs @@ -0,0 +1,187 @@ +//! Page dictionaries affect the PDF viewport independently of TeX's canvas. +use super::{ + Affine, magnify, + page_resources::{PdfObjects, parse_entries, resolve_value}, + print_sp, +}; +use crate::render::DisplayList; +use lopdf::{Dictionary, Object}; + +/// The reference device suppresses its generated box when the token text +/// contains this spelling, even before the PDF consumer parses the dictionary. +pub(crate) fn supplies_media_box(attributes: &[u8]) -> bool { + attributes + .windows(b"/MediaBox".len()) + .any(|part| part == b"/MediaBox") +} + +#[derive(Clone, Debug, PartialEq, Eq)] +pub(crate) struct Viewport { + crop: [u64; 4], + rotation: i64, + user_unit: u64, +} + +impl Viewport { + pub(crate) fn unit(&self) -> f64 { + f64::from_bits(self.user_unit) + } + + pub(crate) fn dimensions(&self) -> [f64; 2] { + let [x0, y0, x1, y1] = self.crop.map(f64::from_bits); + let [width, height] = [(x1 - x0) * self.unit(), (y1 - y0) * self.unit()]; + if matches!(self.rotation, 90 | 270) { + [height, width] + } else { + [width, height] + } + } + + /// Map y-down coordinates on the original TeX canvas to the PDF viewport. + pub(crate) fn transform(&self, original_height: f64) -> Affine { + let [x0, y0, x1, y1] = self.crop.map(f64::from_bits); + let matrix = match self.rotation { + 90 => [0.0, 1.0, -1.0, 0.0, original_height - y0, -x0], + 180 => [-1.0, 0.0, 0.0, -1.0, x1, original_height - y0], + 270 => [0.0, -1.0, 1.0, 0.0, y1 - original_height, x1], + _ => [1.0, 0.0, 0.0, 1.0, -x0, y1 - original_height], + }; + Affine(matrix.map(|value| value * self.unit())) + } +} + +pub(crate) fn resolve( + pages: &mut [DisplayList], + root_bytes: &[u8], + objects: &PdfObjects, +) -> Result<(), String> { + if root_bytes.is_empty() + && pages + .iter() + .all(|page| page.pdf_resources.attributes.is_empty()) + { + return Ok(()); + } + let root = parse_entries(root_bytes)?; + for page in pages { + let Some(pdf) = &page.pdf else { + continue; + }; + let resource = &mut page.pdf_resources; + let local = if resource.attributes.is_empty() { + Dictionary::new() + } else { + parse_entries(&resource.attributes)? + }; + + // Custom content or font resources may change the meaning of native + // paint indices. Group composition still uses those same indices. + resource.overrides_paint = local.has(b"Contents") || local.has(b"Resources"); + resource.needs_pdf_for_preview |= resource.overrides_paint || local.has(b"Group"); + + let supplied_media = supplies_media_box(&resource.attributes); + let media_value = if supplied_media { + attribute(&local, &root, b"MediaBox", objects)? + } else if local.has(b"MediaBox") { + attribute(&local, &Dictionary::new(), b"MediaBox", objects)? + } else { + None + }; + let crop = attribute(&local, &root, b"CropBox", objects)?; + let rotation = attribute(&local, &root, b"Rotate", objects)? + .map_or(0, |value| value.as_i64().unwrap_or(0).rem_euclid(360)); + let unit = attribute(&local, &Dictionary::new(), b"UserUnit", objects)? + .map_or(Ok(1.0), |value| finite_number(&value))?; + if unit <= 0.0 { + return Err("native PDF UserUnit must be positive".into()); + } + let rotation = if rotation % 90 == 0 { rotation } else { 0 }; + if !supplied_media + && media_value.is_none() + && crop.is_none() + && rotation == 0 + && unit == 1.0 + { + continue; + } + let dimension = |sp| { + print_sp(magnify(sp, page.magnification), pdf.file.decimal_digits) + .parse::() + .expect("formatted PDF page dimension is numeric") + }; + let media = match media_value { + Some(value) => rectangle(value, objects)?, + None if supplied_media => [0.0, 0.0, 595.0, 842.0], + None => [0.0, 0.0, dimension(page.width), dimension(page.height)], + }; + let crop = crop + .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()); + } + resource.viewport = Some(viewport); + } + Ok(()) +} + +fn attribute( + local: &Dictionary, + root: &Dictionary, + name: &[u8], + objects: &PdfObjects, +) -> Result, String> { + for dictionary in [local, root] { + if let Ok(entry) = dictionary.get(name) { + let value = resolve_value(entry.clone(), objects)?; + if !matches!(value, Object::Null) { + return Ok(Some(value)); + } + } + } + Ok(None) +} + +fn finite_number(value: &Object) -> Result { + let number = match value { + Object::Integer(n) => *n as f64, + Object::Real(n) => *n, + _ => return Err("native PDF page geometry must use numeric coordinates".into()), + }; + if number.is_finite() { + Ok(number) + } else { + Err("native PDF page geometry must be finite".into()) + } +} + +fn rectangle(value: Object, objects: &PdfObjects) -> 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) = (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/page_resources.rs b/crates/texrra-tex-core/src/pdf_device/page_resources.rs index 936e0fc..1b19d7f 100644 --- a/crates/texrra-tex-core/src/pdf_device/page_resources.rs +++ b/crates/texrra-tex-core/src/pdf_device/page_resources.rs @@ -285,7 +285,10 @@ pub(crate) fn parse_name(bytes: &[u8]) -> Result, String> { } } -fn parse_entries(bytes: &[u8]) -> Result { +pub(super) fn parse_entries(bytes: &[u8]) -> Result { + if bytes.is_empty() { + return Ok(Dictionary::new()); + } let mut wrapped = b"<< ".to_vec(); wrapped.extend_from_slice(bytes); wrapped.extend_from_slice(b"\n>>"); @@ -321,6 +324,9 @@ fn encode_value(object: Object) -> Result, String> { #[derive(Clone, Debug, Default, PartialEq, Eq)] pub struct PageResources { pub(crate) entries: Arc<[u8]>, + pub(crate) attributes: Arc<[u8]>, + pub(crate) viewport: Option, + pub(crate) overrides_paint: bool, pub(crate) opacity: BTreeMap, Transparency>, pub(crate) needs_pdf_for_preview: bool, } @@ -331,20 +337,27 @@ pub(crate) struct Transparency { pub stroke: Option, } -fn resolve_dictionary(entry: Object, objects: &PdfObjects) -> Result { - let mut entry = entry; +pub(super) fn resolve_value(mut entry: Object, objects: &PdfObjects) -> Result { let mut seen = BTreeSet::new(); loop { match entry { - Object::Dictionary(dictionary) => return Ok(dictionary), Object::Reference((number, 0)) if seen.insert(number) => { entry = objects.written_body(number)?.parse()?; } - _ => return Err("PDF resource must refer to a dictionary".into()), + Object::Reference(_) => return Err("invalid or circular native PDF reference".into()), + value => return Ok(value), } } } +fn resolve_dictionary(entry: Object, objects: &PdfObjects) -> Result { + if let Object::Dictionary(dictionary) = resolve_value(entry, objects)? { + Ok(dictionary) + } else { + Err("PDF resource must refer to a dictionary".into()) + } +} + fn alpha(dictionary: &Dictionary, key: &[u8]) -> Result, String> { let Ok(value) = dictionary.get(key) else { return Ok(None); @@ -363,12 +376,14 @@ fn alpha(dictionary: &Dictionary, key: &[u8]) -> Result, String> impl PageResources { pub(crate) fn from_page( bytes: Arc<[u8]>, + attributes: Arc<[u8]>, names: &BTreeSet>, objects: &PdfObjects, ) -> Result { if names.is_empty() { return Ok(Self { entries: bytes, + attributes, ..Self::default() }); } @@ -379,6 +394,7 @@ impl PageResources { let definitions = resolve_dictionary(definitions.clone(), objects)?; let mut resources = Self { entries: bytes, + attributes, ..Self::default() }; for name in names { @@ -411,6 +427,8 @@ pub(crate) struct ResourceOutput { page_references: BTreeMap, link_references: BTreeMap>, page_entries: Vec, + page_attributes: Vec, + page_tree_attributes: Dictionary, font_entries: BTreeMap, annotation_entries: Vec>>, catalog: Option, @@ -419,6 +437,8 @@ pub(crate) struct ResourceOutput { pub(crate) struct RemappedResources { pub pages: Vec>, + pub page_attributes: Vec>, + pub page_tree_attributes: Vec, pub fonts: BTreeMap>, pub page_objects: BTreeMap, pub link_objects: BTreeMap<(usize, usize), usize>, @@ -432,6 +452,7 @@ impl ResourceOutput { pages: &[crate::render::DisplayList], objects: Option<&PdfObjects>, fonts: BTreeMap, + page_tree: &[u8], catalog: Option<&[u8]>, info: Option<&[u8]>, ) -> Result { @@ -453,10 +474,21 @@ impl ResourceOutput { .into_iter() .map(|(font, entries)| Ok((font, parse_entries(entries)?))) .collect::, String>>()?; + let page_attributes = pages + .iter() + .map(|page| parse_entries(&page.pdf_resources.attributes)) + .collect::, _>>()?; + let page_tree_attributes = parse_entries(page_tree)?; let catalog = catalog.map(parse_entries).transpose()?; let info = info.map(parse_entries).transpose()?; let mut pending = objects.written.clone(); - for dictionary in page_entries.iter().chain(font_entries.values()).chain(&catalog).chain(&info) { + for dictionary in page_entries.iter() + .chain(&page_attributes) + .chain(std::iter::once(&page_tree_attributes)) + .chain(font_entries.values()) + .chain(&catalog) + .chain(&info) + { for (_, entry) in dictionary.iter() { references(entry, &mut pending)?; } @@ -522,6 +554,8 @@ impl ResourceOutput { page_references: objects.page_references.clone(), link_references, page_entries, + page_attributes, + page_tree_attributes, font_entries, annotation_entries, catalog, @@ -581,6 +615,8 @@ impl ResourceOutput { }; RemappedResources { pages: self.page_entries.into_iter().map(&encode).collect(), + page_attributes: self.page_attributes.into_iter().map(&encode).collect(), + page_tree_attributes: encode(self.page_tree_attributes), fonts: self.font_entries.into_iter() .map(|(font, dictionary)| (font, encode(dictionary))) .collect(), diff --git a/crates/texrra-tex-core/src/pdf_unicode.rs b/crates/texrra-tex-core/src/pdf_unicode.rs index 0f9ba13..092f874 100644 --- a/crates/texrra-tex-core/src/pdf_unicode.rs +++ b/crates/texrra-tex-core/src/pdf_unicode.rs @@ -129,6 +129,7 @@ pub struct PdfFinalOptions<'a> { pub generate_unicode: i32, pub glyph_unicode: &'a GlyphUnicodeMap, pub fonts: &'a crate::execution::FontCatalog, + pub page_tree_attributes: &'a [u8], pub catalog: Option<&'a crate::pdf_device::catalog::PdfCatalog>, pub objects: Option<&'a crate::pdf_device::page_resources::PdfObjects>, pub info: crate::pdf_device::PdfInfo<'a>, diff --git a/crates/texrra-tex-core/src/render.rs b/crates/texrra-tex-core/src/render.rs index dfe61e9..a826eb3 100755 --- a/crates/texrra-tex-core/src/render.rs +++ b/crates/texrra-tex-core/src/render.rs @@ -317,6 +317,11 @@ impl DisplayList { })) } + /// Physical size of one PDF user space unit, in big points. + pub fn pdf_user_unit(&self) -> f64 { + self.pdf_resources.viewport.as_ref().map_or(1.0, |viewport| viewport.unit()) + } + /// Compare the inputs consumed by SVG rendering. Font data for glyphs not /// present on this page and source locations do not affect its SVG. pub fn same_svg_paint(&self, other: &Self) -> bool { @@ -326,6 +331,7 @@ impl DisplayList { && self.magnification == other.magnification && self.images == other.images && self.pdf_resources.opacity == other.pdf_resources.opacity + && self.pdf_resources.viewport == other.pdf_resources.viewport && self.pdf_resources.needs_pdf_for_preview == other.pdf_resources.needs_pdf_for_preview && self.items.len() == other.items.len() && self.items.iter().zip(&other.items).all(|(left, right)| { @@ -435,10 +441,16 @@ impl DisplayList { } else { 1.0 }; - let (physical_width, physical_height) = (width * mag, height * mag); + let viewport = self.pdf_resources.viewport.as_ref(); + let [physical_width, physical_height] = viewport + .map_or([width * mag, height * mag], |geometry| geometry.dimensions()); let mut out = format!( "\n" ); + if let Some(viewport) = viewport { + let [a, b, c, d, e, f] = viewport.transform(height * mag).0; + out.push_str(&format!("\n")); + } if self.magnification != 1000 || self.units == DisplayUnits::TeX { out.push_str(&format!("\n")); } @@ -761,6 +773,9 @@ impl DisplayList { if self.magnification != 1000 || self.units == DisplayUnits::TeX { out.push_str("\n"); } + if viewport.is_some() { + out.push_str("\n"); + } out.push_str("\n"); out } diff --git a/crates/texrra-tex-core/src/source_map.rs b/crates/texrra-tex-core/src/source_map.rs index 92a085a..397da58 100644 --- a/crates/texrra-tex-core/src/source_map.rs +++ b/crates/texrra-tex-core/src/source_map.rs @@ -84,6 +84,19 @@ impl Bounds { } } impl Bounds { + fn clipped_by(self, width: i64, height: i64) -> Option { + let x = self.x.max(0); + let y = self.y.max(0); + let right = self.x.saturating_add(self.width).min(width); + let bottom = self.y.saturating_add(self.height).min(height); + (right >= x && bottom >= y && width > 0 && height > 0).then_some(Self { + x, + y, + width: right.saturating_sub(x), + height: bottom.saturating_sub(y), + }) + } + pub fn contains(self, x: i64, y: i64) -> bool { let right = i128::from(self.x) + i128::from(self.width); let bottom = i128::from(self.y) + i128::from(self.height); @@ -117,6 +130,7 @@ pub struct MappedPaint { pub enum UnmappedReason { MissingProvenance, UnsupportedPrimitive, + ClippedByPage, } #[derive(Clone, Copy, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)] pub struct UnmappedPaint { @@ -296,6 +310,19 @@ impl SourceMap { entries: Vec::new(), unmapped: Vec::new(), }; + let viewport = page.pdf_resources.viewport.as_ref().map(|viewport| { + let unit = page.units.bp(1) * f64::from(page.magnification) / 1000.0; + let dimensions = viewport.dimensions().map(|value| (value / unit).ceil()); + if dimensions.iter().any(|value| !value.is_finite() || *value >= i64::MAX as f64) { + return Err("native PDF viewport exceeds source map dimensions"); + } + [map.width, map.height] = dimensions.map(|value| value as i64); + let mut transform = viewport.transform(page.height as f64 * unit); + for distance in &mut transform.0[4..] { + *distance /= unit; + } + Ok(transform) + }).transpose()?; let mut transform = Affine::IDENTITY; let mut graphics_stack = Vec::new(); let mut pdf_projection = PdfProjection::for_page(page); @@ -303,6 +330,11 @@ impl SourceMap { let placement = pdf_projection .as_mut() .map_or(Some(transform), |projection| projection.observe(item)); + let placement = if page.pdf_resources.overrides_paint { + None + } else { + placement.map(|graphics| viewport.map_or(graphics, |frame| frame.concatenate(graphics))) + }; if let DisplayItem::PdfGraphics { x, y, operation } = item { if pdf_projection.is_some() { continue; @@ -414,12 +446,24 @@ impl SourceMap { .filter(|s| !s.tokens.is_empty()), placement, ) { - (Some((kind, bounds)), Some(source), Some(transform)) => map.entries.push(MappedPaint { - item_index, - kind, - bounds: bounds.transformed(transform)?, - source: source.clone(), - }), + (Some((kind, bounds)), Some(source), Some(transform)) => { + let bounds = bounds.transformed(transform)?; + let visible = if viewport.is_some() { + bounds.clipped_by(map.width, map.height) + } else { + Some(bounds) + }; + if let Some(bounds) = visible { + map.entries.push(MappedPaint { + item_index, kind, bounds, source: source.clone(), + }); + } else { + map.unmapped.push(UnmappedPaint { + item_index, reason: UnmappedReason::ClippedByPage, + }); + } + } + (geometry, _, placement) => map.unmapped.push(UnmappedPaint { item_index, reason: if geometry.is_some() && placement.is_some() { diff --git a/crates/texrra-tex-core/tests/execution_fractions.rs b/crates/texrra-tex-core/tests/execution_fractions.rs index dae25c1..d70f311 100644 --- a/crates/texrra-tex-core/tests/execution_fractions.rs +++ b/crates/texrra-tex-core/tests/execution_fractions.rs @@ -246,7 +246,7 @@ fn genuine_fraction_primitives_and_retained_boxes_survive_format_roundtrip() { let envelope: serde_json::Value = serde_json::from_slice(&bytes).unwrap(); let payload: serde_json::Value = serde_json::from_str(envelope["payload"].as_str().unwrap()).unwrap(); - assert_eq!(payload["schema"], 42); + assert_eq!(payload["schema"], 43); let state = State::initex().with_etex(); let loaded = FormatImage::decode(&bytes) .unwrap() diff --git a/crates/texrra-tex-core/tests/execution_pdf_unicode.rs b/crates/texrra-tex-core/tests/execution_pdf_unicode.rs index 4ce6102..ab1f70b 100644 --- a/crates/texrra-tex-core/tests/execution_pdf_unicode.rs +++ b/crates/texrra-tex-core/tests/execution_pdf_unicode.rs @@ -334,7 +334,7 @@ fn old_schema_and_missing_unicode_state_are_rejected_even_with_valid_checksums() let envelope: serde_json::Value = serde_json::from_slice(&encoded).unwrap(); let original: serde_json::Value = serde_json::from_str(envelope["payload"].as_str().unwrap()).unwrap(); - assert_eq!(original["schema"], 42); + assert_eq!(original["schema"], 43); for (schema, expected) in [ (1, "incompatible native format"), (2, "incompatible native format"), diff --git a/crates/texrra-tex-core/tests/execution_vcenter.rs b/crates/texrra-tex-core/tests/execution_vcenter.rs index efa1f68..95392f6 100644 --- a/crates/texrra-tex-core/tests/execution_vcenter.rs +++ b/crates/texrra-tex-core/tests/execution_vcenter.rs @@ -164,7 +164,7 @@ fn new_format_owns_vcenter_and_boxed_math_without_reinjecting_old_meanings() { let envelope: serde_json::Value = serde_json::from_slice(&bytes).unwrap(); let payload: serde_json::Value = serde_json::from_str(envelope["payload"].as_str().unwrap()).unwrap(); - assert_eq!(payload["schema"], 42); + assert_eq!(payload["schema"], 43); let executor = FormatImage::decode(&bytes) .unwrap() .new_job( diff --git a/docs/P2_M1_PROGRESS.md b/docs/P2_M1_PROGRESS.md index 1a412e2..3bd7cf0 100644 --- a/docs/P2_M1_PROGRESS.md +++ b/docs/P2_M1_PROGRESS.md @@ -1211,6 +1211,34 @@ TeX 字体表。 - `small-font` 核对小至1sp的字号返回受控导出错误,未发布 PDF。 两组原有设备及 PK 定向回归共四项通过。 +### 页面字典、视口与增量预览 + +schema43 接入 \pdfpageattr 和 \pdfpagesattr 两个原生 token 参数。 +局部属性由发页捕获,根 Pages 属性由作业收尾时捕获,沿用分组、赋值 +和格式转储机制。生成页面保留 TeX 布局原点,必要时以文档提供的 +MediaBox 供实际 PDF 消费。页面和根字典的间接引用进入与普通 PDF +对象相同的重映射,沿用实际页对象与字体资源的身份。 +[pdfTeX 的 Page 字典写出](https://github.com/TeX-Live/texlive-source/blob/trunk/texk/web2c/pdftexdir/pdftex.web#L19387-L19416) +[pdfTeX 的根 Pages 字典写出](https://github.com/TeX-Live/texlive-source/blob/trunk/texk/web2c/pdftexdir/pdftex.web#L20180-L20204) + +原生 SVG 和来源映射读取页及根字典的实际裁切、旋转和用户单位。 +裁掉的已知绘制保留明确状态。替换 Contents 或 Resources 的字典会 +改变绘制来源,通过发布 PDF 合成预览,受影响的原绘制在来源映射中 +标明为不受支持。Group 也通过发布 PDF 合成。仅改变普通页面元数据时, +原生 SVG 继续使用其既有布局和设备视口。 + +保存的三页参考中,局部属性的 outer、inner、outer 顺序、MediaBox、 +继承旋转和实际对象引用一致,三页 144 DPI 灰度图逐像素一致。 +参考与原生分别从各自格式重载,页属性和根属性继续生效。编辑第二页的 +裁切/旋转复用950步,只重发第二页。PDF、SVG 和归一化来源映射与 +独立零复用一致。追加页面 Group 时,PDF 合成预览继续采用该页 +240 × 160 bp 的视口。 + +在 `target/p3-pdf-page-dictionary-native` 保留实际回执。 + +- `receipt.json` 为 `1d6ee45530a70951b88bc3e4469cc871f316b861d8c3236c6dd371fbb4dc6e79`。 +- `checkpoint/receipt.json` 为 `94f1ff6e479b5344f802dee6101dfb0b13960500b149e6dcc7d8187d78363520`。 + ### PDF 字面中的矩阵与来源映射 来源映射与 PDF 写入共用设备原点的取整。实际字面中的 `q`、`Q` 和 diff --git a/src/native_preview.rs b/src/native_preview.rs index 65bc965..89a1bc6 100644 --- a/src/native_preview.rs +++ b/src/native_preview.rs @@ -31,7 +31,7 @@ struct PdfPreview<'a> { } impl PdfPreview<'_> { - fn render_page(&self, index: usize) -> Result, String> { + fn render_page(&self, index: usize, unit: f64) -> Result, String> { let document = self .document .get_or_init(|| { @@ -48,11 +48,19 @@ impl PdfPreview<'_> { .iter() .nth(index) .ok_or("preview PDF page is missing")?; - Ok(Arc::from(hayro_svg::convert( + let svg = hayro_svg::convert( page, &RenderCache::new(), &InterpreterSettings::default(), &SvgRenderSettings::default(), + ); + if unit == 1.0 { + return Ok(Arc::from(svg)); + } + let (width, height) = page.render_dimensions(); + let (width, height) = (f64::from(width) * unit, f64::from(height) * unit); + Ok(Arc::from(format!( + "{svg}" ))) } } @@ -137,7 +145,7 @@ impl PreviewState { let svg = self.slots[index] .get_or_init(|| { if page.has_embedded_pdf() { - pdf.render_page(index) + pdf.render_page(index, page.pdf_user_unit()) } else { page.try_to_svg().map(Arc::from) }